Skip to content

Commit

Permalink
Don't print empty attributes
Browse files Browse the repository at this point in the history
This was a side-effect of #33, causing empty class lists in Active
Admin: https://travis-ci.org/activeadmin/active_admin/jobs/32816473
  • Loading branch information
seanlinsley committed Aug 18, 2014
1 parent fa57c64 commit 1526789
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
13 changes: 11 additions & 2 deletions lib/arbre/html/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ module HTML
class Attributes < Hash

def to_s
self.collect do |name, value|
map do |name, value|
next if value_empty?(value)
"#{html_escape(name)}=\"#{html_escape(value)}\""
end.join(" ")
end.compact.join ' '
end

def any?
super{ |k,v| !value_empty?(v) }
end

protected

def value_empty?(value)
value.respond_to?(:empty?) ? value.empty? : !value
end

def html_escape(s)
ERB::Util.html_escape(s)
end
Expand Down
3 changes: 1 addition & 2 deletions lib/arbre/html/tag.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,8 @@ def child_is_text?
children.size == 1 && children.first.is_a?(TextNode)
end


def attributes_html
attributes.any? ? " " + attributes.to_s : nil
" #{attributes}" if attributes.any?
end

def set_for_attribute(record)
Expand Down
22 changes: 12 additions & 10 deletions spec/arbre/unit/html/tag_attributes_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@
end

it "should render the attributes to html" do
expect(tag.to_s).to eq <<-HTML
<tag id="my_id"></tag>
HTML
expect(tag.to_s).to eq "<tag id=\"my_id\"></tag>\n"
end

it "shouldn't render attributes that are empty" do
tag.class_list # initializes an empty ClassList
tag.set_attribute :foo, ''
tag.set_attribute :bar, nil

expect(tag.to_s).to eq "<tag id=\"my_id\"></tag>\n"
end

it "should get an attribute value" do
Expand Down Expand Up @@ -45,16 +51,12 @@

describe "rendering attributes" do
it "should html safe the attribute values" do
tag.set_attribute(:class, "\">bad things!")
expect(tag.to_s).to eq <<-HTML
<tag class="&quot;&gt;bad things!"></tag>
HTML
tag.set_attribute(:class, '">bad things!')
expect(tag.to_s).to eq "<tag class=\"&quot;&gt;bad things!\"></tag>\n"
end
it "should should escape the attribute names" do
tag.set_attribute(">bad", "things")
expect(tag.to_s).to eq <<-HTML
<tag &gt;bad="things"></tag>
HTML
expect(tag.to_s).to eq "<tag &gt;bad=\"things\"></tag>\n"
end
end
end

0 comments on commit 1526789

Please sign in to comment.