Skip to content

Commit

Permalink
to_text formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
alexch committed Jun 15, 2010
1 parent cf6574d commit add9a6f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/erector/convenience.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ def to_pretty(options = {})
to_s(options.merge(:prettyprint => true))
end

# Render (like to_s) but stripping all tags.
# Render (like to_s) but stripping all tags and inserting some
# appropriate formatting.
def to_text(options = {})
CGI.unescapeHTML(to_s(options.merge(:prettyprint => false)).gsub(/<[^>]*>/, ''))
html = to_s(options.merge(:prettyprint => false))
html.gsub!(/(<(ul|ol)>)?<li>/, "\n* ")
html.gsub!(/<(\/?(ul|ol|p|br))( \/)?>/, "\n")
CGI.unescapeHTML(html.gsub(/<[^>]*>/, ''))
end

def to_html(*args)
to_s(*args)
end

# Emits the result of joining the elements in array with the separator.
Expand Down
45 changes: 45 additions & 0 deletions spec/erector/convenience_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@
end
end

describe "#to_html" do
it "returns html" do
Erector.inline do
div "foo"
end.to_html.should == "<div>foo</div>"
end
end

describe "#to_text" do
it "strips tags" do
Erector.inline do
Expand Down Expand Up @@ -79,6 +87,43 @@ def funny
end
Funny.new.to_text(:content_method_name => :funny).should == "haha"
end

it "puts a blank line (two newlines) after a /p tag" do
Erector.inline do
p "first paragraph"
p "second paragraph"
end.to_text.should == "\nfirst paragraph\n\nsecond paragraph\n"
end

it "puts a newline after a br tag" do
Erector.inline do
text "first line"
br
text "second line"
end.to_text.should == "first line\nsecond line"
end

it "formats a UL (unordered list) using asterisks for bullets" do
Erector.inline do
ul do
li "vanilla"
li "chocolate"
li "strawberry"
end
end.to_text.should == "\n* vanilla\n* chocolate\n* strawberry\n"
end

# it's too hard to keep track of numbers with a regexp munger, so just use asterisks for bullets
# todo: integrate text output into core rendering code
it "formats an OL (ordered list)" do
Erector.inline do
ol do
li "vanilla"
li "chocolate"
li "strawberry"
end
end.to_text.should == "\n* vanilla\n* chocolate\n* strawberry\n"
end
end

describe "#join" do
Expand Down

0 comments on commit add9a6f

Please sign in to comment.