| Path: | lib/more/facets/buildable.rb |
| Last Update: | Tue Dec 02 09:46:42 -0500 2008 |
Build content programatically with Ruby and Ruby‘s blocks.
require 'facets'
require 'xmlhelper'
builder = BuildingBlock.new(XMLHelper, :element)
doc = builder.html do
head do
title "Test"
end
body do
i "Hello"
br
text "Test"
text "Hey"
end
end
produces
<html><head><title>Test</title><body><i>Hello</i><br />TestHey</body></html>
All calls within the block are routed via the Helper Module‘s constructor method (element in the above example) unless they are defined by the helper module, in which case they are sent to the helper module directly. The results of these invocations are appended to the output buffer. To prevent this, prefix the method with ‘call_’.
Sometimes keywords can get in the way of a construction. In these cases you can ensure use of constructor method by calling the special build! command. You can also add verbatium text to the output via the #<< operator. Some common Ruby‘s built-in methods treated as keywords:
inspect
instance_eval
respond_to?
singleton_method_undefined
initialize
method_missing
to_str
to_s
And a few other speciality methods besides:
to_buffer
build!
<<
This work was of course inspired by many great minds, and represents a concise and simple means of accomplishing this pattern of design, which is unique to Ruby.
Buildable is mixin variation of BuildingBlock.
require 'facets/buildable'
require 'xmlmarkup' # hypothetical library
module XMLMarkup
include Buildable
alias :build :element
end
doc = XMLMarkup.build do
html do
head do
title "Test"
end
body do
i "Hello"
br
text "Test"
text "Hey"
end
end
end
produces
<html><head><title>Test</title><body><i>Hello</i><br />TestHey</body></html>
This is based on BuildingBlock. Refer to it for more information.
Copyright (c) 2006 Thomas Sawyer
Ruby License
This module is free software. You may use, modify, and/or redistribute this software under the same terms as Ruby.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.