Oct 24

Just quick post how to use acts_as_flying_saucer with rails 3.1 and Heroku.

I was testing acts_as_flying_saucer with rails 3.1.It is working fine so far.
but when i have added external style sheet it was hanging on dev mode.
and later on i figure out it is external style sheet causing an issue.
So i precomplied css and then try to generate pdf it is working.
Now it is time to test on heroku.
I am using cedar stack and ruby 1.9.2 after precomplied step pdf.
By default pdf is generated on system /tmp directory.
In heroku we can set application tmp path to generate pdf i.e ./tmp

I was testing acts_as_flying_saucer with rails 3.1.It is working fine so far,but when i have added external style sheet it was hanging on dev mode rails is hanging

After litte bit of googling  i figure out it is external style sheet causing an issue because of asset pipeline and thread issue for serving static file mainly in dev mode.

So i simply pre complied css or we can manually (actual full path) or manipulate asset path .after this PDF is generated properly.

Now it is time to test on Heroku.I am using cedar stack and ruby 1.9.2 after pre complied step.

Now point tmp directory to application tmp directory.

ActsAsFlyingSaucer::Config.options = {:tmp_path => "./tmp"}
Tagged with:
Oct 24
It’s about more than 6 months i haven’t written any post.
Why ?
Recently join new organiztion,
Can’t get time because we are working almost more than 10 to 12 hr day with messy code.
So we are spending more time to refactoring and optimising code,and scaling application also.
Now i started making my time to writing.
In my current organization we are generating various Pdf report.
We are using prawn but now we are switching to  acts_as_flying_saucer.
So there are couple of challenges i have faced
1) XHTML code is not proper
2) Special character in html
Solution
Cleanup Html code
I am using tidy library clean up html code.
By passing :clean=>true it will cleanup html befor generating pdf.
3) Send PDF as email
Solution
Generate PDF on server and do some processing like attached to mail.
:send_attachment => true it will generate pdf and return path of pdf file then do some processing.
So couple of new feature is added to acts_as_flying_saucer
1) Clean up  html by passing :clean=>true
2) Generate pdf on server (locally) by passing :send_attachment=>true
3) acts_as_flying_saucer is also working with rails 3.1 (precomplie asset) and heroku.

It’s about more than 6 months i haven’t written any post Why ?

because recently join new organization, and can’t get much more time , we are working almost more than 10 to 12 hr day with messy code.So we are spending more time to  refactoring and optimizing code,and scaling application.😥

In my current organization we are generating various PDF report.We are using prawn but now we are switching to acts_as_flying_saucer.

So there are couple of challenges i have faced

  1. XHTML code is not proper
  2. Special character in html

Solution: Cleanup Html code

Continue reading »

Tagged with:
Aug 22
Hi all,
We needed to use net/http of ruby for sending parameters between two modules.
We decided to use the get and the post request of http as follows:
url = URI.parse(“http://SERVER:PORT”)
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(“/method_name?parameter=a”)
response = http.request(request)
In the above get request the parameter “a” is taken to the “http://SERVER:PORT/method_name” and data related to it is queried.
url = URI.parse(“http://SERVER:PORT”)
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(“/method_name”)
request.set_form_data({“parameter1” => “a”, “parameter2” => “b”, “parameter3” => “c” })
response = http.request(request)
In the above post request three parameters are taken parameter1, parameter2 and parameter3  with the value a,b and c respectively to the “http://SERVER:PORT/method_name” for posting.
When you need to pass a array in the parameters for posting. you can specify it as:
request.set_form_data({“parameter1” => “a”, “parameter2” => [“1”, “2”, “3”], “parameter3” => “c” })
Here the parameter2 takes a array with value 1,2,3.
Now the fun begins,
If you are using ruby 1.9.2 this works fine parameter2 is passed as a array.(parameter2 = [“1”, “2”, “3”])
However if you are uing ruby 1.8.7 this doesnot work, parameter2 appends all the values of the array to form  a string and passes it.(parameter2 = “123”)
You have to override the set_form_data method for it to work and pass parameter as a array.
It can be done as below. You an place this in a file and let the file be included while loading the app.
module Net
module HTTPHeader
def set_form_data(request, params, sep = ‘&’)
request.body = params.map {|k,v|
if v.instance_of?(Array)
v.map {|e| “#{urlencode(k.to_s)}=#{urlencode(e.to_s)}”}.join(sep)
else
“#{urlencode(k.to_s)}=#{urlencode(v.to_s)}”
end
}.join(sep)
request.content_type = ‘application/x-www-form-urlencoded’
end
alias form_data= set_form_data
def urlencode(str)
str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf(‘%%%02x’, s[0]) }
end
end
end
And then use set_form data as follows:
request.set_form_data(request, {“parameter1” => “a”, “parameter2” => [“1”, “2”, “3”], “parameter3” => “c” })
Thus we can pass a array in parameters while use net/http of ruby 1.8.7.
References : http://blog.assimov.net/post/653645115/post-put-arrays-with-ruby-net-http-set-form-data

In one of our projects, we needed to use net/http of ruby for sending parameters between two modules which resided on two different servers.

We decided to use the get and the post request of http as follows:

url = URI.parse("http://SERVER:PORT")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new("/method_name?parameter=a")

response = http.request(request) 

In the above get request the parameter “a” is send to the “http://SERVER:PORT/method_name” and data related to it is queried.

url = URI.parse("http://SERVER:PORT")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new("/method_name")

request.set_form_data({"parameter1" => "a", "parameter2" => "b", "parameter3" => "c" })

response = http.request(request) 

In the above post request three parameters are taken parameter1, parameter2 and parameter3 with the value a,b and c respectively to the “http://SERVER:PORT/method_name” for posting.

When you need to pass a array in the parameters for posting. you can specify it as:

request.set_form_data({"parameter1" => "a", "parameter2" => ["1", "2", "3"], "parameter3" => "c" }) 

Here the parameter2 takes a array with value 1,2,3.

Now the fun begins,

Continue reading »

Tagged with:
Mar 20

Today I will demonstrate how did I manage to get Selenium (browser => “firefox”) running under headless state (click here to know more on this) .

Now we need Xvfb to accomplish this dirty task.

For Ubuntu the package is fairly straight forward just type in the command .

sudo aptitude install Xvfb

Under Fedora the same can be achieve using command .

sudo yum install xorg-x11-server-Xvfb

For more on Xvfb package  check your distribution provider .

Continue reading »

Tagged with:
Aug 18

Amazon Simple Queue Service (Amazon SQS) is a distributed queue messaging service. The idea of SQS is to remove the direct associations between producer and consumer and act as mediator between them.

e.g

Consider that you have a large  application like websites monitoring which involve many stages like

  • Downloading a website
  • Processing the downloaded website
  • Generating report of the above processing

So instead of clubbing the above three one can just split them on their specific need(based on the work they do)  with each doing their respective task and on completion notify the other about it completion.

The traditional approach (called as Client-Server architecture) is to send the notification using a simple HTTPREST , SOAP etc request. But it too has some disadvantage as it require extra care and  precision  to handle all possible response e.g Time-out,Server down etc.

One can save this time and effort my using SQS.

e.g Instead of sending the direct request to Server one can use to SQS to interact with Server/Client an can eventually cut down some of drawback of traditional architecture.

Setting up Amazon SQS in Ruby: There are various library available for using Amazon SQS in Ruby (e.g right_aws, sqs)

Pre-requitise:

  • aws-access-key-id
  • aws-secret-access-key
  • ruby-library(right_aws or sqs gem)
    both of which is provide by the Amazon (or you can ask for incase) during the process of account-registration

In your irb console

require "rubygems"

require "right_aws"

aws_access_key_id  = "Your access key id"

aws_secret_access_key = "Your secret access Key"

sqs = RightAws::SqsGen2.new(aws_access_key_id,aws_secret_access_key)

This basically initialize the sqs object for you to work on.

One can create a new queue just by a single method.

 queue(queue_name, create=true, visibility=nil) 

carefully look at parameter supplied.


queue_name => name of  queue.

create => true (create a queue if it does not exist (optional)).

visibility => set visibility (which make the message reappear after a specified time if not  delete from queue).

One key point about visibility is that one can’t set visibility more than 7200 sec for a  queue or a message .But you can set so from RightScale (Cloud Computing management Platform).

e.g

my_queue = queue('queue_1')

just look at few other methods.

1. send_message or push :- Send message to the specified queue.

 
 my_queue.send_message "This is my first message"

2. receive or pop :- Receive message from the specified queue.

 
 message_received = my_queue.receive

puts message_received.body
=> "This is my first message"

2.1 receive_messages : – There is also a method called receive_messages to receive an  array of messages but it never returned me more than one message so if it work for you  it fine then syntax is like this

 
 receive_messages(number_of_message=1,visibility=nil)

 my_queue.receive_messages(2,60) => return and array of messages

3. delete : –  Delete a  message or a queue

  
 my_queue.delete => "delete the my_queue for SQS"
 
 message_received.delete => "delete the message from the intended queue"

4. size :- Specify the no of message in the queue

 
 my_queue.size => 4 ("4" message in my_queue)

5. name :- Specify name of the queue

  
 my_queue.name => "queue_1" (Name of the queue)

Note : – There is delay lag in all request and response sent/received to/from  SQS server don’t assume to work it instantaneous approximately of around 45 sec -1 minute(can be more)

e.g

If you send  a message to the queue don’t assume it to appear instantaneously in the queue

Pricing Model => $0.10 per 100,000 requests.

Message Size => 64 KB

For more information on Pricing and message size click  here.

Thank you

Tagged with:
Aug 05

In previous article we have seen that how to start nailgun server,and use of nailgun in shortly.

Now in this article how to use nailgun using ruby application which directly/indirectly use java library or java application. You can start with nailgun manually as shown previous article and configure ng as per need.Or you can install nailgun plugin from github.
Continue reading »

Tagged with:
May 12

In previous article we have seen that how pdf is generated  using act_as_flying_saucer plugin.

Following code snippets is used for generating pdf with bookmark .


<html>
  <head>

    <bookmarks>
      <bookmark <strong>name="Section 1" href="#section_1"</strong>>
        <bookmark name="Section 1.1" href="#section_11"></bookmark>
        <bookmark name="Section 1.2" href="#section_12"></bookmark>
      </bookmark>
      <bookmark name="Section 2" href="#section_2"></bookmark>
      <bookmark name="Section 2" href="#section_3"></bookmark>
    </bookmarks>

  </head>

  <body>

    <div style="page-break-before: always;">
      <a <strong>name="section_1"</strong>>Section 1</a>
    </div>
    <div style="page-break-before: always;">
      <a name="section_11">Section 1.1</a>
    </div>
    <div style="page-break-before: always;">
      <a name="section_12">Section 1.1.2</a>
    </div>
    <div style="page-break-before: always;">
       <a name="section_2">Section 2</a>
    </div>
    <div style="page-break-before: always;">
       <a name="section_3">Section 3</a>
    </div>

  </body>

</html>

<bookmark name=”section 1″  href=”#section_1″> tag is used to generate bookmark.
which contains name attribute for displaying name of bookmark.
href attribute is used for navigation purpose.

<bookmark> tag can be nested so it can be used for generating nested bookmark
<bookmark> tag is wrapper with <bookmarks> tag. This tag placed in html header.

Now in html body whichever anchor tag has name attribute with value as same as bookmark
href value on that position user is navigated.

Mainly two tag is used which is displayed below.

<bookmarks>
<bookmark name=”Name Of Bookmark”  href=”#bookmark1“>< /bookmark>
</bookmarks>
<a name=”bookmark1″>Text</a>

Tagged with:
May 12

Pdf with password protected in rails

In previous article we have seen that how pdf is generated  using act_as_flying_saucer plugin. Now  act_flying_saucer  has added support for  password protected pdf.

To generate PDF with password protection just pass :password=>”xxx” to render_pdf method.

render_pdf :file=>'pdf/generate_pdf.html.erb',:password=>"xxx"</pre>

You can install act_as_flying_saucer plugin

 script/plugin install git@github.com:amardaxini/acts_as_flying_saucer.git

For  further details you can visit article or visit http://github.com/amardaxini/act_as_flying_saucer

Tagged with:
May 01

In this article i have just taken a short example describing vertical table,and its implementation using rails.

When table has no fixed column it has dynamic fields .data is not stored on separate column but data stores in vertical fashion.

For implementing vertical table table has mainly 2 columns key and value pair.key is like database column name and value contains actual data.

Lets take an e.g

Consider website in which it contains various products and its comparison ,searching and many more features.product can be mobile,car etc.Product has many items.item may be nokia 6600,nokia n72 etc.

Here our aim is not compare aur search items.Here our main aim is how vertical table concept is applied.Suppose we have to build only single product comparison site then each product has it’s own attributes that can be easily build with adding column for each product.

we are developing generic site(multiple product).so there is no fixed attributes,each product has it’s own attributes either we create different model for each product or we can proceed with vertical table concept.

Vertical table

  • Product has many Product Attributes.
  • Product has many Items.
  • Item has many Item Attributes.
  • Item Attribute belongs to Product Attribute.

Product Attribute mainly requires 3 fields

name : which is used for key in vertical table(i.e column name)

option_type : which is used for viewing different form of data when item is created .(textbox,dropdown,checkbox,multi option)

option : which contain option if its drop down or multi option(serialize)

Item has only name field which is optional.

Item attribute mainly required 3 fields

name : key name or column name

value : actual value

item_id : foreign key of item

It is used where table has dynamic fields,and it only concern with data.

Here data grows vertically.

It has mainly key ,value pair.

Source code of above example is hosted on github http://github.com/amardaxini/vertical_table_demo

For More info about vertical table you can visit http://weblogs.foxite.com/andykramek/archive/2009/05/03/8369.aspx

Tagged with:
Jan 19

Rails Pdf Plugin act_as_flying_saucer

There are various ways to generate pdf documents in any language.In Rails we can use prawn library ,HtmlDoc,PrinceXml and many other library,using their api we can generate pdf document.Basically the primary goal is converting HTML web pages to PDF Document,without much changing existing CSS and HTML.

Using the Flying Saucer Project we can achieve this.we can convert HTML + CSS to PDF documents without much changing HTML and CSS. It also support CSS 2 and many properties of CSS 3 for printing Header,Footer,Page Number,Paginated Tables and many more.This Project is built on Java so Java is required on system.

Lets Start How to generate PDF Using Flying Saucer.

 script/plugin install git://github.com/amardaxini/acts_as_flying_saucer.git

This Plugin forked From

http://github.com/dagi3d/acts_as_flying_saucer

Which has older version of flying saucer project.

Next Step after installing plugin add flying_saucer.rb file at config/initializers.


ActsAsFlyingSaucer::Config.options = {
:java_bin => "/usr/bin/java",          # java binary
:classpath_separator => ':',  # classpath separator. unixes system use ':' and windows ';'
:tmp_path => "/tmp",          # path where temporary files will be stored
}

After Setting Java path , classpath separator and tmp path now do following step.

class PdfController < ActionController::Base
  acts_as_flying_saucer

  def generate_pdf
    render_pdf :template => 'pdf/pdf_template'
  end
end
  render_pdf :file=>'pdf/generate_pdf.html.erb'
  render_pdf :template=>'pdf/generate_pdf.pdf.erb',
             :send_file => { :filename => 'pdfdoc.pdf' }

Add act_as_flying_saucer to controller then render_pdf.There are various ways to render pdf using “template” or “file“,:send_file option use to send pdf file to client side.if we are using any external css file then this css shoulda have media option as ‘print’.


<%= stylesheet_link_tag 'pdf' ,:media=>'print' %>

If pdf containing images which generate on the fly.so instad of using

<%= image_tag %>

use

 <img src=" " >

Before rendering PDF validate HTML,like whether all tags are close properly or not.otherwise it gives an parse error.

Now You are ready to Generate PDF. Hurray!!!!!!!!!

How to generate Header, Footer,Page Number and Automation Of HTML Validation will be discussed in next post.

Tagged with:
preload preload preload