Sha256: b3eecb0fe9573e79abe2cd1f20f2099d0ae6a3caf7f394d4cb81044f9a206523

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 KB

Contents

require_relative 'resource'
require_relative 'resource/fields'
require_relative 'location'

module Contentful
  class DynamicEntry < Entry
    KNOWN_TYPES = {
      'String'   => :string,
      'Text'     => :string,
      'Symbol'   => :string,
      'Integer'  => :integer,
      'Float'    => :float,
      'Boolean'  => :boolean,
      'Date'     => :date,
      'Location' => Location
    }

    def self.create(content_type)
      unless content_type.is_a? ContentType
        content_type = ContentType.new(content_type)
      end

      fields_coercions = Hash[
                         content_type.fields.map do |field|
                           [field.id.to_sym, KNOWN_TYPES[field.type]]
                         end
      ]

      Class.new DynamicEntry do
        content_type.fields.each do |f|
          define_method Support.snakify(f.id).to_sym do |wanted_locale = default_locale|
            fields(wanted_locale)[f.id.to_sym]
          end
        end

        define_singleton_method :fields_coercions do
          fields_coercions
        end

        define_singleton_method :content_type do
          content_type
        end

        define_singleton_method :to_s do
          "Contentful::DynamicEntry[#{content_type.id}]"
        end

        define_singleton_method :inspect do
          "Contentful::DynamicEntry[#{content_type.id}]"
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
contentful-0.8.0 lib/contentful/dynamic_entry.rb
contentful-0.7.0 lib/contentful/dynamic_entry.rb