Created
February 9, 2012 13:12
-
-
Save sunaot/1779874 to your computer and use it in GitHub Desktop.
just a joke
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
module Static | |
def static! method_name, var_name, &block | |
instance_eval do | |
@static_vars ||= {} | |
namespace = {:method_name => method_name, :var_name => var_name} | |
def namespace.identifier | |
self.to_s.to_sym | |
end | |
reminder = proc { @static_vars[namespace.identifier] } | |
define_method(method_name) do | |
block.call(namespace, reminder.call) | |
end | |
end | |
end | |
def rememb namespace, context | |
instance_eval do | |
@static_vars ||= {} | |
@static_vars[namespace.identifier] = context.eval("#{namespace[:var_name]}") | |
end | |
end | |
def self.use klass | |
me = self | |
klass.instance_eval do | |
include me | |
extend me | |
end | |
end | |
end | |
# synopsis | |
class Foo | |
Static.use(self) | |
static! :baz, :hoge do |er, hoge| | |
hoge ||= "hello, wolrd" | |
hoge += "+" | |
rememb er, binding | |
next hoge | |
end | |
# 1.9 only | |
static! :bar, :hoge, &-> er, hoge { | |
hoge ||= "say goodbye" | |
hoge += "+" | |
rememb er, binding | |
return hoge | |
} | |
# 1.8 style | |
static! :bar, :hoge, &lambda {|er, hoge| | |
hoge ||= "say goodbye" | |
hoge += "+" | |
rememb er, binding | |
return hoge | |
} | |
end | |
# test | |
require 'expectations' | |
Expectations do | |
expect "hello, wolrd+++" do | |
foo = Foo.new | |
foo.baz | |
foo.baz | |
foo.baz | |
end | |
expect "say goodbye+++" do | |
foo = Foo.new | |
foo.bar | |
foo.bar | |
foo.bar | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment