默认的 Rails 4 项目生成器现在会在控制器和模型下创建目录“concerns”。我找到了一些有关如何使用路由问题的解释,但没有找到有关控制器或模型的解释。
我很确定这与社区当前的“DCI 趋势”有关,并且愿意尝试一下。
问题是,我应该如何使用这个功能,是否有关于如何定义命名/类层次结构以使其工作的约定?如何在模型或控制器中包含问题?
所以我自己发现了。这实际上是一个非常简单但功能强大的概念。它与代码重用有关,如下例所示。基本上,这个想法是提取常见和/或上下文特定的代码块,以清理模型并避免它们变得过于臃肿和混乱。
作为一个例子,我将放置一个众所周知的模式,可标记模式:
# app/models/product.rb
class Product
include Taggable
...
end
# app/models/concerns/taggable.rb
# notice that the file name has to match the module name
# (applying Rails conventions for autoloading)
module Taggable
extend ActiveSupport::Concern
included do
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
class_attribute :tag_limit
end
def tags_string
tags.map(&:name).join(', ')
end
def tags_string=(tag_string)
tag_names = tag_string.to_s.split(', ')
tag_names.each do |tag_name|
tags.build(name: tag_name)
end
end
# methods defined here are going to extend the class, not the instance of it
module ClassMethods
def tag_limit(value)
self.tag_limit_value = value
end
end
end
因此,按照 Product 示例,您可以将 Taggable 添加到您想要的任何类并共享其功能。
这很好地解释了DHH http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns:
在 Rails 4 中,我们将邀请程序员使用关注点
默认 app/models/concerns 和 app/controllers/concerns 目录
它们自动成为加载路径的一部分。与
ActiveSupport::Concern 包装器,它足以支持此操作
轻量级保理机制大放异彩。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)