Integration of Google reCaptcha with Rails application

ReCaptcha is a powerful captcha service to be use with a form to stop spam. This blog demonstrates the use of reCaptcha in rails application. Here I have used the ruby version 1.9.3 and Rails version 3.2.8.

Environment

  • Ruby version – 1.9.3
  • Rails – 3.2.8

Step#1

Create an account with Recaptcha “http://www.google.com/recaptcha” and register your site name with your google account to retrieve the public and private key that will be used later on the application

Step#2 

Installation of Recaptcha

  • Gem
  • Open your Gemfile and add this code
gem 'recaptcha', :require => 'recaptcha/rails'
  • Plugin
  • rails plugin install git://github.com/ambethia/recaptcha.git

Step#3

Create a file named recaptcha.rb in RAILS_ROOT/config/initializer and fill it with these codes

ENV['RECAPTCHA_PUBLIC_KEY'] = 'youractualpublickey' ENV['RECAPTCHA_PRIVATE_KEY'] = 'youractualprivatekey'

Step#4

Usages Open your views file and add this code

<%= recaptcha_tags %>

Step#5

Validation In controller, you can check the captcha validation by the following

if @model.save && verify_recaptcha(:model => @developer, :message => "Oh! It's error with reCAPTCHA!") #captcha is valid else #captcha is invalid end

Creation of a New Rails App using Refinery CMS

Refinery CMSRefineryCMS is a powerful Ruby on Rails CMS. Here I have created a blog-cms application using Ruby 1.9.3 and Rails 3.2.8

Step#1
Install the RefineryCms gem version 2.0.8 from the terminal

gem install refinerycms

Create a new rails application with ‘MySQL’ database using the command line in the terminal

refinerycms myblog -d mysql

It will automatically run the following commands

bundle install</div>
<div>rake  db:create db:migrate</div>
<div>rake  db:seed

Step#2
Go to the app on the terminal

cd myblog

Step#3
Start the rails server in the terminal

rails s

Step#4
Open a browser window and navigate to “http://localhost:3000/”
The signup window pops up to prompt you to create your first Refinery user. This is the Superuser of Refinery, which has the ability to create other users.
That’s it!
The application runs now.
Other useful information to customize Refinery CMS application

  • You can change the “Site Name” to a name of your choice currently displaying in the home page

In “config/initializers/refinery/core.rb”
config.site_name = “Company Name”

  • You can customize the design or functionality

To override files from refinerycms to the existing app we have to use the below commands

rake refinery:override view=file_name

Here are some examples:

rake refinery:override view=pages/home</div>
<div>rake refinery:override view=refinery/pages/home</div>
<div>rake refinery:override view=**/*menu</div>
<div>rake refinery:override view=_menu_branch</div>
<div>rake refinery:override javascript=admin</div>
<div>rake refinery:override javascript=refinery/site_bar</div>
<div>rake refinery:override stylesheet=home</div>
<div>rake refinery:override stylesheet=refinery/site_bar</div>
<div>rake refinery:override controller=pages</div>
<div>rake refinery:override model=page</div>
<div>rake refinery:override model=refinery/page</div>
<div>rake refinery:override presenter=refinery/page_presenter

Implementation of other refinerycms engines are also available

For example:

Add the gem to your applications Gemfile

  • gem ‘refinerycms-page-images’, ‘~> 2.0.0′
  • Execute bundle install
  • rails generate refinery:engine name

Example:

  • rails generate refinery:page_images
  • rake db:migrate

Facebook Integration in Rails3 using ‘omniauth’ gem

feature11. Create a Facebook Application by using your ‘Facebook Developer account’
2. Get the ‘App ID’ and ‘App Secret’ of your created application

Add following gems to your Gemfile

  • gem ‘omniauth’
  • gem ‘omniauth-facebook’

Run ‘bundle install’

Create a middleware file named ‘omniauth.rb’ in ‘config/initializers’ path

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
{:scope ≥ 'email, read_stream, read_friendlists, friends_likes, friends_status, offline_access, publish_stream'}
end

This will hold the facebook_app_key and facebook_secret_key with permissions

Set your custom callback url in routes

match '/auth/:provider/callback', :to ≥ 'sessions#create' match '/auth/failure', :to ≥ 'sessions#failure'

Write the following codes in the Sessions Controller

def create
auth_hash = request.env['omniauth.auth'] # Got The precise information from facebook
if  !auth_hash.nil?
@user = User.find_or_create_from_auth_hash(auth_hash)
self.current_user = @user
redirect_to '/'
end
end
def failure
flash[:notice] = "Sorry, but you didn't allow access to our app!"
redirect_to '/'
end

Write the following code in your view page. You can use a custom image for the Facebook like ‘facebook.png’.

<%=link_to image_tag('/images/facebook.png'),
"/auth/facebook" %>

Implementing Sortable Columns in Rails through Helper

Use of a sortable column in a listing view. For an example there is a list of “Programs”

Step# 1

  • Here our controller is named as “Programs” and the model is named as “Program”
  • Add the following helper methods to the controller
class ProgramsController < ApplicationController
helper_method :sort_column, :sort_direction
protected
def sort_column
Program.column_names.include?(params[:sort]) ? params[:sort] : "position"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def your_custom_action
end
end

Step# 2

  • In Helper class of “Program” add the following codes
module ProgramsHelper
def sortable(column, title = nil)
title ||= column.titleize
active = column == sort_column
ascending = active && sort_direction == 'asc'
direction_html = ascending ? ' ▲ ' : ' ▼ ' if active
css_class = active ? "current #{sort_direction}" : nil
direction = ascending ? "desc" : "asc"
link_to(title, { :sort => column, :direction => direction }, :remote => true, :class => css_class) << raw(direction_html)
end
end

 

Step# 3

  • In the view (index.html.slim) file add the helper method “sortable” in the columns you want to sort
  • Please note: Here slim is used for the view pages
#main
table style="text-align:left;"
tr
th align="left" = sortable "name"
th align="left" = sortable "created_at", "Added"
th align="left" = sortable "subscription_level_id", "Subscription"
th align="left" = sortable "rating_average", "Rating"
- programs.each do |program|
= content_tag_for :tr, program, 'row_for' do
td= link_to program.name, program_url(program)
td.attribute= program.created_at.strftime("%B %Y")
td.attribute= program.subscription_level.name.capitalize if program.subscription_level
td.attribute= ratings_for program
.pagination_container style="padding-bottom:20px;"
= will_paginate programs

How to use Nested Attributes in Rails 3 Forms

For example, say we want to add multiple addresses(attributes) having many fields inside a create/edit employee form

Step# 1

  •         Create a model named Employee
  •         Create another model named Address
  •         Add the following relationship in Employee model
class Employee < ActiveRecord::Base
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:city].blank? }
end
  •    Nested attribute form rejects if the city field of the address is blank

Step# 2

  •        In Employees controller add the following in the “new” action
def new
@employee = Employee.new
@employee.addresses << Address.new
end

Step# 3

  •         In the view file add the following inside the form attribute
<%= form_for @employee, :html => { :multipart => true, :id => 'new-employee' } do |f|
<%= f.label :name, 'Name' %>
<%= f.text_field :name %>
 
<% end %>

Successful Mobile App And Ruby On Rails Projects

Andolasoft is remarkable and energetic to start the ball rolling in numerous products in mobile application development and Ruby on rails development arena.

Among them Christmas Tree Puzzle game app, job management app for iOS. Also Social email reminder app, Social media Job portal app in RoR are getting used by lots of people everyday.

Some of our new projects are product based and we are focusing on the advance technology of mobile and web application development like IPhone, Android, RoR, PHP/CakePHP. Very soon we are going to launch/release some new apps those are under development and will available in the market very shortly. Check out our recent portfolio and domains and technologies. We’re also growing by increasing our team size. We’ve a team of dedicated and skilled developers and designers who’re helping Andolasoft to do the job perfectly in right time. Quality assurance is one of our aim for all projects with a quick turnaround period. Continuously we keep hunting and hiring right folks with mobile as well as web technologies. Please check out current job openings.