Class: USerializer::ArraySerializer
- Inherits:
-
Object
- Object
- USerializer::ArraySerializer
- Defined in:
- lib/userializer/array_serializer.rb
Instance Method Summary collapse
-
#initialize(objs, opts = {}, embed_empty_array: false) ⇒ ArraySerializer
constructor
A new instance of ArraySerializer.
- #merge_root(res, opts) ⇒ Object
- #scope ⇒ Object
- #to_hash ⇒ Object
- #to_json ⇒ Object
Constructor Details
#initialize(objs, opts = {}, embed_empty_array: false) ⇒ ArraySerializer
Returns a new instance of ArraySerializer.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/userializer/array_serializer.rb', line 7 def initialize(objs, opts = {}, embed_empty_array: false) @objs = objs.compact @opts = opts @meta = opts[:meta] @embed_empty_array = clss = @objs.map(&:class).uniq obj_class = clss.first raise HeterogeneousArray if clss.count > 1 @root_key = opts[:root]&.to_sym @root_key ||= ActiveSupport::Inflector.pluralize( ActiveSupport::Inflector.underscore(obj_class.name).split('/').last ).to_sym if obj_class serializer = opts[:each_serializer] @serializer = if serializer&.is_a?(Proc) serializer elsif serializer proc { serializer } end end |
Instance Method Details
#merge_root(res, opts) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/userializer/array_serializer.rb', line 32 def merge_root(res, opts) res[@root_key] ||= [] if @embed_empty_array @objs.each do |obj| serializer(obj, opts).merge_root(res, @root_key, false, opts) end end |
#scope ⇒ Object
54 |
# File 'lib/userializer/array_serializer.rb', line 54 def scope; @opts[:scope]; end |
#to_hash ⇒ Object
39 40 41 42 43 44 45 46 47 48 |
# File 'lib/userializer/array_serializer.rb', line 39 def to_hash res = {} res[@root_key] = [] if @root_key merge_root(res, @opts) res[:meta] = @meta if @meta res end |
#to_json ⇒ Object
50 51 52 |
# File 'lib/userializer/array_serializer.rb', line 50 def to_json Oj.dump(to_hash, mode: :compat) end |