举个例子:
module ModelHelper
def self.special_function(some_parameter)
do_some_special_thing
end
end
class Student < ActiveRecord::Base
def to_special
ModelHelper.special_function(a_variable_of_here)
end
end
class Teacher < ActiveRecord::Base
def to_special
ModelHelper.special_function(another_variable_of_here)
end
end
我在哪里放model_helper.rb
?
答案 0 :(得分:2)
我通常在lib中创建一个文件并包含它。类似于lib / special_model.rb:
module SpecialModel
included do
def to_special
do_some_special_thing
end
end
end
然后在app / models / student.rb中:
class Student
include SpecialModel
end
在使用模块时,您可能还想查看ActiveSupport :: Concern以获得一些rails帮助:
http://api.rubyonrails.org/classes/ActiveSupport/Concern.html