tksask
tksask

Reputation: 105

Ruby recursive method with block

Any ideas why this doesn't work?

def find_or_wait_for(selector_type, selector, wait = 0)
  sleep(wait) if wait.positive?
  yield if block_given?
  find(selector_type, selector)
rescue Capybara::ElementNotFound
  find_or_wait_for(selector_type, selector, wait + 1) { yield if block_given? } if wait < 5

  raise
end

Expected result: same initial block being executed every time the method is called.

Actual result: it executes the block only the first time, it seems like the block is 'lost' inside de rescue.

Upvotes: 2

Views: 289

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Capture the block and pass it to the subsequent calls directly.

def find_or_wait_for(*args, &cb)
  yield if block_given?
  # do something
rescue Capybara::ElementNotFound
  find_or_wait_for(*args, &cb)
  raise
end

Upvotes: 3

Related Questions