Guest User

Untitled

a guest
Feb 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. def parse_string(string)
  2.  
  3. # string is going to be something like:
  4. # 1 small cucumber, finely diced
  5. # or something more complex like
  6. # 4 x 200g tuna steaks
  7. if string.sub!(/^\s*(\d\S*)\s+/, '')
  8. self.quantity = eval($1 + ".to_f")
  9. end
  10.  
  11. words = string.split(/\W+/).map {|w| w.singularize.downcase}
  12. if words.empty?
  13. errors.add( :original, "is missing or invalid")
  14. end
  15.  
  16. # we want to grab each word in the words, then each pair of words, then each
  17. # triplet of words, etc. until all combinations have been tested against
  18. # existing units and foods - we exit as soon as we find a food because (in
  19. # English) units always preceed foods
  20. words.length.downto(1) do |number_of_words|
  21. (0..words.length - number_of_words).each do |index|
  22. phrase = words.slice(index, number_of_words).join(" ")
  23. if f = Food.find_by_name(phrase)
  24. self.food = f
  25. return true
  26. elsif unit.nil? and ( u = Unit.find_by_name(phrase) or ( a = Abbreviation.find_by_name(phrase) and u = a.unit ))
  27. self.unit = u
  28. words.fill(nil, index, number_of_words)
  29. end
  30. end
  31. end
  32. return !self.unit.nil?
  33. end
Add Comment
Please, Sign In to add comment