Sha256: 9b10d794e9309bb3c94d711741a95e3fde297a16969e5619b3867b13e7070677

Contents?: true

Size: 1.5 KB

Versions: 21

Compression:

Stored size: 1.5 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,
      'RichText' => RichTextCoercion
    }

    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, configuration)
      return value if type.nil?
      return value if value.nil?

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

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
contentful-2.17.1 lib/contentful/field.rb
contentful-2.17.0 lib/contentful/field.rb
contentful-2.16.3 lib/contentful/field.rb
contentful-2.16.2 lib/contentful/field.rb
contentful-2.16.1 lib/contentful/field.rb
contentful-2.16.0 lib/contentful/field.rb
contentful-2.15.4 lib/contentful/field.rb
contentful-2.15.3 lib/contentful/field.rb
contentful-2.15.2 lib/contentful/field.rb
contentful-2.15.1 lib/contentful/field.rb
contentful-2.15.0 lib/contentful/field.rb
contentful-2.14.0 lib/contentful/field.rb
contentful-2.13.3 lib/contentful/field.rb
contentful-2.13.2 lib/contentful/field.rb
contentful-2.13.1 lib/contentful/field.rb
contentful-2.13.0 lib/contentful/field.rb
contentful-2.12.0 lib/contentful/field.rb
contentful-2.11.1 lib/contentful/field.rb
contentful-2.11.0 lib/contentful/field.rb
contentful-2.10.1 lib/contentful/field.rb