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.