Sha256: ad04e3012d97bc2d7fe7b891ffd4d9beaaa4e2958fc31d4ba7e5b046a6ed0f5c

Contents?: true

Size: 1.86 KB

Versions: 9

Compression:

Stored size: 1.86 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
          return doc["value"] = [] if multiple

          doc["value"] = nil
        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) # rubocop:disable Metrics/AbcSize
          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|
              next if v.nil? || v.is_a?(Numeric)

              raise "Invalid number type #{v.class}"
            end

            doc["value"] = value
          when "boolean"
            doc["value"] = !!value
          when "date"
            maybe_multiple(value) do |v|
              next if v.nil? || v.respond_to?(:to_date)

              raise "Invalid date type #{v.class}"
            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, &block)
          if multiple
            raise "Expected Array, got #{value.class}" unless value.is_a?(Array)

            value.map(&block)
          else
            yield value
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
ecoportal-api-0.10.8 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.7 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.6 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.5 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.4 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.3 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.2 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.1 lib/ecoportal/api/v1/schema_field_value.rb
ecoportal-api-0.10.0 lib/ecoportal/api/v1/schema_field_value.rb