Skip to content

Instantly share code, notes, and snippets.

@jbgutierrez
Created December 2, 2009 09:12
Show Gist options
  • Save jbgutierrez/247074 to your computer and use it in GitHub Desktop.
Save jbgutierrez/247074 to your computer and use it in GitHub Desktop.
Get rid of complex HTML logic in Helpers with Composite Pattern
# Composite Pattern
class TagNode
include ActionView::Helpers::TagHelper
def initialize(name, options = {})
@name = name.to_s
@attributes = options
@children = []
end
def to_s
value = @children.each { |c| c.to_s }.join
content_tag(@name, value.to_s, @attributes)
end
def <<(tag_node)
@children << tag_node
end
end
# Usage
table = TagNode.new(:table, table_tag_options)
table << thead = TagNode.new(:thead)
thead << tr = TagNode.new(:tr, :class => 'odd')
thead << tr = TagNode.new(:tr, :class => 'even')
table << tbody = TagNode.new('tbody')
tbody << tr = TagNode.new(:tr, :class => cycle('', 'odd'))
return table.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment