0

举个例子:

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

4

1 回答 1

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

于 2013-01-03T18:17:17.787 回答