Ruby: Metaclass and Class Variables

I looked at some articles that say class variables do not work well in Ruby . They suggest using a metaclass (or singleton class). This is my sample code.

class Joe
  class << self # here we're putting methods in Joe "meta class" 
    attr_accessor :foo
  end
  def self.foo2
  end
  def self.foo2=value
  end
end

puts Joe.singleton_methods

I understand that foo and foo2 are essentially the same, although there is no way to use attr_accesor with foo2.

I do not understand that with class << self syntax. Is there any concatenation, or ... what is it? Is this some kind of expansion, inheritance or correction of monkeys?

Edit (Bonus): While I'm here, is there a way to cache data in the view helper? I tried using this <self class, but helper methods do not find the accessor.

+3
source share
4

class<< foo " foo". , :

class Foo
   class << self
     # class method defined as INSTANCE method
     # the only instance being Foo (the class)
     def boo
       ...
     end
   end
end

class Foo
  def self.boo #class method
  end
end

class << some_object
   def something # adds a method to some_object ONLY
   end
end

, " " , " ", "" ( "" ), " , ". , , .

:

class Joe
  # here we're putting methods in the "class of class"
  class << self
    include ClassMethodsForJoe
    attr_accessor :foo
  end
end
Joe.foo # this is the method we made
+10

class << foo foo, , foo ( foo "real" class). ( , ). , , - .

, def foo.bar

class <<foo
  def bar

. . << <<. .

+6
+1

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


All Articles