Class: Kortype::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/kortype/type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Type.



4
5
6
7
8
9
10
11
12
# File 'lib/kortype/type.rb', line 4

def initialize name, type, options = {}
  @name = name
  if type.is_a?(String) || type.is_a?(Symbol)
    @type = eval(type.to_s)
  else
    @type = type
  end
  @options = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/kortype/type.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/kortype/type.rb', line 3

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/kortype/type.rb', line 3

def type
  @type
end

Instance Method Details

#valueObject



14
15
16
17
18
19
20
21
22
# File 'lib/kortype/type.rb', line 14

def value
  @value ||= if options[:default]
    if Proc === options[:default]
      options[:default].call
    else
      options[:default]
    end
  end
end

#value=(value) ⇒ Object

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/kortype/type.rb', line 24

def value=(value)
  if @type === value
    return @value = value
  elsif @options[:parse] && Proc === @options[:parse]
    @value = @options[:parse].call(value)
  elsif Kortype::Parse.has_parse?(@type)
    @value = Kortype::Parse.parse(value, @type)
  else
    if @type.respond_to? :parse
      begin
      @value = @type.parse value
      rescue
        raise Kortype::TypeError.new, "#{value} is not parse to a #{@type}"
      end
    else
      @value = value
    end
  end
  raise Kortype::TypeError.new, "#{value} is not parse to a #{@type}" unless @type === @value
  @value
end