Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Here are three ways of running a proc with "local variables" set.
- # Really they aren't local variables but functions, it seems it is
- # impossible to set local variables or run procs with bindings which
- # have the variables set. Trust me I've tried.
- # METHOD 1: WITH A CLASS
- # ----------------------
- # Create a class then set methods for each arg, then run the proc in
- # the newly created class.
- #
- def in_class(args, proc)
- k = Class.new
- args.each do |a,v|
- k.send(:define_method, a) { v }
- end
- k.new.instance_exec &proc
- end
- # METHOD 2: USING METHOD MISSING
- # ------------------------------
- # Only create one class, which is then stored in a @var, this then
- # takes the arguments and uses method missing to pass the correct
- # value from the hash.
- #
- def in_missing_class(a, f)
- if @k
- if f.arity > 0
- @k.new(a).instance_exec(a, &f)
- else
- @k.new(a).instance_exec(&f)
- end
- else
- @k = Class.new {
- def initialize(args)
- @a = args
- end
- def method_missing(sym, *args)
- if @a.has_key?(sym)
- @a[sym]
- else
- super
- end
- end
- }
- in_missing_class(a, f)
- end
- end
- # METHOD 3: USING METHOD MISSING AGAIN
- # ------------------------------------
- # This time create a single instance of a class which has a method
- # allowing you to set the hash of args each time it is called, this
- # way you aren't creating lots of different instances of a class.
- #
- def in_missing_object(a, f)
- if @o
- @o._run a, f
- else
- @o = Class.new {
- def _run(a, f)
- @a = a
- if f.arity > 0
- instance_exec(a, &f)
- else
- instance_exec &f
- end
- end
- def method_missing(sym, *args)
- if @a.has_key?(sym)
- @a[sym]
- else
- super
- end
- end
- }.new
- end
- end
- a = {:name => "world"}
- f = proc { puts "Hello, #{name}!" }
- in_class(a, f)
- #=> Hello, world!
- in_missing_class(a, f)
- #=> Hello, world!
- in_missing_object(a, f)
- #=> Hello, world!
Add Comment
Please, Sign In to add comment