从Rails模型中的类和实例方法调用帮助器

时间:2018-03-23 20:49:41

标签: ruby-on-rails ruby

我需要在类和实例方法中调用模型中的辅助方法,例如: model_instance.methodclass Model < ActiveRecord::Base include ModelHelper def method helper_method(self.data) end def self.method(data) self.helper_method(data) end end 。但是,类方法总是返回&#34; NoMethodError:未定义的方法&#39; helper_method&#39;对于#&lt; Class ...&gt;&#34;

model.rb:

module ModelHelper
  def helper_method(data)
    # logic here
  end
end

model_helper.rb:

def self.helper_method(data)

我甚至尝试在助手中添加class Model < ActiveRecord::Base include ModelHelper def method helper_method(self.data) end # Expose Model.method() class << self include ModelHelper def method(data) helper_method(data) end end end 无济于事。

经过相当多的搜索后,我无法找到任何关于如何实现这一目标的信息,或者至少找不到任何有用的信息。

2 个答案:

答案 0 :(得分:1)

答案结果非常简单,并且不需要任何Rails魔术:你只需重新包含帮助器并在类块中定义类方法:

method

根本不需要更改助手。

现在,您可以在课程和实例上调用./sdell -s 100

答案 1 :(得分:0)

如果method中没有其他逻辑,那么您可以这样做:

class Model < ActiveRecord::Base
  include ModelHelper
  extend  ModelHelper
end

获取实例(@model.helper_method)和类(Model.helper_method)方法。

如果由于遗留(或其他)原因,希望将method用作实例类方法,但method没有做helper_method之外的任何事情,那么你可以这样做:

class Model < ActiveRecord::Base
  include ModelHelper
  extend  ModelHelper

  alias method helper_method
  singleton_class.send(:alias_method, :method, :helper_method)
end

现在你可以@model.methodModel.method

顺便说一句,使用模块在课堂中包含方法是诱人的,但是如果你不小心的话可以迅速离开你,留下你做了很多@model.method(:foo).source_location,试图找出有什么东西来了从。问我怎么知道...

相关问题