Ruby on rails 在ruby中使用include方法

Ruby on rails 在ruby中使用include方法,ruby-on-rails,ruby,include,Ruby On Rails,Ruby,Include,假设我有这个 module Command extend ActiveSupport::Concern included do @path ||= File.join("#{file_path}", "some_file") end def file_path File.expand_path("some_other_file") end ... 当包含模块时,我得到未定义的局部变量或方法文件\u路径。

假设我有这个

module Command
    extend ActiveSupport::Concern

      included do
        @path ||= File.join("#{file_path}", "some_file")
      end

      def file_path
        File.expand_path("some_other_file")
      end
...

当包含模块时,我得到
未定义的局部变量或方法文件\u路径
。那么,有没有一种方法可以在包含模块时识别
文件路径
方法?(当然,不必将
文件路径
放在
包含的
方法中)

您正在调用方法
文件路径
,在方法
包含的
中,
do..end
块中。这意味着with scope设置为
命令
类。但是
file\u path
是实例方法,因此
Command.file\u path
抛出了一个合法错误。您必须在包含
命令
模块的类实例上调用方法
file\u path
。举例说明:

module A
    def self.included(mod)
        p foo
    end
    def foo
        2
    end
end

class B
    include A
end

# `included': undefined local variable or method `foo' for A:Module (NameError)
出现错误是因为包含的方法
中的self是
A
A
没有名为
foo
的类方法,因此出现错误。现在要修复它,我们应该如下所示:

module A
    def self.included(mod)
        p mod.new.foo
    end
    def foo
        2
    end
end

class B
    include A
end

# >> 2
您可以尝试以下方法:

模块命令 扩展ActiveSupport::关注点

  def self.extended(klass)
    @path ||= File.join("#{klass.file_path}", "some_file")
  end

  def file_path
    File.expand_path("some_other_file")
  end

然后将模块扩展到您所称的位置

我没拿布洛克。。你在哪里找到代码的?好的,谢谢,很有趣!但是我应该更喜欢@newben的回答吗。因为模块
Command
包含在某些类生成器Initializer
具有
初始化(param1,param2)
方法。所以按照你的方法,我得到了一个合法的“错误数量的参数(0代表2)”@用户1611830任何适合你的。。因为我不知道你的内部代码。我只是给了你一些提示,如何前进。