Class: Trax::Model::Attributes::Types::Enum

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

Defined Under Namespace

Classes: TypeCaster

Class Method Summary collapse

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

inherited

Class Method Details

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

note: we dont validate enum attribute value because typecaster will turn it into nil which we allow



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

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
  else
    ::Trax::Core::NamedClass.new(klass_name, ::Trax::Core::Types::Enum, :parent_definition => klass, &block)
  end

  klass.attribute(attribute_name, ::Trax::Model::Attributes::Types::Enum::TypeCaster.new(target_klass: attribute_klass))
  klass.default_value_for(attribute_name) { options[:default] } if options.key?(:default)
  define_scopes(klass, attribute_name, attribute_klass) unless options.key?(:define_scopes) && !options[:define_scopes]
end

.define_scopes(klass, attribute_name, attribute_klass) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/trax/model/attributes/types/enum.rb', line 23

def self.define_scopes(klass, attribute_name, attribute_klass)
  klass.class_eval do
    scope_method_name = :"by_#{attribute_name}"
    scope_not_method_name = :"by_#{attribute_name}_not"

    scope scope_method_name, lambda { |*values|
      values.flat_compact_uniq!
      where(attribute_name => attribute_klass.select_values(*values))
    }
    scope scope_not_method_name, lambda { |*values|
      values.flat_compact_uniq!
      where.not(attribute_name => attribute_klass.select_values(*values))
    }
  end
end