Class: USerializer::HasMany

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, opts) ⇒ HasMany

Returns a new instance of HasMany.



5
6
7
8
9
10
11
12
13
# File 'lib/userializer/has_many.rb', line 5

def initialize(key, opts)
  @key = key

  @opts = opts
  @ids_key = opts[:ids_key] || build_ids_key(key)

  @embed_key = opts[:embed_key] || :id
  @conditional_block = opts[:if] || proc { true }
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



3
4
5
# File 'lib/userializer/has_many.rb', line 3

def key
  @key
end

Instance Method Details

#entities(ser) ⇒ Object



31
32
33
34
35
36
# File 'lib/userializer/has_many.rb', line 31

def entities(ser)
  obj = ser.send(@key) || []
  return obj unless @opts[:scope]

  obj.send(@opts[:scope])
end

#merge_attributes(res, ser, opts) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/userializer/has_many.rb', line 15

def merge_attributes(res, ser, opts)
  return unless @conditional_block.call(ser.object, opts)

  res[@ids_key] = (entities(ser) || []).compact.map do |obj|
    obj.nil? ? nil : obj.send(@embed_key)
  end.compact
end

#merge_root(res, ser, opts) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/userializer/has_many.rb', line 23

def merge_root(res, ser, opts)
  objs = entities(ser) || []

  return if objs.empty? || !@conditional_block.call(ser.object, opts)

  ArraySerializer.new(objs, @opts).merge_root(res, opts)
end