Class: USerializer::HasOne

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, opts) ⇒ HasOne

Returns a new instance of HasOne.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/userializer/has_one.rb', line 3

def initialize(key, opts)
  @key = key
  @opts = opts
  @id_key = opts[:id_key] || "#{key}_id".to_sym
  @root_key = opts[:root]&.to_sym

  serializer = opts[:serializer]

  @serializer = if serializer&.is_a?(Proc)
                  @serializer = serializer
                elsif serializer
                  proc { serializer }
                end

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

Instance Attribute Details

#id_keyObject (readonly)

Returns the value of attribute id_key.



21
22
23
# File 'lib/userializer/has_one.rb', line 21

def id_key
  @id_key
end

#keyObject (readonly)

Returns the value of attribute key.



21
22
23
# File 'lib/userializer/has_one.rb', line 21

def key
  @key
end

Instance Method Details

#merge_attributes(res, ser, opts) ⇒ Object



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

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

  obj = ser.send(@key)
  res[@id_key] = obj.nil? ? nil : obj.send(@embed_key)
end

#merge_root(res, ser, opts) ⇒ Object



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

def merge_root(res, ser, opts)
  obj = ser.send(@key)

  return if obj.nil? || !@conditional_block.call(ser.object, opts)

  serializer(obj, opts).merge_root(res, root_key(obj), false, opts)
end