Quickly find module inclusion in Ruby
Given I have a class like so:
class Location < ActiveEnum::Base
include WithLabel
end
Normally I would check for inclusion of something via a declarative method like:
Location.ancestors.include?(ActiveEnum::Base)
=> true
Location.ancestors.include?(String)
=> false
Location.included_modules.include?(WithLabel)
=> true
However it never occured to me that <
is defined on Class
and returns true if is a subclass of the requested module.
So we can do something like this now:
Location < ActiveEnum::Base
=> true
Location < String
=> nil
Location < WithLabel
=> true
Subtle difference is that the 'falsey' case returns nil instead of false.
Also the definition of this method states that it returns true if module is a subclass of other but I've found that it returns true for methods that are included as well. Take that as you will.
Tweet