How to create a form page in Refinery CMS app

Refinerycms

Refinery is a powerful CMS based on Rails framework. It gives a fully generated site with admin control features. However, we can extend it to create our own customized forms like Job Inquiry, Contact Us etc… by following this tutorial. Here is the environment we have used on this tutorial.Ruby 1.9.3, Rails 3.2.8 & RefineryCMS 2.0.8

Step#1

Cd to refinerycms application

Execute the following command to get all the options & usages to create a form engine in refinery CMS

rails g refinery:form

Step#2

Execute the following command to create a form. Let’s create a Job Inquiry form

rails generate refinery:form job_inquiry name:string message:text job_type:radio brochure:checkbox qualification:select

Step#3

Run the following commands

bundle install
 
rails generate refinery:job_inquiries
 
rake db:migrate<code></code>
 
<code>rake db:seed<code>

ss

This will create a “job inquiry” engine in the “vendor/extensions” folder

Step#4
Add the “job type” and “qualification” data in the “/vendor/extensions/job_inquiries/app/models/refinery/job_inquiries/job_inquiry.rb” model. You can also add other fields as per your requirement.

module Refinery
module JobInquiries
class JobInquiry < Refinery::Core::BaseModel       self.table_name = 'refinery_job_inquiries'       attr_accessible :name, :message, :job_type, :brochure, :qualification, :position       acts_as_indexed :fields => [:name, :message]
# Add some validation here if you want to validate the user's input
# We have validated the first string field for you.
validates :name, :presence => true
JOB_TYPES = ["Freelance", "Fulltime", “Contract”]
QUALIFICATIONS = ["MCA", "MTECH", "BTECH"]
end
end
end

Step#5

Restart the rails server to get the effect

That’s it! We will have a fully functional Job Inquiry form attached in our refinery application. This will also add the following functionalities automatically.

  • Mail send feature to Admin after submitting the job inquiry form
  • Auto email respond functionality to the user after submitting the form
  • Adds Job Inquiry menu in the Admin side to manage auto email respond message, mail id change to get job inquiry
  • Adds an Inbox in the Job Inquiry Menu for Admin to manage all the forms submitted through the Job Inquiry form

SEE ALSO: Creation of a new Rails App using Refinery CMS

If you have any other tips or rules that you follow, let us know in the comments below.

How to install Devise in Rails 3.x

ror41-150x150Devise is a flexible authentication solution for Rails based on Warden. Devise handles authentication across the entire stack. It has the following features:

  • Rack based
  • MVC based on Rails engines
  • Allows you to have multiple roles (or models/scopes) signed in at the same time
  • Modularity concept: use just what you really need

It is composed of 12 modules:

  • Database Authenticatable
  • Token Authenticatable
  • Omniauthable
  • Confirmable
  • Recoverable
  • Registerable
  • Rememberable
  • Trackable
  • Timeoutable
  • Validatable
  • Lockable

Steps to install the Devise

Step#1

Add the following gem in your Gemfile

gem 'devise'

Then run

bundle install

Step#2

To invoke the Devise in your application, run the devise generator

 rails g devise:install

The generator will install an initialize, which describes all devise’s configuration options.

Step#3

Create a model “User” using devise to handle authentication.

rails g devise User

This generator creates a few interesting things like a file, a migration and a devise_for in route.

Step#4

Run the migration

rake db:migrate

Step#5

Devise provides some helper methods to recognize a user after sign in and default route paths for “sign in”, “sign up” and “sign out”

We can modify our ‘app/views/layout/application.html.erb’ file to allow us to “sign out”, “sign in” and “sign up” by writing the following block

<div>
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. Not you?
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or
<%= link_to "Sign in", new_user_session_path %>
<% end %>
</div>

Configuring views

Since Devise is an engine, all its views are packaged inside the devise gem.

Get all the view files for devise by running the following generate command

rails generate devise:views

You can also configure the message language, mailer from address and other things by editing the devise config files as located in following locations

devise.en.yml – config/locales
 
devise.rb – config/initializers

Now you are done to use the app with authentication!

How to use Amazon S3 Bucket with Paperclip to store images in Rails3

Amazon_S3_Online_Service-resized200-150x150

“S3 Bucket” is Amazon Simple Storage Service – a “highly durable and available store” and can be used to reliably store graphical and other applications contents such as media files, static assets and user uploads. It allows you to off-load your entire storage infrastructure. This feature facilitates better scalability, reliability, and speed than just storing files on the file-system.

It is an online storage web service offered by Amazon Web Services and provides storage through web services interfaces (REST, SOAP etc.)

Here is an example on how to use Amazon S3 with paperclip in Ruby on Rails applications.

Step#1

  • In rails 3.x

Install aws-s3 gem by adding in Gemfile

gem 'aws-s3'

And run

Run “bundle install”

Step#2

To get AWS S3 bucket ‘Access Key ID’ and ‘Secret Access Key’ go to the “http://aws.amazon.com/s3”

Create s3.yml file under config directory and enter your Amazon S3 credentials

development:
bucket: bucket-dev-name
access_key_id: xxxxx
secret_access_key: xxxxx
test:
bucket: bucket-test-name
access_key_id: xxxxx
secret_access_key: xxxxx
production:
bucket: bucket-prod-name
access_key_id: xxxxx
secret_access_key: xxxxx

Step#3

Open your model file that would hold the attachment and modify it as follows

###Paperclip
has_attached_file :photo,:styles =>{ :thumb => "100x100", :medium => "200x200", :large => "600x400" },:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",:path => ":attachment/:id/:style.:extension",:bucket => 'yourbucket'

Step#4

In view, to display the image

How to use ActiveRecord Callbacks in Rails

Rails3Callbacks are a great technique for achieving simplicity and flexibility. A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you’ll commonly see callbacks that run before, after or even around other bits of code. Callback functions are minimizing the length of codes in controllers.

Implementing Callbacks

There are four types of callbacks accepted by the callback macros:

  • Method references (symbol)
  • Callback objects
  • Inline methods (using a proc)
  • Inline eval methods (using a string) – deprecated

Here is the list of some useful callback functions while saving AcriveRecord objects

  • before_save
  • after_save

before_save:

This method is called before an ActiveRecord object is saved.

class Post < ActiveRecord::Base before_save :update_slug protected def update_slug self[:slug] = [year, season_slug, season_type_slug].compact.join '/' end end

after_save:
Once the active record object saved some method will be fired in that scenario we have to use the after_save callback.

class Post < ActiveRecord::Base after_save :handle_status_changed protected def handle_status_changed Setting.create(:post_id=>self.id , :status => true) end end

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" >