Jul 22

Lately there have been too many people wanting to know how to execute Javascript in Celerity.
Let me show you how it done.
First a quick note on JRuby installation.
Here are few useful links to install JRuby under

    1. Linux(ubuntu) should work for other linux packages as well.
    2. Windows.

Just to confirm,kindly type jruby -v on terminal or cmd depending on OS you are using and you should get the version of jruby you are running.

Mine output was

jruby -v
jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2010-03-11 6586) (OpenJDK Client VM 1.6.0_0) [i386-java]

Now go ahead and just install celerity gem.
More about celerity installation can be found here also just quickly check whether the sample code work for you.If it work then your ready go and for those it don’t well you just need to tweak a bit.

Ok enough of installation,now we start with running javascript under celerity.
Here is my test HTML File “index.html.”

 <html>
  <head>
    <script type=”text/javascript”>
      function populateDropDown() {
        var select = document.getElementById(‘colors’);
        var options = [‘Ruby’, ‘JRuby’, ‘IronRuby’, ‘Rails’];
        var index;
        for(index = 0; index < options.length; index++) {
          var option = document.createElement(‘option’);
          option.appendChild(document.createTextNode(options[index]));
          option.value = options[index];
          select.appendChild(option);
        }
     }
  </script>
  <script type=”text/javascript”>
    function add_new_language() {
      var wrapper = document.getElementById(‘wrapper’);
      var input = document.createElement(‘input’);
      var br = document.createElement(‘br’);
      input.setAttribute(‘type’,’text’);
      wrapper.appendChild(br);
      wrapper.appendChild(input);
    }
  </script>
 </head>
 <body onload=”populateDropDown()”>
  <h1>Select Your Favourite Language</h1>
  <form>
    <select id=”colors”>
    </select>   <a href=”#” onclick=”add_new_language()” >More Language</a>
    <br/>
    <span id=”wrapper”>
    </span>
  </form>
 </body>
</html>

Here my sample code in JRuby.

 require "rubygems"
 require "celerity"

 browser = Celerity::Browser.new(:browser => :firefox)
 browser.goto("file:///home/guest/Desktop/index.html")

Now basically one can run the javascript just by a simply calling the method fire_event on the html tag that has the associated event that you want to fire.
 e.g the anchor tag above has a onclick event associated with it.

 
browser.document.get_html_elements_by_tag_name('a').first.fire_event('click')
 

Now modified the html content i.e (after javascript execution) can be obtain using “browser.xml”.

Here mine output.

 
  puts browser.xml

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<html>
 <head>
  <script type=”text/javascript”>
   //<![CDATA[
     function populateDropDown() {
       var select =        document.getElementById(‘colors’);
       var options = [‘Ruby’, ‘JRuby’, ‘IronRuby’, ‘Rails’];
       var index;
       for(index = 0; index < options.length; index++) {
         var option = document.createElement(‘option’);
         option.appendChild(document.createTextNode(options[index]));
         option.value = options[index];
         select.appendChild(option);
       }
     }
  //]]>
  </script>

  <script type=”text/javascript”>
   //<![CDATA[
     function add_new_language() {
       var wrapper =document.getElementById(‘wrapper’);
       var input = document.createElement(‘input’);
       var br = document.createElement(‘br’);
       input.setAttribute(‘type’,’text’);
       wrapper.appendChild(br);
       wrapper.appendChild(input);
     }
   //]]>
  </script>
 </head>

 <body onload=”populateDropDown()”>
  <h1>Select Your Favourite Language</h1>

    <form>
      <select id=”colors”>
        <option value=”Ruby” selected=”selected”>Ruby</option>
        <option value=”JRuby”>JRuby</option>
        <option value=”IronRuby”>IronRuby</option>
        <option value=”Rails”>Rails</option>
      </select>

      <a href=”#” onclick=”add_new_language()” >More Language</a>
      <br/>
      <span id=”wrapper”>
        <br/>
        <input type=”text”/> <!— generated by javascipt –>
      </span>
    </form>
 </body>
</html>

Here how I made the whole flow generic.

#List of Tag that has event Handler
TAGS   =  ['iframe' ,'img', 'frame', 'frameset', 'ilayer', 'input', 'layer', 'select', 'a', 'area', 'form', 'object', 'script', 'embed', 'applet', 'option', 'button']

# defining a Constant with list of event_hander
EVENT_HANDLERS  = ['onclick','onmouseover','onselect','onsubmit']

# List of events that can trigger a function
EVENTS    = ['click','mouseover','select','submit']

 TAGS.each do |tag|
    browser.document.get_html_elements_by_tag_name(tag).each do |element|
       EVENT_HANDLERS.each_with_index do |event_handle,i| 
          element.fire_event(EVENTS[i]) if element.hasAttribute(event_handle) 
       end 
    end
 end

Note : – One didn’t need to fire_event for onload as the onload event is fired as soon as the page is load using browser.goto .

Other options available are : –

    Johnson in Ruby
    Watir in Ruby
    Selenium in JRuby

Thank You

Tagged with:
Feb 10

Static site using rails

As we know rails is mainly used for dynamic website.we can also display static web pages or we can deploy full static website using rails. The following code can help us to display static pages.

Step 1:-Create Rails project


rails static_site

Step 2:-Generate StaticPage Controller


ruby script/generate controller static_pages page

Step 3:- Create StaticPage Class in Model

 class StaticPage
   Formats = {
       "html" => "text/html",
       "png" => "image/png",
       "jpg" => "image/jpg"
     }
 end

Step 4:- Add following line in routes.rb


map.page "page/:filename.:format", :controller => 'static_pages', :action => 'page'

Here we are passing filename as parameter which is static file name.

This will generate url as http://sitename/page/static_filename.html

Step 5:- Now add following line into static_pages controller


def page
 send_file
 "#{Rails.root}/app/views/static_pages/#{params[:filename]}.#{params[:format]}",:disposition =>'inline',:type => StaticPage::Formats[params[:format]]
 end

Step 6:- All the static pages place in RAILS_ROOT/app/views/static_pages/ folder

Step 7 :- Start server and Type url as shown below.


ruby script/server

Url may be

http://railstech.com/page/contactus.html or
http://railstech.com/page/faq.html
Or In Development Mode
http://localhost:3000/page/faq.htm
http://localhost:3000/page/contactus.html

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>

I have updated source code http://github.com/amardaxini/Ajax-Demo

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:
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:
preload preload preload