如何创建Rails 4引起争论的关注点

jes*_*sal 11 ruby ruby-on-rails ruby-on-rails-4 activesupport-concern

我有一个名为User的ActiveRecord类.我正在尝试创建一个关注点Restrictable,其中包含一些这样的参数:

class User < ActiveRecord::Base
  include Restrictable # Would be nice to not need this line
  restrictable except: [:id, :name, :email]
end
Run Code Online (Sandbox Code Playgroud)

我想提供一个实例方法restricted_data,该方法可以对这些参数执行某些操作并返回一些数据.例:

user = User.find(1)
user.restricted_data # Returns all columns except :id, :name, :email
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Gab*_*ira 18

如果我正确理解你的问题,那就是如何写出这样一个问题,而不是关于实际的回报价值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
Run Code Online (Sandbox Code Playgroud)

然后你可以:

class C
  include Restrictable
  restrictable except: [:this, :that, :the_other]
end

c = C.new
c.restricted_data  #=> "This is forbidden: [:this, :that, :the_other]"
Run Code Online (Sandbox Code Playgroud)

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