Module: Decanter::ValueParser::Core::ClassMethods

Defined in:
lib/decanter/value_parser/core.rb

Instance Method Summary collapse

Instance Method Details

#allow(*args) ⇒ Object



49
50
51
# File 'lib/decanter/value_parser/core.rb', line 49

def allow(*args)
  @allowed = args
end

#parse(name, values, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/decanter/value_parser/core.rb', line 11

def parse(name, values, options={})

  value_ary = values.is_a?(Array) ? values : [values]

  # want to treat 'false' as an actual value
  if value_ary.all? { |value| value.nil? || value == "" }
    if options[:required]
      raise ArgumentError.new("No value for required argument: #{name}")
    else
      return { name => nil }
    end
  end

  if @allowed && value_ary.all? { |value| @allowed.include?(value.class) }
    return { name => values }
  end

  unless @parser
    raise ArgumentError.new("No parser for argument: #{name} with types: #{value_ary.map(&:class).join(', ')}")
  end

  case @result
  when :raw
    # Parser result must be a hash
    parsed = @parser.call(name, values, options)
    parsed.is_a?(Hash) ?
      parsed :
      raise(ArgumentError.new("Result of parser #{self.name} with values #{values} was #{parsed} when it must be a hash."))
  else
    # Parser result will be treated as a single value belonging to the name
    { name => @parser.call(name, values, options) }
  end
end

#parser(&block) ⇒ Object



45
46
47
# File 'lib/decanter/value_parser/core.rb', line 45

def parser(&block)
  @parser = block
end

#result(opt) ⇒ Object



53
54
55
# File 'lib/decanter/value_parser/core.rb', line 53

def result(opt)
  @result = opt
end