In Rhomobile, as we know that global variable can be accessed through out the application, even in the views, we can use them as a session variable. Let’s assume having a small application with some pages where we need to show the logged in user’s name. So to achieve this, global variable can play a great role. First of all we need to declare the variables in application.rb so that they are available to all the controllers. That can be done as shown below. class AppApplication < Rho::RhoApplication> # This Method Is Called At The Application StartUp def initialize # Initialize the session variable $session ||= {} end end
|
Now on the login controller, verify the email id and password from local db and set the name of the user logged in as shown below
|
class LoginController < Rho::RhoController # This Method Is Used For Showing The Login Form def index # Get the message @message = @params["message"] end # This Method Is Used For Validating The Credentials def validate # Validate the user user_detail = User.find(:first, :conditions => { :email => @params['email'], :password => @params['password'] }) if user_detail $session[:username] = user_detail.username else redirect :action=> :index, :query => { :message => "Invalid credentials, please try with correct credentials." } end end
Note: Assuming the User table containing the email, password and username column and the method gets the email & password as parameter after submiting the login form. So on the view, we can now user the username directly as like below,
<p>UserName : <%= $session[:username] %></p>
Similarly, we can use this global variable where ever required. |