Ruby on rails ruby/rails:如何确定是否包含模块?

Ruby on rails ruby/rails:如何确定是否包含模块?,ruby-on-rails,ruby,module,Ruby On Rails,Ruby,Module,在这里扩展我的问题(),使用我现有的解决方案,确定是否包含我的模块的最佳方法是什么 我现在做的是在每个模块上定义实例方法,这样当它们被包含时,一个方法就可用了,然后我只是在父模块中添加了一个catcher(method\u missing()),这样我就可以捕获它们是否未被包含。我的解决方案代码如下所示: module Features FEATURES = [Running, Walking] # include Features::Running FEATURES.each d

在这里扩展我的问题(),使用我现有的解决方案,确定是否包含我的模块的最佳方法是什么

我现在做的是在每个模块上定义实例方法,这样当它们被包含时,一个方法就可用了,然后我只是在父模块中添加了一个catcher(
method\u 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's 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.include?(功能)
例如:

模块M
结束
C类
包括M
结束
C.包括?(M)#=>正确
其他方式 检查 这是可行的,但它有点间接,因为它生成中间的
包含的\u模块
数组

C.include_模块。include?(M)#=>true
因为
C.included\u模块
的值为
[M,内核]

检查
C.include?(M)#=>true
因为
C.concenters
的值为
[C,M,Object,Kernel,BasicObject]

使用像
true这样的运算符

这个问题有点复杂,所以我不确定这是否是您想要的,但要检查是否包含模型,您可以执行
object.class.include?模块
您可以使用
respond\u to?
检查方法是否可用。对
C
语法进行了投票。你知道我在哪里可以学到糖的语法吗?我还没有找到与“用Java思考”相当的Ruby,这是对该语言的全面介绍。@makhan,这是方法模块。#@makhan来自Russ Olsen的“雄辩Ruby”是Ruby IDOM的一个很好的(而且是全面的)概述。正确的代码是:
Man.include\u模块。include?(功能)
而不是
包含?
我试图编辑anwer,但你需要更改6个以上的字符才能编辑,这篇文章的其余部分看起来不错:-)谢谢你,@Alexander。明显的改进。
Man.new.can_walk?
# => true
Car.new.can_run?
# => true
Car.new.can_walk? # method_missing catches this
# => false