Difference between class_eval and instance_eval in a module
Code:
module Mod1
def self.included(base)
base.class_eval do
class << self
attr_accessor :test
end
@test = 'test1'
end
end
end
module Mod2
def self.included(base)
base.instance_eval do
class << self
attr_accessor :test
end
@test = 'test2'
end
end
end
class Foo1
include Mod1
end
class Foo2
include Mod2
end
puts Foo1.test
puts Foo2.test
Output is:
test1
test2
I realize one evaluates in the context of the class while the other evaluates in the context of the instance, but... in this case, why are they returning as such? (I'd ha开发者_开发百科ve expected an exception in one or the other.)
In your example there is no difference.
> Foo1.instance_eval { puts self }
Foo1
> Foo1.class_eval { puts self }
Foo1
The instance of a class is the class itself. instance_eval
gives you nothing "extra" here. But if you use it on an instance of a class, then you get different behaviour. I.e. Foo1.new.instance_eval ...
.
See here for a good explanation:
How to understand the difference between class_eval() and instance_eval()?
精彩评论