Sarav's Weblog

Technical Articles for RoR Developers

Curb Gem – Libcurl bindings for Ruby

Curb – Libcurl bindings for Ruby

  • *
  • *

Curb (probably CUrl-RuBy or something) provides Ruby-language bindings for the libcurl(3), a fully-featured client-side URL transfer library. cURL and libcurl live at .

Curb is a work-in-progress, and currently only supports libcurl’s ‘easy’ mode.

Curb is copyright (c)2006 Ross Bamford, and released under the terms of the Ruby license. See the LICENSE file for the gory details.
You will need

* A working Ruby installation (1.8+, tested with 1.8.5)
* A working (lib)curl installation, with development stuff (7.5+, tested with 7.15)
* A sane build environment

… will usually be as simple as:
$ gem install curb

Or, if you downloaded the archive:
$ rake install

If you have a wierd setup, you might need extconf options. In this case, pass them like so:

$ rake install EXTCONF_OPTS='--with-curl-dir=/path/to/libcurl --prefix=/what/ever'

Currently, Curb is tested only on GNU/Linux x86 – YMMV on other platforms. If you do use another platform and experience problems, or if you can expand on the above instructions, please get in touch via the mailing list on Curb’s Rubyforge page.

Curb has fairly extensive RDoc comments in the source. You can build the documentation with:

$ rake doc

Simple fetch via HTTP:

c = Curl::Easy.perform("")
puts c.body_str

Same thing, more manual:

c ="")
puts c.body_str

Additional config:

Curl::Easy.perform("") do |curl|
curl.headers["User-Agent"] = "myapp-0.0"
curl.verbose = true

Same thing, more manual:

c ="") do |curl|
curl.headers["User-Agent"] = "myapp-0.0"
curl.verbose = true


Supplying custom handlers:

c ="")

c.on_body { |data| print(data) }
c.on_header { |data| print(data) }


Reusing Curls:

c =

["", ""].map do |url|
c.url = url


c = Curl::Easy.http_post("",
Curl::PostField.content('thing[name]', 'box',
Curl::PostField.content('thing[type]', 'storage')

HTTP POST file upload:

c ="")
c.multipart_form_post = true

Resource from:

How to use helpers in ruby Console?

We can use rails helper methods in ruby console by using “extend” method.


>> helper.extend ApplicationHelper
>> helper.number_to_currency(232324)
=> "$232,324.00"

Should I freeze my Rails application?

Ruby on Rails allows you to “freeze” the version of Rails used by your application. When you freeze Rails, your application will always use that version of Rails and the associated Ruby Gems, regardless of what version is installed on the server. You can choose which version of Rails you want to freeze to.

Freezing Rails is recommended if you are using a Rails application for a business site or another production environment where stability is the most important concern. If you don’t freeze your application, there is a small possibility that your application might stop working due to compatibility problems when a new version of Rails is installed on our servers.

However, keep in mind that if you freeze your application to use a current (or older) version of Rails, you will not get the security benefits of automatic upgrades. You should make sure you’re keeping track of Rails versions yourself (for example, by subscribing to the Rails mailing lists) and upgrading your frozen version of Rails as necessary.

On this page:

  • * Freezing Rails
  • * Unfreezing Rails
  • * Freezing to a different version

Freezing Your Application

cd "application path of your system"
rake rails:freeze:gems

This will copy the Rails files to the “vendor/rails” directory of your application. When the Rails framework runs, your application will first check for the presence of this directory. If it exists, Rails will load the Rails components from the directory instead of using the main server copy of Rails. As long as you do not delete these files, your application will continue to use your “frozen” version of Rails.

Freezing to a different version

Although we’ve explained how to freeze Rails to the current version on the server, Rails allows you to freeze to almost any version.

For example, this command freezes your application to Rails 2.2.2:

rake rails:freeze:edge RELEASE=2.2.2

And this freezes Rails to the current development version:

rake rails:freeze:edge

The ability to freeze to different versions of rails can be useful when upgrading. For example, imagine you created a new Rails application and froze it to version 2.2.3 to ensure stability. When you became aware of a Rails upgrade (version 2.3.4 became available), you could upgrade your frozen version of Rails during an off-peak hour:

rake rails:freeze:edge RELEASE=2.3.4

Then you’d test your application to ensure it worked properly. If so, you’re all set, with the latest version of Rails installed. If not, you could downgrade back to the previous version until you were able to fix the problem, using:

rake rails:freeze:edge RELEASE=2.2.3

By the way, you can tell what version of Rails your application uses with this command:


Finally, some Rails upgrades provide configuration file changes (in particular, changes to “config/boot.rb”). To get the benefit of these changes, run this command after switching Rails versions:

rake rails:update

blackbook gem (Contact Importer gem for Ruby on Rails)

Blackbook automates the nitty-gritty of importing contacts from various services and files and exporting them as VCard, XML, or simple Hash. Utilize those contacts from services like AOL, GMail, Yahoo Mail, Hotmail or CSV to help your social networking site become GIGANTIC overnight! You‘ll be able to get big and sell for millions before anyone figures out it‘s just like every other social network.



The current list of supported services and file types:


  • AOL
  • CSV files
  • Gmail
  • Hotmail
  • Yahoo! Mail


  • Simple hash (default)
  • Vcard
  • XML

If you create an additional importer or exporter – or simply find a bug – please consider submitting it as a patch to the project so the community can all benefit from your hard work and ingenuity.


# An example of fetching Gmail contacts – by default, returns an array of hashes with :name and :email

  contacts = Blackbook.get :username => '', :password => 'whatever'

# or returning XML

  contacts = Blackbook.get :username => '', :password => 'whatever', :as =>  :x ml

# or importing from a CSV file

  contacts = Blackbook.get :csv, :file => #<File:/path/to/file.csv>


  • Mechanize and its dependencies, for interacting with online providers
  • Fastercsv for reading CSV, Mechanize >= 0.7.0 for page scraping


  • sudo gem install blackbook

Paypal on Rails – ActiveMerchant tips

Anyone who has looked into using ActiveMerchant and PayPal together knows it is quite a challenge. ActiveMerchant is great, but there is no documentation for using it with Paypal. Here are some tips to help you get it working:

Here is a page with some good references.

Setting up Paypal

The paypal website is a bit tough to navigate and they don’t make it obvious to figure out what are all the things you need to do to get it all setup.

  1. You will need a sandbox (developer) paypal account to test your set up. Sign up here
  2. The sandbox does not send emails, so you will have to use the Sandbox Email Tab to validate your sandbox account email address.
  3. Launch the sandbox
  4. Create a sandbox business account. and go through the normal paypal verification stuff. (It does not use your real bank account.)
  5. Go to the Merchant Services tab and signup for a Website Payments Pro Account.
  6. Verify your merchant account. You will be asked to enter you SSN number, use 111 + six random numbers. If you get an error message, try a different six numbers, the fake ssn must be unique in the sand box.
  7. Under the My Account tab and the Profile subtab and the Billing Agreements link, make sure you accept the Agreement.
  8. Same for the PayPal Monthly Billing link.
  9. Follow these instructions to create your API Certificate. Do not make the API Signature. You only need to do the “Step 1. Generate Certificate” part.
  10. Make sure you save the username & password given and download and save the pem file.

Paypal should now be set up. You will have to go through and do all the same stuff for your real paypal account, once your development is done and working.

Setting up ActiveMerchant

  1. Install ActiveMerchant by following the instructions, you will need to install the money gem, which ActiveMerchant requires.
  2. Rename the pem file to cert_key_pem_dev.txt and put it in your config dir.
  3. Add the following code to your environments/development.rb:
    config.after_initialize do
      ActiveMerchant::Billing::Base.gateway_mode = :test
      ActiveMerchant::Billing::PaypalGateway.pem_file = + '/config/cert_key_pem_dev.txt')
    $PAYPAL_LOGIN = ''
  5. Use the actual username and password in the previous code (don’t use the empty strings 🙂
  6. Do the same for the environments/test.rb
  7. Do the same for the environments/production.rb, except remove the line: ActiveMerchant::Billing::Base.gateway_mode = :test and use the cert_key_pem_prod.txt file (which you can get through your real paypal account (renaming to cert_key_pem_prod.txt ).
  8. Do something like this in your code:
    amount = 1000 #$10.00
    credit_card =
        :type       => 'visa',
        :number     => '4242424242424242',
        :month      => 8,
        :year       => 2009,
        :first_name => 'Bob',
        :last_name  => 'Bobsen',
        :verification_value=> '123'
    flash[:error] = credit_card.errors and return unless credit_card.valid?
    billing_address = {
        :name     => "John Smith",
        :address1 => '123 First St.',
        :address2 => '',
        :city     => 'Los Angeles',
        :state    => 'CA',
        :country  => 'US',
        :zip      => '90068',
        :phone    => '310-555-1234'
    gateway =>$PAYPAL_LOGIN, :password=>$PAYPAL_PASSWORD)
    res = gateway.authorize(amount, credit_card, :ip=>request.remote_ip, :billing_address=>billing_address)
    if res.success?
        gateway.capture(amount, res.authorization)
        flash[:notice] = "Authorized"
        redirect_to somewhere_url
        flash[:error] = "Failure: " + res.message.to_s
  10. Make sure State and Country are two character code.
  11. The credit card errors is actually a hash, not an array (like AR.errors), so you will need a helper to display the error.

Last Tip

  1. When testing with paypal, you must use port 80: ./script/server -p 80

Want to See How Much Sploggers Steal from Your Blog? FairShare from Attributor Will Help You Find Out

At this very moment at the Creative Commons Technology Summit in Cambridge Attributor is previewing a new free product for bloggers and various web publishers that is intended for everyone to see exactly who is stealing our content and how they use it to make money off our work.

Attributor is a company that works with various web publishers – big and small – to point them to places where people steal their content. The crawler finds your content republished elsewhere and analyzes it to see if you got a link back and if the content is monetized on the site it is found on with ads. In addition to helping you identify the thieves Attributor also offers handy tools to demand that your content is removed or at least a link back to your own site is added.

I spent some time last week on the phone with Attributor as they were generous enough to analyze Profy feed as they are looking to connect to bloggers and probably see how we react to their ideas and products. I was very curious as I know many bloggers would have been as we are invariably concerned with everything about our blogs stats so it is no wonder I wanted to see the results of such analysis a lot (the screenshots used here are from Attributor report for Profy).

Do a “git export” like “svn export”

git export
Probably the simplest way to achieve this is with git archive. If you really need just the expanded tree you can do something like this.

git archive master | tar -x -C /your/path/to/export

Most of the time that I need to ‘export’ something from git, I want a compressed archive in any case so I do something like this.

git archive master | bzip2 >source-tree.tar.bz2

git help archive for more details, it’s quite flexible.