module Contentful::Management::Resource::FieldAware

Module for creating Fields based off of ContentTypes

Public Class Methods

create_fields_for_content_type(entry, method = :instance) click to toggle source

Creates fields for entry based on it's ContentType

@param [Entry] entry the expected entry to modify

# File lib/contentful/management/resource/field_aware.rb, line 9
def self.create_fields_for_content_type(entry, method = :instance)
  entry.content_type.fields.each do |field|
    accessor_name = Support.snakify(field.id)

    FieldAware.create_getter(entry, accessor_name, field, method)
    FieldAware.create_setter(entry, accessor_name, field, method)
  end
end
create_getter(entry, accessor_name, field, method) click to toggle source

Creates getters for field @private

# File lib/contentful/management/resource/field_aware.rb, line 20
def self.create_getter(entry, accessor_name, field, method)
  entry.send("#{method}_eval") do
    send(FieldAware.define(method), accessor_name) do
      fields[field.id.to_sym]
    end

    send(FieldAware.define(method), "#{accessor_name}_with_locales") do
      fields_for_query(false)[field.id.to_sym]
    end
  end
end
create_setter(entry, accessor_name, field, method) click to toggle source

Creates setters for field @private

# File lib/contentful/management/resource/field_aware.rb, line 34
def self.create_setter(entry, accessor_name, field, method)
  entry.send("#{method}_eval") do
    send(FieldAware.define(method), "#{accessor_name}=") do |value|
      FieldAware.create_setter_field(self, field, value, locale, default_locale)
    end

    send(FieldAware.define(method), "#{accessor_name}_with_locales=") do |values|
      values.each do |locale, value|
        FieldAware.create_setter_field(self, field, value, locale, default_locale)
      end
    end
  end
end
create_setter_field(entry, field, value, locale, default_locale) click to toggle source

Sets fields with value for locale @private

# File lib/contentful/management/resource/field_aware.rb, line 50
def self.create_setter_field(entry, field, value, locale, default_locale)
  fields = entry.instance_variable_get(:@fields)

  return unless localized_or_default_locale(field, default_locale, locale)

  fields[locale] ||= {}
  fields[locale][field.id.to_sym] = value
end
define(class_or_instance) click to toggle source

@private

# File lib/contentful/management/resource/field_aware.rb, line 71
def self.define(class_or_instance)
  "define_#{class_or_instance == :instance ? 'singleton_' : ''}method"
end
localized_or_default_locale(field, default_locale, locale) click to toggle source

Verifies if field is localized or default locale matches current locale

@param [Field] field an entry field @param [String] default_locale @param [String] locale

@return [Boolean]

# File lib/contentful/management/resource/field_aware.rb, line 66
def self.localized_or_default_locale(field, default_locale, locale)
  field.localized || default_locale == locale
end