Class: Lean::Attributes::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/lean-attributes/attributes/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Attribute

Returns a new instance of Attribute.



6
7
8
9
10
# File 'lib/lean-attributes/attributes/attribute.rb', line 6

def initialize(options = {})
  @default  = options[:default]
  @name     = options[:name].to_sym
  @type     = options[:type].to_s.to_sym
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/lean-attributes/attributes/attribute.rb', line 4

def name
  @name
end

Instance Method Details

#coercion_methodObject



12
13
14
15
16
17
18
# File 'lib/lean-attributes/attributes/attribute.rb', line 12

def coercion_method
  "    def \#{coercion_method_name(name)}(value)\n      \#{coercion_method_name}(value)\n    end\n  EOS\nend\n"

#coercion_method_name(from = nil) ⇒ Object



20
21
22
# File 'lib/lean-attributes/attributes/attribute.rb', line 20

def coercion_method_name(from = nil)
  ['coerce', from, 'to', @type.to_s.downcase].compact.join('_')
end

#defaultObject



24
25
26
27
28
29
30
# File 'lib/lean-attributes/attributes/attribute.rb', line 24

def default
  if @default.is_a?(Symbol) && @type != :Symbol
    return "send(:#{@default})"
  end

  @default.inspect
end

#getter_methodObject



32
33
34
35
36
# File 'lib/lean-attributes/attributes/attribute.rb', line 32

def getter_method
  return getter_method_with_default unless @default.nil?

  "attr_reader :#{@name}"
end

#getter_method_with_defaultObject



38
39
40
41
42
43
44
# File 'lib/lean-attributes/attributes/attribute.rb', line 38

def getter_method_with_default
  "    def \#{name}\n      @\#{name} ||= \#{default}\n    end\n  EOS\nend\n"

#setter_methodObject



46
47
48
49
50
51
52
53
# File 'lib/lean-attributes/attributes/attribute.rb', line 46

def setter_method
  "    def \#{name}=(value)\n      value = \#{coercion_method_name}(value) unless value.is_a?(\#{@type})\n      @\#{name} = value\n    end\n  EOS\nend\n"