recipe-site/_plugins/custom_stuff.rb

44 lines
1.2 KiB
Ruby

require "liquid"
require "jekyll"
module Jekyll
module FractionaliseFilter
def fractionalise(input, limit = 0)
input = input.to_s
if not input.include? "."
# if input is a whole number, just return it
return input
end
if input.split(".").length != 2
# generally when liquid filters fail they just print nothing, so we'll do that too
return ""
end
leading_integer, decimal = input.split(".")
decimal = "0.#{decimal}"
rational = case decimal
# handle common weird cases so that e.g. 0.3 returns "1/3" and not "3/10" or "5404319552844595/18014398509481984"
when "0.3", "0.33", "0.333"
Rational(1, 3)
when "0.6", "0.67", "0.666"
Rational(2, 3)
else
decimal.to_r
end
if limit != 0 and rational.denominator > limit
# apply a maximum size for the denominator to avoid the (imo) much more readable "0.41" becoming "41/100" unless wanted
return input
end
"<span title='#{input}'>#{leading_integer != "0" ? "#{leading_integer} " : ""}<span class='fraction'><span class='numerator'>#{rational.numerator}</span><span class='denominator'>#{rational.denominator}</span></span></span>"
end
end
end
Liquid::Template.register_filter(Jekyll::FractionaliseFilter)