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, *enum_args, &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
39
40
41
42
43
44
45
46
47
# File 'lib/match_enum.rb', line 8

def initialize(method, *enum_args, &block)
  options = enum_args.pop if Hash === enum_args.last
  @method = method
  @enum_args = enum_args
  @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_block_args = @block.arity
  @num_block_args = 0 if @num_block_args == -1 # correct ruby error
  if enum_args.empty?
    return if @@enum_methods[@num_block_args]
    @@enum_methods[@num_block_args] = true
  end

  args = (1..(@num_block_args)).map {|i| 'arg_' << i.to_s}.join(',')
  invoke_enum = if @enum_args.empty?
    "target.send(@method) do |#{args}|"
                else
    "target.send(@method, *@enum_args) do |#{args}|"
                end
  eval <<-EOS
  def enum_#{@num_block_args}(target)
    @counter = 0
    #{invoke_enum}
      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



49
50
51
# File 'lib/match_enum.rb', line 49

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

#failure_messageObject



65
66
67
68
# File 'lib/match_enum.rb', line 65

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)


53
54
55
56
57
58
59
60
61
62
63
# File 'lib/match_enum.rb', line 53

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