Usage of PDFKit with Rails 3.2.8 and Ruby 1.9.3

PDFkit is a powerful library which generates PDF from HTML + CSS. It uses “wkhtmltopdf” on the back-end which renders HTML using Webkit. Here is a simple example which describes the installation of “wkhtmltopdf” and usages of pdfkit. I have used rails 3.2.8 and ruby 1.9.3 as my environment.

Step-1:

Install the “wkhtmltopdf” library

Download the “wkhtmltopdf” library from the link
http://code.google.com/p/wkhtmltopdf/

Windows

  • Download the exe file and install it.
  • Remember the installation path

Linux

  • Download the binary for your architecture at the http://code.google.com/p/wkhtmltopdf/downloads/list
  • Extract the file to a directory that is in your PATH, such as /opt or /usr/local/bin and run from there.

For Debian/Ubuntu use the following command:

apt-get install wkhtmltopdf

Step-2: Installing PDFKit

In your bundle file write

gem 'pdfkit'

Then install

bundle install

Step-3: Configuration of PDFKit

Create a new file “pdfkit.rb” in “config/initializers/” path and write the following

If you are in windows then you need to give the path to the exe file generated after installation. If you are in linux and the path is set as the default path then you don’t need to give the path.

PDFKit.configure do |config|
config.wkhtmltopdf = 'C:Program Fileswkhtmltopdfwkhtmltopdf .exe'
config.default_options = {
:page_size => 'Legal',
:print_media_type => true
}
# config.root_url = "http://localhost" # Use only if your external hostname is unavailable on the server.
end

Step-4: Middleware Setup

Write the following in the “config/application.rb

require 'pdfkit'
 
config.middleware.use PDFKit::Middleware
config.threadsafe!

Step-5: Usages

Creating PDF in a file path

Now to generate the pdf file by writing down the following codes on one of your controller actions

kit = PDFKit.new"<h1>Hello</h1><p>This is PDF!!!</p>"
file_path = your_file_path
pdf = kit.to_file file_path

Now you can find the PDF file being generated on the file path.

Displaying PDF on browser

<p id="pdf_link"><%= link_to "Download Invoice (PDF)", order_path(@order, :format => "pdf") %></p>

Your PDF will be displayed on the browser.

You can also add “.pdf” to any of our application’s URLs to get a PDF version of that page.

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

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 Implement Security Patches On Ruby On Rails Applications

The security of any software product or application is something that every software solution provider is wary of. It is no different in the case of a Ruby on Rails application.

Even after an application is successfully developed and deployed, there can be possibilities for many unseemly activities.

US-based high-end software solution provider Andolasoft.Inc sheds some light on some of the basic precautions that are worked upon before deploying an application.

The Company’s Ruby on Rails developers pay special attention to security issues in every undertaken venture.
Authentication and authorization of the User model are two different things.

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

Actions like create/update/delete always need to be protected. Even popular plug-ins like Restful authentication and Clearance only authenticate whereas providing no helper methods for authorization.

Mass assignment of sensitive attributes from re-assignment should be protected.

This can be taken care of by disabling mass assignment with the help of attr_accessible or attr_protected in the respective models. Attributes like account_id’s and user_id’ should be protected.

Also disabling updates on protected attributes can be by using attr_readonly so that the Ids don’t get updated once set.

Content types of files being uploaded can be faked, so uploaded files should be placed in protected directories or servers.

Also, file extensions should be checked and the web-server should be disabled so as not to execute such files in the uploaded directories.

Sessions are prone to vulnerabilities like hijacks, replaying cookies, and session fixation. Extra caution must be taken regarding storing data in sessions.

Active record Objects should never be stored in sessions which might change that Object’s behavior while migration and future code change.

The best practice is to only store the ids of the records. Also, sensitive data like User access privileges and money based information should not be stored in sessions.

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.