Class: USerializer::ArraySerializer
- Inherits:
-
Object
- Object
- USerializer::ArraySerializer
- Defined in:
- lib/userializer/array_serializer.rb
Instance Method Summary collapse
-
#initialize(objs, opts = {}) ⇒ 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 = {}) ⇒ 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 |
# File 'lib/userializer/array_serializer.rb', line 7 def initialize(objs, opts = {}) @objs = objs.compact @opts = opts @meta = opts[:meta] 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
31 32 33 34 35 |
# File 'lib/userializer/array_serializer.rb', line 31 def merge_root(res, opts) @objs.each do |obj| serializer(obj, opts).merge_root(res, @root_key, false, opts) end end |
#scope ⇒ Object
52 |
# File 'lib/userializer/array_serializer.rb', line 52 def scope; @opts[:scope]; end |
#to_hash ⇒ Object
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/userializer/array_serializer.rb', line 37 def to_hash res = {} res[@root_key] = [] if @root_key merge_root(res, @opts) res[:meta] = @meta if @meta res end |
#to_json ⇒ Object
48 49 50 |
# File 'lib/userializer/array_serializer.rb', line 48 def to_json Oj.dump(to_hash, mode: :compat) end |