mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
64 lines
1.4 KiB
Ruby
64 lines
1.4 KiB
Ruby
module ActiveModel
|
|
class Serializer
|
|
class << self
|
|
def inherited(base)
|
|
base._attributes = {}
|
|
end
|
|
|
|
attr_accessor :_root, :_attributes
|
|
|
|
def root(root)
|
|
@_root = root
|
|
end
|
|
alias root= root
|
|
|
|
def root_name
|
|
name.demodulize.underscore.sub(/_serializer$/, '') if name
|
|
end
|
|
|
|
def attributes(*attrs)
|
|
@_attributes = attrs.map(&:to_s)
|
|
|
|
attrs.each do |attr|
|
|
define_method attr do
|
|
object.read_attribute_for_serialization(attr)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
def initialize(object, options={})
|
|
@object = object
|
|
@scope = options[:scope]
|
|
@root = options[:root] || self.class._root
|
|
@root = self.class.root_name if @root == true
|
|
@meta_key = options[:meta_key] || :meta
|
|
@meta = options[@meta_key]
|
|
end
|
|
attr_accessor :object, :scope, :root, :meta_key, :meta
|
|
|
|
alias read_attribute_for_serialization send
|
|
|
|
def attributes
|
|
self.class._attributes.each_with_object({}) do |name, hash|
|
|
hash[name] = send(name)
|
|
end
|
|
end
|
|
|
|
def serializable_hash(options={})
|
|
return nil if object.nil?
|
|
attributes
|
|
end
|
|
|
|
def as_json(options={})
|
|
if root = options[:root] || self.root
|
|
hash = { root.to_s => serializable_hash }
|
|
hash[meta_key.to_s] = meta if meta
|
|
hash
|
|
else
|
|
serializable_hash
|
|
end
|
|
end
|
|
end
|
|
end
|