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

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

我该怎么做呢?

如果我正确地理解了你的问题,那就是关于如何编写这样一个问题,而不是关于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键有点奇怪,因为它实际上限制了这些值而不是允许它们。

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

将问题视为您正在混合的模块。不要太复杂。

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