Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def parse_string(string)
- # string is going to be something like:
- # 1 small cucumber, finely diced
- # or something more complex like
- # 4 x 200g tuna steaks
- if string.sub!(/^\s*(\d\S*)\s+/, '')
- self.quantity = eval($1 + ".to_f")
- end
- words = string.split(/\W+/).map {|w| w.singularize.downcase}
- if words.empty?
- errors.add( :original, "is missing or invalid")
- end
- # we want to grab each word in the words, then each pair of words, then each
- # triplet of words, etc. until all combinations have been tested against
- # existing units and foods - we exit as soon as we find a food because (in
- # English) units always preceed foods
- words.length.downto(1) do |number_of_words|
- (0..words.length - number_of_words).each do |index|
- phrase = words.slice(index, number_of_words).join(" ")
- if f = Food.find_by_name(phrase)
- self.food = f
- return true
- elsif unit.nil? and ( u = Unit.find_by_name(phrase) or ( a = Abbreviation.find_by_name(phrase) and u = a.unit ))
- self.unit = u
- words.fill(nil, index, number_of_words)
- end
- end
- end
- return !self.unit.nil?
- end
Add Comment
Please, Sign In to add comment