Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 4582b411a7687c44a49e7577138c03e3daa0d603 0 parents
@wagenet authored
Showing with 104 additions and 0 deletions.
  1. +48 −0 README.textile
  2. +39 −0 lib/proxy_block.rb
  3. +17 −0 proxy_block.gemspec
48 README.textile
@@ -0,0 +1,48 @@
+h1. ProxyBlock
+
+h2. Overview
+
+Simply modify methods that take a block to also provide a proxy
+
+
+h2. Usage
+
+h3. Example Classes
+
+<pre><code>
+ class Wrapper
+
+ def hello
+ puts 'hello world'
+ end
+
+ def wrap(word = 'wrap')
+ puts "#{word} start"
+ yield
+ puts "#{word} end"
+ end
+ proxy_block :wrap
+
+ end
+</code></pre>
+
+
+h3. Standard behavior is maintained
+
+<pre><code>
+ w = Wrapper.new
+ w.wrap{ w.hello }
+ # => word start
+ # => hello world
+ # => world end
+</code></pre>
+
+
+h3. Proxy Form
+<pre><code>
+ w = Wrapper.new
+ w.wrap.hello
+ # => word start
+ # => hello world
+ # => world end
+</code></pre>
39 lib/proxy_block.rb
@@ -0,0 +1,39 @@
+class Object
+ def proxy_block(method)
+ unless self.class.method_defined?("orig_#{method}")
+ alias_method "orig_#{method}", method
+ class_eval %{
+ def #{method}(*args, &block)
+ if block_given?
+ orig_#{method}(*args, &block)
+ else
+ BlockProxy.new(self, :orig_#{method}, *args)
+ end
+ end
+ }
+ end
+ end
+end
+
+class BlockProxy
+
+ # Make sure the proxy is as dumb as it can be.
+ # Blatanly taken from Jim Wierich's BlankSlate post:
+ # http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc
+ instance_methods.each { |m| undef_method m unless m =~ /^__/ }
+
+ def initialize(target, method, *args)
+ @target = target
+ @method = method
+ @args = args
+ end
+
+ def proxy_target; @target; end
+ def proxy_method; @method; end
+ def proxy_args; @args; end
+
+ def method_missing(method_name, *args, &block)
+ proxy_target.send(proxy_method, *proxy_args){ proxy_target.send(method_name, *args, &block) }
+ end
+
+end
17 proxy_block.gemspec
@@ -0,0 +1,17 @@
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = 'proxy_block'
+ s.version = '0.1'
+ s.summary = 'Simply modify methods that take a block to also provide a proxy'
+# s.description = ''
+ s.files = Dir['[A-Z]*', 'lib/**/*.rb']
+ s.require_path = 'lib'
+ s.has_rdoc = false
+# s.extra_rdoc_files = rd.rdoc_files.reject {|fn| fn =~ /\.rb$/}.to_a
+# s.rdoc_options = rd.options
+
+ s.author = 'Peter Wagenet'
+ s.email = 'peter.wagenet@gmail.com'
+ s.homepage = 'http://in.finitu.de'
+end
Please sign in to comment.
Something went wrong with that request. Please try again.