Skip to content

Commit

Permalink
provide option for preserving user input
Browse files Browse the repository at this point in the history
  • Loading branch information
balvig committed Mar 8, 2016
1 parent f285c8b commit d2c527b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 22 deletions.
8 changes: 2 additions & 6 deletions lib/ingreedy.rb
Expand Up @@ -7,12 +7,8 @@
module Ingreedy
ParseFailed = Class.new(StandardError)

def self.locale
@locale ||= nil
end

def self.locale=(locale)
@locale = locale
class << self
attr_accessor :locale, :preserve_amounts
end

def self.parse(query)
Expand Down
30 changes: 14 additions & 16 deletions lib/ingreedy/rationalizer.rb
Expand Up @@ -12,44 +12,42 @@ def initialize(options)
end

def rationalize
if @word
result = normalized_word
elsif @fraction
result = rationalized_fraction
elsif @integer
result = @integer
elsif @float
result = rationalized_float
if Ingreedy.preserve_amounts
(normalized_word || compound_fraction || @float || @integer)
else
(normalized_word || rationalized_fraction || rationalized_float || @integer).to_r
end

result.to_r
end

private

def normalized_word
return unless @word
Ingreedy.dictionaries.current.numbers[@word.downcase]
end

def normalized_fraction
@fraction.tap do |fraction|
vulgar_fractions.each do |char, amount|
Ingreedy.dictionaries.current.vulgar_fractions.each do |char, amount|
fraction.gsub!(char, amount.to_s)
end
end
end

def vulgar_fractions
Ingreedy.dictionaries.current.vulgar_fractions
end

def rationalized_fraction
return unless @fraction
result = normalized_fraction
result = result.to_r + @integer.to_i if @integer
result = result.to_r + @integer.to_i
result
end

def compound_fraction
return unless @fraction
"#{@integer} #{normalized_fraction}".strip
end

def rationalized_float
return unless @float
@float.tr(",", ".")
end
end
Expand Down
26 changes: 26 additions & 0 deletions spec/ingreedy_spec.rb
Expand Up @@ -41,6 +41,32 @@
end
end

describe Ingreedy, "amount parsing preserving original value" do
around do |example|
Ingreedy.preserve_amounts = true
example.run
Ingreedy.preserve_amounts = false
end

{
"1 cup flour" => "1",
"2 cups flour" => "2",
"1 1/2 cups flour" => "1 1/2",
"¼ cups flour" => "1/4",
"1 ½ cups flour" => "1 1/2",
"1½ cups flour" => "1 1/2",
"1.0 cup flour" => "1.0",
"1.5 cups flour" => "1.5",
"1,5 cups flour" => "1,5",
"1/2 cups flour" => "1/2",
".25 cups flour" => ".25",
}.each do |query, expected|
it "parses the correct amount" do
expect(Ingreedy.parse(query).amount).to eq(expected)
end
end
end

describe Ingreedy, "english units" do
context "abbreviated" do
{
Expand Down

0 comments on commit d2c527b

Please sign in to comment.