I know it's possible to define instance methods using class_eval
. Is it possible to define class methods within the context of class_eval
?
Is it possible to define class methods within `class_eval`?
999 Views Asked by Andrew Grimm At
2
There are 2 best solutions below
0

Foo.class_eval do
...
end
is identical to:
class Foo
...
end
We need Module#class_eval to operate on a variable that holds the name of a class. For example, if:
klass = Foo
you can write:
klass.class_eval do
...
end
whereas the keyword class
demands a constant.
Here class_eval
does two things:
- it changes
self
to the value ofklass
(Foo
); and then it - "opens" the value of
klass
(Foo
) in the same way the keywordclass
does.
Yes, it is possible:
As far as I can tell, this is because within
class_eval
,self
is the Foo class, and doingdef Foo.bar
would create a class method.