From 53b68c335f7090af213d3968edcd113809485f50 Mon Sep 17 00:00:00 2001 From: nex3 Date: Mon, 20 Nov 2006 06:11:16 +0000 Subject: [PATCH] Added a parallel to ActionView's capture method (Haml::Helpers#capture_haml). git-svn-id: svn://hamptoncatlin.com/haml/branches/edge@161 7063305b-7217-0410-af8c-cdc13e5119b9 --- lib/haml/helpers.rb | 16 ++++++++++++++++ test/helper_test.rb | 4 ++++ test/results/helpers.xhtml | 6 +++++- test/templates/helpers.haml | 6 +++++- 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/haml/helpers.rb b/lib/haml/helpers.rb index 40cdbfa0..06cd4c38 100644 --- a/lib/haml/helpers.rb +++ b/lib/haml/helpers.rb @@ -59,6 +59,22 @@ module Haml def tab_down(i = 1) buffer.tabulation -= i end + + # Captures the result of the given block of Haml code and returns + # them as a string. For example, after the following, + # + # - foo = capture_haml(13) do |a| + # %p= a + # + # the local variable foo would be assigned to "

13

\n". + def capture_haml(*args, &block) + buffer_buffer = buffer.buffer + position = buffer_buffer.length + + block.call(*args) + + buffer_buffer.slice!(position..-1) + end # Gets a reference to the current Haml::Buffer object. def buffer # :nodoc: diff --git a/test/helper_test.rb b/test/helper_test.rb index 2a2fb3c8..cbd86474 100644 --- a/test/helper_test.rb +++ b/test/helper_test.rb @@ -95,5 +95,9 @@ class HelperTest < Test::Unit::TestCase old_rails = "" assert(result == new_rails || result == old_rails) end + + def test_capture_haml + assert_equal("\"

13

\\n\"\n", render("- foo = capture_haml(13) do |a|\n %p= a\n= foo.dump")) + end end diff --git a/test/results/helpers.xhtml b/test/results/helpers.xhtml index 0aada943..2538b396 100644 --- a/test/results/helpers.xhtml +++ b/test/results/helpers.xhtml @@ -27,7 +27,11 @@

reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally loooooooooooooooooong

+
+

Big!

+

Small

+ +

baz

boom

foo - diff --git a/test/templates/helpers.haml b/test/templates/helpers.haml index a88d4375..eb8e2af9 100644 --- a/test/templates/helpers.haml +++ b/test/templates/helpers.haml @@ -12,8 +12,12 @@ - tab_up %p reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally loooooooooooooooooong - tab_down += capture_haml do + %div + %h1 Big! + %p Small + / Invisible %p baz - buffer.tabulation = 10 %p boom - concat "foo\n" -