Is it possible to define class methods in class_eval class?

I know it is possible to define instance methods with class_eval

. Is it possible to define class methods in context class_eval

?

+3


source to share


2 answers


Yes, it is possible:

class Foo
end

Foo.class_eval do
  def self.bar
    puts "I'm a class method defined using class_eval and self"
  end

  def baz
    puts "I'm an instance method defined using class_eval without self"
  end
end

Foo.bar # => "I'm a class method defined using class_eval and self"

foo = Foo.new
foo.baz # => "I'm an instance method defined using class_eval without self"

      



As far as I can tell, this is because, internally class_eval

, self

is a class Foo, and execution def Foo.bar

will create a method of the class.

+4


source


Foo.class_eval do
  ...
end

      

identical:

class Foo
  ...
end

      

We need Module # class_eval to work with a variable that contains the class name. For example, if:

klass = Foo

      



You can write:

klass.class_eval do
  ...
end

      

whereas the keyword class

requires a constant.

It class_eval

does two things here:

  • it changes self

    to value klass

    ( Foo

    ); and then he
  • "opens" the value klass

    ( Foo

    ) in the same way as the keyword does class

    .
0


source







All Articles