Sha256: 90c397efdd6cbc65af839d0b69c5ddf99e3e0367a27abf57095b429aac3610c1

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

module Ecoportal
  module API
    class V1
      # @todo Rename to PersonDetailsField
      class SchemaFieldValue < Common::BaseModel
        passthrough :id, :alt_id, :type, :name, :shared, :multiple

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

        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

        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

        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
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ecoportal-api-0.9.7 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.9.6 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.9.5 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.9.4 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.9.3 lib/ecoportal/api/v1/schema_field_value.rb