Class: AttrJson::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_json/config.rb

Overview

Intentionally non-mutable, to avoid problems with subclass inheritance and rails class_attribute. Instead, you set to new Config object changed with #merge.

Constant Summary collapse

RECORD_ALLOWED_KEYS =
%i{
  default_container_attribute
  default_accepts_nested_attributes
}
MODEL_ALLOWED_KEYS =
%i{
  unknown_key
  bad_cast
  time_zone_aware_attributes
}
DEFAULTS =
{
  default_container_attribute: "json_attributes",
  unknown_key: :raise
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Config

Returns a new instance of Config.



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/attr_json/config.rb', line 30

def initialize(options = {})
  @mode = options.delete(:mode)
  unless mode == :record || mode == :model
    raise ArgumentError, "required :mode argument must be :record or :model"
  end
  valid_keys = mode == :record ? RECORD_ALLOWED_KEYS : MODEL_ALLOWED_KEYS
  options.assert_valid_keys(valid_keys)

  options.reverse_merge!(DEFAULTS.slice(*valid_keys))

  @attributes = options
end

Instance Attribute Details

#modeObject (readonly)

Returns the value of attribute mode.



28
29
30
# File 'lib/attr_json/config.rb', line 28

def mode
  @mode
end

Instance Method Details

#merge(changes = {}) ⇒ Object

Returns a new Config object, with changes merged in.



44
45
46
# File 'lib/attr_json/config.rb', line 44

def merge(changes = {})
  self.class.new(attributes.merge(changes).merge(mode: mode))
end