Class: Trax::Model::Attributes::Types::Struct

Inherits:
Trax::Model::Attributes::Type show all
Defined in:
lib/trax/model/attributes/types/struct.rb

Defined Under Namespace

Classes: TypeCaster, Value

Class Method Summary collapse

Methods inherited from Trax::Model::Attributes::Type

inherited

Class Method Details

.define_attribute(klass, attribute_name, **options, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/trax/model/attributes/types/struct.rb', line 8

def self.define_attribute(klass, attribute_name, **options, &block)
  klass_name = "#{klass.fields_module.name.underscore}/#{attribute_name}".camelize
  attribute_klass = if options.key?(:extends)
    _klass_prototype = options[:extends].is_a?(::String) ? options[:extends].safe_constantize : options[:extends]
    _klass = ::Trax::Core::NamedClass.new(klass_name, _klass_prototype, :parent_definition => klass, &block)
    _klass.include(::Trax::Model::ExtensionsFor::Struct)
    _klass
  else
    ::Trax::Core::NamedClass.new(klass_name, Value, :parent_definition => klass, &block)
  end

  klass.attribute(attribute_name, typecaster_klass.new(target_klass: attribute_klass))
  klass.validates(attribute_name, :json_attribute => true) unless options.key?(:validate) && !options[:validate]
  klass.default_value_for(attribute_name) { {} }
  define_model_accessors(klass, attribute_name, attribute_klass, options[:model_accessors]) if options.key?(:model_accessors) && options[:model_accessors]
end