Подтвердить что ты не робот

Ruby/rails: Как определить, включен ли модуль?

Расширение моего вопроса здесь (ruby ​​/rails: расширение или включение других модулей), используя мое существующее решение, что лучший способ определить, включен ли мой модуль?

То, что я делал на данный момент, это то, что я определил методы экземпляра для каждого модуля, поэтому, когда они будут включены, будет доступен метод, а затем я просто добавлю улавливатель (method_missing()) в родительский модуль, чтобы я мог поймать, если они не включено. Мой код решения выглядит так:

module Features
  FEATURES = [Running, Walking]

  # include Features::Running
  FEATURES.each do |feature|
    include feature
  end

  module ClassMethods
    # include Features::Running::ClassMethods
    FEATURES.each do |feature|
      include feature::ClassMethods
    end
  end

  module InstanceMethods
    def method_missing(meth)
      # Catch feature checks that are not included in models to return false
      if meth[-1] == '?' && meth.to_s =~ /can_(\w+)\z?/
        false
      else
        # You *must* call super if you don't handle the method,
        # otherwise you'll mess up Ruby method lookup
        super
      end
    end
  end

  def self.included(base)
    base.send :extend, ClassMethods
    base.send :include, InstanceMethods
  end
end

# lib/features/running.rb
module Features::Running
  module ClassMethods
    def can_run
      ...

      # Define a method to have model know a way they have that feature
      define_method(:can_run?) { true }
    end
  end
end

# lib/features/walking.rb
module Features::Walking
  module ClassMethods
    def can_walk
      ...

      # Define a method to have model know a way they have that feature
      define_method(:can_walk?) { true }
    end
  end
end

Итак, в моих моделях я:

# Sample models
class Man < ActiveRecord::Base
  # Include features modules
  include Features

  # Define what man can do
  can_walk
  can_run
end

class Car < ActiveRecord::Base
  # Include features modules
  include Features

  # Define what man can do
  can_run
end

И тогда я могу

Man.new.can_walk?
# => true
Car.new.can_run?
# => true
Car.new.can_walk? # method_missing catches this
# => false

Я правильно написал это? Или есть лучший способ?

4b9b3361

Ответ 1

Если я правильно понял ваш вопрос, вы можете сделать это:

Man.included_modules.include?(Features)?

Например:

module M
end

class C
  include M
end

C.included_modules.include?(M)
  #=> true

а

C.included_modules
  #=> [M, Kernel]

Другие способы:

как сказал @Markan:

C.include? M
  #=> true

или

C.ancestors.include?(M)
  #=> true

или просто:

C < M
  #=> true