18

我有一个名为 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

我该怎么做呢?

4

2 回答 2

26

如果我正确理解你的问题,这是关于如何写这样一个问题,而不是关于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]"

That would comply with the interface you designed, but the except key is a bit strange because it's actually restricting those values instead of allowing them.

于 2014-11-13T04:01:16.897 回答
1

我建议从这篇博文开始: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
于 2014-11-13T03:37:52.140 回答