Class: Ecoportal::API::V1::SchemaFieldValue

Inherits:
Common::BaseModel show all
Defined in:
lib/ecoportal/api/v1/schema_field_value.rb

Direct Known Subclasses

Internal::SchemaFieldValue

Instance Attribute Summary

Attributes inherited from Common::BaseModel

#_key, #_parent

Instance Method Summary collapse

Methods inherited from Common::BaseModel

#as_json, #as_update, #consolidate!, #dirty?, #doc, embeds_one, #initial_doc, #initialize, #original_doc, passthrough, #print_pretty, #replace_doc!, #replace_original_doc!, #reset!, #to_json

Methods included from Common::BaseClass

#class_resolver, #redef_without_warning, #resolve_class

Constructor Details

This class inherits a constructor from Ecoportal::API::Common::BaseModel

Instance Method Details

#clearObject



8
9
10
11
12
13
14
# File 'lib/ecoportal/api/v1/schema_field_value.rb', line 8

def clear
  if multiple
    doc["value"] = []
  else
    doc["value"] = nil
  end
end

#maybe_multiple(value) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/ecoportal/api/v1/schema_field_value.rb', line 60

def maybe_multiple(value)
  if multiple
    unless value.is_a?(Array)
      raise "Expected Array, got #{value.class}"
    end
    value.map {|v| yield v }
  else
    yield value
  end
end

#valueObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ecoportal/api/v1/schema_field_value.rb', line 16

def value
  case type
  when "text", "phone_number", "number", "boolean", "select"
   doc["value"]
  when "date"
   if doc["value"]
     maybe_multiple(doc["value"]) do |v|
       Date.iso8601(v)
     end
   end
  else
   raise "Unknown type #{type}"
  end
end

#value=(value) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ecoportal/api/v1/schema_field_value.rb', line 31

def value=(value)
  case type
  when "text", "phone_number", "select"
    doc["value"] = maybe_multiple(value) do |v|
      v&.to_s
    end
  when "number"
    maybe_multiple(value) do |v|
      unless v.nil? || v.is_a?(Numeric)
        raise "Invalid number type #{v.class}"
      end
    end
    doc["value"] = value
  when "boolean"
    doc["value"] = !!value
  when "date"
    maybe_multiple(value) do |v|
      unless v.nil? || v.respond_to?(:to_date)
        raise "Invalid date type #{v.class}"
      end
    end
    doc["value"] = maybe_multiple(value) do |v|
      v&.to_date&.to_s
    end
  else
    raise "Unknown type #{type}"
  end
end