How to customize Devise authentication in Rails3?

Rails31Devise is an authentication solution for Rails application development. Since devise is an engine and all the files created by it are packaged inside the gem. We need to invoke some generators in order to customize it according to our choice.

Configuring views:

  • If you want to modify the views generated by devise, then you just need to invoke the following generator, and it will copy all views to your application.
rails generate devise:views
  • If you have more than one role in your application (such as “User” and “Admin”), Devise offers an easy way to customize views. Just write the following line inside your “config/initializers/devise.rb”
config.scoped_views = true
  • Now you will be able to have views based on the role like “users/sessions/new” and “admins/sessions/new”. You can also use the generator to generate scoped views like below:
rails generate devise:views users

Configuring controllers:

If the customization at the views level is not enough, you can customize the controller generated by devise using following steps.
Step#1

  • Create a custom controller
class Users::SessionsController < Devise::SessionsController
[Your code goes here]
end

Now you can customize your methods according to the conditions.

Step#2

  • Now tell the route to use this controller in “config/routes.rb”
devise_for :users, :controllers => { :sessions => "users/sessions" }

ustomizing Error Messages:

Devise has its own error messages that are shown when something goes wrong. All of these messages are stored in a locale file (config/locales/devise.en.yml), making it easy to maintain them. Here you can see the list of error messages created by devise and you can customize them according to your choice.

Customizing Registration process:

You can also customize the registration process of devise. Here is an example to explain the customization of Registration process where devise sends an activation email automatically after a new user registration happens.

Step#1

  • Modify the “users” migration file created by devise. Uncomment the block of fields under Confirmable.
t.string   :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string   :unconfirmed_email

Step#2

  • Customize the “User” model like below:
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable, :confirmable

We have added “:confirmable” module for devise to the model. Confirmable is responsible to verify if an account is already confirmed to sign in, and to send emails with confirmation instructions. Confirmation instructions are sent to the user email after creating a record.

Then add the field names that are defined in step#1 to the ‘attr_accessible’.

Step#3

  • Run the migration
rake db:migrate

Step#4

  • Now set the default URL for according to your requirement in “config/enviroments/development.rb”
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Now if you register for a new user then devise will send a confirmation email with required instructions.

File Uploading Through Paperclip in Rails 3.x

Rails3Paperclip is an easy file attachment library for Rails Applications. Attached files are saved to the file system, database or cloud and referenced in the browser by an easily understandable specification.

Here is an example to explain the image attachment for a user profile in an application. This example narrates about saving the image in the file system. However, the images can be saved in S3 bucket [Amazon Simple Storage Service, S3] or database.

Step#1

ImageMagick must be installed in the system and Paperclip must have access to it. ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats. You can download it by visiting the following URL:

http://www.imagemagick.org/script/index.php

Step#2
Include the paperclip gem in your Gemfile

gem "paperclip"

Then run the bundler to install the gem

bundle install

Step#3
Add the fields for the image processing as below in your migration file

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :photo_file_name
t.string :photo_content_type
t.string :photo_file_size
t.timestamps
end
end
end

Then run your migration files

rake db:migrate

Step#4

Modify the user model for cropping and save image in your system folder

has_attached_file :photo, :styles => { :small => "150x150>" },
:url => "/system/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/system/:attachment/:id/:style/:basename.:ex

Here you can specify the file path and the image size as per the requirement.

Step#5
Modify your view file to upload an image

<pre class="plain plain">&lt;%= form_for :user,:url =&gt; {:action =&gt; "create"}, :html =&gt; { :multipart =&gt; true } do |f| %&gt;
&lt;%= f.file_field :photo %&gt;
&lt;% end %&gt;</pre>

Step#6
Write the following code to display the image of a user

<%= image_tag @user.photo.url (:small)%>

Please stay connected with us by subscribing our email.
Also feel free to share your opinions in the comments section below:

How to Generate SEO Friendly URL in Rails 3.x

Rails3SEO friendly URLs are more important to make a page popular & search engines to crawl.

FriendlyId is the slugging and permalink plug-in for Ruby on Rails. It allows you to create pretty URLs and work with human-friendly strings.

The URLs created by slug are very useful for SEO. It is designed for generation of URL slug and history maintenance.

Steps to create Pretty URLs:

Step#1

Include gem in your Gem file:

gem 'friendly_id'

Then run bundle install.

Step#2

Modify your model on which you want the pretty URL:

extend FriendlyId
 
friendly_id :title, use: :slugged

Step#3

Add the slug column in your migration file to add it on the table

add_column :articles, :slug, :string

Then run

rake db:migrate

Now if you create an article with Title like “This is a demo title for testing”,
it will create a SEO friendly URL like “this-is-a-demo-title-for-testing” and will
save into the articles table under slug column.

Collecting Contacts Using Cardmagic-Contacts Pplug-in in Rails 2.3.8

Rails3

Cardmagic-Contacts is a rails plug-in which provides an interface to fetch contact list information from various email providers including Hotmail, AOL, Gmail, Plaxo, Yahoo and many more.

This example narrates how to extract contact list using Rails 2.3.8 and cardmagic-contacts plug-in

Step#1

  • Download the plug-in by running the command below to store the plug-in in the folder “vendor/plug-ins”

Windows

ruby script/plugin install git://github.com/cardmagic/contacts

Linux

ruby script/plugin http://github.com/cardmagic/contacts

Step#2

  • Write down the following code on the top of the controller class
require 'contacts'

Step#3

  • Pass the required gmail/yahoo/hotmail/AOL login & password from view
<div>
 
<div style="margin-left:25px;" >Invite <img src="../images/yahoo.JPG">Yahoo
 
Friends </div>
 
<div style="margin-left:25px;">Yahoo Email: <input type="text" name="email"
 
id="yahoo_email_id"></div>
<div style="margin-left:25px;">Password:   <input type="password"
 
name="email"  id="yahoo_pwd_id"></div>
 
<div style="margin-left:122px;margin-top:20px;"><input type="button"
 
value="Login" name="btn_submit" id="btn_submit" ></div>
 
</div>

Step#4

  • Create an action to fetch the list of contacts for a specific email id

def grab_contacts #Grab gmail contacts @gmail_contacts=Contacts::Gmail.new(login, password).contacts #or @gmail_contacts=Contacts.new(:gmail, login, password).contacts #Grab yahoo contacts @yahoo_contacts = Contacts::Yahoo.new(login, password).contacts #or @yahoo_contacts = Contacts.new(:yahoo, login, password).contacts #Grab hotmail contacts @hotmail_contacts =Contacts::Hotmail.new(login, password).contacts #or @hotmail_contacts = Contacts.new(:hotmail, login, password).contacts end

Step#5

  • Here is also alternate method to get the contacts by providing  email_id and password
any_mail = Contacts.guess(login, password).contacts

The “Contacts.guess” method will automatically concatenate the entire
address book from each of the successful logins. If the login and password is
working with multiple email accounts then it will grab the contacts from all accounts.

Step#6

  • Display the friends list in your view page
<table>
<th>
<td >Friends Name</td>
<td >Friends Email</td>
</th>
<tr>
<% @gmail_contacts.each do |contact| %>
<td><%=contact[0]%></td>
<td><%=contact[1]%></td>
<% end %>
</tr>
</table>

What is the Importance of Filters in Rails

Rails

In Ruby on Rails development, filters play a vital role. They are the methods executed ‘before’, ‘after’  or  ‘around’ a controller action.

For example, one filter might check to see if the user has the credentials to access that particular controller or action.

Filters are inherited, so if you set a filter on ‘ApplicationController’, it would run on every controller in your application.

Below is an example to explain how a filter can be used to restrict a non-logged in user to access specified actions in a controller

Step#1

  • In Application controller write the following block of code according to the requirement.
def user_login_required
 if !session[:username]
 flash[:notice] = "Oops you need to login!"
 redirect_to :controller => "user_sessions", :action => "new"
 end
end

Step#2

  • Now write the before_filter block in the controller you want to restrict the not registered users. You can also restrict particular actions of a controller by writing the action name.
class UsersController < ApplicationController
 before_filter :user_login_required, :only => [:profile]
 def profile
 [Your code block goes here]
 end
end

In the above block the ‘before_filter’ restrict the not registered user to access
the profile page and redirect them to login page. We can also restrict multiple
actions by writing like this

before_filter :user_login_required, :only => [:profile,:edit]

In this case the filter is applied to only these two methods of a particular controller.

before_filter :user_login_required, :except => [:index,:show]

In this case the filter is applied to all other actions except index and show
action of a particular controller.

If you write the before_filter block in the “ApplicationController” then the
filter will be applied to all the controllers.

Planning anything on Ruby on Rails? Talk to Andolasoft’s experts to get a clearer idea.

How to implement Multiple Database(DB) Connection in Rails3

Rails 3In some scenarios, we need data from an external database to execute in different applications. Here, we need a bridge that will connect these two different databases.

In Ruby on Rails, this can be achieved through ActiveRecord’s establish_connection().

Following are the steps to create a rails application which uses multiple databases, where the existing database and the external database will work simultaneously.

Let’s say there are two different rails applications say “myapp” and “remoteapp” where “myapp” depends upon “remoteapp” user table.

Step#1

Edit the ‘database.yml‘ file for the ‘myapp‘ project
Add a new connection for ‘remoteapp‘ as below:

# Connection name, it will be used to connect from myapp
connect_remote:
adapter: mysql2
username: user_name             # username of the remoteapp database
password: password             # password of the remoteapp database
pool: 5
database: remoteapp_db_name    # database name of the remoteapp
host: www.remoteapphost.com      # host name of the db

Step#2

In models folder create a new file called user.rb if it is not already there. Write below code to establish connection with remote app’s database.

class User < ActiveRecord::Base
establish_connection("connect_remote")
end

Here use the connection name defined in the database.yml file in the establish_connection() method.
Like this you can create models to connect with remote databases.
Step#3

It will give you the flexibility for managing users’ data of remote app’s database like it is present in the myapp database.
Use the normal way to get data from the user’s table like

User.all                   #To get all the records
User.find(id)              #To get required record

Here you can also insert or update data in users table by normal way as it is
present in myapp application

#insert new record
user = User.new params[:user]
user.save
 
#update existing record
user = User.find params[:id]
user.update_attributes(params[:user])