【问题标题】:Using methods defined in a module with class methods in Ruby将模块中定义的方法与 Ruby 中的类方法一起使用
【发布时间】:2014-01-24 07:53:02
【问题描述】:

我有一个小问题,我想不通。因为我想重用我的类中定义的许多方法,所以我决定将它们放入一个 Helper 中,我可以在需要时轻松地包含它。基本类如下所示:

class MyClass
  include Helper::MyHelper
  def self.do_something input
    helper_method(input)
  end
end

这里是助手:

  module Helper
    module MyHelper
      def helper_method input
        input.titleize
      end
    end
  end

现在我不能从我的班级中调用“helper_method”,因为我认为这是一个范围问题?我做错了什么?

【问题讨论】:

  • 你应该研究一下 include 和 extend 之间的区别...

标签: ruby-on-rails ruby scope helper


【解决方案1】:

我猜这是因为do_something input 内部的self 指针是InternshipInputFormatter,而不是InternshipInputFormatter 的实例。所以调用helper_method(input) 的正确别名将是self.helper_method(input),但是您将Helper::MyHelper 作为实例方法而不是单例方法包含InternshipInputFormatter 类中,因此请尝试用模块的实例方法扩展类作为类的signelton方法:

class InternshipInputFormatter
   extend Helper::MyHelper
   def self.do_something input
      helper_method(input)
   end
end 

InternshipInputFormatter.do_something 1
# NoMethodError: undefined method `titleize' for 1:Fixnum

如您所见,调用已停止helper_method 内的执行。请参考document,了解includeextend之间的详细区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2011-06-09
    • 2013-09-29
    • 2011-05-12
    • 2016-06-30
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多