One requirement of a project I’m undertaking at the moment is that the user should be able to enter ingredients into a CMS like this;

1/2 kg sugar

but that when it renders it should convert their 1/2 into the “half” html escape sequence, and similarly for other fractions. There doesn’t appear to be a gem out there that does exactly this, but there was a really nice snippet that provided a good base. With that, it was just a case of using a regex to pull out the fraction characters and a gsub to replace them with an escape sequence. The following therefore went into the application helper file;

#Accepts string and looks for instances of number/number, then attempts to parse those into
#html escape sequences.
def escape_fractions string_with_fractions
#snippet inspired by http://snippets.dzone.com/posts/show/2323
string_with_fractions.gsub(/\d\/\d/) do |match|
case match
when "1/2" then '@amp;frac12;' # One half
when "1/4" then '@amp;frac14;' # One quarter
when "3/4" then '@amp;frac34;' # Three quarters
when "1/3" then '@amp;#x2153;' # One third
when "2/3" then '@amp;#x2154;' # Two thirds
when "1/5" then '@amp;#x2155;' # One fifth
when "2/5" then '@amp;#x2156;' # Two fifths
when "3/5" then '@amp;#x2157;' # Three fifths
when "4/5" then '@amp;#x2158;' # Four fifths
when "1/6" then '@amp;#x2159;' # One sixth
when "5/6" then '@amp;#x215A;' # Five sixths
when "1/8" then '@amp;#x215B;' # One eighth
when "3/8" then '@amp;#x215C;' # Three eighths
when "5/8" then '@amp;#x215D;' # Five eighths
when "7/8" then '@amp;#x215E;' # Seven eighths
else match
end
end.html_safe
end

**NB You’ll need to replace all @ symbols with & – couldn’t for the life of me work out how to stop wordpress escaping them!**

Anyway, this allowed the view to do things like this;

<% @recipe.ingredients.each_line do |ingredient_line| %>
<li><%= escape_fractions ingredient_line %></li>
<% end %>

### Like this:

Like Loading...

*Related*

& to &

Or & amp; and tell people to remove the space.

`&`

Use the code tag to not mangle HTML escapes.