Junchao Gu
Junchao Gu

Reputation: 1865

Invoke private method from class

I have a Ruby class method and I want to use a private method of an object of this class, but Rails throws an error.

The specific context is: I have a model class Team. I defined

def self.to_csv(**options)
    # blah blah blah
    teams = self.all
    teams.each do |team|
         csv_row = team.export_as_csv_row #a private method
         # and it failed here
    end
end

I am using Ruby 2.2.1 and Rails 4.2. If I cannot do this, if there any way to protect export_as_csv_row from other classes seeing it?

Upvotes: 0

Views: 1547

Answers (1)

dimakura
dimakura

Reputation: 7655

You can easily invoke private methods on any instance using Object#send method:

team.send :export_as_csv_row

More details are available in the Object#send documentation.

Upvotes: 4

Related Questions