123456789_123456789_123456789_123456789_123456789_

Class: ActiveModel::SchematizedJson::DataAccessor

Do not use. This class is for internal use only.
Relationships & Source Files
Inherits: Object
Defined in: activemodel/lib/active_model/schematized_json.rb

Class Method Summary

Instance Method Summary

Constructor Details

.new(schema, data:) ⇒ DataAccessor

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 70

def initialize(schema, data:)
  @schema, @data = schema, data
  update_data_with_schema_defaults
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, **kwargs) (private)

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 80

def method_missing(method_name, *args, **kwargs)
  key = method_name.to_s.remove(/(\?|=)/)

  if @schema.key? key.to_sym
    if method_name.ends_with?("?")
      @data[key].present?
    elsif method_name.ends_with?("=")
      @data[key] = lookup_schema_type_for(key).cast(args.first)
    else
      @data[key]
    end
  else
    super
  end
end

Instance Method Details

#assign_data_with_type_casting(new_data)

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 75

def assign_data_with_type_casting(new_data)
  new_data.each { |k, v| public_send "#{k}=", v }
end

#lookup_schema_type_for(key) (private)

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 100

def lookup_schema_type_for(key)
  type_or_default_value = @schema[key.to_sym]

  case type_or_default_value
  when :boolean, :integer, :string
    ActiveModel::Type.lookup type_or_default_value
  when TrueClass, FalseClass
    ActiveModel::Type.lookup :boolean
  when Integer
    ActiveModel::Type.lookup :integer
  when String
    ActiveModel::Type.lookup :string
  else
    raise ArgumentError, "Only boolean, integer, or strings are allowed as JSON schema types"
  end
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean (private)

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 96

def respond_to_missing?(method_name, include_private = false)
  @schema.key?(method_name.to_s.remove(/[?=]/).to_sym) || super
end

#update_data_with_schema_defaults (private)

Types that are declared using real values, like true/false, 5, or “hello”, will be used as defaults. Types that are declared using symbols, like :boolean, :integer, :string, will be nulled out.

[ GitHub ]

  
# File 'activemodel/lib/active_model/schematized_json.rb', line 119

def update_data_with_schema_defaults
  @data.reverse_merge!(@schema.to_h { |attr, type| [ attr.to_s, type.is_a?(Symbol) ? nil : type ] })
end