Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define class methods within `class_eval`?

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?

like image 309
Andrew Grimm Avatar asked Sep 27 '22 13:09

Andrew Grimm


1 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 within class_eval, self is the Foo class, and doing def Foo.bar would create a class method.

like image 168
Andrew Grimm Avatar answered Nov 11 '22 16:11

Andrew Grimm