Skip to content

Commit

Permalink
Protype of new tag helper syntax, i.e. tag.span class: 'bookmark'
Browse files Browse the repository at this point in the history
  • Loading branch information
marekkirejczyk committed Jun 21, 2016
1 parent 578f2c8 commit b401467
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
40 changes: 39 additions & 1 deletion actionview/lib/action_view/helpers/tag_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,43 @@ module TagHelper
PRE_CONTENT_STRINGS[:textarea] = "\n"
PRE_CONTENT_STRINGS["textarea"] = "\n"

# TagBuilder work in progress
# TODO:
# * Documentation
# * More tests
# * support for NEED_CLOSING element
# * Method missing -> raise if unknown html tag
# * fill NEED_CLOSING
# * include support for escape argument
# * blocks
# * Extract to sepearete file (?)

class TagBuilder
include ActionView::Helpers::TagHelper

VOID_ELEMENTS = %w(base br col embed hr img input keygen link meta param source track wbr).to_set
VOID_ELEMENTS.merge(VOID_ELEMENTS.map(&:to_sym))

private

def render_tag(name, content_or_options = nil, options = nil, &block)
if block_given?
content_tag(name, yield(self), content_or_options)
elsif content_or_options.is_a? String
content_tag(name, content_or_options, options)
elsif VOID_ELEMENTS.include?(name)
tag(name, content_or_options, false, escape = true)
else
content_tag(name, "", content_or_options)
end
end

def method_missing(called, *args, &block)
render_tag(called, args[0], args[1], &block)
end

end


# Returns an empty HTML tag of type +name+ which by default is XHTML
# compliant. Set +open+ to true to create an open tag compatible
Expand Down Expand Up @@ -72,7 +109,8 @@ module TagHelper
#
# tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)})
# # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
def tag(name, options = nil, open = false, escape = true)
def tag(name = nil, options = nil, open = false, escape = true)
return TagBuilder.new if name == nil
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
end

Expand Down
13 changes: 13 additions & 0 deletions actionview/test/template/tag_helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ class TagHelperTest < ActionView::TestCase

tests ActionView::Helpers::TagHelper

def test_builder_tag
assert_equal "<br />", tag.br
assert_equal "<span class=\"bookmark\"></span>", tag.span(class: "bookmark")
end

def test_builder_content_tag
assert_equal "<div id=\"post_1\">Content</div>", tag.div("Content", id: "post_1")
end

def test_builder_nested
assert_equal "<div id=\"header\"><span>hello</span></div>", tag.div(id: 'header') { |tag| tag.span 'hello' }
end

def test_tag
assert_equal "<br />", tag("br")
assert_equal "<br clear=\"left\" />", tag(:br, :clear => "left")
Expand Down

0 comments on commit b401467

Please sign in to comment.