Class: Friendly::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly/attribute.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, name, type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



36
37
38
39
40
41
42
# File 'lib/friendly/attribute.rb', line 36

def initialize(klass, name, type, options = {})
  @klass         = klass
  @name          = name
  @type          = type
  @default_value = options[:default]
  build_accessors
end

Instance Attribute Details

#default_valueObject (readonly)

Returns the value of attribute default_value.



34
35
36
# File 'lib/friendly/attribute.rb', line 34

def default_value
  @default_value
end

#klassObject (readonly)

Returns the value of attribute klass.



34
35
36
# File 'lib/friendly/attribute.rb', line 34

def klass
  @klass
end

#nameObject (readonly)

Returns the value of attribute name.



34
35
36
# File 'lib/friendly/attribute.rb', line 34

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



34
35
36
# File 'lib/friendly/attribute.rb', line 34

def type
  @type
end

Class Method Details

.convertersObject



22
23
24
# File 'lib/friendly/attribute.rb', line 22

def converters
  @converters ||= {}
end

.custom_type?(klass) ⇒ Boolean

Returns:



26
27
28
# File 'lib/friendly/attribute.rb', line 26

def custom_type?(klass)
  !sql_type(klass).nil?
end

.deregister_type(type) ⇒ Object



9
10
11
12
# File 'lib/friendly/attribute.rb', line 9

def deregister_type(type)
  sql_types.delete(type.name)
  converters.delete(type)
end

.register_type(type, sql_type, &block) ⇒ Object



4
5
6
7
# File 'lib/friendly/attribute.rb', line 4

def register_type(type, sql_type, &block)
  sql_types[type.name] = sql_type
  converters[type]     = block
end

.sql_type(type) ⇒ Object



14
15
16
# File 'lib/friendly/attribute.rb', line 14

def sql_type(type)
  sql_types[type.name]
end

.sql_typesObject



18
19
20
# File 'lib/friendly/attribute.rb', line 18

def sql_types
  @sql_types ||= {}
end

Instance Method Details

#assign_default_value(document) ⇒ Object



63
64
65
# File 'lib/friendly/attribute.rb', line 63

def assign_default_value(document)
  document.send(:"#{name}=", default)
end

#convert(value) ⇒ Object



48
49
50
51
# File 'lib/friendly/attribute.rb', line 48

def convert(value)
  assert_converter_exists(value)
  converters[type].call(value)
end

#defaultObject



53
54
55
56
57
58
59
60
61
# File 'lib/friendly/attribute.rb', line 53

def default
  if !default_value.nil?
    default_value
  elsif type.respond_to?(:new)
    type.new
  else
    nil
  end
end

#typecast(value) ⇒ Object



44
45
46
# File 'lib/friendly/attribute.rb', line 44

def typecast(value)
  !type || value.is_a?(type) ? value : convert(value)
end