Wednesday, December 28, 2011

Rehash method of Ruby Hash Class

Hello Guys,
        There is an interesting method provided by hash called 'rehash'. It rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hash. If Hash.rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator.

   a = [ "p", "q" ]
   b = [ "r", "s" ]
   h = { a => 100, b => 200 }
   h[a] returns 100
   a[0] = "z"
   h[a] returns nil. we have to rebuild the hash after updating key using rehash method of hash.
   h.rehash returns {["z", "q"] => 100, ["r", "s"] => 200}
   h[a] returns 100

Monday, December 26, 2011

Convert HTML to HAML and Javascript to Coffee script

Hello Guys,
        If you are using Rails 3 than as per it's standard format we have to use Haml and Coffee script instead of normal html and javascript.

There are some online tool available for conversation from one format to other.

HAML to HTML

HTML to HAML
http://html2haml.heroku.com/

JS to Coffee Script or visa versa
http://js2coffee.org/

Sunday, December 11, 2011

Generate .yml fixtures from database tables

Hello Guys,
          Wondering about how to create fixtures from tables? Here is the simple task which generate .yml from database tables.

namespace :db do
  desc 'Generate .yml test fixtures from an existing database'
  task :generate_fixtures => :environment do
    sql = "Select * From %s"
    skip_tables = ["schema_migrations"]
    ActiveRecord::Base.establish_connection
    tables = ActiveRecord::Base.connection.tables - skip_tables
    tables.each do |table_name|
      count = "0000"
      File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'w') do |file|
        table_content = ActiveRecord::Base.connection.select_all(sql % table_name)
        file.write
table_content.inject({}) { |hash, record|
          hash["#{table_name}_#{
count.succ!}"] = record
          hash
        }.to_yaml
      end
    end
  end
end

When you invoke above task using rake db:generate_fixtures --trace. It generates all the fixtures of your database tables under db/fixtures folder of your rails application.

create_fixtures(fixtures_directory, table_names, class_names = {}) is the inbuilt method available to create fixtures for testing.

Friday, December 9, 2011

Serialize and deserialize object in ruby

Hello Rubies,
          Want to serialize and deserialize the ruby object? than use the inbuilt method of ruby.

Assume have the field says 'content' as text field of xyz table and it stores the value in serialize hash format but when we do the sql query to retrieve content than it gives output as normal string format.

content has value:
---
ruby:
  :value: 50
  :label: "ruby %"
java:
  :value: 30
  :label: "java %"
c:
  :value: 50
  :label: "c %"

Lets trying to get the content value by raw sql statement like "select content from xyz" than it return text (string) object.

now we load the object in serialize form by
puts YAML::load(content)
visa versa we have string and set to serialize object than need to use  
puts YAML::dump(content)
Same way around if you have deserialize content and want the serialize form then use content.to_yaml. It gives result in serialized form.

Thursday, December 8, 2011

undefined method 'manage_gems’ for Gem:Module (NoMethodError)

Then ruby gems will create a new file called 'gem1.8' and it will conflict with your older 'gem' file. You can find both these files in /usr/bin

So when ever you say gem list (or something with gem) it gives the error '/usr/bin/gem:11: undefined method 'manage_gems' for Gem:Module (NoMethodError)'

As a workaround,  I have followed the below steps and it worked for me. My solution was to create a symbolic between 'gem' file and 'gem1.8' file.

Steps:

first copy your 'gem' file (as a backup)

cp /usr/bin/gem /<my other path>/

Now delete the 'gem' file

sudo rm -f /usr/bin/gem

Now create the symbolic link

ln -s /usr/bin/gem1.8 /usr/bin/gem

Thats it, now run gem list and it should work.

Thursday, December 1, 2011

Use build with has_one and belongs_to association

Suppose we have association between two models as has_one and belongs_to. We want to create the child record with parent record using build method than need to follow below easy steps.

eg. Class User < ActiveRecord::Base
        has_one :profile
      end
      
     Class Profile < ActiveRecord::Base
        belongs_to :user
     end
   
When we are creating the user than required to create associated profile by using below methods:

@user.build_profile or
@user.profile.build

It create associated profile record along with user.

Wednesday, November 30, 2011

Handle JSON or XML request and response

Hello Guys,
        Some time we required to pass the request in particular format and get response back in same format. 

1. Consider the request and response format as JSON

Request:
curl -H "Accept: application/json" -i -X GET http://DOMAIN:PORT/controller/action/parameters
eg. curl -H "Accept: application/json" -i -X GET http://127.0.0.1:3000/posts/show/1

Response:
In the show method of posts controller we have to check whether request type is JSON than return response back to JSON format.

def show
  if request.format == Mime::JSON 
     post = Post.find_by_id(params[:id])
     render :json => post.to_json, :status => 200
  end
end

Now we get response as the requested post in .json. we will parse the json by JSON::load(response)

2. Consider the request and response format as XML

Request:
curl -H "Accept: application/xml" -i -X GET http://DOMAIN:PORT/controller/action/parameters
eg. curl -H "Accept: application/xml" -i -X GET http://127.0.0.1:3000/posts/show/1

Response:
In the show method of posts controller we have to check whether request type is XML than return response back to XML format

def show
  if request.format == Mime::XML
     post = Post.find_by_id(params[:id])
     render :xml => post, :status => 200
  end
end

Now we get response as the requested post in .xml. we will parse the xml using Hpricot or any other parser.

Hope this post will help you to deal with json and xml format.

How to invoke method in ruby?

Guys,
         Do you aware about the method invocation in ruby using different ways?
 want to know? There are 3 different ways to invoke a method in ruby.

a) Using period operator
    eg. we have class called 'Car' and we need to access the method called 'car_detail'
    car = Car.new
    car.car_detail

b) Using .send method
    car = Car.new
    car.send(:car_detail)

c) Using .call method
    car = Car.new
    car.method(:car_detail).call

So, these are the three ways to invoke method in ruby.  Hope this post will help you.

Monday, November 21, 2011

Anemone - web crawler

Hello Guys,
         Anemone is a free, multi-threaded ruby web spider framework. It is useful for collecting information about websites. It's crawl sites with initial level. With Anemone you can write task to generate statistics on a site just by giving it the URL. Anemone supports the nokogiri for HTML and XML parsing.

Lets see the simple example.. so you can get the idea how it works
 
First of all we have to install the anemone gem by
gem install anemone

It will install anemone along with dependencies robots, nokogiri.

require 'anemone'

desc "crawl the website data at initial level"
task :crawl_website => :environment do
  Anemone.crawl("http://priyankapathak.wordpress.com/") do |anemone|
    anemone.on_every_page do |page|
      puts page.url
      # store the visited pages in file system or db
    end
  end
end

As an above example, that will take a domain as 'http://priyankapathak.wordpress.com', and start tracing every page. If you want to store traced pages than just write the code to store at db or file 
system. Invoke above task by rake crawl_website --trace

There are many other inbuilt methods available with anemone. like
  • after_crawl - run a block on the PageHash (a data-structure of all the crawled pages) after the crawl is finished
  • focus_crawl - use a block to select which links to follow on each page
  • on_every_page - run a block on each page as they are encountered
  • on_pages_like - given one or more RegEx patterns, run a block on every page with a matching URL
  • skip_links_like - given one or more RegEx patterns, skip the any link that matches patten
If you find this ruby web spider interesting and want more information then simply follow below links.

Sunday, November 20, 2011

Allow ajax upload

Hello Rubies,
          Do you know how to upload the file through ajax? Last time i was juggling for ajax upload. There is some patch which i have used to allow ajax upload with rails 2.3.x. Follow below instruction to implement it.

Lets, consider the scenario. Where we have content page which has file(.pdf) upload and content area portion.

new.rhtml

<%= form_remote_tag(:url => {:controller => 'contents', :action => 'create'}, :html => { :multipart => true })%>     
    <p id='error_msgs'> </p>
    <p> Content: <%= text_area 'content', 'body' %> </p>
    <p> PDF: <%= file_column_field 'content', 'pdf_path' %> </p>
     <p> <%= submit_tag('Create') %> </p>
</form>
This form allow us to create content along with pdf upload through ajax.

Now want to add some basic validation for file?

class Content < ActiveRecord::Base
   validates_file_format_of :pdf_path , :in => ["pdf"]
   file_column(:pdf_path, :root_path => "#{RAILS_ROOT}/PDFs", :fix_file_extensions => nil)
end

Above we added the validation for file which must be in .pdf format only and store in our application's PDFs directory. You have to assume that your using file column here otherwise you can use normal file_field as well.

In controller of contents we have method called 'create' which need to enhance.

class ContentsController < ApplicationController
   
  def create
     @content = Content.new(params[:content])   
     responds_to_parent do
        if @content.save     
           render :update do |page|
              flash[:notice] = "content created successfully"
              page.redirect_to contents_url
           end
        else
           render :update do |page|
             page.replace_html "error_msgs", "#{error_messages_for :content}"
           end
        end
     end 
  end

end

Here you observed something ?.. we have used the responds_to_parent instead of respond_to block.

Now you guys are wondering about method 'responds_to_parent'. correct?
rails_responds_to_parent  is the method of gem 'rails_responds_to_parent t'. Now install that via
gem install rails_responds_to_parent

For the ajax support we have to add the patch called 'remote_upload' in lib folder of rails application

lib/remote_upload.rb

module ActionView
  module Helpers
    module PrototypeHelper
      alias_method :form_remote_tag_old, :form_remote_tag
      def form_remote_tag(options = {})
         if options[:html] && options[:html][:multipart]     
           uid = "a#{Time.now.to_f.hash}"                               
          <<-STR   
            <iframe name="#{uid}" id="#{uid}" src="about:blank" style="position:absolute;left:-100px;width:0px;height:0px;border:0px"></iframe>
            <form method="post" action="#{url_for options[:url].update({:iframe_remote => true})}" enctype="multipart/form-data" target="#{uid}" #{%(onsubmit="#{options[:loading]}") if options[:loading]}>
           STR
         else
            form_remote_tag_old(options)
         end
      end                            
    end
  end
end

This code will override the prototype's form_remote_tag method and allow iframe support.

Now, we have to include below lines in config/environment.rb to allow access of remote_upload and responds_to_parent

require 'remote_upload.rb'
require 'rails_responds_to_parent'

See our work completed. Now we will freely upload the file through ajax. Find interesting?
If you have any suggestion or query then post the comment.

to get the gem source of rails_responds_to_parent

Wednesday, November 16, 2011

How to set and skip callback with rails

Rubies,
     Want to set and skip the callback dynamically? Here is the some method which we can use to get required output.

For rails 3

Active Support provides the methods call 'skip_callback'  and 'set_callback'.
Lets we see the usage of those methods.

Assume in model we have after_save callback called 'process_me'. Now we have to skip the callback during the execution of certain method and than reset back.

# skip the callback
ModelName.skip_callback(:save, :after, :process_me)

# set the callback
ModelName.set_callback(:save, :after, :process_me)

For rails 2 

Active Record provides the some built in methods to restrict callback.

model_object.send(:update_without_callbacks) - restrict callback during update method's invocation
model_object.send(:create_without_callbacks) - restrict callback during create
method's invocation
model_object.send(:create_or_update_without_callbacks) - restrict callback during create/update method's invocation

Monday, November 14, 2011

Configure FCK Editor with rails 2.3.x (undefined method 'relative_url_root')

If you are trying to install fckeditor along with rails 2.3.x and get the error like
undefined method 'relative_url_root' then simply follow the below steps.

We require to add some patch for that.

Go to the fckeditor folder of plugin. and add patch for fckeditor

app/controllers/fckeditor_controller.rb

def upload_directory_path
   Replace this line (#136)
      uploaded = request
.relative_url_root.to_s+"#{UPLOADED}/#{params[:Type]}"
   With
      uploaded = ActionController::Base
.relative_url_root.to_s+"#{UPLOADED}/#{params[:Type]}"
    "#{uploaded}#{params[:CurrentFolder]}"
  end

lib/fckeditor.rb

Replace this line (#38)
  js_path = "#{request.relative_url_root}/javascripts"
with
  js_path = "#{ActionController::Base.relative_url_root}/javascripts"

Now restart your server. It solve the above error and fckeditor now configure successfully with your application.

Thursday, October 13, 2011

Escape or Encode the character using javascript or ruby

Guys,
          When we are storing the data in the database using any encoding method like UTF-8 and retrieve data in javascript it gives us in output in decode and unescape format.

To solve above issue using javascript or ruby
Javascript functions:
escape(String) - unescape(String)
encodeURI(String) - decodeURI(String)
encodeURIComponent(String) - decodeURIComponent(String)

Ruby methods:
CGI.escape(String) - CGI.unescape(String) or CGI.unescapeHTML(String)
URI.escape(String) - URI.unescape(String)

Online tool for escape/unescape, encode/decode the character.
http://www.the-art-of-web.com/javascript/escape/

Wednesday, October 12, 2011

How to create low stack ruby application using sinatra

Hello Guys,
        Yesterday i learn something new. How we create the low stack ruby application? So, here is the one of the possible solution. We can use the sinatra gem for it.

Sinatra is a DSL for quickly creating low stack web application in Ruby. Lets now install the sinatra gem by
gem install sinatra

To create simple web application by following below steps:

# test_sinatra.rb
require 'rubygems' if RUBY_VERSION < '1.9'
require 'sinatra'

get '/test' do   
    file_name = "google"
    file_store = "#{RAILS_ROOT}/tmp/#{file_name}.pdf"   
  send_file file_store, :filename => file_name ,:disposition => 'inline', :encoding => "utf-8"
end

if you want to pass the argument than use below 2 cases.

case 1:
get '/test/:arg' do 
  puts "Here is your supplied arg : " + params[:arg]
end

case 2:
get '/test?' do
  puts "Here is your supplied arg : " + params[:input_args]
end

so after ? = we can pass N numbers of query parameters. here i conduct the input_args as query parameter

There are all HTTP methods supported by sinatra.

Run the sinatra app by ruby test_sinatra.rb -p 9999

Find it interesting? Read more information about sinatra by referring http://www.sinatrarb.com/intro.html

http://titusd.co.uk/2010/04/07/a-beginners-sinatra-tutorial/

Wednesday, October 5, 2011

Avoid the memory blockage during large xml request

Guys,
        When i am playing with handling the xml request through net::http discover the problem of memory blockage and just worried about how to handle that. This problem happen b'coze i have bulk of xml data in the request. So, i form the one of the solution by using the block of net http.

When we using the block of net::http. It yields each fragment of the entity body in turn as a string as it are read from the socket.

Lets we consider 2 scenario:

require 'rubygems'
require 'net/https'
require 'uri'
uri = URI.parse("http://google.com")
http = Net::HTTP.new(uri.host, uri.port)

case 1:
response = http.post('http://google.com', 'query=language')

case 2:
# using block
   File.open('test.txt',  'w') { |f|
      http.post('http://google.com', 'query=language') do |str|
          f.write str
       end
   }

In case 1 it loads the entire response in memory. While in case 2 it read each fragment and write into file. so when we use block it's avoid memory blockage.
For more information just follow

Hope above post will help you to avoid memory blockage and increase performance.

Tuesday, October 4, 2011

undefined method 'add_to_rails_paths' for Cms:Module (NoMethodError)

Hello guys,
          During the browser cms configuration i have got the some errors which i have listed below with appropriate fix.

Error:
/gems/bcms_event-1.0.0/rails/init.rb:2:in `evaluate_init_rb': undefined method `add_to_rails_paths' for Cms:Module (NoMethodError)

Solution:
In bcms_event-1.0.0/rails/init.rb add below line
require 'browsercms'

Error:
/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:466:in `load_missing_constant': uninitialized constant Cms::S3 (NameError)

Solution:
install dependency via gem install right_aws

Keep in mind browser cms application runs with ruby 1.8.7 or latest.

Content Management System - Browser CMS

Hello rubies,
        I have integrated browser cms in one of the rails application. Awesome to deal with it. Install the browser cms as per your rails version.

If you are using rails below 3 than use browsercms 3.1.2
else use latest version browsercms 3.3.2

After installing cms create the rails application by using command
bcms new project_name -d mysql
cd project_name
rake db:install
rails server

This will create the cms using browsercms. Now you will deal with it by 
adding additional pages, portlets, sections..etc

Want to create in built demo application using browser cms?
bcms demo project_name -d mysql
cd project_name 
rake db:install
rails server

This will create a BrowserCMS project which used MySql as the data
storage. Run the application using http://localhost:3000/cms. and use it's
default user credential cmsadmin/cmsadmin

Get more information regarding browser cms by referring
https://github.com/browsermedia/browsercms/wiki

Monday, October 3, 2011

How to integrate newrelic rpm with rails

Hello,
          If you want to measure the performance (loading time) of your application than use newrelic rpm plugin/gem.

Either install newrelic plugin or gem.

script/plugin install http://newrelic.rubyforge.org/svn/newrelic_rpm
or
gem install newrelic_rpm
Add config.gem "newrelic_rpm" in environment.rb

Now in config edit the newrelic.yml
If you want to monitor application in development mode than set monitor mode

development:
  <<: *default_settings
   monitor_mode: true
   developer_mode: true

Now access the http://localhost:#{port}/newrelic. it shows the time consumption as per request. so from this you will get idea from where most time consumed. Based on that you can optimize the code to save time.


Want to get more information?
follow - https://github.com/mislav/newrelic_rpm

Wednesday, September 21, 2011

Ajax to allow file download

Hello Guys,
          Yesterday i was trying to download the attachment during ajax request. So i find out the some simple way which might help you people.

Below is the controller code snippet:

def download
   file_path = "#{RAILS_ROOT}/test.txt"
   respond_to do |format|
      format.js{
        render :update do |page|
          page.redirect_to :action =>'ajax_download' ,:file => file_path        
        end
      } 
   end
end

def ajax_download
    send_file params[:file]
end

In view i have link for download as:

<%= link_to_remote "Download", :url => {:controller => "test", :action => "download"}%>

Here my parent request is download and than it internally invoke ajax_download action to download attachment.

Friday, September 16, 2011

Read and Write normal text file using ruby

Hello rubies,
        Want to read or write the normal text file using ruby? There is inbuilt File library with ruby. lets we use that and generate simple .txt file and read that.
       
Write .txt file:

Lets we have dummy data:

dummy_data =  [[1,"Ruby on rails","50%"], [2, ".net", "70%"], [3, "java", "80%"]]
File.open("#{RAILS_ROOT}"+"/data.txt", 'w') do |file|
      # set header
         file << "S.No.\tTechnology\tTrend\n"
      # set data
         dummy_data.each do |d|
            file << "#{d[0]}\t#{d[1]}\t#{d[2]}\n"
         end 
end  

Now data.txt is generated in rails_root. lets we read content of .txt file.

file = File.new("#{RAILS_ROOT}/data.txt").read.to_a
data = file.reverse
# pop out the header first
header = data.pop.to_a
h_data = {}
header.each do |h|
  splited_header = h.split("\t")
  splited_header.collect{|h| h_data[h.strip] = []}
end

data.each do |d|
  content =  d.split("\t")
  h_data.keys.sort.each_with_index do |k, index|
    h_data[k] << content[index].strip
  end
end
puts "collected_data : " + h_data.inspect

# find highest trend
max_trend = h_data["Trend"].max
puts "#{h_data['Technology'][h_data['Trend'].index(max_trend)]} has highest(#{max_trend}) trend in IT Market."


This is the simplest way to reach our goal. hope this will help you out.

Monday, September 5, 2011

Command for postgresql

Hello Guys,
         Postgres is one of the best database which i ever used. There are the some basic commands which you will use during psql session.

psql is the postgres sql console session.

psql -U <username>  to enter in postgres console session.

Basic commands which you run on psql prompt:

 \h                   - Help with SQL commands
 \c [DBNAME]    - Connect with database              
 \d [NAME]        - Describe table, index, sequence or view
 \d{t|i|s|v|S} [PATTERN]
                       - List tables/indexes/sequences/views/system tables
 \da [PATTERN]  - List aggregate functions
 \db [PATTERN]  - List tablespaces
 \dc [PATTERN]  - List conversions
 \dC                 - List casts
 \dd [PATTERN] - Show comment for object
 \dD [PATTERN] - List domains
 \df [PATTERN]  - List functions
 \dg [PATTERN] - List groups
 \dn [PATTERN] - List schemas 
 \do [NAME]      - List operators
 \dl                  - List large objects
 \dp [PATTERN] - List table, view, and sequence access privilege
 \dT [PATTERN] - List data types
 \du [PATTERN] - List users
 \l                   - List all databases
 \z [PATTERN]   - List table, view, and sequence access privilege
 \q                  - Quit
  \?                 - Help with psql commands

Query browser command
pg_tables - List all the tables
pg_namespace - List all the schemas (namespaces)
pg_views - List all the views
pg_index - List all index

Here are lots of other commands. If you want to require more information about postgres follow http://www.postgresql.org/.

Saturday, September 3, 2011

Integrate CKEditor in ruby on rails

Hello guys,
                  If you want to integrate WYSIWYG editor then just use simple ckeditor. It much better then any other editors.

Implement CKeditor with rails(2.3.x) application just install
   sudo gem install ckeditor
or configure gem in environment.rb by
   config.gem 'ckeditor', :version => '3.4.3'

Now configure javascript files of ckeditor by
    rake ckeditor:install
and than generate config file for ckeditor.
   rake ckeditor:config

Lets now include ckeditor.js in view

<%= javascript_include_tag :ckeditor %>
<%= ckeditor_textarea 'object', 'field', :toolbar => 'Basic', :width => '100%', :height=> '150px'  %>

so, now run your application and see the ckeditor with basic toolbar. If you want to use additional toolbar then use toolbar as Full. Also there are many other option available like skin and swf_params. It's possible to integrate paperclip along with ckeditor.

Follow https://github.com/jeremy6d/rails-ckeditor to get more information about ckeditor.
Hope this article will help you. If you have any suggestion or query than post comment.

Friday, September 2, 2011

Ajax based pagination

Hello Guys,
          There are different plugin and gem available for pagination. I would like to prefer will_paginate gem for pagination in rails.

First of all we have to add mislav-will_paginate gem via
sudo gem install mislav-will_paginate
 
or specify in your environment.rb

config.gem "mislav-will_paginate", :lib => "will_paginate", :source => "http://gems.github.com"

in your pagination.js add the javascript code to support ajax based pagination

document.observe("dom:loaded", function() {
  var container = $(document.body)

  if (container) {
    # uncomment below code to load spinner
    //var img = new Image
    //img.src = '/images/spinner.jpeg'  
    function createSpinner() {
      //return new Element('img', { src: img.src, 'class': 'spinner' })
    }

    container.observe('click', function(e) {
      var el = e.element()
      if (el.match('.pagination.ajax a')) {
          el.up('.pagination.ajax').insert(createSpinner())
//      if (el.match('.pagination a')) {
//        el.up('.pagination').insert(createSpinner())
        new Ajax.Request(el.href, { method: 'get' })
        e.stop()
      }
    })
  }
})

Now you have to include pagination.js in your view through
<%= javascript_include_tag 'pagination' %>

Lets we implement pagination on index method of users controller.

users_controller.rb

def index
  @users = User.all.paginate(:per_page => 20,:page => params[:page])
  respond_to do |format|
    format.html
    format.js {
      render :update do |page|       
        page.replace_html 'user_list', :partial => 'user_list', :locals => {:users => @users}
      end
    }
    end
end

Now move towards the views. here we have 3 views which listed below.

i) index.html.erb
   <h1> Listing Users </h1>
   <table>
     <tr>
       <th> Name </th>
       <th> Surname </th>
     </tr>
     <tbody id='user_list'>
        <%= render :partial =>'user_list', :locals => {:users => @users} %>
     </tbody>
   </table>

ii) _user_list.html.erb

  <% users.each do |user| %>
    <tr>
      <td> <%= user.name %> </td>
      <td> <%= user.surname %> </td>
    </tr>
  <% end %>
  <tr>
   <td colspan="2"> 
      <%= will_paginate users, :class => 'pagination ajax', :id=>"flickr_pagination"%>
   </td>
  </tr>

iii) index.js.erb
      $("#user_list").html("<%= escape_javascript(render :partial => "user_list") %>");

This is the file which actually play with ajax during pagination.

Now add pagination.css in style sheet for better formatting

#flickr_pagination {
  text-align: center;
  padding: 0.3em 0.3em 0.3em 0.3em;
  clear:both;
  margin:5px 0px 5px 0px;
  }
#flickr_pagination * {
  font: 10pt Arial,Helvetica,Geneva,sans-serif;
  } 
#flickr_pagination a, #flickr_pagination span {
  padding: 0.2em 0.5em; 
  }
#flickr_pagination span.disabled {
  color: #AAA
AAA;
  }
#flickr_pagination span.current {
  font-weight: bold;
  color: #898989; 
  }
#flickr_pagination a {
  border: 1px solid #DDDDDD;
  color: #0072BC;
  text-decoration: none; 
  }
#flickr_pagination a:hover, #flickr_pagination a:focus {
  border-color: #DDDDDD;
  background: #898989;
  color: #FFFFFF; 
  }
#flickr_pagination .page_info {
  color: #aaaaaa;
  padding: 0.8em 0em 0em 0em; 
  }
#flickr_pagination .prev_page, #flickr_pagination .next_page {
  border-width: 1px; 
  }
#flickr_pagination .prev_page {
  margin: 0em 1em 0em 0em; 
  }
#flickr_pagination .next_page {
  margin: 0em 0em 0em 1em; 
  }

you have to include pagination.css in your view through
<%= stylesheet_link_tag 'pagination' %>

Finally we done with ajax pagination. If you want different styles for pagination then just replace the style sheet. http://woork.blogspot.com/2008/03/perfect-pagination-style-using-css.html

Hope this post will help you to implement ajax pagination in rails.

Generate .xlsx file in ruby using simplexls

Hello Rubies,
          Generate simple .xlsx file using spreadsheet cause the problem it shows extension as .xlsx but it actually .xls file itself.
          So, now we required better option to generate .xlsx file in ruby by using simple_xlsx_writer gem.

First of all we require to install simple_xlsx_writer by using
  sudo gem install simple_xlsx_writer
 
Lets generate example.xlsx

require 'simple_xlsx'

def generate_xlsx
   dummy_data = [
     ["Jyoti", "1960-07-27", "http://priyankapathak.wordpress.com"]
     , ["Ramesh", "1956-06-20", "http://twitter.com/pathakpriyanka"]] 
   file_name = "#{RAILS_ROOT}/tmp/example.xlsx"

   serializer = SimpleXlsx::Serializer.new(file_name) do |doc|   
      doc.add_sheet("Testsheet") do |sheet|
         sheet.add_row(["Name", "Birth Date", "URL"])
         dummy_data.each do |data|
             sheet.add_row[data[0], 
                 Date.parse(data[1]), '=HYPERLINK("'+data[2]+'","Hit me")'
         end
      end 
   end
   send_file file_name
end

This code helps you to generate simple .xlsx file. Want more information than simply follow http://rubydoc.info/gems/simple_xlsx_writer
Hope this post help you. If have any query or suggestion than post a comment.

Wednesday, August 31, 2011

Generate CSV file using FasterCSV

Generate csv file using different tools like FasterCSV or CSV builder.

FasterCSV is better tool to generate csv file using ruby.
First of all need to install gem using gem install fastercsv.

Create .csv file by following below steps.
 
require 'fastercsv'

file_path = Tempfile.new(
"test.csv", File.join(Rails.root,"tmp"))
FasterCSV.open(file_path.path, "w:windows-1252") do |content|
  content << ["Name", "Surname", "Birthdate", "HSC Percentage", "URL"]
  content << ["Priyanka", "Pathak", Date.parse("May 20, 1986"), 80, '=HYPERLINK("http://priyankapathak.wordpress.com","Get me here")']
end

This will simply generate test.csv file with your required format like hyperlink in csv.

Hope this post will help you.

Friday, August 26, 2011

Inbulit ruby on rails test method

Hello rubies,
      One of best feature which rails provides is inbuilt testing. I like to write the test case to trace behavior of application.
      Below the list of the method which you use during functional and integration tests.

Functional Test

  1. HTML request
      a. Get method
          get :action_name, :parent_params => {:child1 => "arg1"}
      b. Post method
          post :action_name, :parent_params => {:child1 => "arg1", :child2 => "arg2"}

  2. Ajax request
      a. Post method
          xhr :post, :action_name, , :parent_params => {:child1 => "arg1"}


Integration Test

  If you want to pass additional header than use  
  headers = {'HTTP_HOST' => "localhost", 'Content-Type' => 'text/xml'}

  1. HTML request
      a. Get method
          get_via_redirect '/controller_name/action_name', {:arg1 => 'test'}
      b. Post method 
          post_via_redirect '/controller_name/action_name', {:arg1 => 'test'}, headers
      c. Put method
        
          put_via_redirect '/controller_name/action_name', {:arg1 => 'test'}
      d. Delete method
          delete_via_redirect '/controller_name/action_name', {:arg1 => 'test'}
      f. Instead of method*_via_redirect you can use alternate method
        http_method like post, put, get, delete        
        request_via_redirect http_method, '/controller_name/action_name', {:arg1 => 'test'}
    
  2. Ajax request
      a. Post method
          xml_http_request :post, "/controller_name/action_name", {:arg1 => 'test'}, headers

This are the basic methods. If you need detail information on this then refer

http://guides.rubyonrails.org/testing.html

Thursday, August 25, 2011

Patch to allow link_to with post method

Hello guys,
     If you want to pass additional parameters with post method in link_to than you have to add patch in url_helper of actionpack module of rails.

Here is the simple patch to allow post method with additional parameters in link_to.

Go to the actionpack folder of rails for eg we have rails 2.3.11.

nano /usr/lib/ruby/gems/1.8/gems/actionpack-2.3.11/lib/action_view/helpers/url_helper.rb

Now just replace below lines

line #562
method, href = html_options.delete("method"), html_options['href']
to 
method, href, values = html_options.delete("method"), html_options['href'], html_options.delete("values")
line #570
"if (#{confirm_javascript_function(confirm)}) 
{ #{method_javascript_function(method, url, href)} };return false;"
to
"if (#{confirm_javascript_function(confirm)}) 
{ #{method_javascript_function(method, values, url, href)} };return false;"

line #574 
"#{method_javascript_function(method, url, href)}return false;"
to
"#{method_javascript_function(method, values, url, href)}return false;"

line #590
def method_javascript_function(method, url = '', href = nil)
to
def method_javascript_function(method, values, url = '', href = nil)

and add below code after line #595
 
  if values.is_a?(Hash) && (method == :post || method == :put) 
    values.each do |name,value| 
      submit_function << "var formElement = document.createElement('input'); " 
      submit_function << "formElement.name = '#{name}'; " 
      submit_function << "formElement.type = 'text'; " 
      submit_function << "formElement.value = '#{value}'; " 
      submit_function << "f.appendChild(formElement); " 
    end 
  end 

Finally now you can access the link_to with post action and query parameters.
<%= link_to "Test to click on",
  {:controller => "users", :action => "dummy_action"}, :method => :post, 
   :values => {:arg1 => "Argument1", :arg2 => "Argument 2"}, 
   :class => 'css_class' %>

Hope this post helps you to overcome the problem of link_to during post method.
If you have any suggestion then post comment. 

Friday, August 19, 2011

Faster XML Parser in ruby on rails

Hello Guys,

Last week i was trying to  parse xml using different xml parser like Hpricot. But when we have large amount of data than segment fault occurs. So i moved to better and faster xml parser called libxml-ruby.

There is simple steps to parse large xml using libxml-ruby. First of all you need to install libxml-ruby by

  gem install libxml-ruby

Lets, we have sample xml

sample.xml
xml = %{
  <users>
    <user>
      <name>Priyanka Pathak</name>
      <mark subject=”biology”> 80 </mark>
    </user>
    <user>
      <name>Rahul Pathak</name>
      <mark subject=”biology”> 85 </mark>
    </user>
  </users>
}

Now create method to parse xml

require 'rubygems'
require 'libxml'
require 'benchmark'

def parse_xml
   Benchmark.bmbm do |r|
      r.report("Process XML"){
        parser = LibXML::XML::Parser.file('sample.xml',:encoding => XML::Encoding::UTF_8)
        doc, collect_data = parser.parse, []
        doc.find('//users/user').each do |e|
           data = {}
           data['name'] = e.find('name').first.content
           mark = e.find('mark').first
           data['mark'] = {:subject => mark.attributes.first.value , :value => mark.content}
           collect_data << data     
        end

        puts "collect data: " + collect_data.inspect
     }
   end
end
Benchmark shows the time required during xml parsing and as per my experience it's faster than other xml parser.

For more information about libxml follow http://libxml.rubyforge.org/rdoc/
Hope this post will help you.

Thursday, August 18, 2011

Validate XSD with XML

If you want to validate the XSD (XML schema) with XML document then here is the easy steps.



First you need to install libxml-ruby via gem install command.



We have 2 files. one is example.xsd and example.xml. Lets we define normal method say validate_xml_schema.

require 'libxml'
def validate_xml_schema
   begin
      schema = XML::Schema.document(XML::Document.file("#{RAILS_ROOT}/example.xsd"))
      xml_instance = XML::Document.file("#{RAILS_ROOT}/example.xml")                  
      if xml_instance.validate_schema(schema)
         puts "Successfully validate schema"
      else
         puts "Oops!! There is some problem in XML formatting"
      end     
   rescue => e
     puts "Exception:" + e.inspect
   end 
end

Here is the two example documents.

example.xml

<?xml version="1.0" encoding="UTF-8"?>
<students>
   <student>
      <roll_no>1001</roll_no>
      <name>Priyanka Pathak</name>
      <mark subject='biology'>48</mark>
      <mark subject='physics'>42</mark>
   </student>
   <student>
      <roll_no>1002</roll_no>
      <name>Rahul Pathak</name>
      <mark subject='biology'>45</mark>     
      <mark subject='physics'>43</mark>
   </student>
</students>


example.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="students">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="student"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="student">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="roll_no"/>
        <xs:element ref="name"/>
        <xs:element minOccurs="1" maxOccurs="2" ref="mark"/>    
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:element name="roll_no" type="xs:integer"/>

  <xs:element name="name" type="xs:string"/>

  <xs:element name="mark">
    <xs:complexType>
      <xs:simpleContent>
          <xs:extension base="xs:integer">
            <xs:attribute name="subject" use="required">
              <xs:simpleType>
                <xs:restriction base="xs:string">          
                  <xs:enumeration value="biology"/>
                  <xs:enumeration value="physics"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>


XSD schema defines structure of nodes and value type.
eg. roll_no must be positive integer.
      name must be string.
      mark must contain subject as attribute with option like 'biology' or 'physics' and value type as decimal.

Hope this post helps you.