Ruby dot parenthesis call syntax

后端 未结 1 655
无人共我
无人共我 2020-12-21 00:23

I was reading the jbuilder\'s README and saw these code:

class Person
  # ... Class Definition ... #
  def to_builder
    Jbuilder.new do |person|
      pers         


        
相关标签:
1条回答
  • 2020-12-21 00:56

    self here is just a parameter passed to the Jbuilder's call method.

    Jbuilder needs the instance of person (which is self in the code) and the attribute names (:name and :age in the code) to produce the json data.

    Example:

    class Thing
       attr_accessor :name, :age
    
       def call(*args)
         puts args.inspect
       end
    end
    
    class Bar
      def to_thing
        Thing.new.(self, :name, :age)
      end
    end
    
    Bar.new.to_thing
    
    0 讨论(0)
提交回复
热议问题