Created
December 5, 2012 20:39
-
-
Save rwjblue/4219290 to your computer and use it in GitHub Desktop.
Using caller to Prevent Recursion in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Inspired by blog post at: http://www.codebenders.com/code-cat/preventing-recursion-in-ruby/ | |
| module RecursionHelper | |
| def prevent_recursion(method_name) | |
| original = instance_method(method_name) | |
| define_method(method_name) do |*args| | |
| return if caller.any?{|c| c =~ /`#{method_name}'\z/} | |
| original.bind(self).call(*args) | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RecursiveX | |
| def foo | |
| bar | |
| "foo done" | |
| end | |
| def bar | |
| foo | |
| end | |
| end | |
| RecursiveX.new.foo rescue $! # => #<SystemStackError: stack level too deep> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require_relative 'recursion_helper' | |
| class RecursiveXWithRecursionPrevention | |
| extend RecursionHelper | |
| def foo | |
| bar | |
| "foo done" | |
| end | |
| prevent_recursion :foo | |
| def bar | |
| foo | |
| end | |
| end | |
| puts RecursiveXWithRecursionPrevention.new.foo # => "foo done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment