preload
Feb 05

Today, I have started testing Beta release of Rails 3.0.By Default Rails 3.0 start with webrick.To start with mongrel do following steps.

1)Install mongrel gem


sudo gem install mongrel

2) After installing mongrel gem go to config/boot.rb file

and add following line

  require "mongrel"

3) Start server as rails server

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:
Nov 26

In many web site we have seen that on selecting country,
state or city list is updated.
In this article i am showing how to update children select list on changing parent list.
To do this i am using jquery and ruby on rails.although it will works for almost all languages
For this article, I am updating city list on changing states.
So one state has many cities,and city belongs to state.

<html>
 <head>
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript">
   $("#states").live("change",function(){
     state_id = $("#states").val();
     $.ajax({
       type: "GET",
       url: "/city_list.xxx",
        /*or any server side url which generate citylist for rails
                 "/states/city_list"or<%= city_list_states_path%> */
      data: "state_id="+state_id,
       /*here we are passing state_id to server based on that on
             he can find out  all the city related to that states */
     success: function(html){
      /*html content response of city_list.xxx */
     $("#city_list").html(html);
      }
    });
   });
 </script>
</head>
<body>
 <div id="state_list">
   <select id="states">
     <option>a</option>
     <option>b</option>
   </select>
 </div>
 <div id="city_list">
   <select id="cities">
   <option value="1">aa</option>
   <option value="2">aaa</option>
 </select>
 </div>
 </body>
</html>


and city_list.xxx gives following html
on processing state id which we have pass as state_id

<select id="cities">
  <option value="3">bb</option>
  <option value="4">bbb</option>
</select>
Tagged with:
Nov 13

In many website we have seen that on checked or unchecked one box

all the check box are checked or unchecked.

Now in this article i am showing how to checked unchecked all the check box

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
     	$("#check_all").live("click",function(event)
	    {
		    if($("#check_all").hasClass('not_checked'))
		    {
			    $("#check_all").removeClass('not_checked');
			    $(".check-box").attr('checked',true);
		    }
		    else
		    {
			    $("#check_all").addClass('not_checked');
			    $(".check-box").attr('checked',false);
		    }
	  });
    </script>
  </head>
  <body>
    <table>
      <tr>
        <td>Select/Deselect</td>
        <td><input type="checkbox" class="check-box not_checked" id="check_all"></td>
      </tr>
      <tr>
        <td>First</td>
        <td><input type="checkbox" class="check-box" id="check_box2"></td>
      </tr>
      <tr>
        <td>Second</td>
        <td><input type="checkbox" class="check-box" id="check_box3"></td>
       </tr>
       <tr>
         <td>Third</td>
         <td><input type="checkbox" class="check-box" id="check_box4"></td>
      </tr>
    </table>
  </body>
</html>

In this setting checked attribute true/false alternatively by clicking on
select/deselect for alternate removing and adding class
not_checked depending upon that we are setting true and false

Tagged with:
Sep 17

Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class.


In my project,I have to track certain action (create and update) of user on particular model basically i am maintaining some kind of log, or audit trails.In my application eventlog model has attribute user and body.


class EventlogObserver < ActiveRecord::Observer
  observe :model1, :model2

  def after_create(record)
    @eventlog = Eventlog.new
    @eventlog.body = record.class.to_S+“Created at”+Time.now
    @eventlog.save
    @event
  end
  def after_update(record)
    @eventlog = Eventlog.new
    @eventlog.body = record.class.to_S+“Updated at”+Time.now
    @eventlog.save
  end
end

This eventlog_observer.rb is stored in app/model

Now Configuration add following line in /config/environment.rb config.active_record.observers = :eventlog_observer

In rails there are various callbacks on which you trigger some common behaviour

  • after_create
  • after_update
  • after_save
  • after_destroy
  • before_create
  • before_update
  • before_save
  • before_destroy

and many more you can also refer from http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

For further reference http://api.rubyonrails.org/classes/ActiveRecord/Observer.html

 
Tagged with:
Aug 31

We can include another html page using jquery load method

example is as shown below

<html xmlns="http://www.w3.org/1999/xhtml"> 
   <head> 
      <title>Loading an Html page</title> 
      <script src="jquery.js" type="text/javascript"></script> 
      $(document).ready(function() { 
        $('#loadpage').load('load.html or any server side page'); 
    });
</head> 
<body> 
   <div id="loadpage" ></div> 
</body> 
</html>
Tagged with:
Aug 19

In normal rails application contain one database,but if we want rails application having more than one database that is multiple data base.   we can achieve this using multiple way.one of the way is i am showing here.it’s just 3 steps.


Lets take an e.g Project has many milestone and milestone has many task

In normal scenario model looks like following way

 
class Project < ActiveRecord::Base 
  has_many :milestones 
end
 
class Milestone < ActiveRecord::Base 
  has_many :tasks 
 belongs_to :project 
end
 
class Task < ActiveRecord::Base 
  belongs_to :milestone 
end

Now  we want that milestone is stored on milestone_db database and task on task_db database
Rails multiple database

Now to achieve this we have to do the following steps

1) Edit Database.yml


 milestone_dev: 
 reconnect: false
 encoding: utf8 
 username: <user_name> 
 adapter: mysql 
 database: milestone_db 
 pool: 5 
 password: <password> 

task_dev: 
 reconnect: false 
 encoding: utf8 
 username: <user_name> 
 adapter: mysql 
 database: task_db 
 pool: 5 
 password: <password> 

Now create milestone_db and task_db database.


2) Edit milestone.rb and task.rb


class Milestone < ActiveRecord::Base 
  #add this line to use milestone_db 
  self.establish_connection :milestone_dev 
  has_many :tasks 
  belongs_to :project 
end 
 

class Task < ActiveRecord::Base 
  #add this line to use task_db 
  set_table_name "tasks" 
  belongs_to :milestone 
end

3) After editing model edit migration file


class CreateMilestones < ActiveRecord::Migration 
  def self.connection 
    Milestone.connection 
  end 
 .....
end

Now rails application is ready with multiple database.

Tagged with:
Aug 10

Here it is how we can do that magic,

if( isset($_GET['function']) ) {
switch( $_GET['function'] ) {
case ‘dosomething’:
dosomething();
break;
case ‘dosomethingelse’:
dosomethingelse();
break;
}
}

And then link to script.php?function=dosomething

url rewriting

Benifit :

When a search engine visits the dynamic url like product.php?id=test it does not give much importance to that URL as search engine sees “?” sign treat it as a url which keeps on changing. so we’re converting the dynamic URL like the product.php?id=test to static url format like product-test.html. We’ll rewrite the url in such a way that in browser’s address bar it will display as a product-test.html but it actually calls the file product.php?id=test. So that why these kind of URL also named as SEO friendly URL.

How to do using Apache ?

To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error.

The Procedure

For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]

The following example will rewrite the test.php to test.html i.e when a URL like http://railstech.com/test.htm is called in address bar it calls the file test.php. As you can see the regular expression in first part of the RewriteRule command and $1 represents the first regular expression of the part of the RewriteRule and [nc] means not case sensitive.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ products.php?id=$1

The following example will rewrite the product.php?id=test to porduct-test.html i.e when a URL like http://railstech/product-test.html calls product.php?id=test automatically.

Tagged with: