简体   繁体   English

在红宝石中使用包含的方法

[英]using included method in ruby

Suppose I have this 假设我有这个

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
...

When the module is included, I get undefined local variable or method file_path . 当包含该模块时,我得到undefined local variable or method file_path So is there a way, to make the file_path method be recognized when the module is included ? 那么有什么方法可以在包含模块时识别file_path方法吗? (of course without putting file_path in the included method) (当然没有在included方法中放置file_path

You are calling the method file_path ,in the method included , do..end block. 您正在调用方法file_path ,在included的方法中,执行do..end块。 That means with scope is set as Command class. 这意味着将scope设置为Command类。 But file_path is the instance_method,so Command.file_path is throwing an legitimate error. file_path是instance_method,因此Command.file_path会抛出一个合法的错误。 You have to call the method file_path ,on the instance of the class which is including the Command module. 您必须在包含Command模块的类的实例上调用方法file_path One example to illustrate this - 一个例子来说明这一点 -

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)

The error is coming because inside the method included self is A . 错误即将到来,因为included self的方法内部是A A has no class method named as foo ,so the error comes out. A没有名为foo类方法,因此出现错误。 Now to fix it we should call it as below: 现在要解决它,我们应该如下调用它:

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

class B
    include A
end

# >> 2

You can try this : 你可以试试这个:

module Command extend ActiveSupport::Concern module命令扩展ActiveSupport :: Concern

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

  def file_path
    File.expand_path("some_other_file")
  end

and then extend your module where you call it ! 然后将模块扩展到您调用它的位置!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM