Method: AttrJson::Model.attr_json

Defined in:
lib/attr_json/model.rb

.attr_json(name, type, **options) ⇒ Object

Type can be an instance of an ActiveModel::Type::Value subclass, or a symbol that will be looked up in ActiveModel::Type.lookup

Parameters:

  • name (Symbol, String)

    name of attribute

  • type (ActiveModel::Type::Value)

    An instance of an ActiveModel::Type::Value (or subclass)

  • options (Hash)

    a customizable set of options

Options Hash (**options):

  • :array (Boolean) — default: false

    Make this attribute an array of given type. Array types default to an empty array. If you want to turn that off, you can add default: AttrJson::AttributeDefinition::NO_DEFAULT_PROVIDED

  • :default (Object) — default: nil

    Default value, if a Proc object it will be #call'd for default.

  • :store_key (String, Symbol) — default: nil

    Serialize to JSON using given store_key, rather than name as would be usual.

  • :validate (Boolean) — default: true

    Mak validation errors on the attributes post up to self, using something similar to an ActiveRecord::Validations::AssociatedValidator



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/attr_json/model.rb', line 213

def attr_json(name, type, **options)
  options.assert_valid_keys(*(AttributeDefinition::VALID_OPTIONS - [:container_attribute] + [:validate]))

  type = _attr_json_maybe_wrap_timezone_aware(type)

  self.attr_json_registry = attr_json_registry.with(
    AttributeDefinition.new(name.to_sym, type, options.except(:validate))
  )

  # By default, automatically validate nested models
  if (type.kind_of?(AttrJson::Type::Model) || type.kind_of?(AttrJson::Type::PolymorphicModel)) && options[:validate] != false
    # Post validations up with something based on ActiveRecord::Validations::AssociatedValidator
    self.validates_with ::AttrJson::Model::NestedModelValidator, attributes: [name.to_sym]
  end

  _attr_jsons_module.module_eval do
    define_method("#{name}=") do |value|
      _attr_json_write(AttrJson.efficient_to_s(name), value)
    end

    define_method("#{name}") do
      attributes[AttrJson.efficient_to_s(name)]
    end
  end
end