DivineRails

Ruby on Rails

Blog

Ruby on Rails blog containing tips, tricks and tutorials. Great for both novice and experienced web developers.

view:  full / summary

Controllers for the Devise Gem

Posted by Jamal Nasir on November 27, 2012 at 8:40 AM Comments comments (1)

The devise gem is a superb gem for authentication. It has a nifty generator for views and other things, but it doesn't have any generator for controllers. So, here in this post I will show you how to get the devise's controllers.


The controllers for the devise reside in it gem location. To import those controllers to your application edit the following command according to your system and then run it. Suppose you are in the application directory.


cp -R ~[email protected]/gems/devise-2.1.2/app/controllers/* app/controllers/


By running the above command you will see that the devise controllers are imported to your app/controllers folder.

Authentication and Authorization in Rails Using Devise and CanCan

Posted by Rq Bukhari on April 29, 2012 at 5:30 AM Comments comments (0)



Are you tired of spending lot of time creating user authentication systems. Are you tired of creating a system to manage different roles of users. There are many useful open source stuff available. Devise and CanCan are my choice for user authentication and authorization.


Devise and CanCan are customizable and easy to use. You don't need to spend lot of time on user authentication and authorization. Here in this post I'm going to explain how to use Devise and CanCan in rails 3.


Devise

 


Installation


Open your gemfile and include these two gems.


   gem 'devise'

   gem 'cancan'


Now install these gems using the "bundle install" command. After the successful installation of gems we have to generate the installation of devise using the commands below


   rails generate devise:install

   rails generate devise user


 

 

Configuration

 


The second command will generate user model and migration. You can include any extra fields you want to include in the migration. It also includes the following modules:


Database Authenticatable:

                  Encrypts and stores a password in the database to validate the authenticity of an user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.

Token Authenticatable:

                  Signs in an user based on an authentication token (also known as “single access token”;). The token can be given both through query string or HTTP Basic Authentication.

Oauthable:

                  Adds OAuth2 support

Confirmable:

                  Sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.

Recoverable:

                  Resets the user password and sends reset instructions.

Registerable:

                  Handles signing up users through a registration process, also allowing them to edit and destroy their account.

Rememberable:

                  Manages generating and clearing a token for remembering the user from a saved cookie.

Trackable:

                  Tracks sign in count, timestamps and IP address.

Timeoutable:

                  Expires sessions that have no activity in a specified period of time.

Validatable:

                  Provides validations of email and password. It’s optional and can be customized, so you’re able to define your own validations.

Lockable:

                  Locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.


You can choose any of them and can configure devise accordingly. Here I show how to choose.

 


# In your model class

User < ActiveRecord::Base

                  devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable


If you want to add a new attribute for user you can also add it easily just include it in the attr_accessible like if you want to add username for user:


                  attr_accessible :username, :email, :password, :password_confir...

 


Including the username in attr_accessible you will also have to include it in migration.

 


# In your migration

 

 create_table :users do |t|

                  t.string :username

                  t.database_authenticatable

                  t.confirmable

                  t.recoverable

                  t.rememberable

                  t.trackable

                  t.timestamps

end 

 

 


# In your routes


                  devise_for :users

 

 


Now run the "rake db:migrate" command to run this new migration and create a user table in database.

 


Use Devise


When devise is configured successfully you can use it by including the before_filter in your controller.

 

# In your controllers


                  before_filter :authenticate_user!


#if you want to skip authenticate_user for some action you can configure like


                  before_filter :authenticate_user!, :except => [:some_action_without_auth]

 


You can access the logged in user details by using current_user.


def index

                  @anything = current_user.anythings

end

 

 


We can also customize the views generated by devise, We just need to generate the views and customize it according to our application.

To generate views simple run the following command:


                  rails generate devise:views

 

Now Coming to the authorization of the application. Suppose we have multiple roles in our application. We have to handle these multiple roles like admin, pro-user, basic-user etc. CanCan provide us this functionality and makes it easy for us to configure it in less time.



 

 

CanCan

 

 

Installation


Installation of cancan is already performed in our application because we included both devise and cancan in our gemfile and installed the gems. I like cancan because of the following reasons:

 

 


>   The code written to check permissions is very readable.

>   The code written to declare permissions is very concise and readable.

>   It keeps permission logic in a single location so it is not duplicated across controllers, views, etc.

>   Aliasing actions (read = index and show) creates more concise and readable code.


 

 

After the installation of cancan you need to set up a typical users HABTM roles relationship. This is not necessary to create a HABTM roles relationship but it makes the use of cancan so easy. The migrations will look like this:


class CreateRoles < ActiveRecord::Migration

                  def self.up

                                    create_table :roles do |t|

                                                      t.string :name

                                                      t.timestamps

                                    end

                  end 

                  def self.down

                                    drop_table :roles

                  end

end 

class UsersHaveAndBelongToManyRoles < ActiveRecord::Migration

                  def self.up

                                    create_table :roles_users, :id => false do |t|

                                                      t.references :role, :user

                                    end

                  end

 

                  def self.down

                                    drop_table :roles_users

                  end

end

 

 


Add the following in your models:


# User Model

class User < ActiveRecord::Base

                  has_and_belongs_to_many :roles

 

 


# Role model

class Role < ActiveRecord::Base

                  has_and_belongs_to_many :users


 

 

Now run "rake db:migrate" and the tables will be created. The next step to configure and use cancan is to create ability class. In this class you will authorize user. You will explain the privileges of different roles. The ability class will look like below:

 

class Ability

                  include CanCan::Ability 

                  def initialize(user)

                                    user ||= User.new # guest user 

                                    if user.role? :super_admin

                                                      can :manage, :all #This shows that the super_admin can manage everything

 

                                    elsif user.role? :product_admin

                                                      can :manage, [Product, Asset, Issue] # Show that the product_admin can manage products and its related other things.

 

                                    elsif user.role? :product_team

                                                      can :read, [Product, Asset]  # manage products, assets he owns

                                                      can :manage, Product do |product|

                                                                        product.try(:owner) == user

                                                      end

                                                      can :manage, Asset do |asset|

                                                                        asset.assetable.try(:owner) == user

                                                      end

                                    end

                  end

end


 

 

It's enough for now. I'll explain some more customization of CanCan and Devise in next post. I hope there is no error in the post if any then let me know.

Thanks.

 

 

Devise Authentication (Update record without providing current password)

Posted by Rq Bukhari on March 7, 2012 at 1:30 AM Comments comments (2)




In this post I'm going to introduce devise authentication in ruby on rails. Devise is a full-featured authentication solution for your application. It handles all the controller logic and views. To learn how to use devise there are many tutorials, screen casts available. I'm not going to share anything about those tutorials. Those who want to know the use of devise they can learn it from the links below:


Devise provides the facility to override controllers, to generate views and modify them. All these are explained in the above links. Here I'm going to share a different thing. Here I'm going to show you how to update user details without providing current password. When I was performing the functionality I searched everything but found no solution for the problem. At last I tried a solution and it worked.


My client's requirement was to update user details from admin panel. Where the admin will update user details without providing user password. Even admin can change the user password. To do so I updated the user attributes one by one because using the update_attributes will not work for you.


def update

  respond_to do |format|

    if @user.update_attribute('first_name', params[:user][:first_name]) &&

       @user.update_attribute('last_name', params[:user][:last_name]) &&

       @user.update_attribute('email', params[:user][:email])

      format.html {

        redirect_to(admin_user_details_path, :notice => 'Record updated Successfully.')

      }

    else

      format.html { render :action => "edit" }

    end

  end

end


This way you can update the firstname, lastname and email of a user without providing current password in devise authentication system.

I hope you like the post and you find it helpful.

Filtering Parameters

Posted by Jamal Nasir on March 1, 2012 at 6:05 AM Comments comments (1)

If you have some sensitive data in parameters and you want to hide it from the request log. Then one of the way is to use filter_parameter_logging in a controller where these parameters are expected.

Example:

filter_parameter_logging param1, param2

Read in detail.

Show Branch name in Terminal

Posted by Jamal Nasir on February 14, 2012 at 8:50 AM Comments comments (1)

If you switch branches oftenly and you don't know in which branch you are in currently. Then run the following

lines in the terminal which will show you the current branch name...

source /etc/bash_completion.d/git
PS1='\[$(tput setaf 3)\]\u@\h:\[$(tput sgr0)$(tput setaf 5)\]\w\[$(tput sgr0)$(tput setaf 2)\] $(__git_ps1 "[%s]") \[$(tput sgr0)\]$ '


Calculate the Last Day of Month with Ruby

Posted by Jamal Nasir on February 7, 2012 at 3:45 AM Comments comments (1)

Date.new(Time.now.year, 12, 31)

The above line will create a date with the current year, 12 months and 31 days.

(12-Time.now.month)

This will subtract the current month number of month from 12. For example;

If it is Febuary (2), the above line of code will give you 10.

12-2=10

last_day_of_month= (Date.new(Time.now.year, 12, 31) << (12-Time.now.month)).day

So, the above line will give you the last day of month.

MVC Architecture

Posted by Rq Bukhari on January 24, 2012 at 6:55 AM Comments comments (3)




MVC architecture is a software architecture used in software engineering. Ruby on rails uses MVC (Model, View, Controller) architecture. The MVC architecture of ruby on rails make it easy to keep the code DRY and makes clear where different types of code belongs. This makes the maintenance of code easy.



DRY is a principal of ruby on rails web development that suggest to not repeat a code again and again. DRY is "Don't Repeat Yourself" which means repeating same code again and again is a bad thing.



MODELS


Model represents the information of application. A model corresponds to a table in the database. It defines the rules to manipulate data.



VIEWS


Views are the user interface of application. Views provides data to the web browsers and other tools that are used to make request from an application. Views are the HTML file with embedded ruby code.



CONTROLLERS


Controllers receives the user input. In ruby on rails controllers are responsible for processing the incoming requests of the web browsers and other tools, interrogating the models for required data and passing the data to views for presentation.


This is a short explanation of MVC architecture. To study ruby on rails and MVC Architecture Click here.


Installing Ruby, Rails and MySQL without RVM on Ubuntu

Posted by Rq Bukhari on January 7, 2012 at 9:30 PM Comments comments (1)




Ruby


The best way to install Ruby is by using RVM but those who don't want to install RVM; this guide may be helpful for them. Installing Ruby without RVM is also easy process. You can directly install it from the apt Using the command:


sudo apt-get install ruby1.9.2-full


We can mention any version of Ruby that we want to install and the version will be installed for us. Sometimes apt not provides us with the installation of Ruby because the version we want to install is not available there. In that situation we can install it through another way. The step by step process is given below to install Ruby.


First we need to install git-core and curl that are required to install Ruby. We will use this command:


sudo apt-get install git-core curl


Next we are going to install the other dependencies too. We will install all the packages we need to install Ruby. Here is the command to install the packages we need:


sudo apt-get install build-essential bison openssl libreadline6 libreadline6-dev zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3  libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev


This command will install build-essential, openssl, sqlite and other packages that we will be needed working on rails application development.


Now we need to download our required version of Ruby. Here I am going to install the version 1.9.2 using the command:


wget http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.2-p180.tar.gz


After downloading the file we need to extract the file, make it and then we will install it using the commands:


tar -zxvf ruby1.9.2-p180.tar.gz


cd ruby1.9.2-p180


./configure


make


sudo make install


The installation of Ruby 1.9.2 is complete now.



Rails


As we installed Ruby successfully, now we are going to install rails. Rails can be installed with this simple command:


gem install rails -v 3.0.10


If you are not installing it in your home directory then don't forget using the sudo. The above command will install rails and other gems with it.



MySQL


After the installation of rails is completed we will move ahead to install MySQL in our machine. Before installing the MySQL gem, we will install the libmysqlclient-dev packages. We will use the command:


sudo apt-get install mysql-server mysql-client libmysql-ruby libmysqlclient-dev


After this command we will install MySQL gem using the command:


sudo gem install mysql


Here our installation completes. I will not recommend you to use this method of Rails installation because using the RVM is the best way to install rails. You can install Rails using RVM from here.

Installing RVM, Ruby, Rails and MySQL on Ubuntu

Posted by Rq Bukhari on January 7, 2012 at 2:05 PM Comments comments (2)




This guide will help you install and set up ruby 1.9.2, RVM, Rails and MySQL on Ubuntu machine. If you are not using Ubuntu then don't try this method to install rails.



RVM


Before starting the installation we will run the sudo apt-get update command so that we have the latest sources. After this the first step is to install Git, curl and build-essential. These packages are required for installing and using RVM. To install these we use the command:


sudo apt-get install build-essential git-core curl


After installing these packages we will install RVM. RVM is Ruby Version Manager created by Wayne E. Seguin. RVM is extremely helpful for installing and managing many different versions of Ruby. Sometimes we need to work on different versions of Ruby in projects so RVM is best for managing different versions of Ruby. We will install RVM with this command:


bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)


After installation we need to load RVM by using this command:


echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] &&source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc


Once loaded and ~/.bashrc is added to the line, we can reload the ~/.bashrc by this simple command:


. ~/.bashrc


The next step is to know about the packages we need to install for Ruby to work. Here is the command that will tell us about the packages that we need to install:


rvm requirements


The command will show different packages that we need to install. We will install the packages using this command:


sudo apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion


To install all the packages this command must be written on a single line, otherwise some of the packages will not be installed.



Ruby


Now the installation of RVM is completed so we can easily install any version of Ruby by using this simple command:


rvm install 1.9.2


This command will take some time and will install the mentioned version of ruby. After the installation we must tell RVM to make our required version as default and useable for us. We will use the command:


rvm --default use 1.9.2



Rails


Now RVM and Ruby is installed the next step is to install Rails. We will use the simple command:


gem install rails -v 3.0.10


We will not use sudo to install rails because RVM is installed in our home directory.



MySQL


Now the installation of Rails is completed and we will install MySQL. Before installing MySQL gem we need to install libmysqlclient-dev package. We will use the command:


sudo apt-get install mysql-server mysql-client libmysql-ruby libmysqlclient-dev


After installing these packages we will install MySQL gem by using this simple command:


sudo gem install mysql

 

Now our installation is complete. If anyone has any question, you can ask here. RVM is very powerful tool and it comes in handy for Ruby development. It’s better to use RVM instead of the packages from apt.

Agile Web Development

Posted by Rq Bukhari on January 7, 2012 at 12:50 AM Comments comments (1)




Feature Planning Workshop

 

A feature planning workshop is essentially a brainstorming session. At a bare minimum, the group will consist of the developer's team manager and the person leading the project from within your own organization. the presence of other developers, software users and other stakeholders could also add value. During the workshop the identified requirements are captured in the form of user stories and prioritized.

 

Estimate and Schedule

 

After the feature planning workshop, the developers estimate how long each user story will take to implement. Work is divided into one or two week cycles (iterations) and resources are allocated accordingly. You should then receive an estimate and an iteration schedule.

 

Weekly/Fortnightly Demonstration and Planning Meetings

 

Once the project is given the go-ahead, you may want to meet developers again to plan the first iteration cycle - that is, to define goals for the iteration and to clarify, detail and re-prioritize features. The development team will then go away and write the code and tests while all the time collaborating with you to make sure they are building what you want.

 

At the end of the iteration, developers should demonstrate the completed features for that iteration. Then you can provide feedback and proceed to plan the second iteration in more detail. The process should keep repeating itself until the application is complete.

 

Completion

Once all the iterations are completed and you are happy with the result, the developers should deploy the final version of the application to your server. But the relationship should not end here - make sure they are there to support you if needed.

 


Rss_feed