diff options
author | Jose and Yehuda <wycats@gmail.com> | 2011-10-15 16:20:45 +0200 |
---|---|---|
committer | Jose and Yehuda <wycats@gmail.com> | 2011-10-15 18:40:37 +0200 |
commit | 2a4aaae72af037715db81fda332190df62f3ec44 (patch) | |
tree | a3d3d34eb59176c2b19385adc9dc2ea5bc709069 /activemodel/lib/active_model/serializer.rb | |
parent | 598fc578fbd38907288e14053bfc6eb8d4da1e3b (diff) | |
download | rails-2a4aaae72af037715db81fda332190df62f3ec44.tar.gz rails-2a4aaae72af037715db81fda332190df62f3ec44.tar.bz2 rails-2a4aaae72af037715db81fda332190df62f3ec44.zip |
Added has_one and has_many
Diffstat (limited to 'activemodel/lib/active_model/serializer.rb')
-rw-r--r-- | activemodel/lib/active_model/serializer.rb | 56 |
1 files changed, 47 insertions, 9 deletions
diff --git a/activemodel/lib/active_model/serializer.rb b/activemodel/lib/active_model/serializer.rb index a2035ae2cb..dc5e2aadb3 100644 --- a/activemodel/lib/active_model/serializer.rb +++ b/activemodel/lib/active_model/serializer.rb @@ -7,20 +7,41 @@ module ActiveModel class_attribute :_attributes self._attributes = Set.new - def self.attributes(*attrs) - self._attributes += attrs - end + class_attribute :_associations + self._associations = {} - attr_reader :object, :scope + class << self + def attributes(*attrs) + self._attributes += attrs + end + + def has_many(*attrs) + options = attrs.extract_options! + options[:has_many] = true + hash = {} + attrs.each { |attr| hash[attr] = options } + self._associations = _associations.merge(hash) + end + + def has_one(*attrs) + options = attrs.extract_options! + options[:has_one] = true + hash = {} + attrs.each { |attr| hash[attr] = options } + self._associations = _associations.merge(hash) + end - def self.inherited(klass) - name = klass.name.demodulize.underscore.sub(/_serializer$/, '') + def inherited(klass) + name = klass.name.demodulize.underscore.sub(/_serializer$/, '') - klass.class_eval do - alias_method name.to_sym, :object + klass.class_eval do + alias_method name.to_sym, :object + end end end + attr_reader :object, :scope + def initialize(object, scope) @object, @scope = object, scope end @@ -30,7 +51,24 @@ module ActiveModel end def serializable_hash - attributes + hash = attributes + + _associations.each do |association, options| + associated_object = object.send(association) + serializer = options[:serializer] + + if options[:has_many] + serialized_array = associated_object.map do |item| + serializer.new(item, scope).serializable_hash + end + + hash[association] = serialized_array + elsif options[:has_one] + hash[association] = serializer.new(associated_object, scope).serializable_hash + end + end + + hash end def attributes |