Class: ActiveData::Attributes::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_data/attributes/base.rb

Direct Known Subclasses

Localized

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &block) ⇒ Base

Returns a new instance of Base.



6
7
8
9
10
# File 'lib/active_data/attributes/base.rb', line 6

def initialize name, options = {}, &block
  @name = name.to_sym
  @options = options
  @options[:default] = block if block
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/active_data/attributes/base.rb', line 4

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/active_data/attributes/base.rb', line 4

def options
  @options
end

Instance Method Details

#defaultObject



20
21
22
# File 'lib/active_data/attributes/base.rb', line 20

def default
  @default ||= @options[:default]
end

#default_blank?Boolean

Returns:



24
25
26
# File 'lib/active_data/attributes/base.rb', line 24

def default_blank?
  @default_blank ||= !!@options[:default_blank]
end

#default_value(instance) ⇒ Object



28
29
30
# File 'lib/active_data/attributes/base.rb', line 28

def default_value instance
  default.respond_to?(:call) ? default.call(instance) : default unless default.nil?
end

#generate_class_methods(context) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/active_data/attributes/base.rb', line 57

def generate_class_methods context
  if values
    context.class_eval "      def \#{name}_values\n        _attributes[:\#{name}].values\n      end\n    EOS\n  end\nend\n"

#generate_instance_methods(context) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_data/attributes/base.rb', line 37

def generate_instance_methods context
  context.class_eval "    def \#{name}\n      read_attribute(:\#{name})\n    end\n\n    def \#{name}= value\n      write_attribute(:\#{name}, value)\n    end\n\n    def \#{name}?\n      read_attribute(:\#{name}).present?\n    end\n\n    def \#{name}_before_type_cast\n      read_attribute_before_type_cast(:\#{name})\n    end\n  EOS\nend\n"

#typeObject



12
13
14
# File 'lib/active_data/attributes/base.rb', line 12

def type
  @type ||= options[:type] || Object
end

#type_cast(value) ⇒ Object



32
33
34
35
# File 'lib/active_data/attributes/base.rb', line 32

def type_cast value
  return value if value.instance_of?(type)
  type.active_data_type_cast(value)
end

#valuesObject



16
17
18
# File 'lib/active_data/attributes/base.rb', line 16

def values
  @values ||= options[:in].dup if options[:in]
end