Class: USerializer::ArraySerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/userializer/array_serializer.rb

Instance Method Summary collapse

Constructor Details

#initialize(objs, opts = {}) ⇒ ArraySerializer

Returns a new instance of ArraySerializer.

Raises:



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

#scopeObject



52
# File 'lib/userializer/array_serializer.rb', line 52

def scope; @opts[:scope]; end

#to_hashObject



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_jsonObject



48
49
50
# File 'lib/userializer/array_serializer.rb', line 48

def to_json
  Oj.dump(to_hash, mode: :compat)
end