我有一个称为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
键有点奇怪,因为它实际上是在限制这些值而不是允许它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句