根据您的用例,您可以采用其中一种方法来将方法附加到它所作用的对象上。那么你不需要在任何你想使用它的地方都包含standardize_name 方法;您只需将其集中在它适用的对象上:
用作 Article.standardized_name(类方法):
如果您的 standardize_name 方法仅将 ActiveRecord 模型作为参数,请考虑将其放入模块中(例如在 lib/standardizable.rb 中)并将其扩展至 ActiveRecord::Base(或其他作为所有域的父类的类类):
module Standardizable
def standardized_name
# in here, self will be the model *class*,
# so the following will return "Article" if you
# extended the module into the Article class:
self.name
end
end
# include the mixin in all ActiveRecord models:
ActiveRecord::Base.extend Standardizable
或者,如果您不想将其包含在 所有 模型中,只需将该模块包含在您希望 standardized_name 可用的各个类中:
class Article < ActiveRecord::Base
extend Standardizable
end
通过以下两种方法,您将能够像这样使用该方法:
standardized_name = Article.standardized_name
用作 Article.new.standardized_name(实例方法):
如果您希望在模型类的instances 上使用该方法,只需将上面示例中的extend 更改为include:
module Standardizable
def standardized_name
# in here, self will be the model object *instance*,
# so the following will return "Article" if you
# included the module into the Article class:
self.class.name
end
end
# include the mixin in all ActiveRecord models:
ActiveRecord::Base.send(:include, Standardizable)
用法如下:
article = Article.new
standardized_name = article.standardized_name
结束与 ActiveSupport::Concern:
在 Rails 3 中总结这两种方法的一个好方法是使用ActiveSupport::Concern:
module Standardizable
extend ActiveSupport::Concern
module ClassMethods
def standardized_name
self.name
end
end
module InstanceMethods
def standardized_name
self.class.standardized_name
end
end
end
ActiveRecord::Base.extend Standardizable
那么你可以同时使用类和实例方法来获取标准化的名称:
standardized_name_from_class = Article.standardized_name
article = Article.new
standardized_name_from_instance = article.standardized_name