[英]Extending ActiveModel::Serializer with custom attributes method
I am trying to create my own attributes
method called secure_attributes
where I pass it an array of attributes and the minimum level the authorized user needs to be to view those attributes.我正在尝试创建我自己的名为
secure_attributes
的attributes
方法,我向它传递一组属性以及授权用户查看这些属性所需的最低级别。 I pass the current level of the authorized user as an instance_option.我将授权用户的当前级别作为 instance_option 传递。 I'd like to extend the Serializer class so I can use this method in multiple serializers, but Im having issues.
我想扩展 Serializer 类,以便我可以在多个序列化器中使用此方法,但我遇到了问题。
This is what i have so far:这是我到目前为止:
in config/initializers/secure_attributes.rb
在
config/initializers/secure_attributes.rb
module ActiveModel
class Serializer
def self.secure_attributes(attributes={}, minimum_level)
attributes.delete_if {|attr| attr == :attribute_name } unless has_access?(minimum_level)
attributes.each_with_object({}) do |name, hash|
unless self.class._fragmented
hash[name] = send(name)
else
hash[name] = self.class._fragmented.public_send(name)
end
end
end
end
end
and then in the individual serializer I have things like this:然后在单个序列化程序中,我有这样的事情:
secure_attributes([:id, :name, :password_hint], :guest)
and then进而
def has_access?(minimum_level=nil)
return false unless minimum_level
return true # based on a bunch of logic...
end
But obviously secure_attributes cannot see the has_access?
但是很明显secure_attributes看不到
has_access?
method and if I put has_access
inside the Serializer class, it cannot access the instance_options.方法,如果我将
has_access
放在 Serializer 类中,它就无法访问 instance_options。
Any idea how I can accomplish what I need?知道我如何完成我需要的吗?
Maybe you want to do following - but I still do not get your real purpose, since you never did anything with the attributes but calling them:也许你想做以下 - 但我仍然没有明白你的真正目的,因为你从来没有对属性做过任何事情,而是调用它们:
module ActiveRecord
class JoshsSerializer < Serializer
class << self
def secure_attributes(attributes={}, minimum_level)
@secure_attributes = attributes
@minimum_level = minimum_level
end
attr_reader :minimum_level, :secure_attributes
end
def initialize(attr, options)
super attr, options
secure_attributes = self.class.secure_attributes.dup
secure_attributes.delete :attribute_name unless has_access?(self.class.minimum_level)
secure_attributes.each_with_object({}) do |name, hash|
if self.class._fragmented
hash[name] = self.class._fragmented.public_send(name)
else
hash[name] = send(name)
end
end
def has_access?(minimum_level=nil)
return false unless minimum_level
return true # based on a bunch of logic...
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.