4 Simple Steps To Implement “Delayed Job” In Rails

Here in this article, I going to tell you the best way to implement “delayed job” in rails

“delayed_job” is a ruby gem used to execute tasks as a background process in Rails environment, increasing page rendering speed.

Delayed::Job (or DJ) allows you to move jobs into the background for asynchronous processing.

Why you need a background process and is it really that important!

Let’s consider a scenario where a mailing application needs to send emails to a huge list of recipients. In such cases it is obvious that the processing time is too long, annoying the users.

Here are some of key points to consider:

  • Incredibly quick & easy to get rolling
  • No addition to your “stack”, runs just fine with Active Record
  • Good choice for beginners while migrating code from foreground to the background

Hence, it’s only wise to move the long running tasks as a background process by using “delayed_job” gem.

Detailed steps to integrate delayed job in a Rails application

Step# 1

  • Add gem to the Gemfile
  • “delayed_job” supports multiple back-ends for storing the job queue
  • To use “delayed_job” with Active Record, use gem ‘delayed_job_active_record’
  • To use “delayed_job” with Mongoid, use gem ‘delayed_job_mongoid’

Example

/Gemfile.rb

  • gem ‘delayed_job_active_record’, ‘4.0.3’
  • Run “bundle install” to install the “delayed_job” gem

Step# 2

  • Generate the related file for the Job run
  • Generate related files required to run the background job by running the following command
    • rails g delayed_job:active_record

It adds following files to the application

  • A Script named “delayed_job” inside “/bin” folder to run the jobs which are in queue.
  • Migration file to create a table to store the job with other information such as priority, attempts, handler, last_error, run_at, locked_at, failed_at, locked_by, queue.

Run the migration file by using the following command

  • rails db:migrate

Set the queue_adapter in config/application.rb

  • config.active_job.queue_adapter = :delayed_job

If you are using the protected_attributes gem, it must appear before delayed_job in your gemfile. If your jobs are failing with:

  • Setup Delayed::Job config in an initializer (config/initializers/delayed_job_config.rb)
    • Delayed::Worker.destroy_failed_jobs = false
    • Delayed::Worker.sleep_delay = 60
    • Delayed::Worker.max_attempts = 3
    • Delayed::Worker.max_run_time = 5.minutes
    • Delayed::Worker.read_ahead = 10
    • Delayed::Worker.default_queue_name = ‘default’
    • Delayed::Worker.delay_jobs = !Rails.env.test?
    • Delayed::Worker.raise_signal_exceptions = :term
    • Delayed::Worker.logger = Logger.new(File.join(Rails.root, ‘log’, ‘delayed_job.log’))

Step# 3

  • Replace script/delayed_job with bin/delayed_job
  • Start up the jobs process

There are two ways to do this.

  • If application is in development mode, we would use the below rake task instead.
    • rake jobs:work
  • If application is in production mode, then it is preferred to use the “delayed_job” script. This demonizes the job process and allows multiple background processes to be spawned.

To use this, pursue the following steps

  • Add gem “daemons” to your Gemfile
  • Run bundle install
  • Make sure you’ve run rails generate delayed_job
  • If you want to just run all available jobs and exit you can use rake jobs:workoff
  • Work off queues by setting the QUEUE or QUEUES environment variable.
    • QUEUE=tracking rake jobs:work
    • QUEUES=mailers,tasks rake jobs:work

Step# 4

  • Add task to run in background
  • In Controller just call .delay.method(params) on any object and it will be processed in the background.

Example:

UsersController before adding to background job

[code language=”html”]
class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
NewsMailer.newsletter_mail(user).deliver
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end
[/code]

 
UsersController after adding to background job

[code language=”html”]
class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
# add .delay method to add it to background process. In case of mail sending remove the .deliver method to make it work.
NewsMailer.delay.newsletter_mail(user)
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end
[/code]

Advantages of implementing above steps:

  • No more waiting for a response, after clicking a link to do a big stuff.
  • Just call .delay.method(params) on any object and it processes in the background.
  • Job objects are serialized to yaml and stored in the delayed_jobs table, so they can be restored by the job runner later.
  • It automatically retries on failure. If a method throws an exception it’s caught and the method reruns later. The method retries up to 25 times at increasingly longer intervals until it passes.
  • “delayed_job” gem maintains log by creating a log file “/log/delayed_job.log”

I am sure this article will give you a clear idea about the way to implement “delayed job” in rails. You can share your thoughts with comments if I have missed anything or if you want to know more.

Do you work on or use Ruby on Rails? Let’s Discuss!

Ruby On Rails Releases Fixes For DoS, XSS Vulnerabilities

In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

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>

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])

How To Implement Event Calendar In Rails App

Event calendar is a way to show multiple, overlapping events across calendar days and rows. This is an interface to add events, edit events, & destroy event. In Rails there is a gem/plugin “event_calendar” to implement it just like Google calendar.

The following steps demonstrate the implementation of event_calendar in both Rails 2.3.x and Rails3.x environment.

Step#1 –

Installing the gem/plugin

  • In rails 2.3.x

Install the required plugin from below path

script/plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file and example

script/generate event_calendar
  • In rails 3.x

Install the required gems

gem 'event-calendar', :require => 'event_calendar'

Run “bundle install

You can also use as a Plugin, to install plugin

rails plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file for the event calendar

rails generate event_calendar

Step#2

Include the necessary style sheet & java-script into your layout/view

<%= stylesheet_link_tag "dialog","fullcalendar","jquery-ui","style" %>
<%= javascript_include_tag "jrails1/fullcalendar.js","jrails1/jquery-
ui.js","jrails1/gcal.js","jrails1/jrails.js","jrails1/jquery.validate.js"%>

Step#3

Create a migration file to add necessary columns as follows

class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.string :name
t.datetime :start_at
t.datetime :end_at
t.timestamps
end
end
def self.down
drop_table :events
end
end

Step#4

Add the necessary paths to the “config/routes” file

  • In Rails 2.3.x
map.calendar '/calendar/:year/:month', :controller => 'calendar', :action => 'index',
 
:requirements => {:year => /d{4}/, :month => /d{1,2}/}, :year => nil, :month => nil
  • In Rails3.x
match '/calendar(/:year(/:month))' => 'calendar#index', :as => :calendar, :constraints => {:year => /d{4}/, :month => /d{1,2}/}

Step#5

Change the Event model to add the calendar as follows

class Event < ActiveRecord::Base
has_event_calendar
end

Step#6

Modify the Calendar controller as follows

class CalendarController < ApplicationController
def index
@month = (params[:month] || Time.zone.now.month).to_i
@year = (params[:year] || Time.zone.now.year).to_i
@shown_month = Date.civil(@year, @month)
@event_strips = Event.event_strips_for_month(@shown_month)
end
end

Step#7

You can also override the events method in helpers/calendar_helper.rb

module CalendarHelper
def month_link(month_date)
link_to(I18n.localize(month_date, :format => "%B"), {:month => month_date.month, :year => month_date.year})
end
# custom options for this calendar
def event_calendar_options
{
:year => @year,
:month => @month,
:event_strips => @event_strips,
:month_name_text => I18n.localize(@shown_month, :format => "%B %Y"),
:previous_month_text => "<< " + month_link(@shown_month.prev_month),
:next_month_text => month_link(@shown_month.next_month) + " >>"
}
end
def event_calendar
calendar event_calendar_options do |args|
event = args[:event]
%(<a href="/events/#{event.id}" title="#{h(event.name)}">#{h(event.name)}</a>)
end
end
end

Step#8

Add the following code to display the calendar in the view file

<%= event_calendar %>

See Also: Security Checks you must do before Rails App release

I hope it helps you. Planning anything in Ruby on Rails? Get in touch with Andolasoft experts. Feel free to give your valuable feedback.