Class: Trafaret::Key
- Inherits:
-
Object
- Object
- Trafaret::Key
- Defined in:
- lib/trafaret/base.rb
Instance Method Summary collapse
- #call(data) ⇒ Object
- #get(obj) ⇒ Object
-
#initialize(name, validator, options = {}, &blk) ⇒ Key
constructor
A new instance of Key.
- #set_validator(validator, options = {}, &blk) ⇒ Object
Constructor Details
#initialize(name, validator, options = {}, &blk) ⇒ Key
Returns a new instance of Key.
3 4 5 6 7 8 9 10 11 12 13 |
# File 'lib/trafaret/base.rb', line 3 def initialize(name, validator, = {}, &blk) @name = name @sname = name.to_s @optional = .delete(:optional) @default = .delete(:default) @to_name = .delete(:to_name) || name @options = set_validator(validator, , &blk) end |
Instance Method Details
#call(data) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/trafaret/base.rb', line 32 def call(data) value = get(data) if value == NoValue if @default value = @default elsif @optional return else return [@name, Trafaret::Error.new("#{@name} is required")] end end value = @validator.call(value, &@blk) if value.is_a? Trafaret::Error [@name, value] else [@to_name, value] end end |
#get(obj) ⇒ Object
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/trafaret/base.rb', line 21 def get(obj) # data = obj.send(@name) if data.respond_to? @name if obj.include? @name obj[@name] elsif obj.include? @sname obj[@sname] else NoValue end end |
#set_validator(validator, options = {}, &blk) ⇒ Object
15 16 17 18 19 |
# File 'lib/trafaret/base.rb', line 15 def set_validator(validator, = {}, &blk) validator = Trafaret.get_validator(validator) @validator = if validator.is_a?(Class) then validator.new() else validator end @validator.add(blk) if blk end |