Class: MatchEnum

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

Defined Under Namespace

Classes: BlankEnumerableError, MatchEnumError, NoBlockGivenError

Constant Summary collapse

@@enum_methods =

avoid re-defining

[]

Instance Method Summary collapse

Constructor Details

#initialize(method, options, &block) ⇒ MatchEnum

Returns a new instance of MatchEnum.



8
9
10
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
# File 'lib/match_enum.rb', line 8

def initialize(method, options, &block)
  @method = method
  @empty_okay = (options and options[:empty])
  @block = block
  if !@block
    raise NoBlockGivenError, 'no block given, you probably need to use brackets instead of "do...end"'
  end

  @num_args = @block.arity
  @num_args = 0 if @num_args == -1 # correct ruby error
  return if @@enum_methods[@num_args]
  @@enum_methods[@num_args] = true

  args = (1..(@num_args)).map {|i| 'arg_' << i.to_s}.join(',')
  eval <<-EOS
  def enum_#{@num_args}(target)
    @counter = 0
    target.send(@method) do |#{args}|
      begin
        @block.call(#{args})
      rescue Spec::Expectations::ExpectationNotMetError => e
        @error_msg = e.to_s
        @failure_object = [#{args}]
        return false
      end
      @counter += 1
    end
    true
  end
  EOS
end

Instance Method Details

#enum(target) ⇒ Object



40
41
42
# File 'lib/match_enum.rb', line 40

def enum(target)
  eval("enum_#{@num_args}(target)")
end

#failure_messageObject



56
57
58
59
# File 'lib/match_enum.rb', line 56

def failure_message
  if @error_msg =~ /expected not/ then '    ' else '' end <<
    "  item #{@counter}: #{@failure_object.inspect}\n#{@error_msg}"
end

#matches?(target) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/match_enum.rb', line 44

def matches?(target)
  if target.nil?
    raise BlankEnumerableError, "Expected an enumerable object, but got nil"
  end

  if !@empty_okay && target.empty?
    raise BlankEnumerableError, "No items in the given enumerator.\nTo allow an empty enumerator pass the :empty option with a true value"
  end

  return enum(target)
end