Last active
December 12, 2015 00:18
-
-
Save lazyatom/4682814 to your computer and use it in GitHub Desktop.
Is this a pattern? Does it have a name? It allow swapping out basically the whole behaviour of the `Thing`.
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 Thing | |
| def self.runner=(custom_runner) | |
| @runner = custom_runner | |
| end | |
| def self.runner | |
| @runner ||= new | |
| end | |
| def run(*args) | |
| self.class.runner.actually_run(*args) | |
| end | |
| def actually_run(*args) | |
| puts "Original mechanism" | |
| end | |
| end | |
| class OtherThing | |
| def actually_run(*args) | |
| puts "Alternative mechanism" | |
| end | |
| end | |
| Thing.new.run | |
| # => "Original mechanism" | |
| Thing.runner = OtherThing.new | |
| Thing.new.run | |
| # => "Alternative mechanism" |
Yes, it's quite odd that the top-level run isn't just a class method (or a method on some other Singleton). Perhaps I missed some compelling reason for creating an instance in the source that inspired this gist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the thing I find most odd about this is that the instance of
Thingon which you call#runis irrelevant. So in a more complex case where there was state on theThinginstance, this would not be available to the implementation of#actually_run, or in fact worse, the state of a different instance would be available.