Class: Templater::ArgumentDescription

Inherits:
Description show all
Defined in:
lib/templater/description.rb

Instance Attribute Summary

Attributes inherited from Description

#block, #name, #options

Instance Method Summary collapse

Methods inherited from Description

#initialize

Constructor Details

This class inherits a constructor from Templater::Description

Instance Method Details

#extract(argument) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/templater/description.rb', line 47

def extract(argument)
  case options[:as]
  when :hash
    if argument.is_a?(String)
      return argument.split(',').inject({}) do |h, pair|
        key, value = pair.strip.split(':')
        raise Templater::MalformattedArgumentError, "Expected '#{argument.inspect}' to be a key/value pair" unless key and value
        h[key] = value
        h
      end
    end
  when :array
    return argument.split(',') if argument.is_a?(String)
  end
  return argument
end

#valid?(argument) ⇒ Boolean

Checks if the given argument is valid according to this description

Parameters

argument<Object>

Checks if the given argument is valid.

Returns

Boolean

Validity of the argument

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/templater/description.rb', line 29

def valid?(argument)
  if argument.nil? and options[:required]
    raise Templater::TooFewArgumentsError
  elsif not argument.nil?
    if options[:as] == :hash and not argument.is_a?(Hash)
      raise Templater::MalformattedArgumentError, "Expected the argument to be a Hash, but was '#{argument.inspect}'"
    elsif options[:as] == :array and not argument.is_a?(Array)
      raise Templater::MalformattedArgumentError, "Expected the argument to be an Array, but was '#{argument.inspect}'"
    end
       
    invalid = catch :invalid do
      block.call(argument) if block
      throw :invalid, :not_invalid
    end
    raise Templater::ArgumentError, invalid unless invalid == :not_invalid
  end
end