Class: Ascribe::Attribute

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Attribute

Returns a new instance of Attribute.



5
6
7
8
9
10
# File 'lib/ascribe/attribute.rb', line 5

def initialize(*args)
  options = args.extract_options!
  @name, @type = args.shift.to_s, args.shift
  self.options = (options || {}).symbolize_keys
  self.default_value = self.options[:default]
end

Instance Attribute Details

#default_valueObject

Returns the value of attribute default_value.



3
4
5
# File 'lib/ascribe/attribute.rb', line 3

def default_value
  @default_value
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/ascribe/attribute.rb', line 3

def name
  @name
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/ascribe/attribute.rb', line 3

def options
  @options
end

#typeObject

Returns the value of attribute type.



3
4
5
# File 'lib/ascribe/attribute.rb', line 3

def type
  @type
end

Instance Method Details

#get(value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/ascribe/attribute.rb', line 12

def get(value)
  if value.nil? && !default_value.nil?
    if default_value.respond_to?(:call)
      return default_value.call
    else
      return Marshal.load(Marshal.dump(default_value))
    end
  end
  value
end

#set(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ascribe/attribute.rb', line 23

def set(value)
  if type.kind_of?(Array)
    if !value.nil? && !type.nil? && !type.include?(value.class)
      raise Ascribe::ValidationError, "#{name} must be an instance of #{type}"
    end
  elsif type.kind_of?(Class)
    if !value.nil? && !type.nil? && (!value.kind_of?(type) || type == nil)
      raise Ascribe::ValidationError, "#{name} must be an instance of #{type}"
    end
  end
  value
end