【问题标题】:How to create a Rails 4 Concern that takes an argument如何创建带有参数的 Rails 4 关注点
【发布时间】:2015-01-10 02:17:03
【问题描述】:

我有一个名为 User 的 ActiveRecord 类。我正在尝试创建一个名为 Restrictable 的关注点,它接受一些这样的参数:

class User < ActiveRecord::Base
  include Restrictable # Would be nice to not need this line
  restrictable except: [:id, :name, :email]
end

然后我想提供一个名为restricted_data 的实例方法,它可以对这些参数执行一些操作并返回一些数据。示例:

user = User.find(1)
user.restricted_data # Returns all columns except :id, :name, :email

我该怎么做呢?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activesupport-concern


    【解决方案1】:

    如果我正确理解您的问题,这是关于如何编写这样的问题,而不是关于 restricted_data 的实际返回值。我会这样实现关注框架:

    require "active_support/concern"
    
    module Restrictable
      extend ActiveSupport::Concern
    
      module ClassMethods
        attr_reader :restricted
    
        private
    
        def restrictable(except: []) # Alternatively `options = {}`
          @restricted = except       # Alternatively `options[:except] || []`
        end
      end
    
      def restricted_data
        "This is forbidden: #{self.class.restricted}"
      end
    end
    

    那么你可以:

    class C
      include Restrictable
      restrictable except: [:this, :that, :the_other]
    end
    
    c = C.new
    c.restricted_data  #=> "This is forbidden: [:this, :that, :the_other]"
    

    这将符合您设计的界面,但 except 键有点奇怪,因为它实际上是限制这些值而不是允许它们。

    【讨论】:

      【解决方案2】:

      我建议从这篇博文开始:https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns 查看第二个示例。

      将关注点视为您正在混合的模块。不要太复杂。

      module Restrictable
        extend ActiveSupport::Concern
      
        module ClassMethods
          def restricted_data(user)
            # Do your stuff
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        相关资源
        最近更新 更多