Created
December 2, 2009 09:12
-
-
Save jbgutierrez/247074 to your computer and use it in GitHub Desktop.
Get rid of complex HTML logic in Helpers with Composite Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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