Class: Apia::FieldSet

Inherits:
Hash
  • Object
show all
Defined in:
lib/apia/field_set.rb

Instance Method Summary collapse

Instance Method Details

#add(field) ⇒ Apia::Field

Add a new field to the fieldset

Parameters:

  • field (Apia::Field)

Returns:

  • (Apia::Field)


16
17
18
# File 'lib/apia/field_set.rb', line 16

def add(field)
  self[field.name] = field
end

#generate_hash(source, request: nil, path: []) ⇒ Hash

Generate a hash for the fields that are defined on this object. It should receive the source object as well as a request

Parameters:

Returns:

  • (Hash)


40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/apia/field_set.rb', line 40

def generate_hash(source, request: nil, path: [])
  each_with_object({}) do |(_, field), hash|
    next unless field.include?(source, request)

    field_path = path + [field]
    next if request&.endpoint && !request&.endpoint&.include_field?(field_path)

    value = field.value(source, request: request, path: field_path)
    next if value == :skip

    hash[field.name.to_sym] = value
  end
end

#specFieldSpec

Generate a default field spec for this field set based on the values provided for the include option.

Returns:



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/apia/field_set.rb', line 58

def spec
  @spec ||= begin
    spec = each_with_object([]) do |(key, field), array|
      next if field.include == false

      if field.include.is_a?(::String)
        array << "#{key}[#{field.include}]"
      elsif field.type.object? || field.type.polymorph?
        array << "#{key}[*]"
      else
        array << key
      end
    end.join(',')
    FieldSpec.parse(spec)
  end
end

#validate(errors, object) ⇒ void

This method returns an undefined value.

Validate this field set and add errors as appropriate

Parameters:



25
26
27
28
29
30
31
# File 'lib/apia/field_set.rb', line 25

def validate(errors, object)
  each_value do |field|
    unless field.type.usable_for_field?
      errors.add object, 'InvalidFieldType', "Type for field #{field.name} must be a scalar, enum or object"
    end
  end
end