You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

step_match_search.rb 2.0 kB

2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # frozen_string_literal: true
  2. module Cucumber
  3. module StepMatchSearch
  4. def self.new(search, configuration)
  5. CachesStepMatch.new(
  6. AssertUnambiguousMatch.new(
  7. configuration.guess? ? AttemptToGuessAmbiguousMatch.new(search) : search,
  8. configuration
  9. )
  10. )
  11. end
  12. class AssertUnambiguousMatch
  13. def initialize(search, configuration)
  14. @search = search
  15. @configuration = configuration
  16. end
  17. def call(step_name)
  18. result = @search.call(step_name)
  19. raise Cucumber::Ambiguous.new(step_name, result, @configuration.guess?) if result.length > 1
  20. result
  21. end
  22. end
  23. class AttemptToGuessAmbiguousMatch
  24. def initialize(search)
  25. @search = search
  26. end
  27. def call(step_name)
  28. best_matches(step_name, @search.call(step_name))
  29. end
  30. private
  31. def best_matches(_step_name, step_matches) # :nodoc:
  32. no_groups = step_matches.select { |step_match| step_match.args.empty? }
  33. max_arg_length = step_matches.map { |step_match| step_match.args.length }.max
  34. top_groups = step_matches.select { |step_match| step_match.args.length == max_arg_length }
  35. if no_groups.any?
  36. longest_regexp_length = no_groups.map(&:text_length).max
  37. no_groups.select { |step_match| step_match.text_length == longest_regexp_length }
  38. elsif top_groups.any?
  39. shortest_capture_length = top_groups.map { |step_match| step_match.args.inject(0) { |sum, c| sum + c.to_s.length } }.min
  40. top_groups.select { |step_match| step_match.args.inject(0) { |sum, c| sum + c.to_s.length } == shortest_capture_length }
  41. else
  42. top_groups
  43. end
  44. end
  45. end
  46. require 'delegate'
  47. class CachesStepMatch < SimpleDelegator
  48. def call(step_name) # :nodoc:
  49. @match_cache ||= {}
  50. matches = @match_cache[step_name]
  51. return matches if matches
  52. @match_cache[step_name] = super(step_name)
  53. end
  54. end
  55. end
  56. end

No Description

Contributors (1)