How does one access protected class methods from instance methods in Ruby

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I must be missing something about how people do this in Ruby.

If #protected is uncommented we get:
in what : protected method zoop called for Foo:Class (NoMethodError)

Is there a better way to approach protected class methods?

class Foo
  class << self
    #protected
    def zoop 
      "zoop"
    end
  end
  public
  def what
    "it is  #{self.class.zoop} "
  end
  protected
end

a = Foo.new
p a.what # => "it is  zoop "

I would like zoop to be protected or private (no calling Foo.zoop ), but so far, I can t seem to find an elegant way.

Answers

It barely matters to make methods private or protected in Ruby, since you can just call send() to get around them.

If you want zoop to stay protected, use send() like this:

def what
  "it is  #{self.class.send(:zoop)} "
end

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/7985896/how-does-one-access-protected-class-methods-from-instance-methods-in-ruby

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils