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

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.

Watch out for the latest Security Patch to deal authentication bypass for RoR

ror41Ruby on Rails framework developers have been continuously releasing security updates since the last two weeks. Its recent updates like 3.0.20 and 2.3.16 versions were to address the remote code execution vulnerability. This was the third security patch released this month. The developers have mentioned that the updates released are extremely important, and have advised the users of 3.0.x and 2.3.x rails framework to update as soon as possible.

The security update will fix the vulnerability in the Rails JSON code. That allowed the hackers to bypass authentication system and inject random SQL into the application database. It occasionally performed denial-of-service attack too. The rails developers have also pointed out that currently it supports only the 2.3.x, 3.1.x, and 3.2.x versions and might release an update for 3.0.x version.

Most recent vulnerability was identified as CVE-2013-0333, which was patched in the framework on 8th of Jan. The Ruby on Rails developers using Rails 2.3 and 3.0 are also advisable to install the new fixes even if they have installed the fix for CVE-2013-0156 earlier.

 

Brief Summery

  • Affected Versions are: 2.3.x, 3.0.x
  • Unaffected Versions are: 3.1.x, 3.2.x, and applications using yajl gem
  • Fixed Versions are: 3.0.20, 2.3.16

How to do tagging in Rails with gem ‘Acts_as_taggable_on’

ror41Tagging is a way to give a keyword and search by that particular keyword. In Rails “acts-as-taggable-on” is one of the popular gem for tagging. With ‘acts_as_taggable_on’, you can tag a single model on several contexts, such as skills, interests, and awards

Below is an example to describe how to implement it in a Rails application:

    Step#1

  • Add the gem to your Gemfile:
  • gem ‘acts-as-taggable-on'
  • Then run the bundle
  • bundle install

    Step#2

  • Run the generator command
  • rails g acts_as_taggable_on:migration
  • Run the migration file
  • rake db:migrate

    This migration will create two tables in the database: tags and taggings.
    Step#3
    Now you have to modify your model where you want to implement tagging.
    For example, we like to implement the tagging on Post model.

  • Add the following codes to the “Post” model to have acts_as_taggable and also add a “tag_list” field to the attr_accessible list.
  • attr_accessible :content, :name, :tag_list
    acts_as_taggable

    Step#4

  • Add a new field to your post form.
  • <%= f.label :tag_list, "Tags (separated by commas)" %>
    <%= f.text_field :tag_list %>

    Step#5

  • Add the following codes, if you want to show the tags for the tagged posts in the listing page:
  • <% @posts.each do |post| %>
    <h2><%= link_to post.name, post %></h2>
    <%= simple_format post.content %>
    <p>
    Tags: <%= raw post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %>
    </p>
    <% end %>

    Step#6

  • Modify your route file to get the tags
  • get 'tags/:tag', to: 'posts#index', as: :tag

    Step#7

  • Modify your controller:
  • class PostsController < ApplicationController
    def index
    if params[:tag]
    @posts = Post.tagged_with(params[:tag])
    else
    @posts = Post.all
    end
    end
    end
    

Voila! You have done it.

Validating RSS Feeds in Rails

Rails1FeedValidator is a gem which validates the RSS feeds through SOAP protocol of the W3C Feed Validation service. It helps to find out errors in RSS or ATOM feeds. In Rails app we can do the feed validation by installing the gem.

    Step#1

  • Install the FeedValidator as a gem:
  • gem feedvalidator

    Run the bundler to install the gem
    Step#2

  • Include the require ‘feed_validator’ into your controller
  • Step#3

  • Generate a migration file and edit the file to add the following fields
  • class CreateFeeds < ActiveRecord::Migration
    def self.up
    create_table :feeds do |t|
    t.string :title
    t.timestamps
    end
    end
    def self.down
    drop_table :feeds
    end
    end
    

    Step#4

  • Validate your feed URL in your controller
  • def create
    site_url = params[:feed][:title].sub(/(\/)+$/,'')
    begin
    v = W3C::FeedValidator.new
    if v.validate_url(site_url) && v.valid?
    @feed = Feed.new(:title => site_url)
    @feed.save
    end
    rescue
    # Do nothing
    end
    redirect_to request.referrer
    end