Class: CouchDB::JSONObject::Property

Inherits:
Object
  • Object
show all
Defined in:
lib/couchdb/json_object.rb

Overview

Private: The propety definition object.

Constant Summary collapse

BuiltinTypes =
{
  :string => lambda { |v| v.to_s },
  :int    => lambda { |v| Integer(v) },
  :float  => lambda { |v| Float(v) },
  :bool   => lambda { |v| !!v },
  :array  => lambda { |v| Array(v) },
  :hash   => lambda { |v| v.to_hash },
  :object => JSONObject
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, options = {}, &blk) ⇒ Property

Returns a new instance of Property.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/couchdb/json_object.rb', line 20

def initialize(name, type, options = {}, &blk)
  @name = name

  if type.is_a?(Symbol)
    raise ArgumentError, "Unknow property type #{type.inspect}." unless BuiltinTypes.has_key?(type)
    type = BuiltinTypes[type] 
  end
  type = Class.new JSONObject, &blk if type == JSONObject

  @convertor =
    if type.respond_to?(:call)
      type
    elsif convert_method = [:convert, :new].detect { |m| type.respond_to? m }
      type.method convert_method
    else
      raise ArgumentError, "Property type should has :convert, :call or :new method."
    end

  @required  = options[:required]
  @default   = options[:default]
  @validator = options[:validate]
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



18
19
20
# File 'lib/couchdb/json_object.rb', line 18

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



18
19
20
# File 'lib/couchdb/json_object.rb', line 18

def name
  @name
end

Instance Method Details

#convert(value) ⇒ Object



51
52
53
54
55
# File 'lib/couchdb/json_object.rb', line 51

def convert(value)
  @convertor.call value
rescue
  raise $!.is_a?(InvalidValue) ? $! : InvalidValue.new(name, value, $!.message)
end

#has_default?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/couchdb/json_object.rb', line 47

def has_default?
  !@default.nil?
end

#required?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/couchdb/json_object.rb', line 43

def required?
  @required
end

#valid_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/couchdb/json_object.rb', line 57

def valid_value?(value)
  @validator.nil? or value.nil? or @validator.call(value)
end