Skip to content

Commit 1526789

Browse files
committed
Don't print empty attributes
This was a side-effect of #33, causing empty class lists in Active Admin: https://travis-ci.org/activeadmin/active_admin/jobs/32816473
1 parent fa57c64 commit 1526789

File tree

3 files changed

+24
-14
lines changed

3 files changed

+24
-14
lines changed

lib/arbre/html/attributes.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,22 @@ module HTML
44
class Attributes < Hash
55

66
def to_s
7-
self.collect do |name, value|
7+
map do |name, value|
8+
next if value_empty?(value)
89
"#{html_escape(name)}=\"#{html_escape(value)}\""
9-
end.join(" ")
10+
end.compact.join ' '
11+
end
12+
13+
def any?
14+
super{ |k,v| !value_empty?(v) }
1015
end
1116

1217
protected
1318

19+
def value_empty?(value)
20+
value.respond_to?(:empty?) ? value.empty? : !value
21+
end
22+
1423
def html_escape(s)
1524
ERB::Util.html_escape(s)
1625
end

lib/arbre/html/tag.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,8 @@ def child_is_text?
141141
children.size == 1 && children.first.is_a?(TextNode)
142142
end
143143

144-
145144
def attributes_html
146-
attributes.any? ? " " + attributes.to_s : nil
145+
" #{attributes}" if attributes.any?
147146
end
148147

149148
def set_for_attribute(record)

spec/arbre/unit/html/tag_attributes_spec.rb

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,15 @@
1313
end
1414

1515
it "should render the attributes to html" do
16-
expect(tag.to_s).to eq <<-HTML
17-
<tag id="my_id"></tag>
18-
HTML
16+
expect(tag.to_s).to eq "<tag id=\"my_id\"></tag>\n"
17+
end
18+
19+
it "shouldn't render attributes that are empty" do
20+
tag.class_list # initializes an empty ClassList
21+
tag.set_attribute :foo, ''
22+
tag.set_attribute :bar, nil
23+
24+
expect(tag.to_s).to eq "<tag id=\"my_id\"></tag>\n"
1925
end
2026

2127
it "should get an attribute value" do
@@ -45,16 +51,12 @@
4551

4652
describe "rendering attributes" do
4753
it "should html safe the attribute values" do
48-
tag.set_attribute(:class, "\">bad things!")
49-
expect(tag.to_s).to eq <<-HTML
50-
<tag class="&quot;&gt;bad things!"></tag>
51-
HTML
54+
tag.set_attribute(:class, '">bad things!')
55+
expect(tag.to_s).to eq "<tag class=\"&quot;&gt;bad things!\"></tag>\n"
5256
end
5357
it "should should escape the attribute names" do
5458
tag.set_attribute(">bad", "things")
55-
expect(tag.to_s).to eq <<-HTML
56-
<tag &gt;bad="things"></tag>
57-
HTML
59+
expect(tag.to_s).to eq "<tag &gt;bad=\"things\"></tag>\n"
5860
end
5961
end
6062
end

0 commit comments

Comments
 (0)