Active Job , Sidekiq And Redis In Rails 4

activejob_sidekiq
activejob_sidekiq

Active Job is a framework for declaring jobs and making them run on a variety of queueing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.

Sidekiq simple, efficient background processing for Ruby. Sidekiq uses threads to handle many jobs at the same time in the same process. It does not require Rails but will integrate tightly with Rails 3/4 to make background processing dead simple.

Redis :-

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperlog logs.

Other features include :-  

  1. Transactions
  2. Pub/Sub
  3. Lua scripting
  4. Keys with a limited time-to-live
  5. LRU eviction of keys
  6. Automatic failover

Installation :-

  1. wget http://download.redis.io/redis-stable.tar.gz
  2. tar xvzf redis-stable.tar.gz
  3. cd redis-stable
  4. make
  5. redis-server

Integrating Sidekiq with Rails :-

Gem file

  1. activejob_backport
  2. sidekiq-cron
  3. sinatra
  4. slim

application.rb

Add this line to configure the sidekiq

include Sidekiq::Worker

config/initializer/active_job_configuration.rb

ActiveJob::Base.queue_adapter = :sidekiq

config/sidekiq.yml

:concurrency: 25

:pidfile: ./tmp/pids/sidekiq.pid

:logfile: ./log/sidekiq.log

:queues:

– default

– [high_priority, 2]

 

config/routes.rb

require ‘sidekiq/web’

mount Sidekiq::Web, at: ‘/sidekiq’ , constraints: ->(request) {SideKiqConstraint.authenticate?(request)}

Note:- SideKiqConstraint.authenticate?(request) is the method which authenticate and ensure only user with role excelfore is able to see sidekiq GUI.

class SideKiqConstraint

def self.authenticate?(request)

if (!request.session[‘user_id’].blank? and !(user= User.find_by(id:request.session[‘user_id’])).blank?)

return user if user.excelfore?

end

end

end

Command to start sidekiq

In Development

sidekiq -C config/sidekiq.yml

In Production

bundle exec sidekiq -d -L sidekiq.log -q mailer,5 -q default -e production

The above steps ensure sidekiq to work background jobs. Now lets see the steps to setup sidekiq for the cron jobs.

config/schedule.yml

my_first_job:

 cron: “*/1 * * * *”

 class: “SidekiqClock1”

Add the below code in config/initializer/active_job_configuration.rb to load the jobs from the schedule.yml file

schedule_file=”config/schedule.yml”

if File.exists?(schedule_file)

Sidekiq::Cron::Job.load_from_hash YAML.load_file(schedule_file)

end

Sample cron job method:-

class SidekiqClock1

include Sidekiq::Worker

def perform

ActionMailer::Base.mail(to: ‘gurudath@gurudath.com’ ,subject: ‘Process Completed’,body:’Gurudath Test’,from:”xbass@gurudath.com”).deliver

end

end

 

AES Cipher Encryption & Decryption Algorithms Using Ruby On Rails

AES Encryption & Decryption Algorithms using Ruby On Rails
AES Encryption & Decryption Algorithms using Ruby On Rails

Encryption and decryption methods using ruby on rails for secure data transfer , using AES Cipher logic.

There are several ways to create a Cipher instance. Generally, a Cipher algorithm is categorized by its name, the key length in bits and the cipher mode to be used. The most generic way to create a Cipher is the following.

cipher = OpenSSL::Cipher.new(‘<name>-<key length>-<mode>’)

There are various cipher modes CBC, CFB, OFB and CTR.
I using 128 bit key size. There are 128, 256 bit key sizes also.

For each algorithm supported, there is a class defined under the Cipher class that goes by the name of the cipher, e.g. to obtain an instance of AES, you could also use like:-

1) cipher = OpenSSL::Cipher.new(‘AES-128-CBC’)
2) cipher = OpenSSL::Cipher.new(‘AES-128-ECB’)

I have used Base64​ schemes for Encoding & Decoding the data

KEY:- Is the secret text which is used as key by cipher
ALGORITHM:- Is the cipher mode with the key bit size(like 128,256)

Base64​ schemes for Encoding & Decoding the data i have made use for security.

U can save the below code in the .rb file and use it.

require ‘openssl’
require ‘base64’

class AesEncryptDecrypt

KEY = “***************************************”
ALGORITHM = ‘AES-128-ECB’

def self.encryption(msg)
begin
cipher = OpenSSL::Cipher.new(ALGORITHM)
cipher.encrypt()
cipher.key = KEY
crypt = cipher.update(msg) + cipher.final()
crypt_string = (Base64.encode64(crypt))
return crypt_string
rescue Exception => exc
puts (“Message for the encryption log file for message #{msg} = #{exc.message}”)
end
end
def self.decryption(msg)
begin
cipher = OpenSSL::Cipher.new(ALGORITHM)
cipher.decrypt()
cipher.key = KEY
tempkey = Base64.decode64(msg)
crypt = cipher.update(tempkey)
crypt << cipher.final()
return crypt
rescue Exception => exc
puts (“Message for the decryption log file for message #{msg} = #{exc.message}”)
end
end

end

Example:-

I have used KEY and ALGORITHM as mentioned below for example:-

KEY = “EncryptDecryptGurudathBN”
ALGORITHM = ‘AES-128-ECB’

Encryption:-
irb(main):007:0> AesEncryptDecrypt.encryption(‘gurudath’)
=> “rUPKObydUJd9cY9agm3Glw==\n”

Decryption:-
irb(main):008:0> AesEncryptDecrypt.decryption(‘rUPKObydUJd9cY9agm3Glw==’)
=> “gurudath”

We will update with more information with upcoming days.

Regards
Gurudath BN

Google Recaptcha With Ruby On Rails Integration.

Google Recaptcha With Ruby On Rails Integration
Google Recaptcha With Ruby On Rails Integration

Google Recaptcha With Ruby On Rails Integration.

Google Recaptcha protects the websites you love from spam and abuse.


Below the steps to be followed to develop a sample ROR application with Google Recaptcha:-


Step 1. Create a Ruby on Rails application:-

a)Open a terminal, navigate to a directory where you have rights to create application and type:
rails new recap

b)After you create the application, switch to its folder:
cd recap

c)Type and run bundle install:
bundle install


Step 2. Create models, views, and controllers:-

a)For this application we will generate a scaffold, which is a starter template provided by Rails that bundles a model, a controller, and the relevant views for our application:
rails generate scaffold User name:string

b)After generating the scaffold we need to create the actual User table in our development database so we need to run migration:
rake db:migrate

c)To start the application run below command and open browser and type http://localhost:3000/users
rails s

d)Configure application with nginx or apache with application url eg:gurudathcap.com

(For configuration settings please see the reference url at the botton of the post.)


Step 3. Integrating Google Recaptcha With Ruby On Rails:-

  a)Please login to Google Recaptcha website to register ur domain to get access.(https://www.google.com/recaptcha/intro/index.html)

  b)Please login and register your site , with the details as shown in below form.

register ur domain to get access

register ur domain to get access

  c)After registeration google provide the

  • Script tag place this snippet before the closing </head> tag on your HTML template.
  • div place this snippet at the end of the <form> where you want the reCAPTCHA widget to appear
registeration google provide

registeration google provide

  d)Once the above steps are done, we can see the recaptcha in the site.

  f)For the server side validation we can use the secret key and the response which is going to be sent as parameters to the form submit action in the controller.

  g)To check whether Google has verified that user, send a GET request with these parameters:URL: https://www.google.com/recaptcha/api/siteverify


Step 4. Application Code change for server side validation.

helper to request google and get the status

helper to request google and get the status

   a)We will write a helper to request google and get the status:-

        def verify_google_recptcha(secret_key,response)
status = `curl “https://www.google.com/recaptcha/api/siteverify? secret=#{secret_key}&response=#{response}”` 
hash = JSON.parse(status)
hash[“success”] == true ? true : false
end

    b)Now we can use this helper the controller to verify status:-

       status = verify_google_recptcha(SECRET_KEY,params[‘g-recaptcha-response’])

where status going to be true or false. If false we will render the form page again for resubmit else we will accept the form.


OUTPUT SLIDES:-

STEP1

STEP1


SETP 2

SETP 2


STEP 3

STEP 3


STEP 4

STEP 4


NOTE :-

To configure application with nginx or apache reference url:-

http://nathanhoad.net/how-to-ruby-on-rails-ubuntu-apache-with-passenger

http://www.rabblemedia.net/installing-rvm-ruby-on-rails-and-passenger-on-ubuntu.html

https://www.digitalocean.com/community/tutorials/how-to-install-rails-and-nginx-with-passenger-on-ubuntu


Now the google recaptcha protects your websites from spam and abuse. We will update with more information with upcoming days.

Regards

Gurudath BN

Use of UUID(Universally unique identifier) in Ruby On Rails Application.

UUID In Ruby On Rails Application :-

I would like to suggest to make use of UUID (Universally Unique Identifier) in the ruby on rails application development. If you want all your objects have unique ID, even across systems and different databases the you can go for UUID (Universally Unique Identifier) .

ror_uuid

Ruby On Rails  + UUID

A UUID like the one below is 36 characters long, including dashes .Displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). For example: 123e4567-e89b-12d3-a456-426655440000

Here are the steps to be followed to develop a sample ror application with uuid. I made use of PostgreSQL database to develop application with UUID.

Rails First Application With UUID Using Postgres As Database :- 

1)Create the application
rails new rails4uuid

2)Create the rvmrc file.
vim .rvmrc
source ~/.rvm/scripts/rvm
type rvm | head -n 1
rvm use ruby-2.1.2
rvm gemset use myreference_rails2.1.2

3)Bundle Install
please add gem ‘pg’ in gem file and bundle install

4)Please verify the database.yml file with proper user name and password.
vim config/database.yml
5)Please install dependies for the UUID
sudo apt-get install libossp-uuid-dev
sudo apt-get install postgresql-contrib-9.1
sudo /etc/init.d/postgresql restart

6)Login to postgres and run following changes.
sudo -u postgres psql postgres
CREATE DATABASE rails4_uuid;
ALTER USER user WITH SUPERUSER;
create extension “adminpack”;
create extension “uuid-ossp”;

NOTE:- user is the user name diven in database.yml file in step 4

7) rails g migration enable_uuid_ossp_extension

class EnableUuidOsspExtension < ActiveRecord::Migration
def change
enable_extension ‘uuid-ossp’
end
end
rake db:migrate Or EnableUuidOsspExtension.new.change

8) To verfiy we can log in to PostgreSQL db and perform this query
SELECT uuid_in(md5(now()::text)::cstring);
9) Create a model for the application , example posts.
rails g model post title:string

10)In migration file please specify id as UUID
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts, id: :uuid do |t|
t.string :title

t.timestamps
end
end
end

11) Give rake db:migrate

12)Login to console and create a post to verify uuid is generated.
Post.create(title:’gurudath’)
=> #<Post id: “966d1a3a-7d2e-474f-ab84-4a607326c4ac”, title: “gurudath”, created_at: “2014-10-04 05:15:50”, updated_at: “2014-10-04 05:15:50”>

Not the ruby on rails application with uuid is ready. If any data needed to migrate from one environment to anothre we can directly shared the data from one environment to another without any ID conflicts.

We will update with more information with upcoming days.

Regards

Gurudath BN