Created
March 9, 2010 20:33
-
-
Save hayeah/327086 to your computer and use it in GitHub Desktop.
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 MQ | |
| attr_reader :current_context | |
| def context(hash) | |
| @current_context ||= {} | |
| begin | |
| old_current_context = @current_context | |
| @current_context = @current_context.merge(hash) | |
| yield | |
| ensure | |
| @current_context = old_current_context | |
| end | |
| end | |
| def call(method,args,context=current_context) | |
| { "method" => method, | |
| "args" => args, | |
| "context" => context} | |
| end | |
| end | |
| class WithUserContext < MQ | |
| def call(method,args) | |
| super(method,args,current_context.merge("user_id" => current_user_id)) | |
| end | |
| def current_user_id | |
| 1 | |
| end | |
| end | |
| p :MQ | |
| mq = MQ.new | |
| mq.context("foo" => 1) do | |
| p mq.call(:foo,[1]) | |
| mq.context("foo" => 2,"bar" => 2) do | |
| p mq.call(:foo,[2]) | |
| end | |
| p mq.call(:foo,[1]) | |
| end | |
| # {"args"=>[1], "method"=>:foo, "context"=>{"foo"=>1}} | |
| # {"args"=>[2], "method"=>:foo, "context"=>{"foo"=>2, "bar"=>2}} | |
| # {"args"=>[1], "method"=>:foo, "context"=>{"foo"=>1}} | |
| p :WithUserContext | |
| mq = WithUserContext.new | |
| mq.context("foo" => 1) do | |
| p mq.call :foo, [] | |
| end | |
| # :WithUserContext | |
| # {"args"=>[], "method"=>:foo, "context"=>{"user_id"=>1, "foo"=>1}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment