Sha256: c91834e77811f7b04a2eee570d5bedef87747b149f3b026a800858e2612dce65

Contents?: true

Size: 1.4 KB

Versions: 10

Compression:

Stored size: 1.4 KB

Contents

require_relative 'location'
require_relative 'coercions'

module Contentful
  # A ContentType's field schema
  # See https://www.contentful.com/developers/documentation/content-management-api/#resources-content-types-fields
  class Field
    # Coercions from Contentful Types to Ruby native types
    KNOWN_TYPES = {
      'String'   => StringCoercion,
      'Text'     => TextCoercion,
      'Symbol'   => SymbolCoercion,
      'Integer'  => IntegerCoercion,
      'Number'   => FloatCoercion,
      'Boolean'  => BooleanCoercion,
      'Date'     => DateCoercion,
      'Location' => LocationCoercion,
      'Object'   => ObjectCoercion,
      'Array'    => ArrayCoercion,
      'Link'     => LinkCoercion
    }

    attr_reader :raw, :id, :name, :type, :link_type, :items, :required, :localized

    def initialize(json)
      @raw = json
      @id = json.fetch('id', nil)
      @name = json.fetch('name', nil)
      @type = json.fetch('type', nil)
      @link_type = json.fetch('linkType', nil)
      @items = json.key?('items') ? Field.new(json.fetch('items', {})) : nil
      @required = json.fetch('required', false)
      @localized = json.fetch('localized', false)
    end

    # Coerces value to proper type
    def coerce(value)
      return value if type.nil?

      options = {}
      options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil?
      KNOWN_TYPES[type].new(value, options).coerce
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
contentful-2.2.2 lib/contentful/field.rb
contentful-2.2.1 lib/contentful/field.rb
contentful-2.2.0 lib/contentful/field.rb
contentful-2.1.3 lib/contentful/field.rb
contentful-2.1.2 lib/contentful/field.rb
contentful-2.1.1 lib/contentful/field.rb
contentful-2.1.0 lib/contentful/field.rb
contentful-2.0.3 lib/contentful/field.rb
contentful-2.0.2 lib/contentful/field.rb
contentful-2.0.1 lib/contentful/field.rb