Given an object and a module, how do I check that the object has been extended by the module?
给定一个对象和一个模块,如何检查该对象是否已被模块扩展?
There doesn't seem to be any corresponding extend? method
似乎没有任何相应的延伸?方法
moirb(main):001:0> module Foobar
irb(main):002:1> end
=> nil
irb(main):003:0> o=Object.new
=> #<Object:0x000001010d1400>
irb(main):004:0> o.class.include? Foobar
=> false
irb(main):005:0> o.extend Foobar
=> #<Object:0x000001010d1400>
irb(main):006:0> o.class.include? Foobar
=> false
irb(main):007:0> o.class.included_modules
=> [PP::ObjectMixin, Kernel]
irb(main):016:0* o.methods.grep /extend/
=> [:extend]
irb(main):019:0> o.class.methods.grep /extend/
=> [:extend]
2 个解决方案
#1
14
Is there any reason why you are not just using is_a?
:
你有没有理由不使用is_a ?:
o.is_a? Foobar
# => true
#2
9
You can use
您可以使用
o.singleton_class.included_modules
Or if you want to be really pithy:
或者如果你想要真正精辟:
o.singleton_class < Foobar
An object's singleton class is where all of its singleton methods live - extending is (as far as I understand) equivalent to including into the singleton class. This is why
对象的单例类是其所有单例方法所在的位置 - 扩展(据我所知)相当于包含在单例类中。这就是为什么
class Foo
extend Bar
end
and
和
class Foo
class << self
include Bar
end
end
Both add the methods from Bar as class methods (ie singleton methods) on Foo
两者都在Bar上添加方法作为Foo上的类方法(即单例方法)
#1
14
Is there any reason why you are not just using is_a?
:
你有没有理由不使用is_a ?:
o.is_a? Foobar
# => true
#2
9
You can use
您可以使用
o.singleton_class.included_modules
Or if you want to be really pithy:
或者如果你想要真正精辟:
o.singleton_class < Foobar
An object's singleton class is where all of its singleton methods live - extending is (as far as I understand) equivalent to including into the singleton class. This is why
对象的单例类是其所有单例方法所在的位置 - 扩展(据我所知)相当于包含在单例类中。这就是为什么
class Foo
extend Bar
end
and
和
class Foo
class << self
include Bar
end
end
Both add the methods from Bar as class methods (ie singleton methods) on Foo
两者都在Bar上添加方法作为Foo上的类方法(即单例方法)