Demonstrates that there was unreleased code in 0-8 that does not exist on 0-8-stable919bb38401/CHANGELOG.mdspecifically:731528e1f6...919bb38401``` git branch --contains919bb384010-9-stable fractaloop-merge-multiple-nested-associations ``` https://gist.github.com/bf4/c8eb0475a39700794b36 ```patch From64ed05c484Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 7 May 2013 17:51:56 -0700 Subject: [PATCH 01/66] Define serializer as DefaultSerializer if not set --- lib/active_model/array_serializer.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index 518323c..30e7f29 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -81,9 +81,11 @@ def _serializable_array serializer = @options[:each_serializer] elsif item.respond_to?(:active_model_serializer) serializer = item.active_model_serializer + else + serializer = DefaultSerializer end - serializable = serializer ? serializer.new(item, @options) : DefaultSerializer.new(item, @options) + serializable = serializer.new(item, @options) if serializable.respond_to?(:serializable_hash) serializable.serializable_hash From0e876624ecMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 8 May 2013 12:57:07 -0700 Subject: [PATCH 02/66] Move reusable code to a module --- lib/active_model/array_serializer.rb | 34 +++++----------------------------- lib/active_model/serializable.rb | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 29 deletions(-) create mode 100644 lib/active_model/serializable.rb diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index 30e7f29..7442390 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -1,3 +1,4 @@ +require 'active_model/serializable' require "active_support/core_ext/class/attribute" require 'active_support/dependencies' require 'active_support/descendants_tracker' @@ -15,6 +16,8 @@ module ActiveModel class ArraySerializer extend ActiveSupport::DescendantsTracker + include ActiveModel::Serializable + attr_reader :object, :options class_attribute :root @@ -33,35 +36,8 @@ def initialize(object, options={}) @object, @options = object, options end - def meta_key - @options[:meta_key].try(:to_sym) || :meta - end - - def include_meta(hash) - hash[meta_key] = @options[:meta] if @options.has_key?(:meta) - end - - def as_json(*args) - @options[:hash] = hash = {} - @options[:unique_values] = {} - - if root = @options[:root] - hash.merge!(root => serializable_array) - include_meta hash - hash - else - serializable_array - end - end - - def to_json(*args) - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do - super - end - else - super - end + def serialize + serializable_array end def serializable_array diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb new file mode 100644 index 0000000..d288df4 --- /dev/null +++ b/lib/active_model/serializable.rb @@ -0,0 +1,34 @@ +module ActiveModel + module Serializable + def meta_key + options[:meta_key].try(:to_sym) || :meta + end + + def include_meta(hash) + hash[meta_key] = options[:meta] if options.has_key?(:meta) + end + + def as_json(*args) + options[:hash] = hash = {} + options[:unique_values] = {} + + if root = options[:root] + hash.merge!(root => serialize) + include_meta hash + hash + else + serialize + end + end + + def to_json(*args) + if perform_caching? + cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do + super + end + else + super + end + end + end +end From76fead041fMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 8 May 2013 13:02:03 -0700 Subject: [PATCH 03/66] Make Serializer reuse Serializable --- lib/active_model/serializable.rb | 8 ++++---- lib/active_model/serializer.rb | 38 +++++++++----------------------------- 2 files changed, 13 insertions(+), 33 deletions(-) diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb index d288df4..07f53ff 100644 --- a/lib/active_model/serializable.rb +++ b/lib/active_model/serializable.rb @@ -8,11 +8,11 @@ def include_meta(hash) hash[meta_key] = options[:meta] if options.has_key?(:meta) end - def as_json(*args) - options[:hash] = hash = {} - options[:unique_values] = {} + def as_json(args={}) + if root = args[:root] || options[:root] + options[:hash] = hash = {} + options[:unique_values] = {} - if root = options[:root] hash.merge!(root => serialize) include_meta hash hash diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 281af42..a085775 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -1,3 +1,4 @@ +require 'active_model/serializable' require "active_support/core_ext/class/attribute" require "active_support/core_ext/module/anonymous" require 'active_support/dependencies' @@ -40,6 +41,8 @@ module ActiveModel class Serializer extend ActiveSupport::DescendantsTracker + include ActiveModel::Serializable + INCLUDE_METHODS = {} INSTRUMENT = { :serialize => :"serialize.serializer", :associations => :"associations.serializer" } @@ -316,37 +319,14 @@ def url_options @options[:url_options] || {} end - def meta_key - @options[:meta_key].try(:to_sym) || :meta - end - - def include_meta(hash) - hash[meta_key] = @options[:meta] if @options.has_key?(:meta) - end - - def to_json(*args) - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do - super - end - else - super - end - end - # Returns a json representation of the serializable # object including the root. - def as_json(options={}) - if root = options.fetch(:root, @options.fetch(:root, root_name)) - @options[:hash] = hash = {} - @options[:unique_values] = {} - - hash.merge!(root => serializable_hash) - include_meta hash - hash - else - serializable_hash - end + def as_json(args={}) + super(root: args.fetch(:root, options.fetch(:root, root_name))) + end + + def serialize + serializable_hash end # Returns a hash representation of the serializable Fromaaa08c25efMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 8 May 2013 17:49:30 -0700 Subject: [PATCH 04/66] Make include_meta and meta_key private --- lib/active_model/serializable.rb | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb index 07f53ff..4730053 100644 --- a/lib/active_model/serializable.rb +++ b/lib/active_model/serializable.rb @@ -1,13 +1,5 @@ module ActiveModel module Serializable - def meta_key - options[:meta_key].try(:to_sym) || :meta - end - - def include_meta(hash) - hash[meta_key] = options[:meta] if options.has_key?(:meta) - end - def as_json(args={}) if root = args[:root] || options[:root] options[:hash] = hash = {} @@ -30,5 +22,15 @@ def to_json(*args) super end end + + private + + def include_meta(hash) + hash[meta_key] = options[:meta] if options.has_key?(:meta) + end + + def meta_key + options[:meta_key].try(:to_sym) || :meta + end end end Fromf179a27ed7Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 15:53:39 -0700 Subject: [PATCH 05/66] Add docs to serializable --- lib/active_model/serializable.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb index 4730053..cf1cbaa 100644 --- a/lib/active_model/serializable.rb +++ b/lib/active_model/serializable.rb @@ -1,4 +1,27 @@ +require 'active_support/core_ext/object/to_json' + module ActiveModel + # Enable classes to Classes including this module to serialize themselves by implementing a serialize method and an options method. + # + # Example: + # + # require 'active_model_serializers' + # + # class MySerializer + # include ActiveModel::Serializable + # + # def initialize + # @options = {} + # end + # + # attr_reader :options + # + # def serialize + # { a: 1 } + # end + # end + # + # puts MySerializer.new.to_json module Serializable def as_json(args={}) if root = args[:root] || options[:root] From1a8709d71cMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 8 May 2013 15:08:58 -0700 Subject: [PATCH 06/66] Move caching to a new module --- lib/active_model/array_serializer.rb | 23 +++------------------ lib/active_model/serializable.rb | 10 --------- lib/active_model/serializer.rb | 31 +++++++--------------------- lib/active_model/serializer/caching.rb | 37 ++++++++++++++++++++++++++++++++++ test/caching_test.rb | 4 ++-- 5 files changed, 49 insertions(+), 56 deletions(-) create mode 100644 lib/active_model/serializer/caching.rb diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index 7442390..5f0df67 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -1,4 +1,5 @@ require 'active_model/serializable' +require 'active_model/serializer/caching' require "active_support/core_ext/class/attribute" require 'active_support/dependencies' require 'active_support/descendants_tracker' @@ -17,6 +18,7 @@ class ArraySerializer extend ActiveSupport::DescendantsTracker include ActiveModel::Serializable + include ActiveModel::Serializer::Caching attr_reader :object, :options @@ -36,22 +38,11 @@ def initialize(object, options={}) @object, @options = object, options end - def serialize + def serialize_object serializable_array end def serializable_array - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'serializable-array']) do - _serializable_array - end - else - _serializable_array - end - end - - private - def _serializable_array @object.map do |item| if @options.has_key? :each_serializer serializer = @options[:each_serializer] @@ -70,13 +61,5 @@ def _serializable_array end end end - - def expand_cache_key(*args) - ActiveSupport::Cache.expand_cache_key(args) - end - - def perform_caching? - perform_caching && cache && respond_to?(:cache_key) - end end end diff --git a/lib/active_model/serializable.rb b/lib/active_model/serializable.rb index cf1cbaa..7122ae2 100644 --- a/lib/active_model/serializable.rb +++ b/lib/active_model/serializable.rb @@ -36,16 +36,6 @@ def as_json(args={}) end end - def to_json(*args) - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do - super - end - else - super - end - end - private def include_meta(hash) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index a085775..2dc8d84 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -1,4 +1,5 @@ require 'active_model/serializable' +require 'active_model/serializer/caching' require "active_support/core_ext/class/attribute" require "active_support/core_ext/module/anonymous" require 'active_support/dependencies' @@ -42,6 +43,7 @@ class Serializer extend ActiveSupport::DescendantsTracker include ActiveModel::Serializable + include ActiveModel::Serializer::Caching INCLUDE_METHODS = {} INSTRUMENT = { :serialize => :"serialize.serializer", :associations => :"associations.serializer" } @@ -73,7 +75,6 @@ def to_s class_attribute :perform_caching class << self - # set perform caching like root def cached(value = true) self.perform_caching = value end @@ -325,20 +326,17 @@ def as_json(args={}) super(root: args.fetch(:root, options.fetch(:root, root_name))) end - def serialize + def serialize_object serializable_hash end # Returns a hash representation of the serializable # object without the root. def serializable_hash - if perform_caching? - cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'serializable-hash']) do - _serializable_hash - end - else - _serializable_hash - end + return nil if @object.nil? + @node = attributes + include_associations! if _embed + @node end def include_associations! @@ -453,21 +451,6 @@ def scope alias :read_attribute_for_serialization :send - def _serializable_hash - return nil if @object.nil? - @node = attributes - include_associations! if _embed - @node - end - - def perform_caching? - perform_caching && cache && respond_to?(:cache_key) - end - - def expand_cache_key(*args) - ActiveSupport::Cache.expand_cache_key(args) - end - # Use ActiveSupport::Notifications to send events to external systems. # The event name is: name.class_name.serializer def instrument(name, payload = {}, &block) diff --git a/lib/active_model/serializer/caching.rb b/lib/active_model/serializer/caching.rb new file mode 100644 index 0000000..50fcf7b --- /dev/null +++ b/lib/active_model/serializer/caching.rb @@ -0,0 +1,37 @@ +module ActiveModel + class Serializer + module Caching + def to_json(*args) + if caching_enabled? + key = expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) + cache.fetch key do + super + end + else + super + end + end + + def serialize(*args) + if caching_enabled? + key = expand_cache_key([self.class.to_s.underscore, cache_key, 'serialize']) + cache.fetch key do + serialize_object + end + else + serialize_object + end + end + + private + + def caching_enabled? + perform_caching && cache && respond_to?(:cache_key) + end + + def expand_cache_key(*args) + ActiveSupport::Cache.expand_cache_key(args) + end + end + end +end diff --git a/test/caching_test.rb b/test/caching_test.rb index 869f0f9..ee1dd26 100644 --- a/test/caching_test.rb +++ b/test/caching_test.rb @@ -68,7 +68,7 @@ def cache_key instance.to_json - assert_equal(instance.serializable_hash, serializer.cache.read('serializer/Adam/serializable-hash')) + assert_equal(instance.serializable_hash, serializer.cache.read('serializer/Adam/serialize')) assert_equal(instance.to_json, serializer.cache.read('serializer/Adam/to-json')) end @@ -90,7 +90,7 @@ def cache_key instance.to_json - assert_equal instance.serializable_array, serializer.cache.read('array_serializer/cache-key/serializable-array') + assert_equal instance.serializable_array, serializer.cache.read('array_serializer/cache-key/serialize') assert_equal instance.to_json, serializer.cache.read('array_serializer/cache-key/to-json') end end From460a250984Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Mon, 13 May 2013 11:50:54 -0700 Subject: [PATCH 07/66] Get rid of refine --- lib/active_model/serializer.rb | 10 ++++++---- lib/active_model/serializer/associations.rb | 30 ----------------------------- 2 files changed, 6 insertions(+), 34 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 2dc8d84..855e020 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -129,7 +129,7 @@ def associate(klass, attrs) #:nodoc: define_include_method attr - self._associations[attr] = klass.refine(attr, options) + self._associations[attr] = [klass, options] end end @@ -217,8 +217,8 @@ def schema end associations = {} - _associations.each do |attr, association_class| - association = association_class.new(attr, self) + _associations.each do |attr, (association_class, options)| + association = association_class.new(attr, self, options) if model_association = klass.reflect_on_association(association.name) # Real association. @@ -381,8 +381,10 @@ def include!(name, options={}) end end + klass, opts = _associations[name] association_class = - if klass = _associations[name] + if klass + options = opts.merge options klass elsif value.respond_to?(:to_ary) Associations::HasMany diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 8606b93..35c0dc0 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -2,34 +2,6 @@ module ActiveModel class Serializer module Associations #:nodoc: class Config #:nodoc: - class_attribute :options - - def self.refine(name, class_options) - current_class = self - - Class.new(self) do - singleton_class.class_eval do - define_method(:to_s) do - "(subclass of #{current_class.name})" - end - - alias inspect to_s - end - - self.options = class_options - - # cache the root so we can reuse it without falling back on a per-instance basis - begin - self.options[:root] ||= self.new(name, nil).root - rescue - # this could fail if it needs a valid source, for example a polymorphic association - end - - end - end - - self.options = {} - def initialize(name, source, options={}) @name = name @source = source @@ -39,8 +11,6 @@ def initialize(name, source, options={}) def option(key, default=nil) if @options.key?(key) @options[key] - elsif self.class.options.key?(key) - self.class.options[key] else default end From5017fb686aMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Mon, 13 May 2013 16:00:16 -0700 Subject: [PATCH 08/66] Associations doesn't depend on source serializer anymore --- lib/active_model/serializer.rb | 4 ++++ lib/active_model/serializer/associations.rb | 12 ++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 855e020..1e9787b 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -392,6 +392,10 @@ def include!(name, options={}) Associations::HasOne end + options[:value] ||= send(name) + options[:embed] = _embed unless options.key?(:embed) + options[:include] = _root_embed unless options.key?(:include) + options[:serializer_options] = self.options association = association_class.new(name, self, options) if association.embed_ids? diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 35c0dc0..ae88024 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -38,19 +38,19 @@ def name end def associated_object - option(:value) || source_serializer.send(name) + option(:value) end def embed_ids? - [:id, :ids].include? option(:embed, source_serializer._embed) + [:id, :ids].include? option(:embed) end def embed_objects? - [:object, :objects].include? option(:embed, source_serializer._embed) + [:object, :objects].include? option(:embed) end def embed_in_root? - option(:include, source_serializer._root_embed) + option(:include) end def embeddable? @@ -61,9 +61,9 @@ def embeddable? def find_serializable(object) if target_serializer - target_serializer.new(object, source_serializer.options) + target_serializer.new(object, option(:serializer_options)) elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) - ams.new(object, source_serializer.options) + ams.new(object, option(:serializer_options)) else object end Fromea3566955cMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 16:30:41 -0700 Subject: [PATCH 09/66] Remove option method just use the reader --- lib/active_model/serializer/associations.rb | 46 +++++++++++++---------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index ae88024..3165258 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -8,16 +8,8 @@ def initialize(name, source, options={}) @options = options end - def option(key, default=nil) - if @options.key?(key) - @options[key] - else - default - end - end - def target_serializer - serializer = option(:serializer) + serializer = options[:serializer] serializer.is_a?(String) ? serializer.constantize : serializer end @@ -26,31 +18,31 @@ def source_serializer end def key - option(:key) || @name + options[:key] || @name end def root - option(:root) || @name + options[:root] || @name end def name - option(:name) || @name + options[:name] || @name end def associated_object - option(:value) + options[:value] end def embed_ids? - [:id, :ids].include? option(:embed) + [:id, :ids].include? options[:embed] end def embed_objects? - [:object, :objects].include? option(:embed) + [:object, :objects].include? options[:embed] end def embed_in_root? - option(:include) + options[:include] end def embeddable? @@ -61,18 +53,20 @@ def embeddable? def find_serializable(object) if target_serializer - target_serializer.new(object, option(:serializer_options)) + target_serializer.new(object, options[:serializer_options]) elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) - ams.new(object, option(:serializer_options)) + ams.new(object, options[:serializer_options]) else object end end + + attr_reader :options end class HasMany < Config #:nodoc: def key - if key = option(:key) + if key = options[:key] key elsif embed_ids? "#{@name.to_s.singularize}_ids".to_sym @@ -82,7 +76,7 @@ def key end def embed_key - if key = option(:embed_key) + if key = options[:embed_key] key else :id @@ -103,7 +97,7 @@ def serializables def serialize_ids ids_key = "#{@name.to_s.singularize}_ids".to_sym - if !option(:embed_key) && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(ids_key) + if !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(ids_key) source_serializer.object.read_attribute_for_serialization(ids_key) else associated_object.map do |item| @@ -123,11 +117,11 @@ def embeddable? end def polymorphic? - option :polymorphic + options[:polymorphic] end def root - if root = option(:root) + if root = options[:root] root elsif polymorphic? associated_object.class.to_s.pluralize.demodulize.underscore.to_sym @@ -137,7 +131,7 @@ def root end def key - if key = option(:key) + if key = options[:key] key elsif embed_ids? && !polymorphic? "#{@name}_id".to_sym @@ -147,7 +141,7 @@ def key end def embed_key - if key = option(:embed_key) + if key = options[:embed_key] key else :id @@ -189,7 +183,7 @@ def serialize_ids else nil end - elsif !option(:embed_key) && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(id_key) + elsif !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(id_key) source_serializer.object.read_attribute_for_serialization(id_key) elsif associated_object associated_object.read_attribute_for_serialization(embed_key) Froma41de0286fMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Mon, 13 May 2013 17:37:36 -0700 Subject: [PATCH 10/66] Passing options[:hash] is not public API of include! --- lib/active_model/serializer.rb | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 1e9787b..c1cd499 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -352,23 +352,8 @@ def include?(name) end def include!(name, options={}) - # Make sure that if a special options[:hash] was passed in, we generate - # a new unique values hash and don't clobber the original. If the hash - # passed in is the same as the current options hash, use the current - # unique values. - # - # TODO: Should passing in a Hash even be public API here? - unique_values = - if hash = options[:hash] - if @options[:hash] == hash - @options[:unique_values] ||= {} - else - {} - end - else - hash = @options[:hash] - @options[:unique_values] ||= {} - end + hash = @options[:hash] + unique_values = @options[:unique_values] ||= {} node = options[:node] ||= @node value = options[:value] From9f5e872621Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 15:50:40 -0700 Subject: [PATCH 11/66] Extract id_key to a method --- lib/active_model/serializer/associations.rb | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 3165258..6b4460e 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -69,7 +69,7 @@ def key if key = options[:key] key elsif embed_ids? - "#{@name.to_s.singularize}_ids".to_sym + id_key else @name end @@ -83,6 +83,10 @@ def embed_key end end + def id_key + "#{@name.to_s.singularize}_ids".to_sym + end + def serialize associated_object.map do |item| find_serializable(item).serializable_hash @@ -96,9 +100,8 @@ def serializables end def serialize_ids - ids_key = "#{@name.to_s.singularize}_ids".to_sym - if !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(ids_key) - source_serializer.object.read_attribute_for_serialization(ids_key) + if !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(id_key) + source_serializer.object.read_attribute_for_serialization(id_key) else associated_object.map do |item| item.read_attribute_for_serialization(embed_key) @@ -134,7 +137,7 @@ def key if key = options[:key] key elsif embed_ids? && !polymorphic? - "#{@name}_id".to_sym + id_key else @name end @@ -148,6 +151,10 @@ def embed_key end end + def id_key + "#{@name}_id".to_sym + end + def polymorphic_key associated_object.class.to_s.demodulize.underscore.to_sym end @@ -172,8 +179,6 @@ def serializables end def serialize_ids - id_key = "#{@name}_id".to_sym - if polymorphic? if associated_object { From0917148617Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 16:20:51 -0700 Subject: [PATCH 12/66] serialize_ids doesn't use source serializer and it's object --- lib/active_model/serializer.rb | 7 ++++++- lib/active_model/serializer/associations.rb | 23 +++++++---------------- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index c1cd499..8aa8b71 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -384,7 +384,12 @@ def include!(name, options={}) association = association_class.new(name, self, options) if association.embed_ids? - node[association.key] = association.serialize_ids + node[association.key] = + if options[:embed_key] || self.respond_to?(name) || !self.object.respond_to?(association.id_key) + association.serialize_ids + else + self.object.read_attribute_for_serialization(association.id_key) + end if association.embed_in_root? && hash.nil? raise IncludeError.new(self.class, association.name) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 6b4460e..667774f 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -100,12 +100,8 @@ def serializables end def serialize_ids - if !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(id_key) - source_serializer.object.read_attribute_for_serialization(id_key) - else - associated_object.map do |item| - item.read_attribute_for_serialization(embed_key) - end + associated_object.map do |item| + item.read_attribute_for_serialization(embed_key) end end end @@ -179,21 +175,16 @@ def serializables end def serialize_ids - if polymorphic? - if associated_object + if associated_object + id = associated_object.read_attribute_for_serialization(embed_key) + if polymorphic? { :type => polymorphic_key, - :id => associated_object.read_attribute_for_serialization(embed_key) + :id => id } else - nil + id end - elsif !options[:embed_key] && !source_serializer.respond_to?(@name.to_s) && source_serializer.object.respond_to?(id_key) - source_serializer.object.read_attribute_for_serialization(id_key) - elsif associated_object - associated_object.read_attribute_for_serialization(embed_key) - else - nil end end end Frombaa690a01aMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 16:24:03 -0700 Subject: [PATCH 13/66] Move if object to the top --- lib/active_model/serializer/associations.rb | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 667774f..2ee98f6 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -158,13 +158,15 @@ def polymorphic_key def serialize object = associated_object - if object && polymorphic? - { - :type => polymorphic_key, - polymorphic_key => find_serializable(object).serializable_hash - } - elsif object - find_serializable(object).serializable_hash + if object + if polymorphic? + { + :type => polymorphic_key, + polymorphic_key => find_serializable(object).serializable_hash + } + else + find_serializable(object).serializable_hash + end end end Fromc1e710aae1Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 16:24:59 -0700 Subject: [PATCH 14/66] Save result of calling associated_object in a local var --- lib/active_model/serializer/associations.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 2ee98f6..30ca5f4 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -177,8 +177,10 @@ def serializables end def serialize_ids - if associated_object - id = associated_object.read_attribute_for_serialization(embed_key) + object = associated_object + + if object + id = object.read_attribute_for_serialization(embed_key) if polymorphic? { :type => polymorphic_key, Fromc04d452823Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 16:31:33 -0700 Subject: [PATCH 15/66] Associations doesn't depend on the source serializer anymore :) --- lib/active_model/serializer.rb | 4 ++-- lib/active_model/serializer/associations.rb | 7 +------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 8aa8b71..b9a892b 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -218,7 +218,7 @@ def schema associations = {} _associations.each do |attr, (association_class, options)| - association = association_class.new(attr, self, options) + association = association_class.new(attr, options) if model_association = klass.reflect_on_association(association.name) # Real association. @@ -381,7 +381,7 @@ def include!(name, options={}) options[:embed] = _embed unless options.key?(:embed) options[:include] = _root_embed unless options.key?(:include) options[:serializer_options] = self.options - association = association_class.new(name, self, options) + association = association_class.new(name, options) if association.embed_ids? node[association.key] = diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 30ca5f4..140c056 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -2,9 +2,8 @@ module ActiveModel class Serializer module Associations #:nodoc: class Config #:nodoc: - def initialize(name, source, options={}) + def initialize(name, options={}) @name = name - @source = source @options = options end @@ -13,10 +12,6 @@ def target_serializer serializer.is_a?(String) ? serializer.constantize : serializer end - def source_serializer - @source - end - def key options[:key] || @name end Frome273a2fb37Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 17:03:59 -0700 Subject: [PATCH 16/66] Use a third argument to pass serializer_options --- lib/active_model/serializer.rb | 3 +-- lib/active_model/serializer/associations.rb | 9 +++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index b9a892b..02a25c5 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -380,8 +380,7 @@ def include!(name, options={}) options[:value] ||= send(name) options[:embed] = _embed unless options.key?(:embed) options[:include] = _root_embed unless options.key?(:include) - options[:serializer_options] = self.options - association = association_class.new(name, options) + association = association_class.new(name, options, self.options) if association.embed_ids? node[association.key] = diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 140c056..c651417 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -2,9 +2,10 @@ module ActiveModel class Serializer module Associations #:nodoc: class Config #:nodoc: - def initialize(name, options={}) + def initialize(name, options={}, serializer_options={}) @name = name @options = options + @serializer_options = serializer_options end def target_serializer @@ -48,15 +49,15 @@ def embeddable? def find_serializable(object) if target_serializer - target_serializer.new(object, options[:serializer_options]) + target_serializer.new(object, serializer_options) elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) - ams.new(object, options[:serializer_options]) + ams.new(object, serializer_options) else object end end - attr_reader :options + attr_reader :options, :serializer_options end class HasMany < Config #:nodoc: From0b9f69529fMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 17:05:41 -0700 Subject: [PATCH 17/66] Add default_embed_options --- lib/active_model/serializer.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 02a25c5..4fec41a 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -377,9 +377,8 @@ def include!(name, options={}) Associations::HasOne end + options = default_embed_options.merge!(options) options[:value] ||= send(name) - options[:embed] = _embed unless options.key?(:embed) - options[:include] = _root_embed unless options.key?(:include) association = association_class.new(name, options, self.options) if association.embed_ids? @@ -452,6 +451,15 @@ def instrument(name, payload = {}, &block) event_name = INSTRUMENT[name] ActiveSupport::Notifications.instrument(event_name, payload, &block) end + + private + + def default_embed_options + { + :embed => _embed, + :include => _root_embed + } + end end # DefaultSerializer From251fdc7ba4Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 14 May 2013 17:26:38 -0700 Subject: [PATCH 18/66] Rename opts to klass_options --- lib/active_model/serializer.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 4fec41a..3468a09 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -366,10 +366,10 @@ def include!(name, options={}) end end - klass, opts = _associations[name] + klass, klass_options = _associations[name] association_class = if klass - options = opts.merge options + options = klass_options.merge options klass elsif value.respond_to?(:to_ary) Associations::HasMany From2b22acff53Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 12:57:30 -0700 Subject: [PATCH 19/66] Use the readers instead of accessing the ivar directly --- lib/active_model/array_serializer.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index 5f0df67..f647432 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -35,7 +35,8 @@ def cached(value = true) end def initialize(object, options={}) - @object, @options = object, options + @object = object + @options = options end def serialize_object @@ -43,16 +44,16 @@ def serialize_object end def serializable_array - @object.map do |item| - if @options.has_key? :each_serializer - serializer = @options[:each_serializer] + object.map do |item| + if options.has_key? :each_serializer + serializer = options[:each_serializer] elsif item.respond_to?(:active_model_serializer) serializer = item.active_model_serializer else serializer = DefaultSerializer end - serializable = serializer.new(item, @options) + serializable = serializer.new(item, options) if serializable.respond_to?(:serializable_hash) serializable.serializable_hash From03669a74bcMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 14:23:09 -0700 Subject: [PATCH 20/66] Associations::Config is now Associations::Base --- lib/active_model/serializer/associations.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index c651417..42bc754 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -1,7 +1,7 @@ module ActiveModel class Serializer module Associations #:nodoc: - class Config #:nodoc: + class Base #:nodoc: def initialize(name, options={}, serializer_options={}) @name = name @options = options @@ -60,7 +60,7 @@ def find_serializable(object) attr_reader :options, :serializer_options end - class HasMany < Config #:nodoc: + class HasMany < Base #:nodoc: def key if key = options[:key] key @@ -102,7 +102,7 @@ def serialize_ids end end - class HasOne < Config #:nodoc: + class HasOne < Base #:nodoc: def embeddable? if polymorphic? && associated_object.nil? false From85bf3d2f3dMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 15:43:37 -0700 Subject: [PATCH 21/66] Move duplicated code to the Base class --- lib/active_model/serializer/associations.rb | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 42bc754..1a04eda 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -45,6 +45,14 @@ def embeddable? !associated_object.nil? end + def embed_key + if key = options[:embed_key] + key + else + :id + end + end + protected def find_serializable(object) @@ -71,14 +79,6 @@ def key end end - def embed_key - if key = options[:embed_key] - key - else - :id - end - end - def id_key "#{@name.to_s.singularize}_ids".to_sym end @@ -135,14 +135,6 @@ def key end end - def embed_key - if key = options[:embed_key] - key - else - :id - end - end - def id_key "#{@name}_id".to_sym end Fromf9e189e9d7Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 15:50:23 -0700 Subject: [PATCH 22/66] Rename associated_object to object --- lib/active_model/serializer/associations.rb | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 1a04eda..ce6c87c 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -25,7 +25,7 @@ def name options[:name] || @name end - def associated_object + def object options[:value] end @@ -42,7 +42,7 @@ def embed_in_root? end def embeddable? - !associated_object.nil? + !object.nil? end def embed_key @@ -84,19 +84,19 @@ def id_key end def serialize - associated_object.map do |item| + object.map do |item| find_serializable(item).serializable_hash end end def serializables - associated_object.map do |item| + object.map do |item| find_serializable(item) end end def serialize_ids - associated_object.map do |item| + object.map do |item| item.read_attribute_for_serialization(embed_key) end end @@ -104,7 +104,7 @@ def serialize_ids class HasOne < Base #:nodoc: def embeddable? - if polymorphic? && associated_object.nil? + if polymorphic? && object.nil? false else true @@ -119,7 +119,7 @@ def root if root = options[:root] root elsif polymorphic? - associated_object.class.to_s.pluralize.demodulize.underscore.to_sym + object.class.to_s.pluralize.demodulize.underscore.to_sym else @name.to_s.pluralize.to_sym end @@ -140,12 +140,10 @@ def id_key end def polymorphic_key - associated_object.class.to_s.demodulize.underscore.to_sym + object.class.to_s.demodulize.underscore.to_sym end def serialize - object = associated_object - if object if polymorphic? { @@ -159,14 +157,11 @@ def serialize end def serializables - object = associated_object value = object && find_serializable(object) value ? [value] : [] end def serialize_ids - object = associated_object - if object id = object.read_attribute_for_serialization(embed_key) if polymorphic? From0b648fceacMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 15:51:55 -0700 Subject: [PATCH 23/66] Use private instead of protected, we don't use explicit receivers --- lib/active_model/serializer/associations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index ce6c87c..f1f7a5b 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -53,7 +53,7 @@ def embed_key end end - protected + private def find_serializable(object) if target_serializer From2dd0090f13Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:02:03 -0700 Subject: [PATCH 24/66] Reorder methods --- lib/active_model/serializer/associations.rb | 84 +++++++++++++++-------------- 1 file changed, 43 insertions(+), 41 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index f1f7a5b..711eac4 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -8,9 +8,8 @@ def initialize(name, options={}, serializer_options={}) @serializer_options = serializer_options end - def target_serializer - serializer = options[:serializer] - serializer.is_a?(String) ? serializer.constantize : serializer + def name + options[:name] || @name end def key @@ -21,14 +20,6 @@ def root options[:root] || @name end - def name - options[:name] || @name - end - - def object - options[:value] - end - def embed_ids? [:id, :ids].include? options[:embed] end @@ -45,6 +36,12 @@ def embeddable? !object.nil? end + private + + def object + options[:value] + end + def embed_key if key = options[:embed_key] key @@ -53,7 +50,10 @@ def embed_key end end - private + def target_serializer + serializer = options[:serializer] + serializer.is_a?(String) ? serializer.constantize : serializer + end def find_serializable(object) if target_serializer @@ -83,15 +83,15 @@ def id_key "#{@name.to_s.singularize}_ids".to_sym end - def serialize + def serializables object.map do |item| - find_serializable(item).serializable_hash + find_serializable(item) end end - def serializables + def serialize object.map do |item| - find_serializable(item) + find_serializable(item).serializable_hash end end @@ -103,18 +103,16 @@ def serialize_ids end class HasOne < Base #:nodoc: - def embeddable? - if polymorphic? && object.nil? - false + def key + if key = options[:key] + key + elsif embed_ids? && !polymorphic? + id_key else - true + @name end end - def polymorphic? - options[:polymorphic] - end - def root if root = options[:root] root @@ -125,22 +123,21 @@ def root end end - def key - if key = options[:key] - key - elsif embed_ids? && !polymorphic? - id_key - else - @name - end - end - def id_key "#{@name}_id".to_sym end - def polymorphic_key - object.class.to_s.demodulize.underscore.to_sym + def embeddable? + if polymorphic? && object.nil? + false + else + true + end + end + + def serializables + value = object && find_serializable(object) + value ? [value] : [] end def serialize @@ -156,11 +153,6 @@ def serialize end end - def serializables - value = object && find_serializable(object) - value ? [value] : [] - end - def serialize_ids if object id = object.read_attribute_for_serialization(embed_key) @@ -174,6 +166,16 @@ def serialize_ids end end end + + private + + def polymorphic? + options[:polymorphic] + end + + def polymorphic_key + object.class.to_s.demodulize.underscore.to_sym + end end end end Fromea6d712cc8Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:04:29 -0700 Subject: [PATCH 25/66] key method is defined on subclasses --- lib/active_model/serializer/associations.rb | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 711eac4..5496740 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -12,10 +12,6 @@ def name options[:name] || @name end - def key - options[:key] || @name - end - def root options[:root] || @name end Fromeb5b27de69Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:13:26 -0700 Subject: [PATCH 26/66] Initialize things in the initialize method and define readers --- lib/active_model/serializer/associations.rb | 41 +++++++++++------------------ 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 5496740..0583d0c 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -3,29 +3,26 @@ class Serializer module Associations #:nodoc: class Base #:nodoc: def initialize(name, options={}, serializer_options={}) - @name = name + @name = name + @object = options[:value] + + @embed = options[:embed] + @embed_key = options[:embed_key] || :id + @embed_in_root = options[:include] + @options = options @serializer_options = serializer_options end - def name - options[:name] || @name - end - - def root - options[:root] || @name - end + attr_reader :root, :name, :embed_in_root + alias :embed_in_root? :embed_in_root def embed_ids? - [:id, :ids].include? options[:embed] + [:id, :ids].include? embed end def embed_objects? - [:object, :objects].include? options[:embed] - end - - def embed_in_root? - options[:include] + [:object, :objects].include? embed end def embeddable? @@ -34,17 +31,7 @@ def embeddable? private - def object - options[:value] - end - - def embed_key - if key = options[:embed_key] - key - else - :id - end - end + attr_reader :object, :embed, :embed_key def target_serializer serializer = options[:serializer] @@ -75,6 +62,10 @@ def key end end + def root + options[:root] || name + end + def id_key "#{@name.to_s.singularize}_ids".to_sym end Fromecbb8bf6a6Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:14:27 -0700 Subject: [PATCH 27/66] Use == || == instead of include? --- lib/active_model/serializer/associations.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 0583d0c..cacf7db 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -18,11 +18,11 @@ def initialize(name, options={}, serializer_options={}) alias :embed_in_root? :embed_in_root def embed_ids? - [:id, :ids].include? embed + embed == :id || embed == :ids end def embed_objects? - [:object, :objects].include? embed + embed == :object || embed == :objects end def embeddable? From296970415aMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 17:12:02 -0700 Subject: [PATCH 28/66] Move key method to the base class --- lib/active_model/serializer/associations.rb | 35 +++++++++++++---------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index cacf7db..4ef0417 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -17,9 +17,20 @@ def initialize(name, options={}, serializer_options={}) attr_reader :root, :name, :embed_in_root alias :embed_in_root? :embed_in_root + def key + if key = options[:key] + key + elsif use_id_key? + id_key + else + @name + end + end + def embed_ids? embed == :id || embed == :ids end + alias use_id_key? embed_ids? def embed_objects? embed == :object || embed == :objects @@ -52,16 +63,6 @@ def find_serializable(object) end class HasMany < Base #:nodoc: - def key - if key = options[:key] - key - elsif embed_ids? - id_key - else - @name - end - end - def root options[:root] || name end @@ -90,16 +91,6 @@ def serialize_ids end class HasOne < Base #:nodoc: - def key - if key = options[:key] - key - elsif embed_ids? && !polymorphic? - id_key - else - @name - end - end - def root if root = options[:root] root @@ -156,6 +147,10 @@ def serialize_ids private + def use_id_key? + embed_ids? && !polymorphic? + end + def polymorphic? options[:polymorphic] end Fromfeaefeeef3Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:26:55 -0700 Subject: [PATCH 29/66] Use name reader --- lib/active_model/serializer/associations.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 4ef0417..6a73b38 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -23,7 +23,7 @@ def key elsif use_id_key? id_key else - @name + name end end @@ -68,7 +68,7 @@ def root end def id_key - "#{@name.to_s.singularize}_ids".to_sym + "#{name.to_s.singularize}_ids".to_sym end def serializables @@ -97,12 +97,12 @@ def root elsif polymorphic? object.class.to_s.pluralize.demodulize.underscore.to_sym else - @name.to_s.pluralize.to_sym + name.to_s.pluralize.to_sym end end def id_key - "#{@name}_id".to_sym + "#{name}_id".to_sym end def embeddable? From1c3f14407cMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 16:33:12 -0700 Subject: [PATCH 30/66] There's no need for target_serializer method --- lib/active_model/serializer/associations.rb | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 6a73b38..cb65249 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -10,6 +10,9 @@ def initialize(name, options={}, serializer_options={}) @embed_key = options[:embed_key] || :id @embed_in_root = options[:include] + serializer = options[:serializer] + @serializer = serializer.is_a?(String) ? serializer.constantize : serializer + @options = options @serializer_options = serializer_options end @@ -42,16 +45,11 @@ def embeddable? private - attr_reader :object, :embed, :embed_key - - def target_serializer - serializer = options[:serializer] - serializer.is_a?(String) ? serializer.constantize : serializer - end + attr_reader :object, :embed, :embed_key, :serializer def find_serializable(object) - if target_serializer - target_serializer.new(object, serializer_options) + if serializer + serializer.new(object, serializer_options) elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) ams.new(object, serializer_options) else Fromcd9e106640Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 17:26:38 -0700 Subject: [PATCH 31/66] All the attr_readers together --- lib/active_model/serializer/associations.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index cb65249..4b5324c 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -45,7 +45,7 @@ def embeddable? private - attr_reader :object, :embed, :embed_key, :serializer + attr_reader :object, :embed, :embed_key, :serializer, :options, :serializer_options def find_serializable(object) if serializer @@ -56,8 +56,6 @@ def find_serializable(object) object end end - - attr_reader :options, :serializer_options end class HasMany < Base #:nodoc: Frome295af2e2bMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 17:27:25 -0700 Subject: [PATCH 32/66] Move embed methods to initialize and define readers --- lib/active_model/serializer/associations.rb | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 4b5324c..7cfa385 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -6,7 +6,9 @@ def initialize(name, options={}, serializer_options={}) @name = name @object = options[:value] - @embed = options[:embed] + embed = options[:embed] + @embed_ids = embed == :id || embed == :ids + @embed_objects = embed == :object || embed == :objects @embed_key = options[:embed_key] || :id @embed_in_root = options[:include] @@ -17,8 +19,11 @@ def initialize(name, options={}, serializer_options={}) @serializer_options = serializer_options end - attr_reader :root, :name, :embed_in_root - alias :embed_in_root? :embed_in_root + attr_reader :root, :name, :embed_ids, :embed_objects, :embed_in_root + alias embed_objects? embed_objects + alias embed_ids? embed_ids + alias use_id_key? embed_ids? + alias embed_in_root? embed_in_root def key if key = options[:key] @@ -30,22 +35,13 @@ def key end end - def embed_ids? - embed == :id || embed == :ids - end - alias use_id_key? embed_ids? - - def embed_objects? - embed == :object || embed == :objects - end - def embeddable? !object.nil? end private - attr_reader :object, :embed, :embed_key, :serializer, :options, :serializer_options + attr_reader :object, :embed_key, :serializer, :options, :serializer_options def find_serializable(object) if serializer Frombbd3c8b157Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 17:28:26 -0700 Subject: [PATCH 33/66] Define embeddable? as an alias of object --- lib/active_model/serializer/associations.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 7cfa385..aa77bf6 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -19,7 +19,8 @@ def initialize(name, options={}, serializer_options={}) @serializer_options = serializer_options end - attr_reader :root, :name, :embed_ids, :embed_objects, :embed_in_root + attr_reader :object, :root, :name, :embed_ids, :embed_objects, :embed_in_root + alias embeddable? object alias embed_objects? embed_objects alias embed_ids? embed_ids alias use_id_key? embed_ids? @@ -35,13 +36,9 @@ def key end end - def embeddable? - !object.nil? - end - private - attr_reader :object, :embed_key, :serializer, :options, :serializer_options + attr_reader :embed_key, :serializer, :options, :serializer_options def find_serializable(object) if serializer From36feb5d44fMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 17:07:04 -0700 Subject: [PATCH 34/66] Refactor embeddable? method --- lib/active_model/serializer/associations.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index aa77bf6..e2e13c2 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -95,11 +95,7 @@ def id_key end def embeddable? - if polymorphic? && object.nil? - false - else - true - end + super || !polymorphic? end def serializables From0b6326eb35Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 17:10:04 -0700 Subject: [PATCH 35/66] Move polymorphic to initialize + reader --- lib/active_model/serializer/associations.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index e2e13c2..d647d81 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -80,6 +80,11 @@ def serialize_ids end class HasOne < Base #:nodoc: + def initialize(name, options={}, serializer_options={}) + super + @polymorphic = options[:polymorphic] + end + def root if root = options[:root] root @@ -132,14 +137,13 @@ def serialize_ids private + attr_reader :polymorphic + alias polymorphic? polymorphic + def use_id_key? embed_ids? && !polymorphic? end - def polymorphic? - options[:polymorphic] - end - def polymorphic_key object.class.to_s.demodulize.underscore.to_sym end From787b7cf24aMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 15 May 2013 17:49:03 -0700 Subject: [PATCH 36/66] Document Associations --- lib/active_model/serializer/associations.rb | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index d647d81..cb3cb00 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -2,6 +2,28 @@ module ActiveModel class Serializer module Associations #:nodoc: class Base #:nodoc: + # name: The name of the association. + # + # options: A hash. These keys are accepted: + # + # value: The object we're associating with. + # + # serializer: The class used to serialize the association. + # + # embed: Define how associations should be embedded. + # - :objects # Embed associations as full objects. + # - :ids # Embed only the association ids. + # - :ids, :include => true # Embed the association ids and include objects in the root. + # + # include: Used in conjunction with embed :ids. Includes the objects in the root. + # + # root: Used in conjunction with include: true. Defines the key used to embed the objects. + # + # key: Key name used to store the ids in. + # + # embed_key: Method used to fetch ids. Defaults to :id. + # + # polymorphic: Is the association is polymorphic?. Values: true or false. def initialize(name, options={}, serializer_options={}) @name = name @object = options[:value] From055f8fe33cMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 16:51:56 -0700 Subject: [PATCH 37/66] AMS::Associations::Base is now AMS::Association. HasMany and HasOne inherits from it. --- lib/active_model/serializer.rb | 8 +- lib/active_model/serializer/associations.rb | 134 ++++++++++++++-------------- 2 files changed, 70 insertions(+), 72 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 3468a09..c4477fb 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -152,7 +152,7 @@ def define_include_method(name) # with the association name does not exist, the association name is # dispatched to the serialized object. def has_many(*attrs) - associate(Associations::HasMany, attrs) + associate(Association::HasMany, attrs) end # Defines an association in the object should be rendered. @@ -162,7 +162,7 @@ def has_many(*attrs) # with the association name does not exist, the association name is # dispatched to the serialized object. def has_one(*attrs) - associate(Associations::HasOne, attrs) + associate(Association::HasOne, attrs) end # Return a schema hash for the current serializer. This information @@ -372,9 +372,9 @@ def include!(name, options={}) options = klass_options.merge options klass elsif value.respond_to?(:to_ary) - Associations::HasMany + Association::HasMany else - Associations::HasOne + Association::HasOne end options = default_embed_options.merge!(options) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index cb3cb00..63760d4 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -1,79 +1,77 @@ module ActiveModel class Serializer - module Associations #:nodoc: - class Base #:nodoc: - # name: The name of the association. - # - # options: A hash. These keys are accepted: - # - # value: The object we're associating with. - # - # serializer: The class used to serialize the association. - # - # embed: Define how associations should be embedded. - # - :objects # Embed associations as full objects. - # - :ids # Embed only the association ids. - # - :ids, :include => true # Embed the association ids and include objects in the root. - # - # include: Used in conjunction with embed :ids. Includes the objects in the root. - # - # root: Used in conjunction with include: true. Defines the key used to embed the objects. - # - # key: Key name used to store the ids in. - # - # embed_key: Method used to fetch ids. Defaults to :id. - # - # polymorphic: Is the association is polymorphic?. Values: true or false. - def initialize(name, options={}, serializer_options={}) - @name = name - @object = options[:value] - - embed = options[:embed] - @embed_ids = embed == :id || embed == :ids - @embed_objects = embed == :object || embed == :objects - @embed_key = options[:embed_key] || :id - @embed_in_root = options[:include] - - serializer = options[:serializer] - @serializer = serializer.is_a?(String) ? serializer.constantize : serializer - - @options = options - @serializer_options = serializer_options - end - - attr_reader :object, :root, :name, :embed_ids, :embed_objects, :embed_in_root - alias embeddable? object - alias embed_objects? embed_objects - alias embed_ids? embed_ids - alias use_id_key? embed_ids? - alias embed_in_root? embed_in_root - - def key - if key = options[:key] - key - elsif use_id_key? - id_key - else - name - end + class Association #:nodoc: + # name: The name of the association. + # + # options: A hash. These keys are accepted: + # + # value: The object we're associating with. + # + # serializer: The class used to serialize the association. + # + # embed: Define how associations should be embedded. + # - :objects # Embed associations as full objects. + # - :ids # Embed only the association ids. + # - :ids, :include => true # Embed the association ids and include objects in the root. + # + # include: Used in conjunction with embed :ids. Includes the objects in the root. + # + # root: Used in conjunction with include: true. Defines the key used to embed the objects. + # + # key: Key name used to store the ids in. + # + # embed_key: Method used to fetch ids. Defaults to :id. + # + # polymorphic: Is the association is polymorphic?. Values: true or false. + def initialize(name, options={}, serializer_options={}) + @name = name + @object = options[:value] + + embed = options[:embed] + @embed_ids = embed == :id || embed == :ids + @embed_objects = embed == :object || embed == :objects + @embed_key = options[:embed_key] || :id + @embed_in_root = options[:include] + + serializer = options[:serializer] + @serializer = serializer.is_a?(String) ? serializer.constantize : serializer + + @options = options + @serializer_options = serializer_options + end + + attr_reader :object, :root, :name, :embed_ids, :embed_objects, :embed_in_root + alias embeddable? object + alias embed_objects? embed_objects + alias embed_ids? embed_ids + alias use_id_key? embed_ids? + alias embed_in_root? embed_in_root + + def key + if key = options[:key] + key + elsif use_id_key? + id_key + else + name end + end - private + private - attr_reader :embed_key, :serializer, :options, :serializer_options + attr_reader :embed_key, :serializer, :options, :serializer_options - def find_serializable(object) - if serializer - serializer.new(object, serializer_options) - elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) - ams.new(object, serializer_options) - else - object - end + def find_serializable(object) + if serializer + serializer.new(object, serializer_options) + elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) + ams.new(object, serializer_options) + else + object end end - class HasMany < Base #:nodoc: + class HasMany < Association #:nodoc: def root options[:root] || name end @@ -101,7 +99,7 @@ def serialize_ids end end - class HasOne < Base #:nodoc: + class HasOne < Association #:nodoc: def initialize(name, options={}, serializer_options={}) super @polymorphic = options[:polymorphic] From35608a8550Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 16 May 2013 17:50:12 -0700 Subject: [PATCH 38/66] Move version.rb file to serializer directory --- active_model_serializers.gemspec | 2 +- lib/active_model/serializer/version.rb | 5 +++++ lib/active_model/serializers/version.rb | 5 ----- 3 files changed, 6 insertions(+), 6 deletions(-) create mode 100644 lib/active_model/serializer/version.rb delete mode 100644 lib/active_model/serializers/version.rb diff --git a/active_model_serializers.gemspec b/active_model_serializers.gemspec index f4f90a8..0971a26 100644 --- a/active_model_serializers.gemspec +++ b/active_model_serializers.gemspec @@ -1,7 +1,7 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path("../lib", __FILE__) -require "active_model/serializers/version" +require "active_model/serializer/version" Gem::Specification.new do |gem| gem.authors = ["José Valim", "Yehuda Katz"] diff --git a/lib/active_model/serializer/version.rb b/lib/active_model/serializer/version.rb new file mode 100644 index 0000000..10e6266 --- /dev/null +++ b/lib/active_model/serializer/version.rb @@ -0,0 +1,5 @@ +module ActiveModel + class Serializer + VERSION = "0.8.1" + end +end diff --git a/lib/active_model/serializers/version.rb b/lib/active_model/serializers/version.rb deleted file mode 100644 index 10e6266..0000000 --- a/lib/active_model/serializers/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module ActiveModel - class Serializer - VERSION = "0.8.1" - end -end Fromfd8cb67b85Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Fri, 17 May 2013 15:01:14 -0700 Subject: [PATCH 39/66] Add CHANGELOG entries --- CHANGELOG.md | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86d9b27..fc05118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,40 @@ # UNRELEASED +* ActiveModel::Serializable was created it has the shared code between + AM::Serializer and AM::ArraySerializer. Basically enable objects to be + serializable by implementing an options method to handle the options + of the serialization and a serialize method that returns an object to + be converted to json by the module. This also removes duplicate code. +6c6bc8872d+ +* ActiveModel::Seriazer::Caching module was created it enables + Serializers to be able to cache to\_json and serialize calls. This + also helps removing duplicate code. +3e27110df7+ +* We got rid of the Association.refine method which generated + subclasses. +24923722d4+ +* Associations doesn't know anymore about the source serializer. + That didn't make any sense. +2252e8fe6d+87eadd09b9+79a6e13e8f+ +* Passing options[:hash] is not public API of include!. That was + removed. +5cbf931705+ +* ActiveModel::Serializer::Associations::Config is now + ActiveModel::Serializer::Association but it's an internal + thing so shouldn't bother. + ActiveModel::Serializer::Associations::Has\* are now + ActiveModel::Serializer::Association::Has\* and inherit from + ActiveModel::Serializer::Association +f5de334ddf+3dd422d99e+ # VERSION 0.8.1 * Fix bug whereby a serializer using 'options' would blow up. @@ -10,8 +45,8 @@ * A new DefaultSerializer ensures that POROs behave the same way as ActiveModels. -* If you wish to override ActiveRecord::Base#to_Json, you can now require - 'active_record/serializer_override'. We don't recommend you do this, but +* If you wish to override ActiveRecord::Base#to\_Json, you can now require + 'active\_record/serializer\_override'. We don't recommend you do this, but many users do, so we've left it optional. * Fixed a bug where ActionController wouldn't always have MimeResponds. Frombbc3ae44ccMon Sep 17 00:00:00 2001 From: Damian Galarza <galarza.d@gmail.com> Date: Tue, 21 May 2013 10:08:48 -0400 Subject: [PATCH 40/66] Allow a controller to properly override scope_name --- lib/active_model/serializer.rb | 2 +- test/serialization_scope_name_test.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index c4477fb..6a5275d 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -284,7 +284,7 @@ def build_json(controller, resource, options) end options[:scope] = controller.serialization_scope unless options.has_key?(:scope) - options[:scope_name] = controller._serialization_scope + options[:scope_name] = controller._serialization_scope unless options.has_key?(:scope_name) options[:url_options] = controller.url_options serializer.new(resource, options) diff --git a/test/serialization_scope_name_test.rb b/test/serialization_scope_name_test.rb index d3db103..bc9c87b 100644 --- a/test/serialization_scope_name_test.rb +++ b/test/serialization_scope_name_test.rb @@ -65,3 +65,35 @@ def test_override_scope_name_with_controller assert_equal '{"admin_user":{"admin":true}}', @response.body end end + +class SerializationActionScopeOverrideTest < ActionController::TestCase + TestUser = Struct.new(:name, :admin) + + class AdminUserSerializer < ActiveModel::Serializer + attributes :admin? + def admin? + current_admin.admin + end + end + + class AdminUserTestController < ActionController::Base + protect_from_forgery + before_filter { request.format = :json } + + def current_admin + TestUser.new('Bob', true) + end + + def render_new_user + render :json => TestUser.new('pete', false), :serializer => AdminUserSerializer, :scope => current_admin, :scope_name => :current_admin + end + end + + tests AdminUserTestController + + def test_override_scope_name_with_controller + get :render_new_user + assert_equal '{"admin_user":{"admin":true}}', @response.body + end + +end From18313df12dMon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Coutable?= <remy@rymai.me> Date: Wed, 22 May 2013 16:54:27 +0300 Subject: [PATCH 41/66] Fix typo for ActiveModel::Serializer::Caching in the CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc05118..feafe7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ be converted to json by the module. This also removes duplicate code.6c6bc8872d-* ActiveModel::Seriazer::Caching module was created it enables +* ActiveModel::Serializer::Caching module was created it enables Serializers to be able to cache to\_json and serialize calls. This also helps removing duplicate code.3e27110df7Fromee846f39afMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 22 May 2013 14:24:22 -0700 Subject: [PATCH 42/66] Fix build in 1.8.7 --- lib/active_model/serializer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 6a5275d..2ac8eac 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -323,7 +323,7 @@ def url_options # Returns a json representation of the serializable # object including the root. def as_json(args={}) - super(root: args.fetch(:root, options.fetch(:root, root_name))) + super(:root => args.fetch(:root, options.fetch(:root, root_name))) end def serialize_object From258248d6c0Mon Sep 17 00:00:00 2001 From: Thomas Scholtes <thomas-scholtes@gmx.de> Date: Fri, 24 May 2013 10:23:59 +0200 Subject: [PATCH 43/66] Don't wrap array items in root element --- lib/active_model/array_serializer.rb | 2 +- test/array_serializer_test.rb | 14 ++++++++++++++ test/test_fakes.rb | 8 ++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index f647432..144bfe8 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -53,7 +53,7 @@ def serializable_array serializer = DefaultSerializer end - serializable = serializer.new(item, options) + serializable = serializer.new(item, options.merge(:root => nil)) if serializable.respond_to?(:serializable_hash) serializable.serializable_hash diff --git a/test/array_serializer_test.rb b/test/array_serializer_test.rb index d3001ac..11bec6c 100644 --- a/test/array_serializer_test.rb +++ b/test/array_serializer_test.rb @@ -31,6 +31,20 @@ def test_array_serializer_with_root ]}, serializer.as_json) end + def test_active_model_with_root + comment1 = ModelWithActiveModelSerializer.new(:title => "Comment1") + comment2 = ModelWithActiveModelSerializer.new(:title => "Comment2") + + array = [ comment1, comment2 ] + + serializer = array.active_model_serializer.new(array, :root => :comments) + + assert_equal({ :comments => [ + { :title => "Comment1" }, + { :title => "Comment2" } + ]}, serializer.as_json) + end + def test_array_serializer_with_hash hash = {:value => "something"} array = [hash] diff --git a/test/test_fakes.rb b/test/test_fakes.rb index ab96371..30ce34b 100644 --- a/test/test_fakes.rb +++ b/test/test_fakes.rb @@ -12,6 +12,14 @@ def as_json(*) end end +class ModelWithActiveModelSerializer < Model + include ActiveModel::Serializers::JSON + attr_accessor :attributes + def read_attribute_for_serialization(name) + @attributes[name] + end +end + class User include ActiveModel::SerializerSupport From9521e912feMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Thu, 23 May 2013 17:34:03 -0700 Subject: [PATCH 44/66] serialize_ids call methods on the corresponding serializer if defined --- lib/active_model/serializer.rb | 7 +-- lib/active_model/serializer/associations.rb | 24 +++++++--- test/serializer_test.rb | 69 +++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 12 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 2ac8eac..c3768f7 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -382,12 +382,7 @@ def include!(name, options={}) association = association_class.new(name, options, self.options) if association.embed_ids? - node[association.key] = - if options[:embed_key] || self.respond_to?(name) || !self.object.respond_to?(association.id_key) - association.serialize_ids - else - self.object.read_attribute_for_serialization(association.id_key) - end + node[association.key] = association.serialize_ids if association.embed_in_root? && hash.nil? raise IncludeError.new(self.class, association.name) diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 63760d4..888b94f 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -34,7 +34,7 @@ def initialize(name, options={}, serializer_options={}) @embed_in_root = options[:include] serializer = options[:serializer] - @serializer = serializer.is_a?(String) ? serializer.constantize : serializer + @serializer_class = serializer.is_a?(String) ? serializer.constantize : serializer @options = options @serializer_options = serializer_options @@ -59,11 +59,11 @@ def key private - attr_reader :embed_key, :serializer, :options, :serializer_options + attr_reader :embed_key, :serializer_class, :options, :serializer_options def find_serializable(object) - if serializer - serializer.new(object, serializer_options) + if serializer_class + serializer_class.new(object, serializer_options) elsif object.respond_to?(:active_model_serializer) && (ams = object.active_model_serializer) ams.new(object, serializer_options) else @@ -94,7 +94,12 @@ def serialize def serialize_ids object.map do |item| - item.read_attribute_for_serialization(embed_key) + serializer = find_serializable(item) + if serializer.respond_to?(embed_key) + serializer.send(embed_key) + else + item.read_attribute_for_serialization(embed_key) + end end end end @@ -143,7 +148,14 @@ def serialize def serialize_ids if object - id = object.read_attribute_for_serialization(embed_key) + serializer = find_serializable(object) + id = + if serializer.respond_to?(embed_key) + serializer.send(embed_key) + else + object.read_attribute_for_serialization(embed_key) + end + if polymorphic? { :type => polymorphic_key, diff --git a/test/serializer_test.rb b/test/serializer_test.rb index 6c7cf7b..588da1c 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -454,6 +454,39 @@ def comments }, json) end + def test_methods_take_priority_over_associations_and_call_the_appropriate_id_method + comment_serializer = Class.new(ActiveModel::Serializer) do + def id + "OMG" + end + end + + post_serializer = Class.new(ActiveModel::Serializer) do + attributes :title + has_many :comments, :serializer => comment_serializer + embed :ids + + def comments + object.comments[0,1] + end + end + + post = Post.new(:title => "My Post") + comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post.comments = comments + + post.class_eval do + define_method :comment_ids, lambda { + self.comments.map { |c| c.read_attribute_for_serialization(:id) } + } + end + json = post_serializer.new(post).as_json + assert_equal({ + :title => "My Post", + :comment_ids => ["OMG"] + }, json) + end + def test_embed_objects serializer = post_serializer @@ -684,6 +717,42 @@ def test_embed_id_for_has_one }, hash.as_json) end + def test_embed_id_for_has_one_overriding_associated_id + author_serializer = Class.new(ActiveModel::Serializer) do + def id + "OMG" + end + end + + serializer_class = Class.new(ActiveModel::Serializer) do + embed :ids + root :post + + attributes :title, :body + has_one :author, :serializer => author_serializer + end + + post_class = Class.new(Model) do + attr_accessor :author + end + + author_class = Class.new(Model) + + post = post_class.new(:title => "New Post", :body => "It's a new post!") + author = author_class.new(:id => 5) + post.author = author + + hash = serializer_class.new(post) + + assert_equal({ + :post => { + :title => "New Post", + :body => "It's a new post!", + :author_id => "OMG" + } + }, hash.as_json) + end + def test_embed_objects_for_has_one author_serializer = Class.new(ActiveModel::Serializer) do attributes :id, :name Fromc023052df8Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Fri, 24 May 2013 15:00:29 -0700 Subject: [PATCH 45/66] Add CHANGELOG.md entries --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index feafe7e..40f7e00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,13 @@f5de334ddf3dd422d99e+* serialize\_ids call methods on the corresponding serializer if they + are defined, instead of talking directly with the serialized object. + Serializers are decorators so we shouldn't talk directly with + serialized objects. + +* Array items are not wrapped anymore in root element. + # VERSION 0.8.1 * Fix bug whereby a serializer using 'options' would blow up. From8795f2bc1eMon Sep 17 00:00:00 2001 From: Steve Klabnik <steve@steveklabnik.com> Date: Sat, 25 May 2013 08:03:29 -0500 Subject: [PATCH 46/66] Add CONTRIBUTING.md --- CONTRIBUTING.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9811ef2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +Contributing to AMS +=================== + +First of all, **thank you**! + +Now, for the details: + +Please file issues on the [GitHub Issues +list](https://github.com/rails-api/active_model_serializers/issues). + +Please discuss new features or ask for feedback about a new feature [on +rails-api-core](https://groups.google.com/forum/#!forum/rails-api-core). + +If you want a feature implemented, the best way to get it done is to submit a +pull request that implements it. Tests and docs would be nice. + +Please include a CHANGELOG with all entries that change behavior. + +❤️ 💖 ❤️ + Fromc97acfd9baMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Tue, 28 May 2013 18:03:19 -0700 Subject: [PATCH 47/66] Always set a serializer for each item of an Array model.active_model_serializer could return nil so we need to ensure that if serializer is not setted we set DefaultSerializer to it. This reverts commit64ed05c484. Fixes #318 --- lib/active_model/array_serializer.rb | 3 +-- test/array_serializer_test.rb | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index 144bfe8..a1b92c4 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -49,9 +49,8 @@ def serializable_array serializer = options[:each_serializer] elsif item.respond_to?(:active_model_serializer) serializer = item.active_model_serializer - else - serializer = DefaultSerializer end + serializer ||= DefaultSerializer serializable = serializer.new(item, options.merge(:root => nil)) diff --git a/test/array_serializer_test.rb b/test/array_serializer_test.rb index 11bec6c..f335382 100644 --- a/test/array_serializer_test.rb +++ b/test/array_serializer_test.rb @@ -52,7 +52,7 @@ def test_array_serializer_with_hash assert_equal({ :items => [ hash.as_json ]}, serializer.as_json) end - def test_array_serializer_with_specified_seriailizer + def test_array_serializer_with_specified_serializer post1 = Post.new(:title => "Post1", :author => "Author1", :id => 1) post2 = Post.new(:title => "Post2", :author => "Author2", :id => 2) @@ -65,4 +65,21 @@ def test_array_serializer_with_specified_seriailizer { :title => "Post2" } ], serializer.as_json) end + + def test_array_serializer_using_default_serializer + hash = { "value" => "something" } + class << hash + def active_model_serializer + nil + end + end + + array = [hash] + + serializer = array.active_model_serializer.new array + + assert_equal([ + { "value" => "something" } + ], serializer.as_json) + end end From1b142a23f1Mon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 29 May 2013 17:07:45 -0700 Subject: [PATCH 48/66] Add campfire notifications --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index ecaf21c..20faf13 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,3 +27,8 @@ matrix: rvm: jruby-18mode - gemfile: Gemfile.edge rvm: rbx-18mode +notifications: + campfire: + on_success: change + rooms: + - secure: "TP0fJ4aqXCRD7CaAgaYW7Pa22j4/uLChdBb59ob/sJvHtfi4Zx3I54xWApmp\nZl1KItFGCV8oQZhQl5hAmHJfJ+1gCNeBvIKwY6TsIyTmyDg1KcJUcJDrwYxO\ntAeYI2PvU5PtKMmpnfnwFQMxL+2nfWJWNzboBCDr4YvoFI+rN+A=" From2c563eaaceMon Sep 17 00:00:00 2001 From: Santiago Pastorino <santiago@wyeworks.com> Date: Wed, 29 May 2013 18:00:32 -0700 Subject: [PATCH 49/66] Turn off Travis' email notifications --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 20faf13..82c47f1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,6 +28,7 @@ matrix: - gemfile: Gemfile.edge rvm: rbx-18mode notifications: + email: false campfire: on_success: change rooms: From143e5d9866Mon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 19:39:00 -0600 Subject: [PATCH 50/66] do not generate id method (was for 1.8 only) see https://github.com/rails-api/active_model_serializers/issues/127 for original motivation --- lib/generators/serializer/serializer_generator.rb | 3 --- lib/generators/serializer/templates/serializer.rb | 11 ----------- test/generators_test.rb | 12 ------------ 3 files changed, 26 deletions(-) diff --git a/lib/generators/serializer/serializer_generator.rb b/lib/generators/serializer/serializer_generator.rb index b7096f8..0da6c87 100644 --- a/lib/generators/serializer/serializer_generator.rb +++ b/lib/generators/serializer/serializer_generator.rb @@ -13,9 +13,6 @@ def create_serializer_file end private - def generate_id_method - RUBY_VERSION =~ /1\.8/ - end def attributes_names [:id] + attributes.select { |attr| !attr.reference? }.map { |a| a.name.to_sym } diff --git a/lib/generators/serializer/templates/serializer.rb b/lib/generators/serializer/templates/serializer.rb index 6c25609..4ebb004 100644 --- a/lib/generators/serializer/templates/serializer.rb +++ b/lib/generators/serializer/templates/serializer.rb @@ -4,16 +4,5 @@ class <%= class_name %>Serializer < <%= parent_class_name %> <% association_names.each do |attribute| -%> has_one :<%= attribute %> <% end -%> -<% if generate_id_method %> - - # due to the difference between 1.8 and 1.9 with respect to #id and - # #object_id, we recommend that if you wish to serialize id columns, you - # do this. Feel free to remove this if you don't feel that it's appropriate. - # - # For more: https://github.com/rails-api/active_model_serializers/issues/127 - def id - object.read_attribute_for_serialization(:id) - end -<% end -%> end <% end -%> diff --git a/test/generators_test.rb b/test/generators_test.rb index b1938ce..b1a05b3 100644 --- a/test/generators_test.rb +++ b/test/generators_test.rb @@ -36,18 +36,6 @@ def test_uses_application_serializer_if_one_exists Object.send :remove_const, :ApplicationSerializer end - def test_serializer_gets_id - run_generator - - assert_file "app/serializers/account_serializer.rb" do |content| - if RUBY_VERSION =~ /1.8/ - assert_match /def id/, content - else - assert_no_match /def id/, content - end - end - end - # def test_uses_namespace_application_serializer_if_one_exists # Object.const_set(:SerializerNamespace, Module.new) # SerializerNamespace.const_set(:ApplicationSerializer, Class.new) From62167d243bMon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 19:43:36 -0600 Subject: [PATCH 51/66] require ruby >= 1.9.2 in gemspec [ci skip] * use consistent quotes --- active_model_serializers.gemspec | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/active_model_serializers.gemspec b/active_model_serializers.gemspec index 0971a26..9711c56 100644 --- a/active_model_serializers.gemspec +++ b/active_model_serializers.gemspec @@ -17,7 +17,10 @@ Gem::Specification.new do |gem| gem.require_paths = ["lib"] gem.version = ActiveModel::Serializer::VERSION - gem.add_dependency 'activemodel', '>= 3.0' + gem.required_ruby_version = ">= 1.9.2" + + gem.add_dependency "activemodel", ">= 3.0" + gem.add_development_dependency "rails", ">= 3.0" gem.add_development_dependency "pry" gem.add_development_dependency "simplecov" Froma857952d12Mon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 19:46:55 -0600 Subject: [PATCH 52/66] remove 1.8 versions from travis --- .travis.yml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 82c47f1..6a195cf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,9 @@ language: ruby rvm: - - 1.8.7 - 1.9.2 - 1.9.3 - 2.0.0 - - ree - - jruby-18mode - jruby-19mode - - rbx-18mode - rbx-19mode gemfile: - Gemfile @@ -18,15 +14,7 @@ matrix: exclude: # Edge Rails is only compatible with 1.9.3 - gemfile: Gemfile.edge - rvm: 1.8.7 - - gemfile: Gemfile.edge rvm: 1.9.2 - - gemfile: Gemfile.edge - rvm: ree - - gemfile: Gemfile.edge - rvm: jruby-18mode - - gemfile: Gemfile.edge - rvm: rbx-18mode notifications: email: false campfire: Fromb686b73edfMon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 19:47:55 -0600 Subject: [PATCH 53/66] add note to changelog [ci skip] --- CHANGELOG.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40f7e00..07f9b02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,26 +4,26 @@ AM::Serializer and AM::ArraySerializer. Basically enable objects to be serializable by implementing an options method to handle the options of the serialization and a serialize method that returns an object to - be converted to json by the module. This also removes duplicate code. + be converted to json by the module. This also removes duplicate code.6c6bc8872d* ActiveModel::Serializer::Caching module was created it enables Serializers to be able to cache to\_json and serialize calls. This - also helps removing duplicate code. + also helps removing duplicate code.3e27110df7* We got rid of the Association.refine method which generated - subclasses. + subclasses.24923722d4* Associations doesn't know anymore about the source serializer. - That didn't make any sense. -2252e8fe6d-87eadd09b9+ That didn't make any sense. +2252e8fe6d+87eadd09b979a6e13e8f* Passing options[:hash] is not public API of include!. That was - removed. + removed.5cbf931705* ActiveModel::Serializer::Associations::Config is now @@ -31,8 +31,8 @@ thing so shouldn't bother. ActiveModel::Serializer::Associations::Has\* are now ActiveModel::Serializer::Association::Has\* and inherit from - ActiveModel::Serializer::Association -f5de334ddf+ ActiveModel::Serializer::Association +f5de334ddf3dd422d99e* serialize\_ids call methods on the corresponding serializer if they @@ -42,6 +42,8 @@ * Array items are not wrapped anymore in root element. +* Remove support for ruby 1.8 versions. + # VERSION 0.8.1 * Fix bug whereby a serializer using 'options' would blow up. From74ba9dc76cMon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 21:59:17 -0600 Subject: [PATCH 54/66] upgrade hash syntax --- Gemfile | 2 +- Rakefile | 2 +- lib/active_model/array_serializer.rb | 2 +- lib/active_model/serializer.rb | 26 +++++++++++------------ lib/active_model/serializer/associations.rb | 6 +++--- lib/active_model_serializers.rb | 4 ++-- lib/generators/serializer/serializer_generator.rb | 6 +++--- 7 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Gemfile b/Gemfile index 7130373..79ab2b9 100644 --- a/Gemfile +++ b/Gemfile @@ -3,4 +3,4 @@ source 'https://rubygems.org' # Specify gem dependencies in active_model_serializers.gemspec gemspec -gem "coveralls", :require => false +gem "coveralls", require: false diff --git a/Rakefile b/Rakefile index 23f17c4..8c5bd75 100644 --- a/Rakefile +++ b/Rakefile @@ -15,4 +15,4 @@ task :bench do load 'bench/perf.rb' end -task :default => :test +task default: :test diff --git a/lib/active_model/array_serializer.rb b/lib/active_model/array_serializer.rb index a1b92c4..e752c81 100644 --- a/lib/active_model/array_serializer.rb +++ b/lib/active_model/array_serializer.rb @@ -52,7 +52,7 @@ def serializable_array end serializer ||= DefaultSerializer - serializable = serializer.new(item, options.merge(:root => nil)) + serializable = serializer.new(item, options.merge(root: nil)) if serializable.respond_to?(:serializable_hash) serializable.serializable_hash diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index c3768f7..e2a6228 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -13,7 +13,7 @@ module ActiveModel # it expects two objects as arguments, a resource and options. For example, # one may do in a controller: # - # PostSerializer.new(@post, :scope => current_user).to_json + # PostSerializer.new(@post, scope: current_user).to_json # # The object to be serialized is the +@post+ and the current user is passed # in for authorization purposes. @@ -30,7 +30,7 @@ module ActiveModel # # def attributes # hash = super - # hash.merge!(:email => post.email) if author? + # hash.merge!(email: post.email) if author? # hash # end # @@ -46,7 +46,7 @@ class Serializer include ActiveModel::Serializer::Caching INCLUDE_METHODS = {} - INSTRUMENT = { :serialize => :"serialize.serializer", :associations => :"associations.serializer" } + INSTRUMENT = { serialize: :"serialize.serializer", associations: :"associations.serializer" } class IncludeError < StandardError attr_reader :source, :association @@ -86,7 +86,7 @@ def attributes(*attrs) attrs.each do |attr| if Hash === attr - attr.each {|attr_real, key| attribute attr_real, :key => key } + attr.each {|attr_real, key| attribute(attr_real, key: key) } else attribute attr end @@ -172,20 +172,20 @@ def has_one(*attrs) # # The +attributes+ hash looks like this: # - # { :name => :string, :age => :integer } + # { name: :string, age: :integer } # # The +associations+ hash looks like this: - # { :posts => { :has_many => :posts } } + # { posts: { has_many: :posts } } # # If :key is used: # # class PostsSerializer < ActiveModel::Serializer - # has_many :posts, :key => :my_posts + # has_many :posts, key: :my_posts # end # # the hash looks like this: # - # { :my_posts => { :has_many => :posts } + # { my_posts: { has_many: :posts } # # This information is extracted from the serializer's model class, # which is provided by +SerializerClass.model_class+. @@ -232,7 +232,7 @@ def schema end end - { :attributes => attrs, :associations => associations } + { attributes: attrs, associations: associations } end # The model class associated with this serializer. @@ -244,7 +244,7 @@ def model_class # # embed :objects # Embed associations as full objects # embed :ids # Embed only the association ids - # embed :ids, :include => true # Embed the association ids and include objects in the root + # embed :ids, include: true # Embed the association ids and include objects in the root # def embed(type, options={}) self._embed = type @@ -323,7 +323,7 @@ def url_options # Returns a json representation of the serializable # object including the root. def as_json(args={}) - super(:root => args.fetch(:root, options.fetch(:root, root_name))) + super(root: args.fetch(:root, options.fetch(:root, root_name))) end def serialize_object @@ -451,8 +451,8 @@ def instrument(name, payload = {}, &block) def default_embed_options { - :embed => _embed, - :include => _root_embed + embed: _embed, + include: _root_embed } end end diff --git a/lib/active_model/serializer/associations.rb b/lib/active_model/serializer/associations.rb index 888b94f..1f2b0b5 100644 --- a/lib/active_model/serializer/associations.rb +++ b/lib/active_model/serializer/associations.rb @@ -12,7 +12,7 @@ class Association #:nodoc: # embed: Define how associations should be embedded. # - :objects # Embed associations as full objects. # - :ids # Embed only the association ids. - # - :ids, :include => true # Embed the association ids and include objects in the root. + # - :ids, include: true # Embed the association ids and include objects in the root. # # include: Used in conjunction with embed :ids. Includes the objects in the root. # @@ -158,8 +158,8 @@ def serialize_ids if polymorphic? { - :type => polymorphic_key, - :id => id + type: polymorphic_key, + id: id } else id diff --git a/lib/active_model_serializers.rb b/lib/active_model_serializers.rb index a708585..c1357c7 100644 --- a/lib/active_model_serializers.rb +++ b/lib/active_model_serializers.rb @@ -74,8 +74,8 @@ def active_model_serializer Set.send(:include, ActiveModel::ArraySerializerSupport) { - :active_record => 'ActiveRecord::Relation', - :mongoid => 'Mongoid::Criteria' + active_record: 'ActiveRecord::Relation', + mongoid: 'Mongoid::Criteria' }.each do |orm, rel_class| ActiveSupport.on_load(orm) do include ActiveModel::SerializerSupport diff --git a/lib/generators/serializer/serializer_generator.rb b/lib/generators/serializer/serializer_generator.rb index 0da6c87..129da44 100644 --- a/lib/generators/serializer/serializer_generator.rb +++ b/lib/generators/serializer/serializer_generator.rb @@ -2,11 +2,11 @@ module Rails module Generators class SerializerGenerator < NamedBase source_root File.expand_path("../templates", __FILE__) - check_class_collision :suffix => "Serializer" + check_class_collision suffix: "Serializer" - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, type: :array, default: [], banner: "field:type field:type" - class_option :parent, :type => :string, :desc => "The parent class for the generated serializer" + class_option :parent, type: :string, desc: "The parent class for the generated serializer" def create_serializer_file template 'serializer.rb', File.join('app/serializers', class_path, "#{file_name}_serializer.rb") Fromc3fa96456cMon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Wed, 29 May 2013 23:13:37 -0600 Subject: [PATCH 55/66] upgrade hash syntax in tests --- test/array_serializer_test.rb | 50 +-- test/association_test.rb | 228 +++++----- test/no_serialization_scope_test.rb | 6 +- test/serialization_scope_name_test.rb | 6 +- test/serialization_test.rb | 102 ++--- test/serializer_test.rb | 776 +++++++++++++++++----------------- test/test_fakes.rb | 36 +- 7 files changed, 602 insertions(+), 602 deletions(-) diff --git a/test/array_serializer_test.rb b/test/array_serializer_test.rb index f335382..d48e802 100644 --- a/test/array_serializer_test.rb +++ b/test/array_serializer_test.rb @@ -6,63 +6,63 @@ class ArraySerializerTest < ActiveModel::TestCase def test_array_serializer model = Model.new user = User.new - comments = Comment.new(:title => "Comment1", :id => 1) + comments = Comment.new(title: "Comment1", id: 1) array = [model, user, comments] - serializer = array.active_model_serializer.new(array, :scope => {:scope => true}) + serializer = array.active_model_serializer.new(array, scope: { scope: true }) assert_equal([ - { :model => "Model" }, - { :last_name => "Valim", :ok => true, :first_name => "Jose", :scope => true }, - { :title => "Comment1" } + { model: "Model" }, + { last_name: "Valim", ok: true, first_name: "Jose", scope: true }, + { title: "Comment1" } ], serializer.as_json) end def test_array_serializer_with_root - comment1 = Comment.new(:title => "Comment1", :id => 1) - comment2 = Comment.new(:title => "Comment2", :id => 2) + comment1 = Comment.new(title: "Comment1", id: 1) + comment2 = Comment.new(title: "Comment2", id: 2) array = [ comment1, comment2 ] - serializer = array.active_model_serializer.new(array, :root => :comments) + serializer = array.active_model_serializer.new(array, root: :comments) - assert_equal({ :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + assert_equal({ comments: [ + { title: "Comment1" }, + { title: "Comment2" } ]}, serializer.as_json) end def test_active_model_with_root - comment1 = ModelWithActiveModelSerializer.new(:title => "Comment1") - comment2 = ModelWithActiveModelSerializer.new(:title => "Comment2") + comment1 = ModelWithActiveModelSerializer.new(title: "Comment1") + comment2 = ModelWithActiveModelSerializer.new(title: "Comment2") array = [ comment1, comment2 ] - serializer = array.active_model_serializer.new(array, :root => :comments) + serializer = array.active_model_serializer.new(array, root: :comments) - assert_equal({ :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + assert_equal({ comments: [ + { title: "Comment1" }, + { title: "Comment2" } ]}, serializer.as_json) end def test_array_serializer_with_hash - hash = {:value => "something"} + hash = { value: "something" } array = [hash] - serializer = array.active_model_serializer.new(array, :root => :items) - assert_equal({ :items => [ hash.as_json ]}, serializer.as_json) + serializer = array.active_model_serializer.new(array, root: :items) + assert_equal({ items: [hash.as_json] }, serializer.as_json) end def test_array_serializer_with_specified_serializer - post1 = Post.new(:title => "Post1", :author => "Author1", :id => 1) - post2 = Post.new(:title => "Post2", :author => "Author2", :id => 2) + post1 = Post.new(title: "Post1", author: "Author1", id: 1) + post2 = Post.new(title: "Post2", author: "Author2", id: 2) array = [ post1, post2 ] - serializer = array.active_model_serializer.new array, :each_serializer => CustomPostSerializer + serializer = array.active_model_serializer.new array, each_serializer: CustomPostSerializer assert_equal([ - { :title => "Post1" }, - { :title => "Post2" } + { title: "Post1" }, + { title: "Post2" } ], serializer.as_json) end diff --git a/test/association_test.rb b/test/association_test.rb index 2cfbd96..3ae225a 100644 --- a/test/association_test.rb +++ b/test/association_test.rb @@ -15,7 +15,7 @@ def read_attribute_for_serialization(name) end def as_json(*) - { :model => "Model" } + { model: "Model" } end def method_missing(meth, *args) @@ -33,8 +33,8 @@ def setup @hash = {} @root_hash = {} - @post = Model.new(:title => "New Post", :body => "Body") - @comment = Model.new(:id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT") + @post = Model.new(title: "New Post", body: "Body") + @comment = Model.new(id: 1, external_id: "COMM001", body: "ZOMG A COMMENT") @post.comments = [ @comment ] @post.comment = @comment @@ -46,66 +46,66 @@ def setup attributes :title, :body end - @post_serializer = @post_serializer_class.new(@post, :hash => @root_hash) + @post_serializer = @post_serializer_class.new(@post, hash: @root_hash) end def include!(key, options={}) @post_serializer.include! key, { - :embed => :ids, - :include => true, - :node => @hash, - :serializer => @comment_serializer_class + embed: :ids, + include: true, + node: @hash, + serializer: @comment_serializer_class }.merge(options) end def include_bare!(key, options={}) @post_serializer.include! key, { - :node => @hash, - :serializer => @comment_serializer_class + node: @hash, + serializer: @comment_serializer_class }.merge(options) end class NoDefaults < AssociationTest def test_include_bang_has_many_associations - include! :comments, :value => @post.comments + include! :comments, value: @post.comments assert_equal({ - :comment_ids => [ 1 ] + comment_ids: [ 1 ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_include_bang_with_embed_false - include! :comments, :value => @post.comments, :embed => false + include! :comments, value: @post.comments, embed: false assert_equal({}, @hash) assert_equal({}, @root_hash) end def test_include_bang_with_embed_ids_include_false - include! :comments, :value => @post.comments, :embed => :ids, :include => false + include! :comments, value: @post.comments, embed: :ids, include: false assert_equal({ - :comment_ids => [ 1 ] + comment_ids: [ 1 ] }, @hash) assert_equal({}, @root_hash) end def test_include_bang_has_one_associations - include! :comment, :value => @post.comment + include! :comment, value: @post.comment assert_equal({ - :comment_id => 1 + comment_id: 1 }, @hash) assert_equal({ - :comments => [{ :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" }] + comments: [{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }] }, @root_hash) end end @@ -119,12 +119,12 @@ def test_with_default_has_many include! :comments assert_equal({ - :comment_ids => [ 1 ] + comment_ids: [ 1 ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end @@ -137,134 +137,134 @@ def test_with_default_has_one include! :comment assert_equal({ - :comment_id => 1 + comment_id: 1 }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_many_with_custom_key @post_serializer_class.class_eval do - has_many :comments, :key => :custom_comments + has_many :comments, key: :custom_comments end include! :comments assert_equal({ - :custom_comments => [ 1 ] + custom_comments: [ 1 ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_one_with_custom_key @post_serializer_class.class_eval do - has_one :comment, :key => :custom_comment_id + has_one :comment, key: :custom_comment_id end include! :comment assert_equal({ - :custom_comment_id => 1 + custom_comment_id: 1 }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_many_with_custom_embed_key @post_serializer_class.class_eval do - has_many :comments, :embed_key => :external_id + has_many :comments, embed_key: :external_id end include! :comments assert_equal({ - :comment_ids => [ "COMM001" ] + comment_ids: [ "COMM001" ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_one_with_custom_embed_key @post_serializer_class.class_eval do - has_one :comment, :embed_key => :external_id + has_one :comment, embed_key: :external_id end include! :comment assert_equal({ - :comment_id => "COMM001" + comment_id: "COMM001" }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_many_with_custom_key_and_custom_embed_key @post_serializer_class.class_eval do - has_many :comments, :key => :custom_comments, :embed_key => :external_id + has_many :comments, key: :custom_comments, embed_key: :external_id end include! :comments assert_equal({ - :custom_comments => [ "COMM001" ] + custom_comments: [ "COMM001" ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_with_default_has_one_with_custom_key_and_custom_embed_key @post_serializer_class.class_eval do - has_one :comment, :key => :custom_comment, :embed_key => :external_id + has_one :comment, key: :custom_comment, embed_key: :external_id end include! :comment assert_equal({ - :custom_comment => "COMM001" + custom_comment: "COMM001" }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_embed_objects_for_has_many_associations @post_serializer_class.class_eval do - has_many :comments, :embed => :objects + has_many :comments, embed: :objects end include_bare! :comments assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @hash) @@ -273,13 +273,13 @@ def test_embed_objects_for_has_many_associations def test_embed_ids_for_has_many_associations @post_serializer_class.class_eval do - has_many :comments, :embed => :ids + has_many :comments, embed: :ids end include_bare! :comments assert_equal({ - :comment_ids => [ 1 ] + comment_ids: [ 1 ] }, @hash) assert_equal({}, @root_hash) @@ -287,7 +287,7 @@ def test_embed_ids_for_has_many_associations def test_embed_false_for_has_many_associations @post_serializer_class.class_eval do - has_many :comments, :embed => false + has_many :comments, embed: false end include_bare! :comments @@ -298,31 +298,31 @@ def test_embed_false_for_has_many_associations def test_embed_ids_include_true_for_has_many_associations @post_serializer_class.class_eval do - has_many :comments, :embed => :ids, :include => true + has_many :comments, embed: :ids, include: true end include_bare! :comments assert_equal({ - :comment_ids => [ 1 ] + comment_ids: [ 1 ] }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end def test_embed_ids_for_has_one_associations @post_serializer_class.class_eval do - has_one :comment, :embed => :ids + has_one :comment, embed: :ids end include_bare! :comment assert_equal({ - :comment_id => 1 + comment_id: 1 }, @hash) assert_equal({}, @root_hash) @@ -330,7 +330,7 @@ def test_embed_ids_for_has_one_associations def test_embed_false_for_has_one_associations @post_serializer_class.class_eval do - has_one :comment, :embed => false + has_one :comment, embed: false end include_bare! :comment @@ -341,18 +341,18 @@ def test_embed_false_for_has_one_associations def test_embed_ids_include_true_for_has_one_associations @post_serializer_class.class_eval do - has_one :comment, :embed => :ids, :include => true + has_one :comment, embed: :ids, include: true end include_bare! :comment assert_equal({ - :comment_id => 1 + comment_id: 1 }, @hash) assert_equal({ - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, @root_hash) end @@ -361,8 +361,8 @@ def test_embed_ids_include_true_does_not_serialize_multiple_times @post.recent_comment = @comment @post_serializer_class.class_eval do - has_one :comment, :embed => :ids, :include => true - has_one :recent_comment, :embed => :ids, :include => true, :root => :comments + has_one :comment, embed: :ids, include: true + has_one :recent_comment, embed: :ids, include: true, root: :comments end # Count how often the @comment record is serialized. @@ -382,7 +382,7 @@ def test_embed_ids_include_true_does_not_serialize_multiple_times def test_include_with_read_association_id_for_serialization_hook @post_serializer_class.class_eval do - has_one :comment, :embed => :ids, :include => true + has_one :comment, embed: :ids, include: true end association_name = nil @@ -399,13 +399,13 @@ def test_include_with_read_association_id_for_serialization_hook include_bare! :comment assert_equal({ - :comment_id => 1 + comment_id: 1 }, @hash) end def test_include_with_read_association_ids_for_serialization_hook @post_serializer_class.class_eval do - has_many :comments, :embed => :ids, :include => false + has_many :comments, embed: :ids, include: false end association_name = nil @@ -422,7 +422,7 @@ def test_include_with_read_association_ids_for_serialization_hook include_bare! :comments assert_equal({ - :comment_ids => [1] + comment_ids: [1] }, @hash) end end @@ -433,13 +433,13 @@ class BarSerializer < ActiveModel::Serializer; end class FooSerializer < ActiveModel::Serializer root :foos attributes :id - has_many :bars, :serializer => BarSerializer, :root => :bars, :embed => :ids, :include => true + has_many :bars, serializer: BarSerializer, root: :bars, embed: :ids, include: true end class BarSerializer < ActiveModel::Serializer root :bars attributes :id - has_many :foos, :serializer => FooSerializer, :root => :foos, :embed => :ids, :include => true + has_many :foos, serializer: FooSerializer, root: :foos, embed: :ids, include: true end class Foo < Model @@ -453,26 +453,26 @@ def active_model_serializer; BarSerializer; end def setup super - foo = Foo.new(:id => 1) - bar = Bar.new(:id => 2) + foo = Foo.new(id: 1) + bar = Bar.new(id: 2) foo.bars = [ bar ] bar.foos = [ foo ] collection = [ foo ] - @serializer = collection.active_model_serializer.new(collection, :root => :foos) + @serializer = collection.active_model_serializer.new(collection, root: :foos) end def test_mutual_relation_result assert_equal({ - :foos => [{ - :bar_ids => [ 2 ], - :id => 1 + foos: [{ + bar_ids: [ 2 ], + id: 1 }], - :bars => [{ - :foo_ids => [ 1 ], - :id => 2 + bars: [{ + foo_ids: [ 1 ], + id: 2 }] }, @serializer.as_json) end @@ -492,77 +492,77 @@ def setup @post_serializer_class.class_eval do root :post - embed :ids, :include => true - has_many :comments, :serializer => comment_serializer_class + embed :ids, include: true + has_many :comments, serializer: comment_serializer_class end end def test_when_it_is_included post_serializer = @post_serializer_class.new( - @post, :include => [:comments] + @post, include: [:comments] ) json = post_serializer.as_json assert_equal({ - :post => { - :title => "New Post", - :body => "Body", - :comment_ids => [ 1 ] + post: { + title: "New Post", + body: "Body", + comment_ids: [ 1 ] }, - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, json) end def test_when_it_is_not_included post_serializer = @post_serializer_class.new( - @post, :include => [] + @post, include: [] ) json = post_serializer.as_json assert_equal({ - :post => { - :title => "New Post", - :body => "Body", - :comment_ids => [ 1 ] + post: { + title: "New Post", + body: "Body", + comment_ids: [ 1 ] } }, json) end def test_when_it_is_excluded post_serializer = @post_serializer_class.new( - @post, :exclude => [:comments] + @post, exclude: [:comments] ) json = post_serializer.as_json assert_equal({ - :post => { - :title => "New Post", - :body => "Body", - :comment_ids => [ 1 ] + post: { + title: "New Post", + body: "Body", + comment_ids: [ 1 ] } }, json) end def test_when_it_is_not_excluded post_serializer = @post_serializer_class.new( - @post, :exclude => [] + @post, exclude: [] ) json = post_serializer.as_json assert_equal({ - :post => { - :title => "New Post", - :body => "Body", - :comment_ids => [ 1 ] + post: { + title: "New Post", + body: "Body", + comment_ids: [ 1 ] }, - :comments => [ - { :id => 1, :external_id => "COMM001", :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" } ] }, json) end @@ -575,14 +575,14 @@ class StringSerializer < ActiveModel::Serializer def test_specifying_serializer_class_as_string @post_serializer_class.class_eval do - has_many :comments, :embed => :objects + has_many :comments, embed: :objects end - include_bare! :comments, :serializer => "AssociationTest::StringSerializerOption::StringSerializer" + include_bare! :comments, serializer: "AssociationTest::StringSerializerOption::StringSerializer" assert_equal({ - :comments => [ - { :id => 1, :body => "ZOMG A COMMENT" } + comments: [ + { id: 1, body: "ZOMG A COMMENT" } ] }, @hash) diff --git a/test/no_serialization_scope_test.rb b/test/no_serialization_scope_test.rb index 719ce4b..31ba475 100644 --- a/test/no_serialization_scope_test.rb +++ b/test/no_serialization_scope_test.rb @@ -7,7 +7,7 @@ def initialize(object, options) end def as_json(*) - { :scope => @options[:scope].as_json } + { scope: @options[:scope].as_json } end end @@ -21,14 +21,14 @@ class NoSerializationScopeController < ActionController::Base serialization_scope nil def index - render :json => ScopeSerializable.new + render json: ScopeSerializable.new end end tests NoSerializationScopeController def test_disabled_serialization_scope - get :index, :format => :json + get :index, format: :json assert_equal '{"scope":null}', @response.body end end diff --git a/test/serialization_scope_name_test.rb b/test/serialization_scope_name_test.rb index bc9c87b..a5e164c 100644 --- a/test/serialization_scope_name_test.rb +++ b/test/serialization_scope_name_test.rb @@ -21,7 +21,7 @@ def current_user end def render_new_user - render :json => TestUser.new('pete', false), :serializer => UserSerializer + render json: TestUser.new('pete', false), serializer: UserSerializer end end @@ -54,7 +54,7 @@ def current_admin end def render_new_user - render :json => TestUser.new('pete', false), :serializer => AdminUserSerializer + render json: TestUser.new('pete', false), serializer: AdminUserSerializer end end @@ -85,7 +85,7 @@ def current_admin end def render_new_user - render :json => TestUser.new('pete', false), :serializer => AdminUserSerializer, :scope => current_admin, :scope_name => :current_admin + render json: TestUser.new('pete', false), serializer: AdminUserSerializer, scope: current_admin, scope_name: :current_admin end end diff --git a/test/serialization_test.rb b/test/serialization_test.rb index c5e1bbe..6fe5075 100644 --- a/test/serialization_test.rb +++ b/test/serialization_test.rb @@ -4,13 +4,13 @@ class RenderJsonTest < ActionController::TestCase class JsonRenderable def as_json(options={}) - hash = { :a => :b, :c => :d, :e => :f } + hash = { a: :b, c: :d, e: :f } hash.except!(*options[:except]) if options[:except] hash end def to_json(options = {}) - super :except => [:c, :e] + super except: [:c, :e] end end @@ -20,9 +20,9 @@ def initialize(object, options={}) end def as_json(*) - hash = { :object => serializable_hash, :scope => @options[:scope].as_json } - hash.merge!(:options => true) if @options[:options] - hash.merge!(:check_defaults => true) if @options[:check_defaults] + hash = { object: serializable_hash, scope: @options[:scope].as_json } + hash.merge!(options: true) if @options[:options] + hash.merge!(check_defaults: true) if @options[:check_defaults] hash end @@ -41,7 +41,7 @@ def active_model_serializer end def as_json(*) - { :serializable_object => true } + { serializable_object: true } end end @@ -50,7 +50,7 @@ def initialize(*) end def as_json(*) - { :hello => true } + { hello: true } end end @@ -59,7 +59,7 @@ def initialize(*) end def as_json(*) - { :rails => 'rocks' } + { rails: 'rocks' } end end @@ -75,7 +75,7 @@ def active_model_serializer class HypermediaSerializer < ActiveModel::Serializer def as_json(*) - { :link => hypermedia_url } + { link: hypermedia_url } end end @@ -94,111 +94,111 @@ def self.controller_path end def render_json_nil - render :json => nil + render json: nil end def render_json_render_to_string - render :text => render_to_string(:json => '[]') + render text: render_to_string(json: '[]') end def render_json_hello_world - render :json => ActiveSupport::JSON.encode(:hello => 'world') + render json: ActiveSupport::JSON.encode(hello: 'world') end def render_json_hello_world_with_status - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :status => 401 + render json: ActiveSupport::JSON.encode(hello: 'world'), status: 401 end def render_json_hello_world_with_callback - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert' + render json: ActiveSupport::JSON.encode(hello: 'world'), callback: 'alert' end def render_json_with_custom_content_type - render :json => ActiveSupport::JSON.encode(:hello => 'world'), :content_type => 'text/javascript' + render json: ActiveSupport::JSON.encode(hello: 'world'), content_type: 'text/javascript' end def render_symbol_json - render :json => ActiveSupport::JSON.encode(:hello => 'world') + render json: ActiveSupport::JSON.encode(hello: 'world') end def render_json_nil_with_custom_serializer - render :json => nil, :serializer => DummyCustomSerializer + render json: nil, serializer: DummyCustomSerializer end def render_json_with_extra_options - render :json => JsonRenderable.new, :except => [:c, :e] + render json: JsonRenderable.new, except: [:c, :e] end def render_json_without_options - render :json => JsonRenderable.new + render json: JsonRenderable.new end def render_json_with_serializer - @current_user = Struct.new(:as_json).new(:current_user => true) - render :json => JsonSerializable.new + @current_user = Struct.new(:as_json).new(current_user: true) + render json: JsonSerializable.new end def render_json_with_serializer_and_implicit_root - @current_user = Struct.new(:as_json).new(:current_user => true) - render :json => [JsonSerializable.new] + @current_user = Struct.new(:as_json).new(current_user: true) + render json: [JsonSerializable.new] end def render_json_with_serializer_and_options - @current_user = Struct.new(:as_json).new(:current_user => true) - render :json => JsonSerializable.new, :options => true + @current_user = Struct.new(:as_json).new(current_user: true) + render json: JsonSerializable.new, options: true end def render_json_with_serializer_and_scope_option - @current_user = Struct.new(:as_json).new(:current_user => true) - scope = Struct.new(:as_json).new(:current_user => false) - render :json => JsonSerializable.new, :scope => scope + @current_user = Struct.new(:as_json).new(current_user: true) + scope = Struct.new(:as_json).new(current_user: false) + render json: JsonSerializable.new, scope: scope end def render_json_with_serializer_api_but_without_serializer - @current_user = Struct.new(:as_json).new(:current_user => true) - render :json => JsonSerializable.new(true) + @current_user = Struct.new(:as_json).new(current_user: true) + render json: JsonSerializable.new(true) end # To specify a custom serializer for an object, use :serializer. def render_json_with_custom_serializer - render :json => Object.new, :serializer => CustomSerializer + render json: Object.new, serializer: CustomSerializer end # To specify a custom serializer for each item in the Array, use :each_serializer. def render_json_array_with_custom_serializer - render :json => [Object.new], :each_serializer => CustomSerializer + render json: [Object.new], each_serializer: CustomSerializer end def render_json_array_with_wrong_option - render :json => [Object.new], :serializer => CustomSerializer + render json: [Object.new], serializer: CustomSerializer end def render_json_with_links - render :json => HypermediaSerializable.new + render json: HypermediaSerializable.new end def render_json_array_with_no_root - render :json => [], :root => false + render json: [], root: false end def render_json_empty_array - render :json => [] + render json: [] end def render_json_array_with_custom_array_serializer - render :json => [], :serializer => CustomArraySerializer + render json: [], serializer: CustomArraySerializer end private def default_serializer_options defaults = {} - defaults.merge!(:check_defaults => true) if params[:check_defaults] - defaults.merge!(:root => :awesome) if params[:check_default_root] - defaults.merge!(:scope => :current_admin) if params[:check_default_scope] - defaults.merge!(:serializer => AnotherCustomSerializer) if params[:check_default_serializer] - defaults.merge!(:each_serializer => AnotherCustomSerializer) if params[:check_default_each_serializer] + defaults.merge!(check_defaults: true) if params[:check_defaults] + defaults.merge!(root: :awesome) if params[:check_default_root] + defaults.merge!(scope: :current_admin) if params[:check_default_scope] + defaults.merge!(serializer: AnotherCustomSerializer) if params[:check_default_serializer] + defaults.merge!(each_serializer: AnotherCustomSerializer) if params[:check_default_each_serializer] defaults end end @@ -279,19 +279,19 @@ def test_render_json_with_serializer end def test_render_json_with_serializer_checking_defaults - get :render_json_with_serializer, :check_defaults => true + get :render_json_with_serializer, check_defaults: true assert_match '"scope":{"current_user":true}', @response.body assert_match '"object":{"serializable_object":true}', @response.body assert_match '"check_defaults":true', @response.body end def test_render_json_with_serializer_checking_default_serailizer - get :render_json_with_serializer, :check_default_serializer => true + get :render_json_with_serializer, check_default_serializer: true assert_match '{"rails":"rocks"}', @response.body end def test_render_json_with_serializer_checking_default_scope - get :render_json_with_serializer, :check_default_scope => true + get :render_json_with_serializer, check_default_scope: true assert_match '"scope":"current_admin"', @response.body end @@ -301,7 +301,7 @@ def test_render_json_with_serializer_and_implicit_root end def test_render_json_with_serializer_and_implicit_root_checking_default_each_serailizer - get :render_json_with_serializer_and_implicit_root, :check_default_each_serializer => true + get :render_json_with_serializer_and_implicit_root, check_default_each_serializer: true assert_match '"test":[{"rails":"rocks"}]', @response.body end @@ -318,7 +318,7 @@ def test_render_json_with_serializer_and_scope_option end def test_render_json_with_serializer_and_scope_option_checking_default_scope - get :render_json_with_serializer_and_scope_option, :check_default_scope => true + get :render_json_with_serializer_and_scope_option, check_default_scope: true assert_match '"scope":{"current_user":false}', @response.body end @@ -333,7 +333,7 @@ def test_render_json_with_custom_serializer end def test_render_json_with_custom_serializer_checking_default_serailizer - get :render_json_with_custom_serializer, :check_default_serializer => true + get :render_json_with_custom_serializer, check_default_serializer: true assert_match '{"hello":true}', @response.body end @@ -349,7 +349,7 @@ def test_render_json_array_with_wrong_option end def test_render_json_array_with_custom_serializer_checking_default_each_serailizer - get :render_json_array_with_custom_serializer, :check_default_each_serializer => true + get :render_json_array_with_custom_serializer, check_default_each_serializer: true assert_match '{"test":[{"hello":true}]}', @response.body end @@ -364,7 +364,7 @@ def test_render_json_array_with_no_root end def test_render_json_array_with_no_root_checking_default_root - get :render_json_array_with_no_root, :check_default_root => true + get :render_json_array_with_no_root, check_default_root: true assert_equal '[]', @response.body end @@ -374,7 +374,7 @@ def test_render_json_empty_array end def test_render_json_empty_array_checking_default_root - get :render_json_empty_array, :check_default_root => true + get :render_json_empty_array, check_default_root: true assert_equal '{"awesome":[]}', @response.body end diff --git a/test/serializer_test.rb b/test/serializer_test.rb index 588da1c..5da28d8 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -3,7 +3,7 @@ class SerializerTest < ActiveModel::TestCase def test_scope_works_correct - serializer = ActiveModel::Serializer.new :foo, :scope => :bar + serializer = ActiveModel::Serializer.new :foo, scope: :bar assert_equal serializer.scope, :bar end @@ -14,51 +14,51 @@ def test_attributes hash = user_serializer.as_json assert_equal({ - :default_user => { :first_name => "Jose", :last_name => "Valim" } + default_user: { first_name: "Jose", last_name: "Valim" } }, hash) end def test_attributes_method user = User.new - user_serializer = UserSerializer.new(user, :scope => {}) + user_serializer = UserSerializer.new(user, scope: {}) hash = user_serializer.as_json assert_equal({ - :user => { :first_name => "Jose", :last_name => "Valim", :ok => true } + user: { first_name: "Jose", last_name: "Valim", ok: true } }, hash) end def test_attributes_method_specifying_keys user = User.new - user_serializer = UserAttributesWithKeySerializer.new(user, :scope => {}) + user_serializer = UserAttributesWithKeySerializer.new(user, scope: {}) hash = user_serializer.as_json assert_equal({ - :user_attributes_with_key => { :f_name => "Jose", :l_name => "Valim", :ok => true } + user_attributes_with_key: { f_name: "Jose", l_name: "Valim", ok: true } }, hash) end def test_attributes_method_specifying_some_keys user = User.new - user_serializer = UserAttributesWithSomeKeySerializer.new(user, :scope => {}) + user_serializer = UserAttributesWithSomeKeySerializer.new(user, scope: {}) hash = user_serializer.as_json assert_equal({ - :user_attributes_with_some_key => { :first_name => "Jose", :l_name => "Valim", :ok => true } + user_attributes_with_some_key: { first_name: "Jose", l_name: "Valim", ok: true } }, hash) end def test_attributes_method_with_unsymbolizable_key user = User.new - user_serializer = UserAttributesWithUnsymbolizableKeySerializer.new(user, :scope => {}) + user_serializer = UserAttributesWithUnsymbolizableKeySerializer.new(user, scope: {}) hash = user_serializer.as_json assert_equal({ - :user_attributes_with_unsymbolizable_key => { :first_name => "Jose", :"last-name" => "Valim", :ok => true } + user_attributes_with_unsymbolizable_key: { first_name: "Jose", :"last-name" => "Valim", ok: true } }, hash) end @@ -69,30 +69,30 @@ def test_attribute_method_with_name_as_serializer_prefix hash = object_serializer.as_json assert_equal({ - :some => { :some => "something" } + some: { some: "something" } }, hash) end def test_serializer_receives_scope user = User.new - user_serializer = UserSerializer.new(user, :scope => {:scope => true}) + user_serializer = UserSerializer.new(user, scope: { scope: true }) hash = user_serializer.as_json assert_equal({ - :user => { - :first_name => "Jose", - :last_name => "Valim", - :ok => true, - :scope => true + user: { + first_name: "Jose", + last_name: "Valim", + ok: true, + scope: true } }, hash) end def test_serializer_receives_url_options user = User.new - user_serializer = UserSerializer.new(user, :url_options => { :host => "test.local" }) - assert_equal({ :host => "test.local" }, user_serializer.url_options) + user_serializer = UserSerializer.new(user, url_options: { host: "test.local" }) + assert_equal({ host: "test.local" }, user_serializer.url_options) end def test_serializer_returns_empty_hash_without_url_options @@ -109,8 +109,8 @@ def test_pretty_accessors hash = user_serializer.as_json assert_equal({ - :my_user => { - :first_name => "Jose", :last_name => "Valim", :super_user => true + my_user: { + first_name: "Jose", last_name: "Valim", super_user: true } }, hash) end @@ -118,19 +118,19 @@ def test_pretty_accessors def test_has_many user = User.new - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1"), Comment.new(:title => "Comment2")] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1"), Comment.new(title: "Comment2")] post.comments = comments - post_serializer = PostSerializer.new(post, :scope => user) + post_serializer = PostSerializer.new(post, scope: user) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + post: { + title: "New Post", + body: "Body of new post", + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ] } }, post_serializer.as_json) @@ -139,21 +139,21 @@ def test_has_many def test_conditionally_included_associations user = User.new - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1"), Comment.new(:title => "Comment2")] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1"), Comment.new(title: "Comment2")] post.comments = comments - post_serializer = PostWithConditionalCommentsSerializer.new(post, :scope => user) + post_serializer = PostWithConditionalCommentsSerializer.new(post, scope: user) # comments enabled post.comments_disabled = false assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + post: { + title: "New Post", + body: "Body of new post", + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ] } }, post_serializer.as_json) @@ -161,9 +161,9 @@ def test_conditionally_included_associations # comments disabled post.comments_disabled = true assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post" + post: { + title: "New Post", + body: "Body of new post" } }, post_serializer.as_json) end @@ -171,21 +171,21 @@ def test_conditionally_included_associations def test_conditionally_included_associations_and_attributes user = User.new - post = Post.new(:title => "New Post", :body => "Body of new post", :author => 'Sausage King', :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1"), Comment.new(:title => "Comment2")] + post = Post.new(title: "New Post", body: "Body of new post", author: 'Sausage King', email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1"), Comment.new(title: "Comment2")] post.comments = comments - post_serializer = PostWithMultipleConditionalsSerializer.new(post, :scope => user) + post_serializer = PostWithMultipleConditionalsSerializer.new(post, scope: user) # comments enabled post.comments_disabled = false assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + post: { + title: "New Post", + body: "Body of new post", + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ] } }, post_serializer.as_json) @@ -193,19 +193,19 @@ def test_conditionally_included_associations_and_attributes # comments disabled post.comments_disabled = true assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post" + post: { + title: "New Post", + body: "Body of new post" } }, post_serializer.as_json) # superuser - should see author user.superuser = true assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :author => "Sausage King" + post: { + title: "New Post", + body: "Body of new post", + author: "Sausage King" } }, post_serializer.as_json) end @@ -215,12 +215,12 @@ def test_has_one blog = Blog.new blog.author = user - json = BlogSerializer.new(blog, :scope => user).as_json + json = BlogSerializer.new(blog, scope: user).as_json assert_equal({ - :blog => { - :author => { - :first_name => "Jose", - :last_name => "Valim" + blog: { + author: { + first_name: "Jose", + last_name: "Valim" } } }, json) @@ -236,17 +236,17 @@ def person object.author end - has_one :person, :serializer => author_serializer + has_one :person, serializer: author_serializer end user = User.new blog = Blog.new blog.author = user - json = blog_serializer.new(blog, :scope => user).as_json + json = blog_serializer.new(blog, scope: user).as_json assert_equal({ - :person => { - :first_name => "Jose" + person: { + first_name: "Jose" } }, json) end @@ -254,8 +254,8 @@ def person def post_serializer Class.new(ActiveModel::Serializer) do attributes :title, :body - has_many :comments, :serializer => CommentSerializer - has_one :author, :serializer => DefaultUserSerializer + has_many :comments, serializer: CommentSerializer + has_one :author, serializer: DefaultUserSerializer end end @@ -263,17 +263,17 @@ def test_associations_with_nil_association user = User.new blog = Blog.new - json = BlogSerializer.new(blog, :scope => user).as_json + json = BlogSerializer.new(blog, scope: user).as_json assert_equal({ - :blog => { :author => nil } + blog: { author: nil } }, json) serializer = Class.new(BlogSerializer) do root :blog end - json = serializer.new(blog, :scope => user).as_json - assert_equal({ :blog => { :author => nil } }, json) + json = serializer.new(blog, scope: user).as_json + assert_equal({ blog: { author: nil } }, json) end def test_custom_root @@ -284,7 +284,7 @@ def test_custom_root root :my_blog end - assert_equal({ :my_blog => { :author => nil } }, serializer.new(blog, :scope => user).as_json) + assert_equal({ my_blog: { author: nil } }, serializer.new(blog, scope: user).as_json) end def test_nil_root_object @@ -295,7 +295,7 @@ def test_nil_root_object root false end - assert_equal(nil, serializer.new(blog, :scope => user).as_json) + assert_equal(nil, serializer.new(blog, scope: user).as_json) end def test_custom_root_with_nil_root_object @@ -306,7 +306,7 @@ def test_custom_root_with_nil_root_object root :my_blog end - assert_equal({ :my_blog => nil }, serializer.new(blog, :scope => user).as_json) + assert_equal({ my_blog: nil }, serializer.new(blog, scope: user).as_json) end def test_false_root @@ -321,20 +321,20 @@ def test_false_root self.root = false end - assert_equal({ :author => nil }, serializer.new(blog, :scope => user).as_json) - assert_equal({ :author => nil }, another_serializer.new(blog, :scope => user).as_json) + assert_equal({ author: nil }, serializer.new(blog, scope: user).as_json) + assert_equal({ author: nil }, another_serializer.new(blog, scope: user).as_json) # test inherited false root serializer = Class.new(serializer) - assert_equal({ :author => nil }, serializer.new(blog, :scope => user).as_json) + assert_equal({ author: nil }, serializer.new(blog, scope: user).as_json) end def test_true_root blog = Blog.new assert_equal({ - :blog_with_root => { - :author => nil, + blog_with_root: { + author: nil, } }, BlogWithRootSerializer.new(blog).as_json) end @@ -348,7 +348,7 @@ def test_root_false_on_load_active_model_serializers blog = Blog.new serializer = BlogSerializer.new(blog) - assert_equal({ :author => nil }, serializer.as_json) + assert_equal({ author: nil }, serializer.as_json) ensure ActiveSupport.on_load(:active_model_serializers) do self.root = nil @@ -364,18 +364,18 @@ def test_embed_ids embed :ids end - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments serializer = serializer.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comment_ids => [1, 2], - :author_id => nil + post: { + title: "New Post", + body: "Body of new post", + comment_ids: [1, 2], + author_id: nil } }, serializer.as_json) end @@ -385,45 +385,45 @@ def test_embed_ids_include_true serializer_class.class_eval do root :post - embed :ids, :include => true + embed :ids, include: true end - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments serializer = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comment_ids => [1, 2], - :author_id => nil + post: { + title: "New Post", + body: "Body of new post", + comment_ids: [1, 2], + author_id: nil }, - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ], - :authors => [] + authors: [] }, serializer.as_json) - post.author = User.new(:id => 1) + post.author = User.new(id: 1) serializer = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comment_ids => [1, 2], - :author_id => 1 + post: { + title: "New Post", + body: "Body of new post", + comment_ids: [1, 2], + author_id: 1 }, - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ], - :authors => [{ :first_name => "Jose", :last_name => "Valim" }] + authors: [{ first_name: "Jose", last_name: "Valim" }] }, serializer.as_json) end @@ -438,8 +438,8 @@ def comments end end - post = Post.new(:title => "My Post") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "My Post") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments post.class_eval do @@ -449,8 +449,8 @@ def comments end json = post_serializer.new(post).as_json assert_equal({ - :title => "My Post", - :comment_ids => [1] + title: "My Post", + comment_ids: [1] }, json) end @@ -463,7 +463,7 @@ def id post_serializer = Class.new(ActiveModel::Serializer) do attributes :title - has_many :comments, :serializer => comment_serializer + has_many :comments, serializer: comment_serializer embed :ids def comments @@ -471,8 +471,8 @@ def comments end end - post = Post.new(:title => "My Post") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "My Post") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments post.class_eval do @@ -482,8 +482,8 @@ def comments end json = post_serializer.new(post).as_json assert_equal({ - :title => "My Post", - :comment_ids => ["OMG"] + title: "My Post", + comment_ids: ["OMG"] }, json) end @@ -495,45 +495,45 @@ def test_embed_objects embed :objects end - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments serializer = serializer.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :author => nil, - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + post: { + title: "New Post", + body: "Body of new post", + author: nil, + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ] } }, serializer.as_json) end def test_sets_can_be_serialized - post1 = Post.new(:title => "Post1", :author => "Author1", :id => 1) - post2 = Post.new(:title => "Post2", :author => "Author2", :id => 2) + post1 = Post.new(title: "Post1", author: "Author1", id: 1) + post2 = Post.new(title: "Post2", author: "Author2", id: 2) set = Set.new set << post1 set << post2 - serializer = set.active_model_serializer.new set, :each_serializer => CustomPostSerializer + serializer = set.active_model_serializer.new set, each_serializer: CustomPostSerializer as_json = serializer.as_json assert_equal 2, as_json.size - assert as_json.include?({ :title => "Post1" }) - assert as_json.include?({ :title => "Post2" }) + assert as_json.include?({ title: "Post1" }) + assert as_json.include?({ title: "Post2" }) end def test_associations_with_as posts = [ - Post.new(:title => 'First Post', :body => 'text'), - Post.new(:title => 'Second Post', :body => 'text') + Post.new(title: 'First Post', body: 'text'), + Post.new(title: 'Second Post', body: 'text') ] user = User.new @@ -541,18 +541,18 @@ def test_associations_with_as custom_blog.public_posts = posts custom_blog.public_user = user - serializer = CustomBlogSerializer.new(custom_blog, :scope => { :scope => true }) + serializer = CustomBlogSerializer.new(custom_blog, scope: { scope: true }) assert_equal({ - :custom_blog => { - :posts => [ - {:title => 'First Post', :body => 'text', :comments => []}, - {:title => 'Second Post', :body => 'text', :comments => []} + custom_blog: { + posts: [ + {title: 'First Post', body: 'text', comments: []}, + {title: 'Second Post', body: 'text', comments: []} ], - :user => { - :first_name => "Jose", - :last_name => "Valim", :ok => true, - :scope => true + user: { + first_name: "Jose", + last_name: "Valim", ok: true, + scope: true } } }, serializer.as_json) @@ -564,13 +564,13 @@ def test_implicity_detection_for_association_serializers const_set(:UserSerializer, UserSerializer) const_set(:PostSerializer, PostSerializer) - has_many :public_posts, :key => :posts - has_one :public_user, :key => :user + has_many :public_posts, key: :posts + has_one :public_user, key: :user end posts = [ - Post.new(:title => 'First Post', :body => 'text', :comments => []), - Post.new(:title => 'Second Post', :body => 'text', :comments => []) + Post.new(title: 'First Post', body: 'text', comments: []), + Post.new(title: 'Second Post', body: 'text', comments: []) ] user = User.new @@ -578,18 +578,18 @@ def test_implicity_detection_for_association_serializers custom_blog.public_posts = posts custom_blog.public_user = user - serializer = implicit_serializer.new(custom_blog, :scope => { :scope => true }) + serializer = implicit_serializer.new(custom_blog, scope: { scope: true }) assert_equal({ - :custom_blog => { - :posts => [ - {:title => 'First Post', :body => 'text', :comments => []}, - {:title => 'Second Post', :body => 'text', :comments => []} + custom_blog: { + posts: [ + {title: 'First Post', body: 'text', comments: []}, + {title: 'Second Post', body: 'text', comments: []} ], - :user => { - :first_name => "Jose", - :last_name => "Valim", :ok => true, - :scope => true + user: { + first_name: "Jose", + last_name: "Valim", ok: true, + scope: true } } }, serializer.as_json) @@ -599,18 +599,18 @@ def test_attribute_key serializer_class = Class.new(ActiveModel::Serializer) do root :user - attribute :first_name, :key => :firstName - attribute :last_name, :key => :lastName + attribute :first_name, key: :firstName + attribute :last_name, key: :lastName attribute :password end serializer = serializer_class.new(User.new) assert_equal({ - :user => { - :firstName => "Jose", - :lastName => "Valim", - :password => "oh noes yugive my password" + user: { + firstName: "Jose", + lastName: "Valim", + password: "oh noes yugive my password" } }, serializer.as_json) end @@ -647,18 +647,18 @@ def can_edit; end def can_view; end def drafts; end - attributes :name, :age, {:can_edit => :boolean}, :can_view - has_many :posts, :serializer => Class.new - has_many :drafts, :serializer => Class.new - has_one :parent, :serializer => Class.new + attributes :name, :age, { can_edit: :boolean }, :can_view + has_many :posts, serializer: Class.new + has_many :drafts, serializer: Class.new + has_one :parent, serializer: Class.new end assert_equal serializer.schema, { - :attributes => { :name => :string, :age => :integer, :can_edit => :boolean, :can_view => nil }, - :associations => { - :posts => { :has_many => :posts }, - :drafts => nil, - :parent => { :belongs_to => :parent } + attributes: { name: :string, age: :integer, can_edit: :boolean, can_view: nil }, + associations: { + posts: { has_many: :posts }, + drafts: nil, + parent: { belongs_to: :parent } } } end @@ -672,15 +672,15 @@ class << self; self; end.class_eval do end attributes :name, :age - has_many :posts, :key => :my_posts, :serializer => Class.new - has_one :parent, :key => :my_parent, :serializer => Class.new + has_many :posts, key: :my_posts, serializer: Class.new + has_one :parent, key: :my_parent, serializer: Class.new end assert_equal serializer.schema, { - :attributes => { :name => :string, :age => :integer }, - :associations => { - :my_posts => { :has_many => :posts }, - :my_parent => { :belongs_to => :parent } + attributes: { name: :string, age: :integer }, + associations: { + my_posts: { has_many: :posts }, + my_parent: { belongs_to: :parent } } } end @@ -693,7 +693,7 @@ def test_embed_id_for_has_one root :post attributes :title, :body - has_one :author, :serializer => author_serializer + has_one :author, serializer: author_serializer end post_class = Class.new(Model) do @@ -702,17 +702,17 @@ def test_embed_id_for_has_one author_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "It's a new post!") - author = author_class.new(:id => 5) + post = post_class.new(title: "New Post", body: "It's a new post!") + author = author_class.new(id: 5) post.author = author hash = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "It's a new post!", - :author_id => 5 + post: { + title: "New Post", + body: "It's a new post!", + author_id: 5 } }, hash.as_json) end @@ -729,7 +729,7 @@ def id root :post attributes :title, :body - has_one :author, :serializer => author_serializer + has_one :author, serializer: author_serializer end post_class = Class.new(Model) do @@ -738,17 +738,17 @@ def id author_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "It's a new post!") - author = author_class.new(:id => 5) + post = post_class.new(title: "New Post", body: "It's a new post!") + author = author_class.new(id: 5) post.author = author hash = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "It's a new post!", - :author_id => "OMG" + post: { + title: "New Post", + body: "It's a new post!", + author_id: "OMG" } }, hash.as_json) end @@ -762,7 +762,7 @@ def test_embed_objects_for_has_one root :post attributes :title, :body - has_one :author, :serializer => author_serializer + has_one :author, serializer: author_serializer end post_class = Class.new(Model) do @@ -771,17 +771,17 @@ def test_embed_objects_for_has_one author_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "It's a new post!") - author = author_class.new(:id => 5, :name => "Tom Dale") + post = post_class.new(title: "New Post", body: "It's a new post!") + author = author_class.new(id: 5, name: "Tom Dale") post.author = author hash = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "It's a new post!", - :author => { :id => 5, :name => "Tom Dale" } + post: { + title: "New Post", + body: "It's a new post!", + author: { id: 5, name: "Tom Dale" } } }, hash.as_json) end @@ -795,7 +795,7 @@ def test_root_provided_in_options root :post attributes :title, :body - has_one :author, :serializer => author_serializer + has_one :author, serializer: author_serializer end post_class = Class.new(Model) do @@ -804,37 +804,37 @@ def test_root_provided_in_options author_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "It's a new post!") - author = author_class.new(:id => 5, :name => "Tom Dale") + post = post_class.new(title: "New Post", body: "It's a new post!") + author = author_class.new(id: 5, name: "Tom Dale") post.author = author assert_equal({ - :blog_post => { - :title => "New Post", - :body => "It's a new post!", - :author => { :id => 5, :name => "Tom Dale" } + blog_post: { + title: "New Post", + body: "It's a new post!", + author: { id: 5, name: "Tom Dale" } } - }, serializer_class.new(post, :root => :blog_post).as_json) + }, serializer_class.new(post, root: :blog_post).as_json) assert_equal({ - :title => "New Post", - :body => "It's a new post!", - :author => { :id => 5, :name => "Tom Dale" } - }, serializer_class.new(post, :root => false).as_json) + title: "New Post", + body: "It's a new post!", + author: { id: 5, name: "Tom Dale" } + }, serializer_class.new(post, root: false).as_json) assert_equal({ - :blog_post => { - :title => "New Post", - :body => "It's a new post!", - :author => { :id => 5, :name => "Tom Dale" } + blog_post: { + title: "New Post", + body: "It's a new post!", + author: { id: 5, name: "Tom Dale" } } - }, serializer_class.new(post).as_json(:root => :blog_post)) + }, serializer_class.new(post).as_json(root: :blog_post)) assert_equal({ - :title => "New Post", - :body => "It's a new post!", - :author => { :id => 5, :name => "Tom Dale" } - }, serializer_class.new(post).as_json(:root => false)) + title: "New Post", + body: "It's a new post!", + author: { id: 5, name: "Tom Dale" } + }, serializer_class.new(post).as_json(root: false)) end def test_serializer_has_access_to_root_object @@ -853,7 +853,7 @@ def test_serializer_has_access_to_root_object root :post attributes :title, :body - has_one :author, :serializer => author_serializer + has_one :author, serializer: author_serializer end post_class = Class.new(Model) do @@ -862,8 +862,8 @@ def test_serializer_has_access_to_root_object author_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "It's a new post!") - author = author_class.new(:id => 5, :name => "Tom Dale") + post = post_class.new(title: "New Post", body: "It's a new post!") + author = author_class.new(id: 5, name: "Tom Dale") post.author = author expected = serializer_class.new(post).as_json @@ -875,47 +875,47 @@ def test_embed_ids_include_true_with_root serializer_class.class_eval do root :post - embed :ids, :include => true - has_many :comments, :key => :comment_ids, :root => :comments - has_one :author, :serializer => DefaultUserSerializer, :key => :author_id, :root => :author + embed :ids, include: true + has_many :comments, key: :comment_ids, root: :comments + has_one :author, serializer: DefaultUserSerializer, key: :author_id, root: :author end - post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com") - comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)] + post = Post.new(title: "New Post", body: "Body of new post", email: "tenderlove@tenderlove.com") + comments = [Comment.new(title: "Comment1", id: 1), Comment.new(title: "Comment2", id: 2)] post.comments = comments serializer = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comment_ids => [1, 2], - :author_id => nil + post: { + title: "New Post", + body: "Body of new post", + comment_ids: [1, 2], + author_id: nil }, - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ], - :author => [] + author: [] }, serializer.as_json) - post.author = User.new(:id => 1) + post.author = User.new(id: 1) serializer = serializer_class.new(post) assert_equal({ - :post => { - :title => "New Post", - :body => "Body of new post", - :comment_ids => [1, 2], - :author_id => 1 + post: { + title: "New Post", + body: "Body of new post", + comment_ids: [1, 2], + author_id: 1 }, - :comments => [ - { :title => "Comment1" }, - { :title => "Comment2" } + comments: [ + { title: "Comment1" }, + { title: "Comment2" } ], - :author => [{ :first_name => "Jose", :last_name => "Valim" }] + author: [{ first_name: "Jose", last_name: "Valim" }] }, serializer.as_json) end @@ -927,15 +927,15 @@ def test_embed_with_include_inserts_at_root end comment_serializer = Class.new(ActiveModel::Serializer) do - embed :ids, :include => true + embed :ids, include: true attributes :id, :body - has_many :tags, :serializer => tag_serializer + has_many :tags, serializer: tag_serializer end post_serializer = Class.new(ActiveModel::Serializer) do - embed :ids, :include => true + embed :ids, include: true attributes :id, :title, :body - has_many :comments, :serializer => comment_serializer + has_many :comments, serializer: comment_serializer end post_class = Class.new(Model) do @@ -952,32 +952,32 @@ def test_embed_with_include_inserts_at_root tag_class = Class.new(Model) - post = post_class.new(:title => "New Post", :body => "NEW POST", :id => 1) - comment1 = comment_class.new(:body => "EWOT", :id => 1) - comment2 = comment_class.new(:body => "YARLY", :id => 2) - tag1 = tag_class.new(:name => "lolcat", :id => 1) - tag2 = tag_class.new(:name => "nyancat", :id => 2) - tag3 = tag_class.new(:name => "violetcat", :id => 3) + post = post_class.new(title: "New Post", body: "NEW POST", id: 1) + comment1 = comment_class.new(body: "EWOT", id: 1) + comment2 = comment_class.new(body: "YARLY", id: 2) + tag1 = tag_class.new(name: "lolcat", id: 1) + tag2 = tag_class.new(name: "nyancat", id: 2) + tag3 = tag_class.new(name: "violetcat", id: 3) post.comments = [comment1, comment2] comment1.tags = [tag1, tag3] comment2.tags = [tag1, tag2] - actual = ActiveModel::ArraySerializer.new([post], :root => :posts).as_json + actual = ActiveModel::ArraySerializer.new([post], root: :posts).as_json assert_equal({ - :posts => [ - { :title => "New Post", :body => "NEW POST", :id => 1, :comment_ids => [1,2] } + posts: [ + { title: "New Post", body: "NEW POST", id: 1, comment_ids: [1,2] } ], - :comments => [ - { :body => "EWOT", :id => 1, :tag_ids => [1,3] }, - { :body => "YARLY", :id => 2, :tag_ids => [1,2] } + comments: [ + { body: "EWOT", id: 1, tag_ids: [1,3] }, + { body: "YARLY", id: 2, tag_ids: [1,2] } ], - :tags => [ - { :name => "lolcat", :id => 1 }, - { :name => "violetcat", :id => 3 }, - { :name => "nyancat", :id => 2 } + tags: [ + { name: "lolcat", id: 1 }, + { name: "violetcat", id: 3 }, + { name: "nyancat", id: 2 } ] }, actual) end @@ -993,7 +993,7 @@ def title klass = Class.new do def read_attribute_for_serialization(name) - { :title => "New post!", :body => "First post body" }[name] + { title: "New post!", body: "First post body" }[name] end def title @@ -1007,12 +1007,12 @@ def body object = klass.new - actual = serializer.new(object, :root => :post).as_json + actual = serializer.new(object, root: :post).as_json assert_equal({ - :post => { - :title => "NEW POST!", - :body => "First post body" + post: { + title: "NEW POST!", + body: "First post body" } }, actual) end @@ -1022,16 +1022,16 @@ def test_can_customize_attributes_with_read_attributes attributes :title, :body def read_attribute_for_serialization(name) - { :title => "New post!", :body => "First post body" }[name] + { title: "New post!", body: "First post body" }[name] end end - actual = serializer.new(Object.new, :root => :post).as_json + actual = serializer.new(Object.new, root: :post).as_json assert_equal({ - :post => { - :title => "New post!", - :body => "First post body" + post: { + title: "New post!", + body: "First post body" } }, actual) end @@ -1062,7 +1062,7 @@ def read_attribute_for_serialization(name) actual = serializer.new(todo.new).as_json assert_equal({ - :overdue => true + overdue: true }, actual) end @@ -1078,13 +1078,13 @@ def read_attribute_for_serialization(name) end serializer = Class.new(ActiveModel::Serializer) do - attribute :overdue?, :key => :foo + attribute :overdue?, key: :foo end actual = serializer.new(todo.new).as_json assert_equal({ - :foo => true + foo: true }, actual) end @@ -1105,21 +1105,21 @@ def self.to_s attachment_serializer = Class.new(ActiveModel::Serializer) do attributes :name, :url - has_one :attachable, :polymorphic => true + has_one :attachable, polymorphic: true end - email = email_class.new :subject => 'foo', :body => 'bar' + email = email_class.new subject: 'foo', body: 'bar' - attachment = Attachment.new :name => 'logo.png', :url => 'http://example.com/logo.png', :attachable => email + attachment = Attachment.new name: 'logo.png', url: 'http://example.com/logo.png', attachable: email actual = attachment_serializer.new(attachment, {}).as_json assert_equal({ - :name => 'logo.png', - :url => 'http://example.com/logo.png', - :attachable => { - :type => :email, - :email => { :subject => 'foo', :body => 'bar' } + name: 'logo.png', + url: 'http://example.com/logo.png', + attachable: { + type: :email, + email: { subject: 'foo', body: 'bar' } } }, actual) end @@ -1142,21 +1142,21 @@ def self.to_s attachment_serializer = Class.new(ActiveModel::Serializer) do embed :ids attributes :name, :url - has_one :attachable, :polymorphic => true + has_one :attachable, polymorphic: true end - email = email_class.new :id => 1 + email = email_class.new id: 1 - attachment = Attachment.new :name => 'logo.png', :url => 'http://example.com/logo.png', :attachable => email + attachment = Attachment.new name: 'logo.png', url: 'http://example.com/logo.png', attachable: email actual = attachment_serializer.new(attachment, {}).as_json assert_equal({ - :name => 'logo.png', - :url => 'http://example.com/logo.png', - :attachable => { - :type => :email, - :id => 1 + name: 'logo.png', + url: 'http://example.com/logo.png', + attachable: { + type: :email, + id: 1 } }, actual) end @@ -1178,29 +1178,29 @@ def self.to_s attachment_serializer = Class.new(ActiveModel::Serializer) do root :attachment - embed :ids, :include => true + embed :ids, include: true attributes :name, :url - has_one :attachable, :polymorphic => true + has_one :attachable, polymorphic: true end - email = email_class.new :id => 1, :subject => "Hello", :body => "World" + email = email_class.new id: 1, subject: "Hello", body: "World" - attachment = Attachment.new :name => 'logo.png', :url => 'http://example.com/logo.png', :attachable => email + attachment = Attachment.new name: 'logo.png', url: 'http://example.com/logo.png', attachable: email actual = attachment_serializer.new(attachment, {}).as_json assert_equal({ - :attachment => { - :name => 'logo.png', - :url => 'http://example.com/logo.png', - :attachable => { - :type => :email, - :id => 1 + attachment: { + name: 'logo.png', + url: 'http://example.com/logo.png', + attachable: { + type: :email, + id: 1 }}, - :emails => [{ - :id => 1, - :subject => "Hello", - :body => "World" + emails: [{ + id: 1, + subject: "Hello", + body: "World" }] }, actual) end @@ -1211,10 +1211,10 @@ def test_multiple_polymorphic_associations end orange_serializer = Class.new(ActiveModel::Serializer) do - embed :ids, :include => true + embed :ids, include: true attributes :plu, :id - has_one :readable, :polymorphic => true + has_one :readable, polymorphic: true end email_class = Class.new(Model) do @@ -1243,47 +1243,47 @@ def readable attachment_serializer = Class.new(ActiveModel::Serializer) do root :attachment - embed :ids, :include => true + embed :ids, include: true attributes :name, :url - has_one :attachable, :polymorphic => true - has_one :readable, :polymorphic => true - has_one :edible, :polymorphic => true + has_one :attachable, polymorphic: true + has_one :readable, polymorphic: true + has_one :edible, polymorphic: true end - email = email_class.new :id => 1, :subject => "Hello", :body => "World" - orange = orange_class.new :id => 1, :plu => "3027", :readable => email + email = email_class.new id: 1, subject: "Hello", body: "World" + orange = orange_class.new id: 1, plu: "3027", readable: email attachment = Attachment.new({ - :name => 'logo.png', - :url => 'http://example.com/logo.png', - :attachable => email, - :readable => email, - :edible => orange + name: 'logo.png', + url: 'http://example.com/logo.png', + attachable: email, + readable: email, + edible: orange }) actual = attachment_serializer.new(attachment, {}).as_json assert_equal({ - :emails => [{ - :subject => "Hello", - :body => "World", - :id => 1 + emails: [{ + subject: "Hello", + body: "World", + id: 1 }], - :oranges => [{ - :plu => "3027", - :id => 1, - :readable => { :type => :email, :id => 1 } + oranges: [{ + plu: "3027", + id: 1, + readable: { type: :email, id: 1 } }], - :attachment => { - :name => 'logo.png', - :url => 'http://example.com/logo.png', - :attachable => { :type => :email, :id => 1 }, - :readable => { :type => :email, :id => 1 }, - :edible => { :type => :orange, :id => 1 } + attachment: { + name: 'logo.png', + url: 'http://example.com/logo.png', + attachable: { type: :email, id: 1 }, + readable: { type: :email, id: 1 }, + edible: { type: :orange, id: 1 } } }, actual) end @@ -1294,8 +1294,8 @@ def test_raises_an_error_when_a_child_serializer_includes_associations_when_the_ end fruit_serializer = Class.new(ActiveModel::Serializer) do - embed :ids, :include => true - has_one :attachment, :serializer => attachment_serializer + embed :ids, include: true + has_one :attachment, serializer: attachment_serializer attribute :color end @@ -1337,24 +1337,24 @@ def initialize(base, flavor) smoothie_serializer = Class.new(ActiveModel::Serializer) do root false - embed :ids, :include => true + embed :ids, include: true - has_one :base, :polymorphic => true - has_one :flavor, :polymorphic => true + has_one :base, polymorphic: true + has_one :flavor, polymorphic: true end banana_attachment = Attachment.new({ - :name => 'banana_blending.md', - :id => 3, + name: 'banana_blending.md', + id: 3, }) strawberry_attachment = Attachment.new({ - :name => 'strawberry_cleaning.doc', - :id => 4 + name: 'strawberry_cleaning.doc', + id: 4 }) - banana = banana_class.new :color => "yellow", :id => 1, :attachment => banana_attachment - strawberry = strawberry_class.new :color => "red", :id => 2, :attachment => strawberry_attachment + banana = banana_class.new color: "yellow", id: 1, attachment: banana_attachment + strawberry = strawberry_class.new color: "red", id: 2, attachment: strawberry_attachment smoothie = smoothie_serializer.new(smoothie.new(banana, strawberry)) @@ -1366,19 +1366,19 @@ def initialize(base, flavor) def tests_includes_does_not_include_nil_polymoprhic_associations post_serializer = Class.new(ActiveModel::Serializer) do root :post - embed :ids, :include => true - has_one :author, :polymorphic => true + embed :ids, include: true + has_one :author, polymorphic: true attributes :title end - post = Post.new(:title => 'Foo') + post = Post.new(title: 'Foo') actual = post_serializer.new(post).as_json assert_equal({ - :post => { - :title => 'Foo', - :author => nil + post: { + title: 'Foo', + author: nil } }, actual) end @@ -1401,30 +1401,30 @@ def name serializable_array = Class.new(Array) array = serializable_array.new - array << tag_class.new(:name => 'Rails') - array << tag_class.new(:name => 'Sinatra') + array << tag_class.new(name: 'Rails') + array << tag_class.new(name: 'Sinatra') - actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}).as_json + actual = array.active_model_serializer.new(array, root: :tags, meta: {total: 10}).as_json assert_equal({ - :meta => { - :total => 10, + meta: { + total: 10, }, - :tags => [ - { :name => "Rails" }, - { :name => "Sinatra" }, + tags: [ + { name: "Rails" }, + { name: "Sinatra" }, ] }, actual) - actual = array.active_model_serializer.new(array, :root => :tags, :meta => {:total => 10}, :meta_key => 'meta_object').as_json + actual = array.active_model_serializer.new(array, root: :tags, meta: {total: 10}, meta_key: 'meta_object').as_json assert_equal({ - :meta_object => { - :total => 10, + meta_object: { + total: 10, }, - :tags => [ - { :name => "Rails" }, - { :name => "Sinatra" }, + tags: [ + { name: "Rails" }, + { name: "Sinatra" }, ] }, actual) end @@ -1447,9 +1447,9 @@ def test_inheritance_does_not_used_cached_attributes item.body = "body" 2.times do - assert_equal({:title => "title"}, + assert_equal({title: "title"}, parent.new(item).attributes) - assert_equal({:body => "body", :title => "title"}, + assert_equal({body: "body", title: "title"}, child.new(item).attributes) end @@ -1464,36 +1464,36 @@ def has_permission? user = User.new user.superuser = true - post = Post.new(:title => 'Foo') + post = Post.new(title: 'Foo') - a_serializer = serializer.new(post, :scope => user, :scope_name => :current_user) + a_serializer = serializer.new(post, scope: user, scope_name: :current_user) assert a_serializer.has_permission? end def test_only_option_filters_attributes_and_associations - post = Post.new(:title => "New Post", :body => "Body of new post") - comments = [Comment.new(:title => "Comment1")] + post = Post.new(title: "New Post", body: "Body of new post") + comments = [Comment.new(title: "Comment1")] post.comments = comments - post_serializer = PostSerializer.new(post, :only => :title) + post_serializer = PostSerializer.new(post, only: :title) assert_equal({ - :post => { - :title => "New Post" + post: { + title: "New Post" } }, post_serializer.as_json) end def test_except_option_filters_attributes_and_associations - post = Post.new(:title => "New Post", :body => "Body of new post") - comments = [Comment.new(:title => "Comment1")] + post = Post.new(title: "New Post", body: "Body of new post") + comments = [Comment.new(title: "Comment1")] post.comments = comments - post_serializer = PostSerializer.new(post, :except => [:body, :comments]) + post_serializer = PostSerializer.new(post, except: [:body, :comments]) assert_equal({ - :post => { - :title => "New Post" + post: { + title: "New Post" } }, post_serializer.as_json) end @@ -1501,11 +1501,11 @@ def test_except_option_filters_attributes_and_associations def test_only_option_takes_precedence_over_custom_defined_include_methods user = User.new - post = Post.new(:title => "New Post", :body => "Body of new post", :author => "Sausage King") - comments = [Comment.new(:title => "Comment")] + post = Post.new(title: "New Post", body: "Body of new post", author: "Sausage King") + comments = [Comment.new(title: "Comment")] post.comments = comments - post_serializer = PostWithMultipleConditionalsSerializer.new(post, :scope => user, :only => :title) + post_serializer = PostWithMultipleConditionalsSerializer.new(post, scope: user, only: :title) # comments enabled post.comments_disabled = false @@ -1513,8 +1513,8 @@ def test_only_option_takes_precedence_over_custom_defined_include_methods user.superuser = true assert_equal({ - :post => { - :title => "New Post" + post: { + title: "New Post" } }, post_serializer.as_json) end diff --git a/test/test_fakes.rb b/test/test_fakes.rb index 30ce34b..a0a244c 100644 --- a/test/test_fakes.rb +++ b/test/test_fakes.rb @@ -8,7 +8,7 @@ def read_attribute_for_serialization(name) end def as_json(*) - { :model => "Model" } + { model: "Model" } end end @@ -26,7 +26,7 @@ class User attr_accessor :superuser def initialize(hash={}) - @attributes = hash.merge(:first_name => "Jose", :last_name => "Valim", :password => "oh noes yugive my password") + @attributes = hash.merge(first_name: "Jose", last_name: "Valim", password: "oh noes yugive my password") end def read_attribute_for_serialization(name) @@ -58,31 +58,31 @@ class UserSerializer < ActiveModel::Serializer attributes :first_name, :last_name def serializable_hash - attributes.merge(:ok => true).merge(options[:scope]) + attributes.merge(ok: true).merge(options[:scope]) end end class UserAttributesWithKeySerializer < ActiveModel::Serializer - attributes :first_name => :f_name, :last_name => :l_name + attributes first_name: :f_name, last_name: :l_name def serializable_hash - attributes.merge(:ok => true).merge(options[:scope]) + attributes.merge(ok: true).merge(options[:scope]) end end class UserAttributesWithSomeKeySerializer < ActiveModel::Serializer - attributes :first_name, :last_name => :l_name + attributes :first_name, last_name: :l_name def serializable_hash - attributes.merge(:ok => true).merge(options[:scope]) + attributes.merge(ok: true).merge(options[:scope]) end end class UserAttributesWithUnsymbolizableKeySerializer < ActiveModel::Serializer - attributes :first_name, :last_name => :"last-name" + attributes :first_name, last_name: :"last-name" def serializable_hash - attributes.merge(:ok => true).merge(options[:scope]) + attributes.merge(ok: true).merge(options[:scope]) end end @@ -95,7 +95,7 @@ class MyUserSerializer < ActiveModel::Serializer def serializable_hash hash = attributes - hash = hash.merge(:super_user => true) if object.super_user? + hash = hash.merge(super_user: true) if object.super_user? hash end end @@ -108,7 +108,7 @@ def initialize(comment, options={}) attr_reader :object def serializable_hash - { :title => @object.read_attribute_for_serialization(:title) } + { title: @object.read_attribute_for_serialization(:title) } end def as_json(options=nil) @@ -116,20 +116,20 @@ def as_json(options=nil) if options[:root] == false serializable_hash else - { :comment => serializable_hash } + { comment: serializable_hash } end end end class PostSerializer < ActiveModel::Serializer attributes :title, :body - has_many :comments, :serializer => CommentSerializer + has_many :comments, serializer: CommentSerializer end class PostWithConditionalCommentsSerializer < ActiveModel::Serializer root :post attributes :title, :body - has_many :comments, :serializer => CommentSerializer + has_many :comments, serializer: CommentSerializer def include_associations! include! :comments unless object.comments_disabled @@ -139,7 +139,7 @@ def include_associations! class PostWithMultipleConditionalsSerializer < ActiveModel::Serializer root :post attributes :title, :body, :author - has_many :comments, :serializer => CommentSerializer + has_many :comments, serializer: CommentSerializer def include_comments? !object.comments_disabled @@ -159,7 +159,7 @@ class AuthorSerializer < ActiveModel::Serializer end class BlogSerializer < ActiveModel::Serializer - has_one :author, :serializer => AuthorSerializer + has_one :author, serializer: AuthorSerializer end class BlogWithRootSerializer < BlogSerializer @@ -175,8 +175,8 @@ class CustomBlog < Blog end class CustomBlogSerializer < ActiveModel::Serializer - has_many :public_posts, :key => :posts, :serializer => PostSerializer - has_one :public_user, :key => :user, :serializer => UserSerializer + has_many :public_posts, key: :posts, serializer: PostSerializer + has_one :public_user, key: :user, serializer: UserSerializer end class SomeSerializer < ActiveModel::Serializer Fromd10b5f6ac0Mon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Thu, 30 May 2013 00:30:20 -0500 Subject: [PATCH 56/66] add ruby 1.8 install note [ci skip] fixes #310 --- README.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 908bf30..a538677 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,13 @@ content. In short, **serializers replace hash-driven development with object-oriented development.** -# Installing Serializers +# Installing The easiest way to install `ActiveModel::Serializers` is to add it to your `Gemfile`: ```ruby -gem "active_model_serializers", "~> 0.8.0" +gem "active_model_serializers" ``` Then, install it on the command line: @@ -28,6 +28,16 @@ Then, install it on the command line: $ bundle install . ``` + #### Ruby 1.8 is no longer supported! + +If you must use a ruby 1.8 version (MRI 1.8.7, REE, Rubinius 1.8, or JRuby 1.8), you need to use version 0.8.x. +Versions after 0.9.0 do not support ruby 1.8. To specify version 0.8, include this in your Gemfile: + +```ruby +gem "active_model_serializers", "~> 0.8.0" +``` + + # Creating a Serializer The easiest way to create a new serializer is to generate a new resource, which From31e1dab69fMon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Thu, 30 May 2013 09:28:13 -0600 Subject: [PATCH 57/66] require rails >= 3.2 * remove ancient confusing comment in SerializerGenerator --- CHANGELOG.md | 2 ++ active_model_serializers.gemspec | 4 ++-- lib/active_model_serializers.rb | 2 -- lib/generators/serializer/serializer_generator.rb | 3 --- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07f9b02..b4c2913 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,8 @@ * Remove support for ruby 1.8 versions. +* Require rails >= 3.2. + # VERSION 0.8.1 * Fix bug whereby a serializer using 'options' would blow up. diff --git a/active_model_serializers.gemspec b/active_model_serializers.gemspec index 9711c56..62e3aaa 100644 --- a/active_model_serializers.gemspec +++ b/active_model_serializers.gemspec @@ -19,9 +19,9 @@ Gem::Specification.new do |gem| gem.required_ruby_version = ">= 1.9.2" - gem.add_dependency "activemodel", ">= 3.0" + gem.add_dependency "activemodel", ">= 3.2" - gem.add_development_dependency "rails", ">= 3.0" + gem.add_development_dependency "rails", ">= 3.2" gem.add_development_dependency "pry" gem.add_development_dependency "simplecov" gem.add_development_dependency "coveralls" diff --git a/lib/active_model_serializers.rb b/lib/active_model_serializers.rb index c1357c7..4ae2d74 100644 --- a/lib/active_model_serializers.rb +++ b/lib/active_model_serializers.rb @@ -11,8 +11,6 @@ module ActiveModel class Railtie < Rails::Railtie generators do |app| - app ||= Rails.application # Rails 3.0.x does not yield `app` - Rails::Generators.configure!(app.config.generators) Rails::Generators.hidden_namespaces.uniq! require_relative "generators/resource_override" diff --git a/lib/generators/serializer/serializer_generator.rb b/lib/generators/serializer/serializer_generator.rb index 129da44..8212d62 100644 --- a/lib/generators/serializer/serializer_generator.rb +++ b/lib/generators/serializer/serializer_generator.rb @@ -25,9 +25,6 @@ def association_names def parent_class_name if options[:parent] options[:parent] - # Only works on 3.2 - # elsif (n = Rails::Generators.namespace) && n.const_defined?(:ApplicationSerializer) - # "ApplicationSerializer" elsif defined?(::ApplicationSerializer) "ApplicationSerializer" else From725952c862Mon Sep 17 00:00:00 2001 From: Tee Parham <tee@neighborland.com> Date: Thu, 30 May 2013 09:32:06 -0600 Subject: [PATCH 58/66] require ruby >= 1.9.3 * remove 1.9.2 from travis --- .travis.yml | 5 ----- active_model_serializers.gemspec | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6a195cf..a001825 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ language: ruby rvm: - - 1.9.2 - 1.9.3 - 2.0.0 - jruby-19mode @@ -11,10 +10,6 @@ gemfile: matrix: allow_failures: - gemfile: Gemfile.edge - exclude: - # Edge Rails is only compatible with 1.9.3 - - gemfile: Gemfile.edge - rvm: 1.9.2 notifications: email: false campfire: diff --git a/active_model_serializers.gemspec b/active_model_serializers.gemspec index 62e3aaa..9b551fa 100644 --- a/active_model_serializers.gemspec +++ b/active_model_serializers.gemspec @@ -17,7 +17,7 @@ Gem::Specification.new do |gem| gem.require_paths = ["lib"] gem.version = ActiveModel::Serializer::VERSION - gem.required_ruby_version = ">= 1.9.2" + gem.required_ruby_version = ">= 1.9.3" gem.add_dependency "activemodel", ">= 3.2" From0d674369ffMon Sep 17 00:00:00 2001 From: Damian Galarza <galarza.d@gmail.com> Date: Tue, 4 Jun 2013 19:17:31 -0400 Subject: [PATCH 59/66] Use minitest/autorun Allows edge gemset to build --- test/test_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_helper.rb b/test/test_helper.rb index 7f33cbf..889d7a6 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -14,7 +14,7 @@ require "active_model_serializers" require "active_support/json" -require "test/unit" +require "minitest/autorun" require 'rails' From173f3f2a17Mon Sep 17 00:00:00 2001 From: Anson Hoyt <anson.hoyt@gmail.com> Date: Thu, 6 Jun 2013 14:41:45 -0400 Subject: [PATCH 60/66] Explain how to include an attribute named "object" --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index a538677..f4e122b 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,18 @@ end Within a serializer's methods, you can access the object being serialized as `object`. +Since this shadows any attribute named `object`, you can include them through `object.object`. For example: + +```ruby +class VersionSerializer < ActiveModel::Serializer + attribute :version_object, key: :object + + def version_object + object.object + end +end +``` + You can also access the `current_user` method, which provides an authorization context to your serializer. By default, the context is the current user of your application, but this From74af00f17aMon Sep 17 00:00:00 2001 From: Jamie Gaskins <jgaskins@gmail.com> Date: Sat, 8 Jun 2013 12:18:34 -0300 Subject: [PATCH 61/66] Remove errant apostrophes Apostrophes don't indicate pluralization. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4e122b..9a957e9 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ the serializer generator: $ rails g serializer post ``` -### Support for PORO's and other ORM's. +### Support for POROs and other ORMs. Currently `ActiveModel::Serializers` adds serialization support to all models that descend from `ActiveRecord` or include `Mongoid::Document`. If you are From88ff42ebc8Mon Sep 17 00:00:00 2001 From: Andre Meij <andre@socialreferral.com> Date: Tue, 18 Jun 2013 16:35:03 +0200 Subject: [PATCH 62/66] Use 1.9 hashes in the readme --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 9a957e9..117fd0d 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ for a serializer for the object and use it if available. class PostsController < ApplicationController def show @post = Post.find(params[:id]) - render :json => @post + render json: @post end end ``` @@ -107,7 +107,7 @@ end #### 2. Specify the serializer when you render the object: ```ruby -render :json => @post, :serializer => FancyPostSerializer +render json: @post, serializer: FancyPostSerializer ``` ## Arrays @@ -124,7 +124,7 @@ end class PostsController < ApplicationController def index @posts = Post.all - render :json => @posts + render json: @posts end end ``` @@ -145,7 +145,7 @@ By default, the root element is the name of the controller. For example, `PostsC generates a root element "posts". To change it: ```ruby -render :json => @posts, :root => "some_posts" +render json: @posts, root: "some_posts" ``` You may disable the root element for arrays at the top level, which will result in @@ -162,7 +162,7 @@ root element of the array with any of those methods will produce To specify a custom serializer for the items within an array: ```ruby -render :json => @posts, :each_serializer => FancyPostSerializer +render json: @posts, each_serializer: FancyPostSerializer ``` ## Disabling the root element @@ -186,7 +186,7 @@ end #### 2. Disable root per render call in your controller ```ruby -render :json => @posts, :root => false +render json: @posts, root: false ``` #### 3. Subclass the serializer, and specify using it @@ -197,7 +197,7 @@ class CustomArraySerializer < ActiveModel::ArraySerializer end # controller: -render :json => @posts, :serializer => CustomArraySerializer +render json: @posts, serializer: CustomArraySerializer ``` #### 4. Define default_serializer_options in your controller From54ce37b956Mon Sep 17 00:00:00 2001 From: Andre Meij <andre@socialreferral.com> Date: Tue, 18 Jun 2013 16:40:14 +0200 Subject: [PATCH 63/66] Change to 1.9 Hash syntax in docs --- DESIGN.textile | 8 ++++---- README.md | 34 +++++++++++++++++----------------- cruft.md | 4 ++-- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/DESIGN.textile b/DESIGN.textile index 336d85d..559982e 100644 --- a/DESIGN.textile +++ b/DESIGN.textile @@ -358,8 +358,8 @@ Here is an example: <pre lang="ruby"> class UserSerializer < ActiveModel::Serializer - has_many :followed_posts, :key => :posts - has_one :owned_account, :key => :account + has_many :followed_posts, key: :posts + has_one :owned_account, key: :account end </pre> @@ -370,8 +370,8 @@ to set it explicitly: <pre lang="ruby"> class UserSerializer < ActiveModel::Serializer - has_many :followed_posts, :key => :posts, :serializer => CustomPostSerializer - has_one :owne_account, :key => :account, :serializer => PrivateAccountSerializer + has_many :followed_posts, key: :posts, serializer: CustomPostSerializer + has_one :owne_account, key: :account, serializer: PrivateAccountSerializer end </pre> diff --git a/README.md b/README.md index 117fd0d..0088065 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ end ## Getting the old version If you find that your project is already relying on the old rails to_json -change `render :json` to `render :json => @your_object.to_json`. +change `render :json` to `render json: @your_object.to_json`. # Attributes and Associations @@ -293,7 +293,7 @@ type of a computed attribute: ```ruby class PersonSerializer < ActiveModel::Serializer - attributes :first_name, :last_name, {:full_name => :string} + attributes :first_name, :last_name, {full_name: :string} def full_name "#{object.first_name} #{object.last_name}" @@ -309,7 +309,7 @@ class PostSerializer < ActiveModel::Serializer attributes :id, :body # look up :subject on the model, but use +title+ in the JSON - attribute :subject, :key => :title + attribute :subject, key: :title has_many :comments end ``` @@ -318,7 +318,7 @@ If you would like to add meta information to the outputted JSON, use the `:meta` option: ```ruby -render :json => @posts, :serializer => CustomArraySerializer, :meta => {:total => 10} +render json: @posts, serializer: CustomArraySerializer, meta: {total: 10} ``` The above usage of `:meta` will produce the following: @@ -336,7 +336,7 @@ The above usage of `:meta` will produce the following: If you would like to change the meta key name you can use the `:meta_key` option: ```ruby -render :json => @posts, :serializer => CustomArraySerializer, :meta => {:total => 10}, :meta_key => 'meta_object' +render json: @posts, serializer: CustomArraySerializer, meta: {total: 10}, meta_key: 'meta_object' ``` The above usage of `:meta_key` will produce the following: @@ -388,7 +388,7 @@ class PostSerializer < ActiveModel::Serializer # only let the user see comments he created. def comments - object.comments.where(:created_by => current_user) + object.comments.where(created_by: current_user) end end ``` @@ -401,7 +401,7 @@ class PostSerializer < ActiveModel::Serializer attributes :id, :title, :body # look up comments, but use +my_comments+ as the key in JSON - has_many :comments, :key => :my_comments + has_many :comments, key: :my_comments end ``` @@ -439,8 +439,8 @@ end You may also use the `:serializer` option to specify a custom serializer class and the `:polymorphic` option to specify an association that is polymorphic (STI), e.g.: ```ruby - has_many :comments, :serializer => CommentShortSerializer - has_one :reviewer, :polymorphic => true + has_many :comments, serializer: CommentShortSerializer + has_one :reviewer, polymorphic: true ``` Serializers are only concerned with multiplicity, and not ownership. `belongs_to` ActiveRecord associations can be included using `has_one` in your serializer. @@ -528,7 +528,7 @@ You can specify that the data be included like this: ```ruby class PostSerializer < ActiveModel::Serializer - embed :ids, :include => true + embed :ids, include: true attributes :id, :title, :body has_many :comments @@ -563,10 +563,10 @@ used to reference them: ```ruby class PostSerializer < ActiveModel::Serializer - embed :ids, :include => true + embed :ids, include: true attributes :id, :title, :body - has_many :comments, :key => :comment_ids, :root => :comment_objects + has_many :comments, key: :comment_ids, root: :comment_objects end ``` @@ -591,10 +591,10 @@ objects: ```ruby class PostSerializer < ActiveModel::Serializer - embed :ids, :include => true + embed :ids, include: true attributes :id, :title, :body - has_many :comments, :embed_key => :external_id + has_many :comments, embed_key: :external_id end ``` @@ -646,7 +646,7 @@ To be clear, it's not possible, yet, to do something like this: ```ruby class SomeController < ApplicationController - serialization_scope :current_admin, :except => [:index, :show] + serialization_scope :current_admin, except: [:index, :show] end ``` @@ -660,13 +660,13 @@ class CitiesController < ApplicationController def index @cities = City.all - render :json => @cities, :each_serializer => CitySerializer + render json: @cities, each_serializer: CitySerializer end def show @city = City.find(params[:id]) - render :json => @city, :scope => current_admin, :scope_name => :current_admin + render json: @city, scope: current_admin, scope_name: :current_admin end end ``` diff --git a/cruft.md b/cruft.md index 3de9d68..22cbf7d 100644 --- a/cruft.md +++ b/cruft.md @@ -9,8 +9,8 @@ have a constant with a Hash of events: ```ruby INSTRUMENT = { - :serialize => :"serialize.serializer", - :associations => :"associations.serializer" + serialize: :"serialize.serializer", + associations: :"associations.serializer" } ``` From027aa38138Mon Sep 17 00:00:00 2001 From: "T.J. Schuck" <tj@getharvest.com> Date: Wed, 26 Jun 2013 16:45:50 -0400 Subject: [PATCH 64/66] Add docs about caching --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index 0088065..62b64fe 100644 --- a/README.md +++ b/README.md @@ -675,3 +675,21 @@ Assuming that the `current_admin` method needs to make a query in the database for the current user, the advantage of this approach is that, by setting `serialization_scope` to `nil`, the `index` action no longer will need to make that query, only the `show` action will. + +## Caching + +To cache a serializer, call `cached` and define a `cache_key` method: + +```ruby +class PostSerializer < ActiveModel::Serializer + cached # enables caching for this serializer + + attributes :title, :body + + def cache_key + [object, current_user] + end +end +``` + +The caching interface uses `Rails.cache` under the hood. Froma62680c883Mon Sep 17 00:00:00 2001 From: stiller <joachim@nolten.org> Date: Thu, 4 Jul 2013 11:32:25 +0200 Subject: [PATCH 65/66] Update README.md Fixed typo. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 62b64fe..65a3b79 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ compliant but do not descend from `ActiveRecord` or include `Mongoid::Document`, you must add an include statement for `ActiveModel::SerializerSupport` to make models serializable. If you also want to make collections serializable, you should include -`ActiveModel::ArraySerializationSupport` into your ORM's +`ActiveModel::ArraySerializerSupport` into your ORM's relation/criteria class. # ActiveModel::Serializer From23748e7f2bMon Sep 17 00:00:00 2001 From: mikegee <michaelpgee@gmail.com> Date: Thu, 29 Aug 2013 16:04:20 -0400 Subject: [PATCH 66/66] add Design and Implementation section to readme credit to @garysweaver --- README.md | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 65a3b79..bb7d887 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[](https://travis-ci.org/rails-api/active_model_serializers) [](https://codeclimate.com/github/rails-api/active_model_serializers) [](https://coveralls.io/r/rails-api/active_model_serializers) +[](https://travis-ci.org/rails-api/active_model_serializers) [](https://codeclimate.com/github/rails-api/active_model_serializers) [](https://coveralls.io/r/rails-api/active_model_serializers) # Purpose @@ -13,7 +13,7 @@ content. In short, **serializers replace hash-driven development with object-oriented development.** -# Installing +# Installing The easiest way to install `ActiveModel::Serializers` is to add it to your `Gemfile`: @@ -28,7 +28,7 @@ Then, install it on the command line: $ bundle install ``` -#### Ruby 1.8 is no longer supported! +#### Ruby 1.8 is no longer supported! If you must use a ruby 1.8 version (MRI 1.8.7, REE, Rubinius 1.8, or JRuby 1.8), you need to use version 0.8.x. Versions after 0.9.0 do not support ruby 1.8. To specify version 0.8, include this in your Gemfile: @@ -177,7 +177,7 @@ In an initializer: ActiveSupport.on_load(:active_model_serializers) do # Disable for all serializers (except ArraySerializer) ActiveModel::Serializer.root = false - + # Disable for ArraySerializer ActiveModel::ArraySerializer.root = false end @@ -693,3 +693,24 @@ end ``` The caching interface uses `Rails.cache` under the hood. + +# Design and Implementation + +## Keep it Simple + +ActiveModel::Serializers is capable of producing complex JSON views/large object +trees, and it may be tempting to design in this way so that your client can make +fewer requests to get data and so that related querying can be optimized. +However, keeping things simple in your serializers and controllers may +significantly reduce complexity and maintenance over the long-term development +of your application. Please consider reducing the complexity of the JSON views +you provide via the serializers as you build out your application, so that +controllers/services can be more easily reused without a lot of complexity +later. + +## Performance + +As you develop your controllers or other code that utilizes serializers, try to +avoid n+1 queries by ensuring that data loads in an optimal fashion, e.g. if you +are using ActiveRecord, you might want to use query includes or joins as needed +to make the data available that the serializer(s) need. ```
40 KiB
0.10.x
Breaking changes:
Features:
- #1550 Add
Rails url_helpers to
SerializationContextfor use in links. (@remear, @bf4) - #1004 JSON API errors object implementation.
- Only implements
detailandsourceas derived fromActiveModel::Error - Provides checklist of remaining questions and remaining parts of the spec.
- Only implements
- #1515 Adds support for symbols to the
ActiveModel::Serializer.typemethod. (@groyoh) - #1504 Adds the changes missing from #1454
and add more tests for resource identifier and relationship objects. Fix association block with link
returning
data: nil.(@groyoh) - #1372 Support cache_store.read_multi. (@LcpMarvel)
- #1018 Add more tests and docs for top-level links. (@leandrocp)
- #1454 Add support for relationship-level links and meta attributes. (@beauby)
- #1340 Add support for resource-level meta. (@beauby)
Fixes:
- #1570 Fixed pagination issue with last page size. (@bmorrall)
- #1516 No longer return a nil href when only adding meta to a relationship link. (@groyoh)
- #1458 Preserve the serializer type when fragment caching. (@bdmac)
- #1477 Fix
fragment_cached?method to check if caching. (@bdmac) - #1501 Adds tests for SerializableResource::use_adapter?,doc typos (@domitian)
- #1488 Require ActiveSupport's string inflections (@nate00)
Misc:
- #1551 Added codebeat badge (@korzonek)
- #1527 Refactor fragment cache class. (@groyoh)
- #1560 Update rubocop and address its warnings. (@bf4 @groyoh)
- #1545 Document how to pass arbitrary options to the serializer (@CodedBeardedSignedTaylor)
- #1496 Run all branches against JRuby on CI (@nadavshatz)
- #1559 Add a deprecation DSL. (@bf4 @groyoh)
- #1543 Add the changes missing from #1535. (@groyoh)
- #1535 Move the adapter and adapter folder to active_model_serializers folder and changes the module namespace. (@domitian @bf4)
- #1497 Add JRuby-9000 to appveyor.yml(@corainchicago)
v0.10.0.rc4 (2016/01/27 11:00 +00:00)
Breaking changes:
- #1360 #1369 Drop support for Ruby 1.9.3 (@karaAJC, @maurogeorge)
- #1131 Remove Serializer#root_name (@beauby)
- #1138 Introduce Adapter::Base (@bf4)
- Adapters now inherit Adapter::Base. 'Adapter' is now a module, no longer a class.
- using a class as a namespace that you also inherit from is complicated and circular at times i.e. buggy (see https://github.com/rails-api/active_model_serializers/pull/1177)
- The class methods on Adapter aren't necessarily related to the instance methods, they're more Adapter functions.
- named
Basebecause it's a Rails-ism. - It helps to isolate and highlight what the Adapter interface actually is.
- Adapters now inherit Adapter::Base. 'Adapter' is now a module, no longer a class.
- #1418 serialized collections now use the root option as is; now, only the root derived from the serializer or object is always pluralized.
Features:
- #1406 Allow for custom dynamic values in JSON API links (@beauby)
- #1270 Adds
assert_response_schematest helper (@maurogeorge) - #1099 Adds
assert_serializertest helper (@maurogeorge) - #1403 Add support for if/unless on attributes/associations (@beauby)
- #1248 Experimental: Add support for JSON API deserialization (@beauby)
- #1378 Change association blocks
to be evaluated in serializer scope, rather than association scope. (@bf4)
- Syntax changes from e.g.
has_many :titles do customers.pluck(:title) end(in #1356) tohas_many :titles do object.customers.pluck(:title) end
- Syntax changes from e.g.
- #1356 Add inline syntax for
attributes and associations (@bf4 @beauby @noahsilas)
- Allows defining attributes so that they don't conflict with existing methods. e.g.
attribute :title do 'Mr. Topum Hat' end - Allows defining associations so that they don't conflict with existing methods. e.g.
has_many :titles do customers.pluck(:title) end- Allows dynamic associations, as compared to compare to using
virtual_value. e.g.has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
- Allows dynamic associations, as compared to compare to using
- Removes dynamically defined methods on the serializer
- Allows defining attributes so that they don't conflict with existing methods. e.g.
- #1336 Added support for Grape >= 0.13, < 1.0 (@johnhamelink)
- #1322 Instrumenting rendering of resources (@bf4, @maurogeorge)
- #1291 Add logging (@maurogeorge)
- #1272 Add PORO serializable base class: ActiveModelSerializers::Model (@bf4)
- #1255 Make more class attributes inheritable (@bf4)
- #1249 Inheritance of serializer inheriting the cache configuration(@Rodrigora)
- #1247 Add support for toplevel JSON API links (@beauby)
- #1246 Add support for resource-level JSON API links (@beauby)
- #1225 Better serializer lookup, use nested serializer when it exists (@beauby)
- #1213
typedirective for serializer to control type field with json-api adapter (@youroff) - #1172 Better serializer registration, get more than just the first module (@bf4)
- #1158 Add support for wildcards in
includeoption (@beauby) - #1127 Add support for nested
associations for JSON and Attributes adapters via the
includeoption (@NullVoxPopuli, @beauby). - #1050 Add support for toplevel jsonapi member (@beauby, @bf4)
- #1251 Rename ArraySerializer to CollectionSerializer for clarity, add ActiveModelSerializers.config.collection_serializer (@bf4)
- #1295 Add config
serializer_lookup_enabledthat, when disabled, requires serializers to explicitly specified. (@trek)
Fixes:
- #1352 Fix generators; Isolate Rails-specifc code in Railties (@dgynn, @bf4)
- #1384Fix database state leaking across tests (@bf4)
- #1297 Fix
fieldsoption to restrict relationships as well (@beauby) - #1239 Fix duplicates in JSON API compound documents (@beauby)
- #1214 retrieve the key from the reflection options when building associations (@NullVoxPopuli, @hut8)
- #1358 Handle serializer file paths with spaces (@rwstauner, @bf4)
- #1195 Fix id override (@beauby)
- #1185 Fix options passing in Json and Attributes adapters (@beauby)
Misc:
- #1383 Simplify reflections handling (@beauby)
- #1370 Simplify attributes handling via a mixin (@beauby)
- #1301 Mapping JSON API spec / schema to AMS (@bf4)
- #1271 Handle no serializer source file to digest (@bf4)
- #1260 Serialization and Cache Documentation (@bf4)
- #1259 Add more info to CONTRIBUTING (@bf4)
- #1233 Top-level meta and meta_key options no longer handled at serializer level (@beauby)
- #1232 fields option no longer handled at serializer level (@beauby)
- #1220 Remove empty rubocop.rake (@maurogeorge)
- #1178 env CAPTURE_STDERR=false lets devs see hard failures (@bf4)
- #1177 Remove Adapter autoloads in favor of require (@bf4)
- #1117 FlattenJson adapter no longer inherits Json adapter, renamed to Attributes (@bf4)
- #1171 add require statements to top of file (@shicholas)
- #1167 Delegate Serializer.attributes to Serializer.attribute (@bf4)
- #1174 Consistently refer to the 'JSON API' and the 'JsonApi' adapter (@bf4)
- #1173 Comment private accessor warnings (@bf4)
- #1166 Prefer methods over instance variables (@bf4)
- #1168 Fix appveyor failure cache not being expired (@bf4)
- #1161 Remove duplicate test helper (@bf4)
- #1360 Update CI to test 2.2.2 -> 2.2.3 (@karaAJC)
- #1371 Refactor, update, create documentation (@bf4)
v0.10.0.rc3 (2015/09/16 15:19 +00:00)
- #1129 Remove SerializableResource.serialize in favor of
.new(@bf4) - #1155 Outside controller use tutorial (@CodedBeardedSignedTaylor)
- #1154 Rubocop fixes for issues introduced by #1089 (@NullVoxPopuli)
- #1089 Add ActiveModelSerializers.logger with default null device (@bf4)
- #1109 Make better use of Minitest's lifecycle (@bf4)
- #1144 Fix Markdown to adapters documentation (@bacarini)
- #1121 Refactor
add_linksin JSONAPI adapter. (@beauby) - #1150 Remove legacy method accidentally reintroduced in #1017 (@beauby)
- #1149 Update README with nested included association example. (@mattmueller)
- #1110 Add lint tests for AR models (@beauby)
- #1131 Extended format for JSONAPI
includeoption (@beauby)- adds extended format for
includeoption to JsonApi adapter
- adds extended format for
- #1142 Updating wording on cache expiry in README (@leighhalliday)
- #1140 Fix typo in fieldset exception (@lautis)
- #1132 Get rid of unnecessary instance variables, and implied dependencies. (@beauby)
- #1139 Documentation for serializing resources without render (@PericlesTheo)
- #1017 Make Adapters registerable so they are not namespace-constrained (@bf4)
- #1120 Add windows platform to loading sqlite3 (@Eric-Guo)
- #1123 Remove url options (@bacarini)
- #1093 Factor
with_adapter+ force cache clear before each test. (@beauby) - #1095 Add documentation about configuration options. (@beauby)
- #1069 Add test coverage; account for no artifacts on CI (@bf4)
- #1103 Move
idandjson_api_typemethods fromSerializertoJsonApi. (@beauby) - #1106 Add Style enforcer (via Rubocop) (@bf4)
- #1079 Add ArraySerializer#object like Serializer (@bf4)
- #1096 Fix definition of serializer attributes with multiple calls to `attri… (@beauby)
- #1105 Add ActiveRecord-backed fixtures. (@beauby)
- #1108 Better lint (@bf4)
- #1102 Remove remains of
embedoption. (@beauby) - #1090 Clarify AMS dependencies (@bf4)
- #1081 Add configuration option to set resource type to singular/plural (@beauby)
- #1067 Fix warnings (@bf4)
- #1066 Adding appveyor to the project (@joaomdmoura, @Eric-Guo, @bf4)
- #1071 Make testing suite running and pass in Windows (@Eric-Guo, @bf4)
- #1041 Adding pagination links (@bacarini)
- adds support for
pagination linksat top level of JsonApi adapter
- adds support for
- #1063 Lead by example: lint PORO model (@bf4)
- #1 Test caller line parsing and digesting (@bf4)
- #1048 Let FlattenJson adapter decide it doesn't include meta (@bf4)
- #1060 Update fragment cache to support namespaced objects (@aaronlerch)
- #1052 Use underscored json_root when serializing a collection (@whatthewhat)
- #1051 Fix some invalid JSON in docs (@tjschuck)
- #1049 Fix incorrect s/options = {}/options ||= {} (@bf4)
- #1037 allow for type attribute (@lanej)
- #1034 allow id attribute to be overriden (@lanej)
- #1035 Fixed Comments highlight (@artLopez)
- #1031 Disallow to define multiple associations at once (@bolshakov)
- #1032 Wrap railtie requirement with rescue (@elliotlarson)
- #1026 Bump Version Number to 0.10.0.rc2 (@jfelchner)
- #985 Associations implementation refactoring (@bolshakov)
- #954 Encapsulate serialization in ActiveModel::SerializableResource (@bf4)
- #972 Capture app warnings on test run (@bf4)
- #1019 Improve README.md (@baojjeu)
- #998 Changing root to model class name (@joaomdmoura)
- #1006 Fix adapter inflection bug for api -> API (@bf4)
- #1016 require rails/railtie before subclassing Rails::Railtie (@bf4)
- #1013 Root option with empty array support (@vyrak, @mareczek)
- #994 Starting Docs structure (@joaomdmoura)
- #1007 Bug fix for ArraySerializer json_key (@jiajiawang)
- #1003 Fix transient test failures (@Rodrigora)
- #996 Add linter for serializable resource (@bf4)
- #990 Adding json-api meta test (@joaomdmoura)
- #984 Add option "key" to serializer associations (@Rodrigora)
- #982 Fix typo (@bf4)
- #981 Remove unused PORO#to_param (@bf4)
- #978 fix generators template bug (@regonn)
- #975 Fixes virtual value not being used (@GriffinHeart)
- #970 Fix transient tests failures (@Rodrigora)
- #962 Rendering objects that doesn't have serializers (@bf4, @joaomdmoura, @JustinAiken)
- #939 Use a more precise generated cache key (@aaronlerch)
- #971 Restore has_one to generator (@bf4)
- #965 options fedault valueserializable_hash and as_json (@bf4)
- #959 TYPO on README.md (@kangkyu)
v0.10.0.rc2 (2015/06/16 21:30 +00:00)
- #958 Splitting json adapter into two (@joaomdmoura)
- adds FlattenJSON as default adapter
- #953 use model name to determine the type (@lsylvester)
- uses model name to determine the type
- #949 Don't pass serializer option to associated serializers (@bf4, @edwardloveall)
- #902 Added serializer file digest to the cache_key (@cristianbica)
- #948 AMS supports JSONAPI 1.0 instead of RC4 (@SeyZ)
- #936 Include meta when using json adapter with custom root (@chrisbranson)
- #942 Small code styling issue (@thiagofm)
- #930 Reverting PR #909 (@joaomdmoura)
- #924 Avoid unecessary calls to attribute methods when fragment caching (@navinpeiris)
- #925 Updates JSON API Adapter to generate RC4 schema (@benedikt)
- adds JSON API support 1.0
- #918 Adding rescue_with_handler to clear state (@ryansch)
- #909 Defining Json-API Adapter as Default (@joaomdmoura)
- remove root key option and split JSON adapter
- #914 Prevent possible duplicated attributes in serializer (@groyoh)
- #880 Inabling subclasses serializers to inherit attributes (@groyoh)
- #913 Avoiding the serializer option when instantiating a new one for ArraySerializer Fixed #911 (@groyoh)
- #897 Allow to define custom serializer for given class (@imanel)
- #892 Fixed a bug that appeared when json adapter serialize a nil association (@groyoh)
- #895 Adding a test to cover 'meta' and 'meta_key' attr_readers (@adomokos)
- #894 Fixing typos in README.md (@adomokos)
- #888 Changed duplicated test name in action controller test (@groyoh)
- #890 Remove unused method
def_serializer(@JustinAiken) - #887 Fixing tests on JRuby (@joaomdmoura)
- #885 Updates rails versions for test and dev (@tonyta)
v0.10.0.rc1 (2015/04/22 06:06 +00:00)
- #810 Adding Fragment Cache to AMS (@joaomdmoura)
- adds fragment cache support
- #868 Fixed a bug that appears when a nil association is included (@groyoh)
- #861 README: Add emphasis to single-word difference (@machty)
- #858 Included resource fixes (@mateomurphy)
- #853 RC3 Updates for JSON API (@mateomurphy)
- #852 Fix options merge order in
each_association(@mateomurphy) - #850 Use association value for determining serializer used (@mateomurphy)
- #843 Remove the mailing list from the README (@JoshSmith)
- #842 Add notes on how you can help to contributing documentation (@JoshSmith)
- #833 Cache serializers for class (@lsylvester)
- #837 Store options in array serializers (@kurko)
- #836 Makes passed in options accessible inside serializers (@kurko)
- #773 Make json api adapter 'include' option accept an array (@sweatypitts)
- #830 Add contributing readme (@JoshSmith)
- #811 Reimplement serialization scope and scope_name (@mateomurphy)
- #725 Support has_one to be compatible with 0.8.x (@ggordon)
- adds
has_oneattribute for backwards compatibility
- adds
- #822 Replace has_one with attribute in template (@bf4)
- #821 Fix explicit serializer for associations (@wjordan)
- #798 Fix lost test
test_include_multiple_posts_and_linked(@donbobka) - #807 Add Overriding attribute methods section to README. (@alexstophel)
- #693 Cache Support at AMS 0.10.0 (@joaomdmoura)
- adds cache support to attributes and associations.
- #792 Association overrides (@kurko)
- adds method to override association
- #794 add to_param for correct URL generation (@carlesjove)
v0.10.0-pre
- Introduce Adapter
- Prefer
ActiveModel::SerializertoActiveModelSerializers:
0.09.x
v0.9.3 (2015/01/21 20:29 +00:00)
Features:
- #774 Fix nested include attributes (@nhocki)
- #771 Make linked resource type names consistent with root names (@sweatypitts)
- #696 Explicitly set serializer for associations (@ggordon)
- #700 sparse fieldsets (@arenoir)
- #768 Adds support for
metaandmeta_keyattribute (@kurko)
v0.9.1 (2014/12/04 11:54 +00:00)
- #707 A Friendly Note on Which AMS Version to Use (@jherdman)
- #730 Fixes nested has_many links in JSONAPI (@kurko)
- #718 Allow overriding the adapter with render option (@ggordon)
- #720 Rename attribute with :key (0.8.x compatibility) (@ggordon)
- #728 Use type as key for linked resources (@kurko)
- #729 Use the new beta build env on Travis (@joshk)
- #703 Support serializer and each_serializer options in renderer (@ggordon, @mieko)
- #727 Includes links inside of linked resources (@kurko)
- #726 Bugfix: include nested has_many associations (@kurko)
- #722 Fix infinite recursion (@ggordon)
- #1 Allow for the implicit use of ArraySerializer when :each_serializer is specified (@mieko)
- #692 Include 'linked' member for json-api collections (@ggordon)
- #714 Define as_json instead of to_json (@guilleiguaran)
- #710 JSON-API: Don't include linked section if associations are empty (@guilleiguaran)
- #711 Fixes rbx gems bundling on TravisCI (@kurko)
- #709 Add type key when association name is different than object type (@guilleiguaran)
- #708 Handle correctly null associations (@guilleiguaran)
- #691 Fix embed option for associations (@jacob-s-son)
- #689 Fix support for custom root in JSON-API adapter (@guilleiguaran)
- #685 Serialize ids as strings in JSON-API adapter (@guilleiguaran)
- #684 Refactor adapters to implement support for array serialization (@guilleiguaran)
- #682 Include root by default in JSON-API serializers (@guilleiguaran)
- #625 Add DSL for urls (@JordanFaust)
- #677 Add support for embed: :ids option for in associations (@guilleiguaran)
- #681 Check superclasses for Serializers (@quainjn)
- #680 Add support for root keys (@NullVoxPopuli)
- #675 Support Rails 4.2.0 (@tricknotes)
- #667 Require only activemodel instead of full rails (@guilleiguaran)
- #653 Add "_test" suffix to JsonApi::HasManyTest filename. (@alexgenco)
- #631 Update build badge URL (@craiglittle)
0.9.0.alpha1 - January 7, 2014
0.9.0.pre
-
The following methods were removed
- Model#active_model_serializer
- Serializer#include!
- Serializer#include?
- Serializer#attr_disabled=
- Serializer#cache
- Serializer#perform_caching
- Serializer#schema (needs more discussion)
- Serializer#attribute
- Serializer#include_#{name}? (filter method added)
- Serializer#attributes (took a hash)
-
The following things were added
- Serializer#filter method
- CONFIG object
-
Remove support for ruby 1.8 versions.
-
Require rails >= 3.2.
-
Serializers for associations are being looked up in a parent serializer's namespace first. Same with controllers' namespaces.
-
Added a "prefix" option in case you want to use a different version of serializer.
-
Serializers default namespace can be set in
default_serializer_optionsand inherited by associations. -
Beginning of rewrite: c65d387705ec534db171712671ba7fcda4f49f68
0.08.x
v0.8.3 (2014/12/10 14:45 +00:00)
v0.8.2 (2014/09/01 21:00 +00:00)
- #612 Feature/adapter (@bolshakov)
- adds adapters pattern
- #615 Rails does not support const_defined? in development mode (@tpitale)
- #613 README: typo fix on attributes (@spk)
- #614 Fix rails 4.0.x build. (@arthurnn)
- #610 ArraySerializer (@bolshakov)
- #607 ruby syntax highlights (@zigomir)
- #602 Add DSL for associations (@JordanFaust)
0.8.1 (May 6, 2013)
- Fix bug whereby a serializer using 'options' would blow up.
0.8.0 (May 5, 2013)
-
Attributes can now have optional types.
-
A new DefaultSerializer ensures that POROs behave the same way as ActiveModels.
-
If you wish to override ActiveRecord::Base#to_Json, you can now require 'active_record/serializer_override'. We don't recommend you do this, but many users do, so we've left it optional.
-
Fixed a bug where ActionController wouldn't always have MimeResponds.
-
An optinal caching feature allows you to cache JSON & hashes that AMS uses. Adding 'cached true' to your Serializers will turn on this cache.
-
URL helpers used inside of Engines now work properly.
-
Serializers now can filter attributes with
onlyandexcept:UserSerializer.new(user, only: [:first_name, :last_name]) UserSerializer.new(user, except: :first_name) -
Basic Mongoid support. We now include our mixins in the right place.
-
On Ruby 1.8, we now generate an
idmethod that properly serializesidcolumns. See issue #127 for more. -
Add an alias for
scopemethod to be the name of the context. By default this iscurrent_user. The name is automatically set when usingserialization_scopein the controller. -
Pass through serialization options (such as
:include) when a model has no serializer defined.
0.7.0 (March 6, 2013)
embed_keyoption to allow embedding by attributes other than IDs- Fix rendering nil with custom serializer
- Fix global
self.root = false - Add support for specifying the serializer for an association as a String
- Able to specify keys on the attributes method
- Serializer Reloading via ActiveSupport::DescendantsTracker
- Reduce double map to once; Fixes datamapper eager loading.
0.6.0 (October 22, 2012)
- Serialize sets properly
- Add root option to ArraySerializer
- Support polymorphic associations
- Support :each_serializer in ArraySerializer
- Add
scopemethod to easily access the scope in the serializer - Fix regression with Rails 3.2.6; add Rails 4 support
- Allow serialization_scope to be disabled with serialization_scope nil
- Array serializer should support pure ruby objects besides serializers
0.05.x
0.5.2 (June 5, 2012)
0.5.1 (May 23, 2012)
0.5.0 (May 16, 2012)
- First tagged version
- Changes generators to always generate an ApplicationSerializer
0.1.0 (December 21, 2011)
First Commit as Rails Serializers 0.0.1
(December 1, 2011).
Prehistory
- Changing Serialization/Serializers namespace to
Serializable(November 30, 2011) - Proposed Implementation to Rails 3.2 by @wycats and @josevalim (November 25, 2011)
- Creation of
ActiveModel::SerializationfromActiveModel::Serializerin Rails (2009) - Integration of
ActiveModel::SerializerintoActiveRecord::Serialization - Creation of
ActiveModel::Serializerin Rails (2009) - Creation of
ActiveModel::Serializers::JSONin Rails (2009)