如何在 Rails 4 中使用关注点 [英] How to use concerns in Rails 4

查看:40
本文介绍了如何在 Rails 4 中使用关注点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认的 Rails 4 项目生成器现在在控制器和模型下创建目录关注".我找到了一些关于如何使用路由问题的解释,但没有找到关于控制器或模型的解释.

The default Rails 4 project generator now creates the directory "concerns" under controllers and models. I have found some explanations about how to use routing concerns, but nothing about controllers or models.

我很确定这与社区当前的DCI 趋势"有关,并想尝试一下.

I am pretty sure it has to do with the current "DCI trend" in the community and would like to give it a try.

问题是,我应该如何使用此功能,是否有关于如何定义命名/类层次结构以使其工作的约定?如何在模型或控制器中包含关注点?

The question is, how am I supposed to use this feature, is there a convention on how to define the naming / class hierarchy in order to make it work? How can I include a concern in a model or controller?

推荐答案

所以我自己发现了.它实际上是一个非常简单但功能强大的概念.它与代码重用有关,如下例所示.基本上,这个想法是提取常见的和/或上下文特定的代码块,以清理模型并避免它们变得过于庞大和混乱.

So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.

举个例子,我会放一个众所周知的模式,可标记模式:

As an example, I'll put one well known pattern, the taggable pattern:

# 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 添加到您想要的任何类并共享其功能.

So following the Product sample, you can add Taggable to any class you desire and share its functionality.

很好地解释了这一点卫生署:

在 Rails 4 中,我们将邀请程序员使用关注默认 app/models/concerns 和 app/controllers/concerns 目录自动成为加载路径的一部分.与ActiveSupport::Concern 包装器,它的支持足以使这个轻量级保理机制大放异彩.

In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.

这篇关于如何在 Rails 4 中使用关注点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆