Class: Typedocs::ArgumentsSpec

Inherits:
Object
  • Object
show all
Defined in:
lib/typedocs/arguments_spec.rb

Overview

Ruby argument pattern:

  • required* optional* (rest requied*)?

  • optional+ requied* # optional is matched forward-wise

s1 -opt-> s2 –req–> s3

|          |
+----------+---------+--rest--> s6 -req-> s7
|         /         /
`-req-> s4 -opt-> s5

Instance Method Summary collapse

Constructor Details

#initializeArgumentsSpec

Returns a new instance of ArgumentsSpec.



11
12
13
14
15
# File 'lib/typedocs/arguments_spec.rb', line 11

def initialize
  # [[type, [spec ...]] ...]
  @specs = []
  @current = nil
end

Instance Method Details

#add_optional(arg_spec) ⇒ Object



47
48
49
# File 'lib/typedocs/arguments_spec.rb', line 47

def add_optional(arg_spec)
  _add :opt, arg_spec
end

#add_required(arg_spec) ⇒ Object



44
45
46
# File 'lib/typedocs/arguments_spec.rb', line 44

def add_required(arg_spec)
  _add :req, arg_spec
end

#add_rest(arg_spec) ⇒ Object



50
51
52
# File 'lib/typedocs/arguments_spec.rb', line 50

def add_rest(arg_spec)
  _add :res, arg_spec
end

#empty?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/typedocs/arguments_spec.rb', line 16

def empty?
  @specs.empty?
end

#error_message_for(args) ⇒ Object



23
24
25
26
27
# File 'lib/typedocs/arguments_spec.rb', line 23

def error_message_for(args)
  matched = match(args)
  errors = matched.select{|arg, spec|!spec.valid?(arg)}
  "Expected: #{to_source}. Errors: #{errors.map{|arg,spec|spec.error_message_for(arg)}.join(' ||| ')}"
end

#to_sourceObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/typedocs/arguments_spec.rb', line 28

def to_source
  @specs.flat_map{|t,s|
    attr =
      case t
      when :req
        ''
      when :opt
        '?'
      when :res
        '*'
      else
        raise
      end
    s.map{|spec| "#{attr}#{spec.to_source}" }
  }.join(' -> ')
end

#valid?(args) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
# File 'lib/typedocs/arguments_spec.rb', line 19

def valid?(args)
  matched = match(args)
  matched && matched.all? {|arg, spec| spec.valid? arg}
end