Monday, March 3, 2014

Week 5 Day 1: Say "Ahoy" to Forms!

Major Activities of the Day: Today began with an assignment to build a Linked List.  Since I haven't done one of those since high school, it was a good refresher.  We then moved on to a lecture about how to work with forms in Sinatra.  This involves two parts.  One is understanding HTML form tags, to construct a form with various types of input, each including proper name and id properties.  The other part is understanding how the input is passed into and accessible in Sinatra through the params hash.  For example, let's say I have a form for pirates:



It would look like this:

Pirates:














How would I access the data sent?  I add to my app a route /pirates that will handle a POST request, access the params hash and create some new pirates, and then return a new page:

post '/pirates' do
  @new_pirates = params[:pirates].map { |pirate_num, attributes|
    Pirate.create(attributes) if attributes[:name] != ""
  }.compact

  erb :"success.html"
end


Simply put, this takes params[:pirates], which is a hash containing numbers (:0, :1, :2, etc.) as keys and pirate attribute hashes as values, and then creates new Pirate objects (which must be defined elsewhere) for any set of defined attributes, and finally renders a page which displays the newly input information (which is stored in @new_pirates), which can also be accessed later (if items are saved to a database).

We spent the afternoon working on two labs where we created Sinatra apps with forms and displayed the output, optionally writing tests and persisting to a database.  I had enough time to write tests for the first lab (I actually developed it entirely with tests first), and persist both to a database.

Skills developed: Linked lists, Sinatra with forms, RSpec testing in Sinatra

No comments:

Post a Comment