Skip to content

Instantly share code, notes, and snippets.

@lazyatom
Last active December 12, 2015 00:18
Show Gist options
  • Save lazyatom/4682814 to your computer and use it in GitHub Desktop.
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`.
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"
@floehopper
Copy link

I think the thing I find most odd about this is that the instance of Thing on which you call #run is irrelevant. So in a more complex case where there was state on the Thing instance, this would not be available to the implementation of #actually_run, or in fact worse, the state of a different instance would be available.

@lazyatom
Copy link
Author

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