File tree Expand file tree Collapse file tree 3 files changed +24
-14
lines changed Expand file tree Collapse file tree 3 files changed +24
-14
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 )
Original file line number Diff line number Diff line change 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
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 ="">bad things! "> </ tag >
51- HTML
54+ tag . set_attribute ( :class , '">bad things!' )
55+ expect ( tag . to_s ) . to eq "<tag class=\" ">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 >bad ="things "> </ tag >
57- HTML
59+ expect ( tag . to_s ) . to eq "<tag >bad=\" things\" ></tag>\n "
5860 end
5961 end
6062end
You can’t perform that action at this time.
0 commit comments