class ActiveRecord::TypedStore::Field

Constants

TYPES

Attributes

accessor[R]
array[R]
blank[R]
default[R]
name[R]
null[R]
type[R]
type_sym[R]

Public Class Methods

new(name, type, options={}) click to toggle source
# File lib/active_record/typed_store/field.rb, line 7
def initialize(name, type, options={})
  type_options = options.slice(:scale, :limit, :precision)
  @type = lookup_type(type, type_options)
  @type_sym = type

  @accessor = options.fetch(:accessor, true)
  @name = name
  if options.key?(:default)
    @default = extract_default(options[:default])
  end
  @null = options.fetch(:null, true)
  @blank = options.fetch(:blank, true)
  @array = options.fetch(:array, false)
end

Public Instance Methods

cast(value) click to toggle source
# File lib/active_record/typed_store/field.rb, line 26
def cast(value)
  casted_value = type_cast(value)
  if !blank
    casted_value = default if casted_value.blank?
  elsif !null
    casted_value = default if casted_value.nil?
  end
  casted_value
end
has_default?() click to toggle source
# File lib/active_record/typed_store/field.rb, line 22
def has_default?
  defined?(@default)
end

Private Instance Methods

extract_default(value) click to toggle source
# File lib/active_record/typed_store/field.rb, line 54
def extract_default(value)
  # 4.2 workaround
  return value if (type_sym == :string || type_sym == :text) && value.nil?

  type_cast(value)
end
lookup_type(type, options) click to toggle source
# File lib/active_record/typed_store/field.rb, line 50
def lookup_type(type, options)
  TYPES.fetch(type).new(**options)
end
type_cast(value, arrayize: true) click to toggle source
# File lib/active_record/typed_store/field.rb, line 61
def type_cast(value, arrayize: true)
  if array && (arrayize || value.is_a?(Array))
    return [] if arrayize && !value.is_a?(Array)
    return value.map { |v| type_cast(v, arrayize: false) }
  end

  # 4.2 workaround
  if type_sym == :string || type_sym == :text
    return value.to_s unless value.blank? && (null || array)
  end

  if type.respond_to?(:cast)
    type.cast(value)
  else
    type.type_cast_from_user(value)
  end
end