Created
December 2, 2011 07:04
-
-
Save cwvh/1422143 to your computer and use it in GitHub Desktop.
The Hoarder Pattern: beautiful on the outside, dead kittens on the inside. Thanks Sinatra!
This file contains 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
## Making kick-ass global objects for fun-and-profit DSLs. | |
module ScopeLifting | |
class Application | |
attr_accessor :options | |
def initialize | |
@options = Hash.new | |
end | |
def local(name, *args, &block) | |
print "#{name}::local: " | |
puts args.join(' ') | |
puts "\t@(cmd ...)\n\t@(cmd ...)" | |
yield | |
end | |
def remote(name, *args, &block) | |
print "#{name}::afterok: " | |
puts args.join(' ') | |
puts "\t@(cmd ...)\n\t@(cmd ...)" | |
yield | |
end | |
end | |
module Delegate | |
def self.delegate(*methods) | |
methods.each do |method_name| | |
define_method(method_name) do |*args, &block| | |
return super(*args, &block) if respond_to? method_name | |
Delegate.target.send(method_name, *args, &block) | |
end | |
private method_name | |
end | |
end | |
delegate :local, :remote, :options | |
class << self | |
attr_accessor :target | |
end | |
self.target = Application.new | |
end | |
end | |
include ScopeLifting::Delegate | |
### Phew! Now for the fun. ### | |
local 'target1' do | |
puts "\tdebug on? #{options[:debug] || false}" | |
puts "\tenabling debug from this target" | |
options[:debug] = true | |
end | |
remote 'target2', [:target1, :target3] do | |
puts "\tdebug on? #{options[:debug]}" | |
end | |
### Console output ### | |
# | |
# target1::local: | |
# @(cmd ...) | |
# @(cmd ...) | |
# debug on? false | |
# enabling debug from this target | |
# | |
# target2::afterok: target1 target3 | |
# @(cmd ...) | |
# @(cmd ...) | |
# debug on? true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment