mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Implement has_one's and serialize_ids
This commit is contained in:
@@ -1,15 +1,18 @@
|
||||
require 'active_model/serializer/associations'
|
||||
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class << self
|
||||
def inherited(base)
|
||||
base._attributes = {}
|
||||
base._attributes = []
|
||||
base._associations = []
|
||||
end
|
||||
|
||||
def serializer_for(resource)
|
||||
"#{resource.class.name}Serializer".safe_constantize
|
||||
end
|
||||
|
||||
attr_accessor :_root, :_attributes
|
||||
attr_accessor :_root, :_attributes, :_associations
|
||||
|
||||
def root(root)
|
||||
@_root = root
|
||||
@@ -21,7 +24,7 @@ module ActiveModel
|
||||
end
|
||||
|
||||
def attributes(*attrs)
|
||||
@_attributes = attrs.map(&:to_s)
|
||||
@_attributes.concat attrs.map(&:to_s)
|
||||
|
||||
attrs.each do |attr|
|
||||
unless method_defined?(attr)
|
||||
@@ -31,6 +34,22 @@ module ActiveModel
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def has_one(*attrs)
|
||||
options = attrs.extract_options!
|
||||
|
||||
attrs.each do |attr|
|
||||
attr = attr.to_s
|
||||
|
||||
unless method_defined?(attr)
|
||||
define_method attr do
|
||||
object.send attr
|
||||
end
|
||||
end
|
||||
|
||||
@_associations << Association::HasOne.new(attr, options)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(object, options={})
|
||||
@@ -51,9 +70,30 @@ module ActiveModel
|
||||
end
|
||||
end
|
||||
|
||||
def associations
|
||||
self.class._associations.each_with_object({}) do |association, hash|
|
||||
if association.embed_ids?
|
||||
hash[association.key] = serialize_ids association
|
||||
elsif association.embed_objects?
|
||||
# TODO
|
||||
hash
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def serialize_ids(association)
|
||||
associated_data = send(association.name)
|
||||
if associated_data.respond_to?(:to_ary)
|
||||
associated_data.map { |elem| elem.send(association.embed_key) }
|
||||
else
|
||||
associated_data.send(association.embed_key)
|
||||
end
|
||||
end
|
||||
|
||||
def serializable_hash(options={})
|
||||
return nil if object.nil?
|
||||
attributes
|
||||
hash = attributes
|
||||
hash.merge! associations
|
||||
end
|
||||
|
||||
def as_json(options={})
|
||||
|
||||
Reference in New Issue
Block a user