Is it possible to define class methods in class_eval class?
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 to share
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 valueklass
(Foo
); and then he - "opens" the value
klass
(Foo
) in the same way as the keyword doesclass
.
0
source to share