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)


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

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

#generate_hash(source, request: nil, path: [], object: nil) ⇒ 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:

  • source (Object, Hash)
  • request (Apia::Request) (defaults to: nil)
  • object (Apia::Object) (defaults to: nil)

    the object that this fieldset belongs to

  • only (Array)

Returns:

  • (Hash)


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

def generate_hash(source, request: nil, path: [], object: nil)
  new_hash = GeneratedHash.enabled? ? GeneratedHash.new(object, source, path: path) : {}
  each_with_object(new_hash) 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:



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

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:



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

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