Class: MatchEnum
- Inherits:
-
Object
- Object
- MatchEnum
- 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
- #enum(target) ⇒ Object
- #failure_message ⇒ Object
-
#initialize(method, *enum_args, &block) ⇒ MatchEnum
constructor
A new instance of MatchEnum.
- #matches?(target) ⇒ Boolean
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) = enum_args.pop if Hash === enum_args.last @method = method @enum_args = enum_args @empty_okay = ( and [: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_message ⇒ Object
65 66 67 68 |
# File 'lib/match_enum.rb', line 65 def if @error_msg =~ /expected not/ then ' ' else '' end << " item #{@counter}: #{@failure_object.inspect}\n#{@error_msg}" end |
#matches?(target) ⇒ 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 |