Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby dot parenthesis call syntax

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

class Person
  # ... Class Definition ... #
  def to_builder
    Jbuilder.new do |person|
      person.(self, :name, :age)
    end
  end
end

I tried to replicate it myself, and it asks for a call method, so:

class Thing
   attr_accessor :name, :age

   def call(*args)
     puts args.inspect
   end
end

Thing.new.(:name, :age) # => [:name, :age]

So why is there a self in the jbuilder call?

like image 788
Dorian Avatar asked Oct 19 '22 23:10

Dorian


1 Answers

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
like image 179
xdazz Avatar answered Oct 23 '22 01:10

xdazz