Permalink
Browse files

Added some comments and a bit more to README

  • Loading branch information...
1 parent b002902 commit 917795a138f6de95918e5df36a065c5996befd02 Mark Evans committed Nov 6, 2009
Showing with 38 additions and 6 deletions.
  1. +27 −6 README.markdown
  2. +11 −0 lib/block_helpers.rb
View
33 README.markdown
@@ -11,6 +11,18 @@ Rails already has a great solution for forms with form-builders, using helpers w
This small gem generates helpers similar to the form-builders, but for the general case.
+Installation
+============
+
+To use in Rails, add to your `environment.rb`:
+
+ config.gem "block_helpers", :source => "http://gemcutter.org"
+
+for Merb, in `init.rb`:
+
+ dependency "block_helpers"
+
+
Example usage
=============
Please note that these examples are very contrived just for brevity! These block helpers are much more useful than just printing 'Hi there Marmaduke!'
@@ -161,16 +173,25 @@ This generates:
Of course, you could use `display` for more than just surrounding markup.
-Installation
-============
+Testing
+=======
+I'm not too sure about other testing frameworks, but with rspec-rails you can use 'eval_erb', e.g.
-To use in Rails, add to your `environment.rb`:
+ eval_erb(%(
+ <% my_block_helper do |h| %>
+ <h2>Hello</h2>
+ <%= h.write_blah %>
+ <% end %>
+ )).should match_html("<h2>Hello</h2> blah blah blah ")
- config.gem "block_helpers", :lib => "block_helpers", :source => "http://gemcutter.org"
+In the above I've used the following simple matcher `match_html`:
-for Merb, in `init.rb`:
+ def match_html(html)
+ # Match two strings, but don't care about whitespace
+ simple_matcher("should match #{html}"){|given| given.strip.gsub(/\s+/,' ').gsub('> <','><') == html.strip.gsub(/\s+/,' ').gsub('> <','><') }
+ end
- dependency "block_helpers"
+Obviously you test however you want but I've included the above in case it's useful.
Compatibility
=============
View
11 lib/block_helpers.rb
@@ -18,22 +18,33 @@ def inherited(klass)
method_name = klass.name.split('::').last.underscore
klass.parent.class_eval %(
def #{method_name}(*args, &block)
+
+ # Get the current helper object which has all the normal helper methods
top_level_helper = if self.is_a?(BlockHelpers::Base)
self.helper
else
self
end
+
+ # We need to save the current helper in the class so that
+ # it's visible to the renderer's 'initialize' method...
#{klass.name}.current_helper = top_level_helper
renderer = #{klass.name}.new(*args)
+ # ...then set it anyway on the renderer so that renderer methods can use it
renderer.send(:helper=, top_level_helper)
+
body = block ? capture(renderer, &block) : nil
processed_body = renderer.display(body)
if processed_body
+
+ # If concat is the old rails/merb version with 2 args...
if top_level_helper.method(:concat).arity == 2
concat processed_body, binding
+ # ...otherwise call with one arg
else
concat processed_body
end
+
end
renderer
end

0 comments on commit 917795a

Please sign in to comment.