6

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?

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
Dorian
  • 22,759
  • 8
  • 120
  • 116
  • I google searched for this after seeing Jbuilder's readme as well lol. Thanks for figuring it out, what an odd and not-the-ruby-way syntax for a method call... – Kevin Nov 15 '22 at 22:28

1 Answers1

4

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
xdazz
  • 158,678
  • 38
  • 247
  • 274