SlideShare a Scribd company logo
1 of 41
Rails Summer of Code
                                     Week 5




Richard Schneeman - @ThinkBohemian
Rails - Week 5
              • Data Flow
              • View to Controller
               • Routes
               • Params
              • Authenticating Users
               • Cryptographic Hashes (cool huh)
               • Authlogic
Richard Schneeman - @ThinkBohemian
Data Flow
    • How do I get data from Server?
     • Controller to View
       • Instance Variables - @dog
    • How do I get data from browser to server?
     • View to Controller
       • forms, links, buttons

Richard Schneeman - @ThinkBohemian
Data Flow
    • Controller to View
     • Controller Gets Object saves it in @variable
     • View gets @variable renders webpage




Richard Schneeman - @ThinkBohemian
Data Flow
    • View to Controller (modify @variable)
     • View has @variable which has ID and attributes
     • Pass @variable.id and new attributes to controller
     • Controller finds object by the ID
       • modifys attributes and saves data


Richard Schneeman - @ThinkBohemian
Data Flow
           • How do I get data from browser to server?
            • Forms
              • form_for
              • form_tag
            • Links
            • Buttons

Richard Schneeman - @ThinkBohemian
form_for
              • form_for - view_helper
               • generates form for object
           Controller                View
              @dog = Dog.new           <%= form_for(@dog) do |f| %>
                                        <div class="field">
              @dog.fur_color             <%= f.label :fur_color %><br />
                                         <%= f.text_field :fur_color %>
                                        </div>
                                         ...
                                        <div class="actions">
                                         <%= f.submit %>
                                        </div>
                                       <% end %>

Richard Schneeman - @ThinkBohemian
form_for
               • form_for - view_helper
                • Uses object’s current state for submit
                        path
           Controller                    View
               @dog = Dog.new              <%= form_for(@dog) do |f| %>
                                            <div class="field">
               @dog.fur_color                <%= f.label :fur_color %><br />
                                             <%= f.text_field :fur_color %>
                                            </div>
                                             ...
                                            <div class="actions">
    @dog is a new Dog, so the form           <%= f.submit %>
    will default to calling the create      </div>
                   action                  <% end %>

Richard Schneeman - @ThinkBohemian
form_tag
          • form_tag - view_helper
           • generates form with no object
           Routes                                       View
  match '/spot/show/' => 'spots#show', :as => :search      <% form_tag search_path do %>
                                                           Username:
                                                             <%= text_field_tag 'username' %>
                                                             <%= submit_tag 'Submit'%>

              • needs a path                               <% end %>



          • Path is set in routes.rb
Richard Schneeman - @ThinkBohemian
form_tag
           • Side note - Shorthand Notation
            • ClassName#MethodName
                                     class Dogs
                                       def show
                                            ...
                                       end
                                     end




             • Dogs#show
       •   Easier than writing “the show method in the dog class”

Richard Schneeman - @ThinkBohemian
Routes
          • Routes
           • Connect controller actions to URLs
           • Example: /dogs/show/2
             • Will call DogsController#show
              • Pass params[:id] = 2
                                routes.rb
                                     resources :dogs


         resources sets up {index, new, create, destroy, edit, update} routes
Richard Schneeman - @ThinkBohemian
Urls and Routes
          • Pass extra info in url with GET method manually
             • /dogs/show/color=brown&name=bob
                    •   params = {:color=> “brown”, :name => “bob”}

          • POST methods show no data in the URL
           • POST is used for sensitive data
             • Password, username, etc.

Richard Schneeman - @ThinkBohemian
Routes
          • Resources ?
             • RESTful Resources



                                     Source: http://peepcode.com


Richard Schneeman - @ThinkBohemian
Routes
           • routes.rb
            • Specify resources
            • forget a route?
     routes.rb
              • run rake routes
         resources :dogs                          Verb      Action, Controller
                                                  GET    {:action=>"index", :controller=>"dogs"}
                                          dogs    POST {:action=>"create", :controller=>"dogs"}
                                       new_dog    GET     {:action=>"new", :controller=>"dogs"}
                                                  GET     {:action=>"show", :controller=>"dogs"}
                                                  PUT    {:action=>"update", :controller=>"dogs"}
                                       dog        DELETE {:action=>"destroy", :controller=>"dogs"}
                                       edit_dog    GET   {:action=>"edit", :controller=>"dogs"}



Richard Schneeman - @ThinkBohemian
Routes
          • Name that Action
             •   dog_path(@dog) (PUT)
                                              1.Find the Verb
             •   dogs_path           (GET)    2.Plural or Singular?
             •   dog_path(@dog) (GET)         3.object.id or no args?
             •   dog_path(@dog) (DELETE)

             •   dogs_path           (POST)




Richard Schneeman - @ThinkBohemian
Routes
          • Name that Action
             •   dog_path(@dog) (PUT)         Update

             •   dogs_path           (GET)    Index

             •   dog_path(@dog) (GET)         Show

             •   dog_path(@dog) (DELETE)      Destroy

             •   dogs_path           (POST)   Create




Richard Schneeman - @ThinkBohemian
Controller Methods
              • Why create & new?
               • New then Create
        dogs_controller.rb                  app/views/dogs/new.html.erb
          def new                            <%= form_for(@dog) do |f| %>
             @dog = Dog.new                  ...
          end



         dogs_controller.rb                 app/views/dogs/create.html.erb
          def create                          <%= @dog.name %>
             @dog = Dog.create(params[...     ...
          end



Richard Schneeman - @ThinkBohemian
Controller Methods
           • What if I want extra actions?
            • Use Index for other stuff ( like search)
            • Create your own if you have to
                         def my_crazy_custom_method
                            puts “This is OK, but not desirable”
                         end




          index, new, create, destroy, edit, & update not enough?


Richard Schneeman - @ThinkBohemian
Controller Methods
   • What if I run out of methods
    • Already used index, new, create, destroy, edit, & update
    • Create a new controller !
      • DogRacesController
      • DogGroomerController
      • etc.
        multiple controllers per heavily used models is normal
Richard Schneeman - @ThinkBohemian
Routes
          • Cool - What about that search_path stuff?
             •   when resources don’t do enough use “match”

                 •   Define custom routes using :as =>
                  match '/dog/show/' => 'dogs#show', :as => :search


                 •   Use route in view as search_path




Richard Schneeman - @ThinkBohemian
Routes
          •   How do I define http://localhost:3000/ ?

              •   Root of your application

                  root :to => "dogs#index"




Richard Schneeman - @ThinkBohemian
link_to
              • Send data using links
                  @dog = Dog.find(:id => 2)


                  <%= link_to 'Some Action', @dog %>


                 • link_to generates a link
                  • Calls a Method
                  • Passes data

Richard Schneeman - @ThinkBohemian
link_to
           • What Path/Method is called by link_to ?
                  @dog = Dog.find(:id => 2)


                  <%= link_to 'Some Action', @dog %>


                 • Default method is GET
                 • @dog is a singular dog


Richard Schneeman - @ThinkBohemian
link_to
           • link_to can take a path directly
                  @dog = Dog.find(:id => 2)


                  <%= link_to 'Some Action', @dog %>



              •   So can form_for, form_tag, button_to ...




Richard Schneeman - @ThinkBohemian
link_to
              • What data does the controller see ?
                  @dog = Dog.find(:id => 2)


                  <%= link_to 'Some Action', @dog %>

                  def show

                 •   dog_id = params[:id]
                     Dog.where(:id => dog_id)
                     ...
                  end

                 • params returns a hash passed via http
                     request
                 • :id is the key passed from @dogs
Richard Schneeman - @ThinkBohemian
link_to
              • Why only pass ID?
                def show
                   dog_id = params[:id]
                   Dog.where(:id => dog_id)

              •Iend
                   ...



               • minimize data sent to and from server
               • decouple data sent from object
                 • security & continuity
               • http methods don’t natively accept ruby
                     objects
Richard Schneeman - @ThinkBohemian
link_to
              • Can I send other stuff besides ID?
               • You betcha!
                 <%= link_to "Link Text", search_path(:foo => {:bar => 42} )%>


                    meaning_of_life = params[:foo][:bar]


                 • pass additional info into view_helper
                     arguments
                 • all data is stored in params
Richard Schneeman - @ThinkBohemian
button_to
              • like link_to except renders as a button
              • default HTTP for buttons method is
                  POST
                <%= button_to "button Text", search_path(:foo => {:bar => 42} )




Richard Schneeman - @ThinkBohemian
Recap
          • This example should make (more) sense now
           • Connect controller actions to URLs
           • Example: /dogs/show/2
             • Will call DogsController#show
               • Pass params[:id] = 2
                                routes.rb
                                     resources :dogs




Richard Schneeman - @ThinkBohemian
Recap
  • Lots of view helpers take data from view to controller
   • Pick the one that best suits your needs
  • Run out of Routes to use?
   • generate a new controller
  • Forget a route
   • Run: rake routes
Richard Schneeman - @ThinkBohemian
Authenticating Users
                 • Cryptographic Hashes
                 • Authlogic




Richard Schneeman - @ThinkBohemian
Crypto Hashes
          • A function that takes any input and returns a
              fixed length string




                                            Passwo
             • function is not reversible
             • minor changes in input


                                                  rds
              • major changes in output                 a12n2
                                                             91234
                                                                  8...



          • Examples: MD5, SHA1, SHA256
Richard Schneeman - @ThinkBohemian
Crypto Hashes
              • Different input
               • Different output




                                                                   Pass
                    myPass




                                                                    iff
                                                                myD
                              A12D
                                                       P29...
                                     34U...
                                              != BG123




Richard Schneeman - @ThinkBohemian
Crypto Hashes
              • Same input
               • Same output




                                                                   ass
                    myPass




                                                               myP
                              A12D                     4U...
                                     34U...
                                              != A12D3




Richard Schneeman - @ThinkBohemian
Crypto Hashes
         • How does this help with user authentication?
          • passwords shouldn’t be stored in a database
            • store crypto-hash instead
         • The same input produce the same output
         • Compare hashed password to stored hash

Richard Schneeman - @ThinkBohemian
Crypto Hashes
         • Good for more than just users!
         • Comparing large datasets for equality
          • Authenticate downloaded files,
          •


Richard Schneeman - @ThinkBohemian
Crypto Hashes
            • Considerations
                •   Collisions - happen

                •   Rainbow tables - exist

                •   Timing Attacks - are not impossible

                •   Don’t use MD5

            •   Helpful techniques

                •   “salt” your hashed data

                •   hash your Hash
Richard Schneeman - @ThinkBohemian
Crypto Hashes
            • Are Awesome
            • Are Useful
            •



Richard Schneeman - @ThinkBohemian
Authlogic
            •   Authentication Gem

            • Don’t write your own authentication
                •   Good for learning, but in production use a library


                                 sudo gem install authlogic




Richard Schneeman - @ThinkBohemian
Authlogic
                               class User < ActiveRecord::Base
                                 acts_as_authentic
                               end




                         class UserSession < Authlogic::Session::Base

                         end




            •   Very flexible, lightweight, and modular

            •   Doesn’t generate code, examples are online
Richard Schneeman - @ThinkBohemian
Questions?
                       http://guides.rubyonrails.org
                        http://stackoverflow.com
                           http://peepcode.com


Richard Schneeman - @ThinkBohemian

More Related Content

Similar to Rails3 Summer of Code 2010- Week 5

Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
RORLAB
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
Henry S
 
Getting the most out of Radiant
Getting the most out of RadiantGetting the most out of Radiant
Getting the most out of Radiant
jomz83
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 

Similar to Rails3 Summer of Code 2010- Week 5 (20)

UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4 UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4
 
Amp and higher computing science
Amp and higher computing scienceAmp and higher computing science
Amp and higher computing science
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
38c
38c38c
38c
 
Asp #1
Asp #1Asp #1
Asp #1
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1
 
Getting the most out of Radiant
Getting the most out of RadiantGetting the most out of Radiant
Getting the most out of Radiant
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
Stop Reinventing The Wheel - The Ruby Standard Library
Stop Reinventing The Wheel - The Ruby Standard LibraryStop Reinventing The Wheel - The Ruby Standard Library
Stop Reinventing The Wheel - The Ruby Standard Library
 
Powershell to the People #suguk
Powershell to the People #sugukPowershell to the People #suguk
Powershell to the People #suguk
 
devise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwandevise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwan
 
Power Automate Techniques that "Save
Power Automate Techniques that "SavePower Automate Techniques that "Save
Power Automate Techniques that "Save
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel
 
UT on Rails3 2010- Week 2
UT on Rails3 2010- Week 2UT on Rails3 2010- Week 2
UT on Rails3 2010- Week 2
 
Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 

More from Richard Schneeman

More from Richard Schneeman (8)

Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQL
 
Rails 3 Beginner to Builder 2011 Week 8
Rails 3 Beginner to Builder 2011 Week 8Rails 3 Beginner to Builder 2011 Week 8
Rails 3 Beginner to Builder 2011 Week 8
 
Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6
 
Rails 3 Beginner to Builder 2011 Week 4
Rails 3 Beginner to Builder 2011 Week 4Rails 3 Beginner to Builder 2011 Week 4
Rails 3 Beginner to Builder 2011 Week 4
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3
 
Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
 
UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

Rails3 Summer of Code 2010- Week 5

  • 1. Rails Summer of Code Week 5 Richard Schneeman - @ThinkBohemian
  • 2. Rails - Week 5 • Data Flow • View to Controller • Routes • Params • Authenticating Users • Cryptographic Hashes (cool huh) • Authlogic Richard Schneeman - @ThinkBohemian
  • 3. Data Flow • How do I get data from Server? • Controller to View • Instance Variables - @dog • How do I get data from browser to server? • View to Controller • forms, links, buttons Richard Schneeman - @ThinkBohemian
  • 4. Data Flow • Controller to View • Controller Gets Object saves it in @variable • View gets @variable renders webpage Richard Schneeman - @ThinkBohemian
  • 5. Data Flow • View to Controller (modify @variable) • View has @variable which has ID and attributes • Pass @variable.id and new attributes to controller • Controller finds object by the ID • modifys attributes and saves data Richard Schneeman - @ThinkBohemian
  • 6. Data Flow • How do I get data from browser to server? • Forms • form_for • form_tag • Links • Buttons Richard Schneeman - @ThinkBohemian
  • 7. form_for • form_for - view_helper • generates form for object Controller View @dog = Dog.new <%= form_for(@dog) do |f| %> <div class="field"> @dog.fur_color <%= f.label :fur_color %><br /> <%= f.text_field :fur_color %> </div> ... <div class="actions"> <%= f.submit %> </div> <% end %> Richard Schneeman - @ThinkBohemian
  • 8. form_for • form_for - view_helper • Uses object’s current state for submit path Controller View @dog = Dog.new <%= form_for(@dog) do |f| %> <div class="field"> @dog.fur_color <%= f.label :fur_color %><br /> <%= f.text_field :fur_color %> </div> ... <div class="actions"> @dog is a new Dog, so the form <%= f.submit %> will default to calling the create </div> action <% end %> Richard Schneeman - @ThinkBohemian
  • 9. form_tag • form_tag - view_helper • generates form with no object Routes View match '/spot/show/' => 'spots#show', :as => :search <% form_tag search_path do %> Username: <%= text_field_tag 'username' %> <%= submit_tag 'Submit'%> • needs a path <% end %> • Path is set in routes.rb Richard Schneeman - @ThinkBohemian
  • 10. form_tag • Side note - Shorthand Notation • ClassName#MethodName class Dogs def show ... end end • Dogs#show • Easier than writing “the show method in the dog class” Richard Schneeman - @ThinkBohemian
  • 11. Routes • Routes • Connect controller actions to URLs • Example: /dogs/show/2 • Will call DogsController#show • Pass params[:id] = 2 routes.rb resources :dogs resources sets up {index, new, create, destroy, edit, update} routes Richard Schneeman - @ThinkBohemian
  • 12. Urls and Routes • Pass extra info in url with GET method manually • /dogs/show/color=brown&name=bob • params = {:color=> “brown”, :name => “bob”} • POST methods show no data in the URL • POST is used for sensitive data • Password, username, etc. Richard Schneeman - @ThinkBohemian
  • 13. Routes • Resources ? • RESTful Resources Source: http://peepcode.com Richard Schneeman - @ThinkBohemian
  • 14. Routes • routes.rb • Specify resources • forget a route? routes.rb • run rake routes resources :dogs Verb Action, Controller GET {:action=>"index", :controller=>"dogs"} dogs POST {:action=>"create", :controller=>"dogs"} new_dog GET {:action=>"new", :controller=>"dogs"} GET {:action=>"show", :controller=>"dogs"} PUT {:action=>"update", :controller=>"dogs"} dog DELETE {:action=>"destroy", :controller=>"dogs"} edit_dog GET {:action=>"edit", :controller=>"dogs"} Richard Schneeman - @ThinkBohemian
  • 15. Routes • Name that Action • dog_path(@dog) (PUT) 1.Find the Verb • dogs_path (GET) 2.Plural or Singular? • dog_path(@dog) (GET) 3.object.id or no args? • dog_path(@dog) (DELETE) • dogs_path (POST) Richard Schneeman - @ThinkBohemian
  • 16. Routes • Name that Action • dog_path(@dog) (PUT) Update • dogs_path (GET) Index • dog_path(@dog) (GET) Show • dog_path(@dog) (DELETE) Destroy • dogs_path (POST) Create Richard Schneeman - @ThinkBohemian
  • 17. Controller Methods • Why create & new? • New then Create dogs_controller.rb app/views/dogs/new.html.erb def new <%= form_for(@dog) do |f| %> @dog = Dog.new ... end dogs_controller.rb app/views/dogs/create.html.erb def create <%= @dog.name %> @dog = Dog.create(params[... ... end Richard Schneeman - @ThinkBohemian
  • 18. Controller Methods • What if I want extra actions? • Use Index for other stuff ( like search) • Create your own if you have to def my_crazy_custom_method puts “This is OK, but not desirable” end index, new, create, destroy, edit, & update not enough? Richard Schneeman - @ThinkBohemian
  • 19. Controller Methods • What if I run out of methods • Already used index, new, create, destroy, edit, & update • Create a new controller ! • DogRacesController • DogGroomerController • etc. multiple controllers per heavily used models is normal Richard Schneeman - @ThinkBohemian
  • 20. Routes • Cool - What about that search_path stuff? • when resources don’t do enough use “match” • Define custom routes using :as => match '/dog/show/' => 'dogs#show', :as => :search • Use route in view as search_path Richard Schneeman - @ThinkBohemian
  • 21. Routes • How do I define http://localhost:3000/ ? • Root of your application root :to => "dogs#index" Richard Schneeman - @ThinkBohemian
  • 22. link_to • Send data using links @dog = Dog.find(:id => 2) <%= link_to 'Some Action', @dog %> • link_to generates a link • Calls a Method • Passes data Richard Schneeman - @ThinkBohemian
  • 23. link_to • What Path/Method is called by link_to ? @dog = Dog.find(:id => 2) <%= link_to 'Some Action', @dog %> • Default method is GET • @dog is a singular dog Richard Schneeman - @ThinkBohemian
  • 24. link_to • link_to can take a path directly @dog = Dog.find(:id => 2) <%= link_to 'Some Action', @dog %> • So can form_for, form_tag, button_to ... Richard Schneeman - @ThinkBohemian
  • 25. link_to • What data does the controller see ? @dog = Dog.find(:id => 2) <%= link_to 'Some Action', @dog %> def show • dog_id = params[:id] Dog.where(:id => dog_id) ... end • params returns a hash passed via http request • :id is the key passed from @dogs Richard Schneeman - @ThinkBohemian
  • 26. link_to • Why only pass ID? def show dog_id = params[:id] Dog.where(:id => dog_id) •Iend ... • minimize data sent to and from server • decouple data sent from object • security & continuity • http methods don’t natively accept ruby objects Richard Schneeman - @ThinkBohemian
  • 27. link_to • Can I send other stuff besides ID? • You betcha! <%= link_to "Link Text", search_path(:foo => {:bar => 42} )%> meaning_of_life = params[:foo][:bar] • pass additional info into view_helper arguments • all data is stored in params Richard Schneeman - @ThinkBohemian
  • 28. button_to • like link_to except renders as a button • default HTTP for buttons method is POST <%= button_to "button Text", search_path(:foo => {:bar => 42} ) Richard Schneeman - @ThinkBohemian
  • 29. Recap • This example should make (more) sense now • Connect controller actions to URLs • Example: /dogs/show/2 • Will call DogsController#show • Pass params[:id] = 2 routes.rb resources :dogs Richard Schneeman - @ThinkBohemian
  • 30. Recap • Lots of view helpers take data from view to controller • Pick the one that best suits your needs • Run out of Routes to use? • generate a new controller • Forget a route • Run: rake routes Richard Schneeman - @ThinkBohemian
  • 31. Authenticating Users • Cryptographic Hashes • Authlogic Richard Schneeman - @ThinkBohemian
  • 32. Crypto Hashes • A function that takes any input and returns a fixed length string Passwo • function is not reversible • minor changes in input rds • major changes in output a12n2 91234 8... • Examples: MD5, SHA1, SHA256 Richard Schneeman - @ThinkBohemian
  • 33. Crypto Hashes • Different input • Different output Pass myPass iff myD A12D P29... 34U... != BG123 Richard Schneeman - @ThinkBohemian
  • 34. Crypto Hashes • Same input • Same output ass myPass myP A12D 4U... 34U... != A12D3 Richard Schneeman - @ThinkBohemian
  • 35. Crypto Hashes • How does this help with user authentication? • passwords shouldn’t be stored in a database • store crypto-hash instead • The same input produce the same output • Compare hashed password to stored hash Richard Schneeman - @ThinkBohemian
  • 36. Crypto Hashes • Good for more than just users! • Comparing large datasets for equality • Authenticate downloaded files, • Richard Schneeman - @ThinkBohemian
  • 37. Crypto Hashes • Considerations • Collisions - happen • Rainbow tables - exist • Timing Attacks - are not impossible • Don’t use MD5 • Helpful techniques • “salt” your hashed data • hash your Hash Richard Schneeman - @ThinkBohemian
  • 38. Crypto Hashes • Are Awesome • Are Useful • Richard Schneeman - @ThinkBohemian
  • 39. Authlogic • Authentication Gem • Don’t write your own authentication • Good for learning, but in production use a library sudo gem install authlogic Richard Schneeman - @ThinkBohemian
  • 40. Authlogic class User < ActiveRecord::Base acts_as_authentic end class UserSession < Authlogic::Session::Base end • Very flexible, lightweight, and modular • Doesn’t generate code, examples are online Richard Schneeman - @ThinkBohemian
  • 41. Questions? http://guides.rubyonrails.org http://stackoverflow.com http://peepcode.com Richard Schneeman - @ThinkBohemian

Editor's Notes