CSC/ECE 517 Fall 2012/ch1b 1w67 ks

From PG_Wiki
Jump to: navigation, search

Contents

Overview/Introduction

Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. [1].

Flash in Ruby

Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message "Your email id is updated" or "Invalid Password" etc, flash is used to store that message. Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.

Session in Ruby

Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.

A session usually consists of a hash of values and a session id, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client.

In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the complete session that the user is logged in. There are some alternative storage modes for session such as Storage table, No SQL data structure etc.[2]

How it works

Session

Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc. The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence leads to cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited as well though it is visible in the url. [3] Session values are stored in a key,value pair.

1. To add a session attribute we say

  session[:username]=params[:username]. 
  Here we assign the username received from the user to the session variable.

2. To delete a session attribute value, just assign the key to nil.

  eg: session[:username]=nil. 
  Here we are deleting the session attribute username.

3. The session can also be reset

  reset_session
  This will reset the complete session hash

Flash

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,we can also pass the flash message as part of the redirection informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes.The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.[4]

1. To set a flash value as a notice [5]

  flash[:notice]= "User logged in successfully" 
  The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  

2. To set a flash value as a warning [5]

   flash[:error]= "Please provide the username and password" 
   The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  

3. To set flash message as part of redirection

  redirect_to( posts_show,  :notice => "Post successfully created" )
  The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully 
  created.

4. The value of flash to be saved for the subsequent requests

  flash.keep
  The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.

5. The value of flash to be saved in the current request

   flash.now
   The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.

Example - Session/Flash

Class ExamplesController < ApplicationController
def index
session[:example_name]=params[:example][:name]
...
end
def update
@example = Example.find(params[:id])
respond_to do |format|
if @example.update_attributes(params[:type])
format.html {redirect_to(@example, flash[:notice] => 'Example was successfully updated.')}
else
format.html { render :action => "edit" }
end
end
end
def
....
end
end

</p>

In the show(@example) view, we can make use of session and flash as-

<%=notice%>

<%=session[:example_name]%>


In the above code, the ExampleController class has a index method that sets the session for the user and update method sets the flash variable ,we set the session variable with the name of the example obtained from the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set the notice to a desired value. Then it is used in the view to display the message.

Advantages/Disadvantages

Session [6]

Session Advantages:

1.A session object helps us store useful information about the application like the session_id, currently logged in user details.
2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby.
3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects of the application.

Session Disadvantages:

1. The session object is a heavy weight object as it is used to store a lot of application related information.
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not taken care of while programming.
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes out of the current scope logically.
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.

Flash

Flash Advantages:

1. A lightweight object that helps us store the information of the state the application is in.
2. Since flash is similar to hash, it helps us abuse the advantages of hash.
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object
4. It is less tedious to manage as its lifetime persists only until the next request.

Disadvantages:

1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to the application.
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.
3. It cannot store dynamic information.

Conclusion/Summary

HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.

References

  1. http://www.youtube.com/watch?v=0m8lmRwS7E0
  2. http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/
  3. http://guides.rubyonrails.org/security.html#sessions/
  4. http://guides.rubyonrails.org/action_controller_overview.html#the-flash
  5. 5.0 5.1 http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/
  6. http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox