Class: FastSerializer::SerializedField

Inherits:
Object
  • Object
show all
Defined in:
lib/fast_serializer/serialized_field.rb

Overview

Data structure used internally for maintaining a field to be serialized.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, optional: false, serializer: nil, serializer_options: nil, enumerable: false, condition: nil) ⇒ SerializedField

Create a new serialized field.

Parameters:

  • name (Symbol)

    the name of the field

  • optional (Boolean) (defaults to: false)

    whether the field is optional

  • serializer (Class) (defaults to: nil)

    the serializer to use for the field

  • serializer_options (Hash) (defaults to: nil)

    the options to pass to the serializer

  • enumerable (Boolean) (defaults to: false)

    whether the field is enumerable

  • condition (Proc) (defaults to: nil)

    a condition to determine whether the field should be serialized



16
17
18
19
20
21
22
23
24
25
# File 'lib/fast_serializer/serialized_field.rb', line 16

def initialize(name, optional: false, serializer: nil, serializer_options: nil, enumerable: false, condition: nil)
  @name = name.to_sym
  @optional = !!optional
  @condition = condition
  if serializer
    @serializer = serializer
    @serializer_options = serializer_options
    @enumerable = enumerable
  end
end

Instance Attribute Details

#conditionObject (readonly)

Returns the value of attribute condition.



6
7
8
# File 'lib/fast_serializer/serialized_field.rb', line 6

def condition
  @condition
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/fast_serializer/serialized_field.rb', line 6

def name
  @name
end

Instance Method Details

#optional?Boolean

Returns true if the field is optional.

Returns:

  • (Boolean)

    true if the field is optional



28
29
30
# File 'lib/fast_serializer/serialized_field.rb', line 28

def optional?
  @optional
end

#serialize(value, options = nil) ⇒ Object

Wrap a value in the serializer if one has been set. Otherwise just returns the raw value.

Parameters:

  • value (Object)

    the value to serialize

  • options (Hash) (defaults to: nil)

    the options to pass to the serializer

Returns:

  • (Object)

    the serialized value



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/fast_serializer/serialized_field.rb', line 37

def serialize(value, options = nil)
  if value && @serializer
    serializer = nil
    serializer = if @enumerable
      ArraySerializer.new(value, serializer: @serializer, serializer_options: serializer_options(options))
    else
      @serializer.new(value, serializer_options(options))
    end
    context = SerializationContext.current
    if context
      context.with_reference(value) { serializer.as_json }
    else
      serializer.as_json
    end
  else
    serialize_value(value)
  end
end