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

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

How to customize OCSNG and GLPI

Using work through customized scripts or applications is smart approach by System Administrators. For a busy system administrator to collect all the h/w and s/w information from the network is really tedious. For this work there fantastic open source tool named “OCS Inventory NG” which would collect all the h/w and s/w information from the network. But the web interface of OCS (where all the information about networked machines are visualized) is not much user friendly, rather confusing.

However, there is another open source application called GLPI, having a cool interface with capability to import & synchronize records from OCS.

For importing records from OCS to GLPI you have to use a plug-in in GLPI named OCS import and this plug-in manages the whole OCS synchronization process. To use OCS Import effectively, one need to make sure that the OCS mode is operational.

Here are the simple steps for the synchronization process:

Activate OCSNG mode in GLPI:

  • Click on Setup; then select General-Restrictions [Tab]-Activate OCSNG mode – Set to YES and then click on Post.

100-11-460x232

  • Next, OCSNG mode, again go to the Setup tab and Click on OCSNG Mode

101-1-460x180

Now you will able to see one connection named localhost as pointed in the above image. Click on that localhost. Now you’ll see a simple form to enter DB credentials for the OCSNG application.

  • Once providing all valid DB information about OCSNG application, click on Post and it pops-up message ‘Connection to OCS database successfully’.

102-1-460x232

  • There is another tab named Import Option in the same window. Here you can set up which information needs to be imported from OCSNG like monitor, printer, devices, registry and software. Choose those information and Click on Post to update the info.

103-1-460x310

  • Beside the Import Options tab, there is a General Information tab where you can define which elements you want to import from OCS like OS, Serial Number, Model etc. You can choose those elements and click on Post to update it in GLPI.

104-1-460x310After completing the above steps you will able to see the data on the GLPI.

105-1-460x127Now we’ll see the steps on how to add custom fields into the Inventory List in GLPI.

How to add a custom field in GLPI:

To add custom fields to GLPI we need another plug-in named Custom Fields. It can be found in the Plug-in folder of GLPI archive.

  • After installing this plug-in you can see a Custom Fields option in the drop down menu of Plug-ins Tab as indicated below.

[Note: To check what other plug-ins are installed you can check the drop down menu of Plug-in tab.]

106-1-460x310

  • By clicking on Custom Fields you can find a list of many device types like in the above image. Just click on the device name(s) on which you want the custom fields, to make it Enabled. You can also disable them in the same way when needed.

[Note: The device types that are enabled in the Manage Custom Fields section will be viewed in the Inventory List to which user can add various custom fields later]

  • Now to add fields click on the ‘Manage Custom Dropdowns‘ below the device list.

Suppose you want to add a custom filed named ‘Assigned to’ in the device Computers. Then first you need to enable the device Computers in Manage Custom Fields. After that go to Manage custom Dropdowns and add a label named ‘Assigned to’. You also need to add a System Name e.g.assigned_to1.You can check the Use Entities or Tree Structure boxes if you want to use them. Please find these steps indicated in the below image.

[Note: Later you can add more drop downs in the same way and click on the Update button to update the list.]

107-1-460x288

  • Now you’ve to add these custom fields to you inventory. For that you need to go to the Inventory tab in the GLPI main menu and Click on Computers and then click on the + sign.

[Note: In the Inventory apart from Computers, other devices will show up if they’re enabled in the Manage Custom Fields section]

108-1-460x116

  • You will get another pop-up window showing the column headers and here you can see that your custom field has been added to the list.

109-1-460x310

  • Select the custom field name from the Dropdown menu and the Click on Add.
  • Click on the arrow image like in the above image to arrange the order of the various fields on the list.

[Note: Repeat the same steps when you add more custom fields to your Inventory.]

Do you have anything to add? Just leave a comment below.

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