Default Green Orange
grzegorz brzezinka.eu
Be curious. Laugh a lot.
    Home Page Home
  • Contact
RSS

Export to Excel (xls) in Rails3

Rails3 2 Comments »

A client wanted to export some tabular data from the database to an editable format, so xls was an obvious choice. Before I mastered the export of the same piece of data into pdf format using Prawn gem, now I want to present you an easy way to achieve fairly the same effect, but in Excel output.

Let’s assume we have a list of clients in an array clients:

Name Surname Age
John Smiths 23
Ann Gooday 97
….

In order to export data to Excel, we will use the Ruby spreadsheet gem (project’s page: http://spreadsheet.ch/ and at Rubygem: http://rubygems.org/gems/spreadsheet). The gem provides a flexible way to manipulate, import and export xls data.

  1. First, we need to register new mimetype – xls.
    Let’s create config/initializers/mime_types.rb and paste:

    Mime::Type.register 'application/vnd.ms-excel', :xls
    
  2. Next, we have to extend the selected controller’s action to respond to xls
    def index
      @clients = Client.all
      require 'spreadsheet'
      respond_to do |format|
          format.pdf
          format.xls {
            clients = Spreadsheet::Workbook.new
            list = clients.create_worksheet :name => 'List of cliets'
            list.row(0).concat %w{Name Surname Age}
            @clients.each_with_index { |client, i|
               list.row(i+1).push client.name,client.surname,client.age
            }
            header_format = Spreadsheet::Format.new :color => :green, :weight => :bold
            list.row(0).default_format = header_format
            #output to blob object
            blob = StringIO.new("")
            clients.write blob
            #respond with blob object as a file
            send_data blob.string, :type => :xls, :filename => "client_list.xls"
          }
    end
    
  3. In the end, we can create a link in the view: link_to clients_path(:format => :xls)
  4. Click the link and enjoy the xls being downloaded. Remember you can style and/or add additional worksheets to your Excel workbook – refer to spreadsheet manual if needed.
References:
  • http://spreadsheet.rubyforge.org/
  • http://stackoverflow.com/questions/4591990/spreadsheet-rails-3-question


Luty 15th, 2012  
Tags: Rails3, Ruby on Rails, spreadsheet, tips&tricks



Linux: how to renew DHCP IP address?

linux 1 Comment »

I have just shown a Turnkey Linux Rails (VirtualBox edition) to my RoR developer friend. He really enjoyed using it, however after a few days he mentioned that he had a problem – every time he moved his laptop to a different network, he needed to restart Linux in orded to detect the proper IP through bridged network card connection. This is a distinct loss of time!

There is a simple command to renew (restart, or rather reflush) the ethernet connection, that will result in the renewing of DHPC IP. Assuming your network connection is eth0 (you can check it with ifconfig command), just type:

ifdown eth0
ifup eth0

And that’s all! The new IP would be printed in the output of the last command.


Lipiec 25th, 2011  
Tags: linux, tips&tricks



Full page background image in Prawn PDF in Rails3

Rails3 0 Comment »

Recently I have worked on project that needed a pdf form to be filled with data gathered in Rails3 app db.

As I have decided to use PRAWN as a PDF generator (with prawn_rails gem – I can really recommend, works with Rails3), I had to choose between recreating the form or just filling in the form that was ready. As time=money, I decided to go for the second possibility.

1. I converted the pdf form to JPG (300 dpi resolution, no compression).

2. I needed A4 page size, so I also need to scale my image. In my example_document.pdf.prawn, I should put:

bg = "#{RAILS_ROOT}/public/pdf/pdf_bg.jpg"

prawn_document (
    :filename=>'foo.pdf',
    :page_size=> "A4",
    :margin => 0) do |pdf|
      pdf.image bg,
        :at  => [0, Prawn::Document::PageGeometry::SIZES["A4"][1]],
        :fit => Prawn::Document::PageGeometry::SIZES["A4"]
  pdf.text "This is pdf with background image ready to fill in"
end

The code above imports the image and positions it in the right left corner (remember! bounding box in pdf has its origin [0,0] in BOTTOM LEFT corner of the page). The size of A4 is set as constant by PRAWN (nice of them, isn’t it?). You can access it by Prawn::Document::PageGeometry::SIZES array. The full list of available page sizes you can find in PRAWN source code at https://github.com/sandal/prawn/blob/master/lib/prawn/document/page_geometry.rb.

3. Now one has to play around a little bit in order to position the data obtained from db in right positions.

Good luck!


Lipiec 25th, 2011  
Tags: pdf, prawn, Rails3, Ruby on Rails



Github error – fatal: Unable to look up github.com (port 9418) (Name or service not known)

Rails3 0 Comment »

  1. I was trying to add a gem to a Rails3 app gemfile directing it to a git repo by:
gem 'example', :git => "git://github.com/gituser/example.git"

While bundle install, I got the error message:

fatal: Unable to look up github.com (port 9418) (Name or service not known)

I tried git clone -q git://github.com/gituser/example.git or rails plugin install git://github.com/gituser/example.git, still I got the same error message. It seems that Github has recently updated DNS and the changes haven’t propagated yet. You can use a workaround:

  1. Run ping github.com and read the current IP
  2. Go to /etc/hosts on your Rails server (assuming its Linux) and add the following line:
    207.97.227.239 github.com wiki.github.com gist.github.com assets0.github.com assets1.github.com assets2.github.com assets3.github.com
    

    where instead of 207.97.227.239 type it the current Github IP

It is suggested to remove this line once the DNS is up and working again.

Source

Czerwiec 12th, 2011  
Tags: Github, Rails3, Ruby on Rails



RubyGems warning/error: Gem::Specification# default_executable = is deprecated with no replacement. It will be removed on or after 2011-10-01.

Rails3, Ruby 3 Comments »

After recent update of RubyGems (to 1.8), while running for example bundle install, the user will see a bunch of warnings, like:

NOTE: Gem::Specification# default_executable = is deprecated with no replacement. It will be removed on or after 2011-10-01.

This is connected with the recent policy of RubyGems team – read the official statement.

They have deprecated 22+ methods! It will take some time for Gem authors to update… Before then, you may run:

gem pristine --all --no-extensions

to get most recent and thus some of the warrnings gone…


Maj 18th, 2011  
Tags: Rails3, Ruby on Rails, tips&tricks



PIK: Multiple Ruby versions for Windows

Rails3, Ruby 0 Comment »

Since Rails3 is quite popular right now, many programmers move their projects to this version. So did I :-) However, because of some major bugs in Ruby 1.8.7, Rails3 needs Ruby >=1.9.1. The problem is that I still have to maintain some Rails 2.3.5 projects…

There is a solution: Ruby Version Manager (RVM)… but not for windows :-P For the latter, you should use PIK gem https://github.com/vertiginous/pik. The installation is pretty easy, just follow the tutorial at github repo step by step.

PROBLEM

So install PIK, add all ruby versions you want to, use the one you need. But well, life is not that easy… Supposing you’ve got some more complicated gem dependencies in your gemfile, when you try to run:

rake db:migrate

you will probably see the message like below:

There was an error. Error - can't dup NilClass /gemname/

or, in case you use sqlite3:

Unknown method sqlite3_backup_finish in sqlite3.dll.

SOLUTION

1. Set gem_home for the choosen ruby version. Probably the path to install gems isn’t set to unique for every Ruby version you’ve installed. This may be highly confusing and cause some errors if you use different gem versions for Rails 2.3.x and Rails3 (which is the case in 99% of cases).

  • Supposing you work on Ruby 1.9.2, you type: pik use 192.
  • Then you can check where is current working dir: which ruby or which rails.
  • Go to c:/Users/username/.pik/config.yml.
  • Edit the proper line in YAML file adding the following lines to the chosen Ruby version
    :gem_home: !ruby/object:Pathname
        path: c:/users/greg/.pik/rubies/Ruby-192-p180
    

    So that the whole version definifion will look like:

    "192: ruby 1.9.2p180 (2011-02-18) [i386-mingw32]":
      :gem_home: !ruby/object:Pathname
        path: c:/users/greg/.pik/rubies/Ruby-192-p180
      :path: !ruby/object:Pathname
        path: C:/Users/Greg/.pik/rubies/Ruby-192-p180/bin
    

    Mind the spaces and tabs!

2. SQLite 3 for Windows needs some additional libraries. You can find them at http://www.sqlite.org/download.html The solution is simple: download the sqlite3.dll and sqlite3.exe and copy it to your Ruby bin directiory, i.e. C:/Users/Greg/.pik/rubies/Ruby-192-p180/bin

I hope this was helpful and saved you some time of your life ;-)


Marzec 28th, 2011  
Tags: Rails3, Ruby on Rails, tips&tricks



Alternative strings’s delimiter for Ruby (on Rails)

Ruby 2 Comments »

Defining a string in Ruby is pretty simple:

s1 = 'Hello!'
s2 = "This is a string.\n Calculations: 2+2=#{2+2}"

You can use both single and double quotes, however double quotes give you much more – expressions enclosed in #{} would be processed by Ruby before string is shown. Pretty cool, heh?
But I am sure most of you have already known that. Let’s proceed than: consider you have a string, that contains many mixed quotes (‘) and double quotes („). How to write it, if the same marks (‘) and („) are considered as string delimiters? Of course you can concatenate string step by step delimiting single quote with double quoted and vice versa, but this is painful. There is a better solution:

Read the rest of this entry »


Grudzień 20th, 2010  
Tags: Ruby on Rails, tips&tricks



How to check if the object/element exist in JavaScript and jQuery?

jQuery 2 Comments »

The simplest mistake sometimes costs several hours of debugging. One of these is checking if the target exists before trying to apply some changes to/using it.

How to check if element in DOM exists, i.e. if the selector $(‘.some_class’) is not empty?

The simplest:

if ($('.some_class')) {
   //some action
}

will not work!

The correct condition uses the .lenght function:

if ($('.some_class').length > 0) {
   //some action
}

Note no brackets after .length.

How to check if JavaScript object’s property exists?

This is tricky, as there are two types of properties: own properties and prototype properties. Not going into details, we can assume, that own properties are the one that are for example serialized by JSON, and prototype properties are the one that can be empty or not, but are given in the object’s definition.

So, in most cases you want to check if the own property exists for the given object. This can be obtained using the hasOwnProperty() method:

if (the_object.hasOwnProperty("name)) {
   //some action
}

If you only want to check whether there is the prototype property, you may use in operator to determine the existence of the property:

if ("name" in the_object)) {
   //some action
}

Grudzień 13th, 2010  
Tags: JavaScript, jQuery, tips&tricks



How to enable the search functionality in jqGrid?

jQuery 10 Comments »

jqGrid is a powerful jQuery based, AJAX tool for representing and editing tabular data in many formats (database output in JSON, XML etc.).

It is really easy to implement, quite well documented and really easy to style (through jQuery UI themes and its excellent themeroller).

I was working on a Joomla-PHP-MySQL project. I have successfully enabled the extended show functionality, adding edit option also went smoothly. However, I got a little bit stuck while trying to enable Search. Basing on demo examples and some blogs, I have managed to develop a piece of code that successfully made the search work like a charm. Below you’d find a php file responsible for returning the get xml data request from jqgrid.

Read the rest of this entry »


Listopad 29th, 2010  
Tags: jqgrid, jQuery, tips&tricks



Ruby on Rails CMS

Ruby, Uncategorized 2 Comments »

I was working on project, that part was a basic tree-like structure of static pages, that needed kind of CMS for client. I had two solutions:

  1. implement awesome_nested_set + rails-ckeditor + paperclip
  2. find a ready-to-go solution

After a little bit of googling tens of out-of-date pages&blogs, I ended up on a great website http://www.whichrubycmsshouldiuse.com/ by Youssef Chaker.
Read the rest of this entry »


Wrzesień 27th, 2010  
Tags: CMS, Ruby on Rails



Previous Entries
  • Newest posts

    • Export to Excel (xls) in Rails3
    • Linux: how to renew DHCP IP address?
    • Full page background image in Prawn PDF in Rails3
    • Github error – fatal: Unable to look up github.com (port 9418) (Name or service not known)
    • RubyGems warning/error: Gem::Specification# default_executable = is deprecated with no replacement. It will be removed on or after 2011-10-01.
  • Tags

    human body eye hosting domain movie image google brain gym Math .htaccess wordpress science riddle Joomla webmastering fun Rails3 jQuery Ruby on Rails tips&tricks
  • In the blog you’ll find:

    • Funny (3)
      • Riddles (2)
    • interesting facts (1)
    • linux (1)
    • Projects (1)
    • science (5)
      • computer (1)
      • human body (1)
      • Math (1)
      • physics (1)
    • Uncategorized (2)
    • webmaster tips (23)
      • Joomla (2)
      • jQuery (6)
      • Rails3 (5)
      • Ruby (11)
      • WordPress (1)
  • Translate!

      Translate to:

      Powered by Google Translate.
Copyright © 2012 grzegorz brzezinka.eu All Rights Reserved
XHTML CSS Zaloguj się
Designed by iSoftware Reviews and