Datasheet
Chapter 1: Building Resources
25
< %= f.text_area :description, :rows = > 5, :cols = > 55, :class = > “input” % >
< /p >
< p >
< b > Ingredients: < /b > < br / >
< %= f.text_area :ingredient_string, :rows = > 5, :cols = > 55, :class = > “input” % >
< /p >
< p >
< b > Directions: < /b > < br / >
< %= f.text_area :directions, :rows = > 15, :cols = > 55, :class = > “input” % >
< /p >
< p >
< %= f.submit “Create”, :class = > “title” % >
< /p >
< % end % >
< %= link_to ‘Back’, recipes_path % >
There are a couple of changes. The fields that need more text now have text areas, things have been
moved around a very little bit, and I ’ ve added CSS classes to the input fields that increase the size of the
text being input (it bothers me when sites use very small text for user input).
The
:ingredient_string accessor used in the preceding form is described in the next section.
Parsing Ingredients
The previous code listing included a bare text area for the user to enter ingredients. However, I ’ d still
like to have the data enter the database with some structure that could enable some useful functionality
later on, such as converting from English to metric units. Even so, I felt it was a little cruel to give the
user a four - element form to fill out for each ingredient. So I wrote a small parser to convert strings like
“ 2 cups carrots, diced ” into ingredient objects. The basic test structure follows — put this code into the
ingredient unit test class (
test/unit/ingredients.rb ):
def assert_parse(str, display_str, hash)
expected = Ingredient.new(hash)
actual = Ingredient.parse(str, recipes(:one), 1)
assert_equal_ingredient(expected, actual)
display_str ||= str
assert_equal(display_str, actual.display_string)
end
The inputs are a string, a second string normalized for expected output, and a hash of expected values.
One ingredient object is created from the hash, another is created from the string, and you test for
equality. Then you test the display output string — if the input is
nil , you assume the incoming string is
the same as the outgoing string.
c01.indd 25c01.indd 25 1/30/08 4:02:28 PM1/30/08 4:02:28 PM