Module: ActiveData::Model::Attributable::ClassMethods

Defined in:
lib/active_data/model/attributable.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, options = {}, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active_data/model/attributable.rb', line 17

def attribute name, options = {}, &block
  default = options.is_a?(Hash) ? options[:default] : options
  type = options.is_a?(Hash) ? normalize_type(options[:type]) : String
  self._attributes = self._attributes.merge(name => {
    default: (block || default),
    type: type
  })

  define_method name do
    read_attribute(name)
  end
  define_method "#{name}_before_type_cast" do
    read_attribute_before_type_cast(name)
  end
  define_method "#{name}?" do
    read_attribute(name).present?
  end
  define_method "#{name}=" do |value|
    write_attribute(name, value)
  end

  if options.is_a?(Hash) && options[:in]
    define_singleton_method "#{name}_values" do
      options[:in].dup
    end
  end
end

#attribute_default(name) ⇒ Object



56
57
58
59
# File 'lib/active_data/model/attributable.rb', line 56

def attribute_default name
  default = _attributes[name][:default]
  default.respond_to?(:call) ? default.call : default
end

#initialize_attributesObject



61
62
63
64
65
66
# File 'lib/active_data/model/attributable.rb', line 61

def initialize_attributes
  _attributes.inject(ActiveSupport::HashWithIndifferentAccess.new) do |result, (name, value)|
    result[name] = nil
    result
  end
end

#normalize_type(type) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/active_data/model/attributable.rb', line 45

def normalize_type type
  case type
  when String, Symbol then
    type.to_s.camelize.safe_constantize
  when nil then
    String
  else
    type
  end
end