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!

Top Reasons To Bring RoR Development On Board

ror411-123

Rails is an innovation in development framework.  It encompasses all the necessary elements to boost a web application’s performance. This framework is designed to address agile development and deliver productivity as well as flexibility to RoR developers. Developed using Ruby programming language, it has transformed the world of web development through its practical approach.

Ruby on Rails is built upon two programming philosophies

  • “Convention over Configuration”: Developers only need to write codes for the irregular or unconventional aspects of the web application.
  • “Don’t Repeat Yourself”: The data is stored in definite place. It saves time and reduces code

Advantages of Ruby on Rails

  • Faster Development: Rails framework enables the developers to write concise and clear syntax and produces fewer codes than its competitors. Therefore it requires less time to code and generates fewer errors. On the other hand it facilitates the programmers to maintain much less code. It is also enabled to integrate numerous tools to automate repetitive tasks such as managing database errors, creating forms etc. it simplifies development process because the language is lightweight and easily readable, almost like the natural language.
  • Increases productivity: Rails framework is specifically featured to reduce the development aspects of applications, instead leveraging creativity and uniqueness of the web application. It empowers productivity by eliminating repetitive programming codes.
  • Assists development of creative interfaces: Rails includes numerous integrations to enable developers in creating rich, intriguing user interfaces. Integrated JavaScript framework is easier to activate and features elements like apparition progressive, drag & drop and many more to ease the designing aspects of the application.
  • Model View Controller design pattern: Rails is developed on MVC architecture that separates the development logics from the presentation layer. It provides a well-structured application to the developers and the code is maintained in a logical and coherent manner.  It encourages abstraction in the application and enables the team to work on separate modules without depending on each other. It focuses on the features rather than minute details. Rails framework delivers ease of project development, conciseness and faster deployment of application.

Rails Development makes web app development easier because it involves less coding while implementing new changes and updates into the development process. It enables the organizations to meet all the business requirements within the budget and schedule.

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.

How To Generate Barcode Using Barby Gem In Rails 2.3.8

A barcode is a series of vertical black lines with white spaces in between. This series of lines and spaces can be read by a device that can decode them. This would be a barcode reader.

In Ruby on Rails there is a gem called “barby” which generates the barcode with various format.

Here is an example to create barcode using barby & Rails 2.3.8.

Step#1

Include the barby gems in your config/environment.rb file

config.gem'barby'
config.gem 'barby-chunky_png'
config.gem 'png''RubyInline'

Install the gems by running the commandrake gems:install. Restart the Rails server.

You might face problem to start the server after the gems installed.Comment out the gems “png” & “RubyInline” in the “config/environment.rb” to get the server started.

Step#2

Create a folder named “Barcodes” to store the barcode images in your “Public” folder.

Step#3

Add the below lines of code in your controller

require'barby'
'barby/outputter/png_outputter'

Step#4

The following method will generate the barcode images and store in the “/public/Barcodes” path. Place this method inside the controller.

The “symbology” is the format in which the barcode will be generated. Default is “Code128B”, If you want to generate in different format you can set the “symbology” according to it.

def generate_barcodes(data) # check to see if we don't already have this barcode image uri = CGI.escape(symbology) + '_' + CGI.escape(data) + '.jpg' fname = RAILS_ROOT + '/public/Barcodes/' + uri #fname = '/var/www/html/arc_cloud/arcdevelopment/' + uri
 
# if the barcode image doesn't already exist then generate and save it
if ! File.exists?(fname)
 
str = 'Barby::'+symbology+'.new("'+data+'")'
 
begin
barcode = eval str
rescue Exception => exc
barcode = Barby::Code128B.new(data) # fall back to Code128 type B
end
 
File.open(fname, 'w') do |f|
f.write barcode.to_jpg
end
 
end
uri
end

Step#5

Following lines of code will call to generate your dynamic barcode
generate_barcodes(@item_id)

Step#6

To show the Barcode images call the following lines of code

<img src="/Barcodes/<%= @job_info.job_number %>.jpg" >

Ruby Rails Development Sphere & Associated Myths

Ruby on Rails development is fast changing the norms of web development across the globe.

Companies around the world are fast catching up with this magical web development framework for exploring and executing its true potentials; thereby serving their clients with really cost-effective, quick and dynamic Ruby on Rails Applications.

Ruby developers and Rails developers are becoming the most sought after skilled professionals, for Software companies to hunt for.

Ruby on Rails, being an Open Source tool, coupled with fast development life cycle, requires much less resources in terms of Programmers and man-hours; which results in the service provider and client being the ultimate beneficiaries.

Silicon Valley based leading Software firm, Andolasoft Inc. is a formidable force to reckon with as far as Ruby on Rails development is concerned.

Never miss an update from us. Join 10,000+ marketers and leaders.

With a vast pool of Programmers as well as Domain Leads, this fairly young Enterprise has carved out many Social Networking Sites, Social Media Marketing web apps.

Andolasoft services include but not limited to RoR Development, RoR Application Migration, Social Media Integration, System Administration, Redesigning of Existing Apps, Performance Improvement Related Tasks and Rescue Support.

Irrespective of all its popularity, RoR also has few myths related to it.

Applications can be built hundreds of thousands times faster than other technologies: The fact is Rails doesn’t write the code automatically.

It just lets the developers work easy by managing certain functionalities; thereby allowing them to focus on other crucial modules.

It also manages the laborious part of lifting of user interactive modules. Having said that, such myths reflects a wrong opinion upon customers, whose expectations sometimes become too high for the service providers.

Even Non-programmers can build web applications: This is by far the silliest perception about Rails development. Although the simplicity of this framework and clean syntax of ruby language assist in quick development, but still experience is required as far as writing code is concerned.

Rails developers do need to write new and unique code, apart from using the Rails conventions on top a comprehensive web development framework.