Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Rails public_method?

I am reading through Avdi Grimm's book 'Objects in Rails' and he uses the method public_method and I dont understand why. Here is the code example:

class Blog
  # ...
  attr_writer :post_source
  # ...
  private
  def post_source
    @post_source ||= Post.public_method(:new)
  end
end

Why would you call Post.public_method(:new) and not Post.new? Do these methods do anything different or are they exactly the same? Thanks for the help.

like image 950
jhamm Avatar asked Dec 05 '25 13:12

jhamm


1 Answers

Post.new

is not equivalent to

Post.public_method(:new)

The former is an invocation of method new, which, by default, creates a new Post object. The latter, however, does not call new immediately. It merely prepares it to be called later. I haven't read that particular book, but if you look around in the associated source code, you'll see this line

@post_source.call # maybe some params are passed here

This is where Post#new finally gets called.

Documentation: Object#public_method, Object#method.

like image 180
Sergio Tulentsev Avatar answered Dec 07 '25 11:12

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!