ruby on rails - Auto-removing all newlines from Haml output -


i'm using haml in rails 3 app, , newlines drive me nuts! example,

%span   foo 

renders as

<span> foo </span> 

but i'd rather want

<span>foo</foo> 

the reason (apart being cleaner xml) newlines problem selenium tests because mess ability xpath queries "//span[.='foo']". i'd have write '\nfoo\n' instead (ew!), or use //span[contains(text(), 'foo')], matches broadly.

i know use alligator operators ("<" , ">") strip whitespace, since don't ever have case want newlines appear in output, i'd end adding them mechanically @ end of each line. , seems undry.

so see 2 solutions:

  1. force haml never emit newlines unless come ruby expression. see nuke_inner_whitespace / nuke_outer_whitespace variables spread around haml code might job, i'm not sure how change them without resorting gratuitous monkey-patching.
  2. hook rails apply gsub!("\n", "") rendered html. (for textarea's , pre's, still use ~ "foo\nbar" make haml emit foo&#x000a;bar.) where's right place hook rails? i'm little lost in code.

any pointers or other suggestions appreciated!

update: i've used jason's monkey patch below while , i'm beginning think it's not worth it. e.g. if want <span>[del]</span> <span>foo</span>, it's difficult not have blank space in between nuked. following render [del]foo on page:

%span   = '[del] ' %span   foo 

so think i'm going adding alligator operators manually (see self-answer down below). live , learn.

thanks again jason! :)

if place less-than sign @ end of element name whitespace around content suppressed:

%span<   foo 

see whitespace removal in haml reference more details.

there doesn't appear clean way force these flags on tags following monkey patch works fine haml 3.0.24:

module haml::precompiler   def parse_tag_with_nuked_whitespace(line)     result = parse_tag_without_nuked_whitespace line     unless result.size == 9 && [false,true].include?(result[4]) && [false,true].include?(result[5])       raise "unexpected parse_tag output: #{result.inspect}"     end     result[4] = true # nuke_outer_whitespace     result[5] = true # nuke_inner_whitespace     result   end   alias_method_chain :parse_tag, :nuked_whitespace end 

it wouldn't hard fork haml , add option engine options nuke whitespace. parse_tag method check option if enabled , set inner , outer flags true. i'll leave exercise reader. :)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -