Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an instance has been extended by a Ruby module?

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]
like image 922
Allyl Isocyanate Avatar asked Aug 24 '12 20:08

Allyl Isocyanate


2 Answers

Is there any reason why you are not just using is_a?:

o.is_a? Foobar
# => true
like image 80
Jörg W Mittag Avatar answered Nov 12 '22 17:11

Jörg W Mittag


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

like image 27
Frederick Cheung Avatar answered Nov 12 '22 16:11

Frederick Cheung