For some time now I’ve been looking for a decent Rails equivalent of
“htmlentities” command, because ERB’s html_escape (or more commonly
just “h”, eg. <%=h @somevariable %> ) just doesn’t go far enough for me.
Back in PHP land, I actually had an extended version of the htmlentities
command to deal with all kinds of crazy characters that appear if you
and paste into a CMS from Word. So anyway, given the apparent lack of a
function to do this in Rails, and because I’m not particularly impressed
ERB’s html_escape, I decided to do something about it and roll my own.
Here’s my code: http://rafb.net/paste/results/9lI1hc62.html
It defines a htmlentities function, designed to be included in a helper,
your environment (that’s what I’m doing with it). Then it overrides the
function to call htmlentities instead of ERB’s html_escape, hopefully
you can just drop this in and your app will start using it.
I’m offering this up for several reasons:
Because I know I’m not the only person who wants such functionality,
can’t seem to find anyone else who has written this yet.
For code review - is there anything wrong with it? Anything missing?
Anything that could be done more efficiently? I’m hardly a Ruby / Rails
guru, so would really appreciate some second opinions here!
I haven’t used this on a production site yet (only wrote it this
my thinking is that this code coupled with Rails’ caching should solve
problem in a nice and efficient manner. This probably isn’t the ideal
solution, as in for sites in non-western alphabets (eg. Japanese,
Arabic etc.) it probably doesn’t help, but the thinking is that this
should be at least as good as PHP’s htmlentities command for most
alphabet users… I hope!
So, any comments? Feel free to use the code anywhere you like, but
just wait until a few other folks have looked it over, just in case
something heinously wrong with it! It comes with no guarantee of
for any purpose whatsoever, and you use it entirely at your own risk.
Regardless, if folks think it’s useful, I’ll put it online somewhere
permanent than RAFB NoPaste!
Rent-A-Monkey Website Development