How to access protected class methods from instance methods in Ruby?

I need to skip 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 the zop to be protected or closed (not calling "Foo.zoop"), but so far I cannot find an elegant way.

+6
source share
2 answers

After further discussions with rue: and drbrain: in ruby-lang, it turns out that my impulse to save memory by placing utility functions at the class level was inappropriate.

In Ruby, instance methods still hang from the class, and the answer should go ahead and put the utility functions at the instance level as private.

In general, a utility function that is accessed only by instance methods:

 class Foo def what "it is '#{zoop}'" end private def zoop "zoop" end end p Foo.new.what # => "it is 'zoop'" 

For the utility function to be called from the instance and class methods, the nested module was apparently popular:

 class Foo module Util def self.zoop "zoop" end end def what "it is '#{Util.zoop}'" end class << self def class_what "for all time it is '#{Util.zoop}'" end end end p Foo.new.what # => "it is 'zoop'" p Foo.class_what # => "for all time it is 'zoop'" p Foo::Util.zoop # visible, alas 
+2
source

It is hardly necessary to make methods private or secure in Ruby, as you can just call send () to get around them.

If you want the zoo to remain protected, use send () as follows:

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

Source: https://habr.com/ru/post/900639/


All Articles