Posts

Showing posts with the label ruby

Writing usable scripts in Ruby

Usable command line tools/scripts There are a lot of command line tools written in ruby, python, bash, c or any other languages. They are usable simply because there is a standard way in dealing with them this way can be summarized in the following points: There has to be a usage example/brief help at the finger tips of the user ( by running with  -- help      or -h) arguments should have default values which are explained in the help misusage or missing mandatory arguments should fire the help message ruby tools OptionParser  is part of the standard library in ruby that takes care of this script packaging.  they show long and short examples This is an example of the script: require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: script_name.rb [options]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|   options[:verbose] = v end end.parse! p options p ARGV # Actual script co...

Ruby script for downloading rails casts

Ryan Bates continuously provide useful Rails tips in this railscasts.com . I had written a bash script for downloading the videos of the episodes in the past. I do not like streaming much and I'd rather keep the episodes for reference. One downside of the script is that I had to check the rss feed or the website for new episodes, and run the script manually passing the correct paramters (start and end of episode ids to be downloaded) Now I decided to get rid of the silly step. so I ported my script to ruby, and it runs down to download whatever episodes are missing using the rss feed and checking what is already present. The script uses simple-rss gem, so you'll have to get that installed. It also uses wget for downloading. I didn't bother using net/http of ruby, wget is fine for me as a linux user. The script flow is simple: Check the current files in the download directory (collecting information) Grab the rss of railscasts.com Iterate over rs...

Patron: a Ruby HTTP client library

I was just trying out Patron , the new ruby client library, by Phillip Toland . Patron is based on libcurl. and providing nice usable interface, which allows you to make http requests easily and with as much customization as you need. Let us take a quick usage sample here: irb(main):036:0> require 'rubygems' => false irb(main):037:0> require 'patron' => false irb(main):038:0> sess = Patron::Session.new => #<Patron::Session:0xb7a9f878> irb(main):039:0> sess.base_url = "http://www.google.com" => "http://www.google.com" irb(main):040:0> resp = sess.get("/intl/en/about.html") => #<Patron::Response @status_line='HTTP/1.0 200 OK'> irb(main):041:0> puts resp.body Checkout the documentation for more samples and usage notes.

Adding Custom Routes for Radiant Projects

While integrating simple_captcha into the guestbook extension of radiant, I had to add a special route for the simple_captcha to work properly. Unfortunately, the routes file of a radiant project does nothing but loading the routes file from radiant gem itself: load File.join(RADIANT_ROOT, "config", "routes.rb") Calling ActionController::Routing::Routes.draw again will clear all the routes that have been defined in the gem routes file. So you have to either modify the code of the gem, or copy the code from routes.rb of the gem radiant to the projects route file. Or you can append your new routes using add_named_route instead of draw . And since the simple captcha route is supposed to be defined before radiant routes. you can manipulate the routes array as in the last line of the following sample. load File.join(RADIANT_ROOT, "config", "routes.rb") ActionController::Routing::Routes.add_named_route(        'simple_captcha',        '/...

A closer look at ruby gems

Have you ever been stuck at "Bulk updating Gem source index for http://gems.rubyforge.org/" while installing a gem?!Due the to the latest drop in the Internet connectivity in the middle east and my own country, Egypt, installing gems started to be like hell.. I had to wait for hours before having my library installed so I decided to have a closer look. surprisingly.. it was due to a bug in rubygems 1.0.1. You can easily overcome this by updating to the latest gem 1.3.1 through gem update --system Gem downloads libraries metadata about all available gems in a gem server. by default we have gem source "http://gems.rubyforge.org/" and recently i added "http://gems.github.com".gem saves this data in a cache file before it performs the required operation, so it doesn't have to download it again the next time. Part of the code that reads the cache looks like this: MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16 } #... # Load custom marshal format, re...

Prawnto, Generating PDF in Rails Applications

Rails wiki lists a number of libraries that can be used to generate PDF files in ruby . Prawnto was very suitable for my need (generating PDF files that contain text with differentfont-size and adding some formatting). Prawn is able to generate more complex PDF documents including adding photos. You can check the installation steps online Prawnto requires you to add code to your controller and to a .prawn layout file. There are several demos available online and can be used as guidance. Below is an example for generating a PDF format of an article. The article has a title and an array of blocks , each block has title and content . The controller code is: def show    @title="My Article"    @blocks= [          {:title=>'Block One', :content=>'content one'},          {:title=>'Block Two', :content=>'content two'},         ...

Writing Prettier Ruby Code with instance_eval

instance_eval is a method of ruby Object class that lets you pass a string of ruby code or a block to be evaluation in the scope of that object. Through instance_eval you can actually add new methods to a particular object. This can help you write more pretty and readable code. for example, we can define a new average method for an array of numbers >> a = [1, 2, 3, 4, 5, 6, 7, 8] => [1, 2, 3, 4, 5, 6, 7, 8] >> a.sum => 36 >> a.size => 8 >> a.average NoMethodError: undefined method `average' for [1, 2, 3, 4, 5, 6, 7, 8]:Array     from (irb):14 >> a.sum / a.size => 4 >> With instance_eval we can add that new method here a.instance_eval do     def average ; sum/size end end >> a.average => 4 In a lot of cases this approach can be useful.

has_and_belongs_to_many & Duplicate entry Error

In one of my Rails projects at eSpace , i had a Many to Many association between two models. this allowed me to look more deeply into the has_and_belongs_to_many association. When you say: class Question    has_and_belongs_to_many :surveys end class Survey    has_and_belongs_to_many :questions end Rails will assume there is a table questions_surveys that include foreign keys to the two entities. So this table should be created by the following migration create_table :questions_surveys,:id => false do |t|     t.integer :question_id, :null => false     t.integer :survey_id, :null => false end :id=>false will prevent the creation of the default primary key for that table.This is very important for has_and_belongs_to_many associations. as the API documentation say; other attributes in thatrelation will be loaded with the objects and will be read only, including the :id. So failing to disable the id generationfor that table wi...

Setting Up RubyOnRails Development Environment on Ubuntu 8.04 Hardy

I started a new fresh installation of Ubuntu 8.04 (Hardy).. i needed to prepare my machine for RubyOnRails development. Below are the steps i need to make: Installing Ruby, Rails, MySQL Install MySQL apt-get install mysql-server mysql-client Install Ruby (1.8.6) and gems apt-get install build-essential ruby irb rdoc ri ruby1.8-dev libzlib-ruby libopenssl-ruby1.8 rubygems libmysql-ruby1.8 Update gem gem update --system rm /usr/bin/gem ln -s /usr/bin/gem1.8 /usr/bin/gem Install Rails & Mongrels gem install rails mongrel mongrel_cluster Installing rails 1.2.5 (needed in my project) gem install rails -v 1.2.5 --include-dependencies Move the mongrel_rails, rails and rake to the /bin directory ln -s /var/lib/gems/1.8/bin/mongrel_rails /bin/ ln -s /var/lib/gems/1.8/bin/rake /bin/ ln -s /var/lib/gems/1.8/bin/rails /bin/ This makes us done with the basic ruby and rails installation. Installing RMagick Rmagick is an image processing library that is needed by some rails projects (including m...

Heads Up With Radiant CMS

Radiant is an open source RubyOnRails based Content Management System, designed for relatively small websites. One of the nice things about radiant is that it the templates themselves are stored in the database like ordinary content, making all interactions with the site once it is deployed through the administration interface. In radiant, a page can be composed of several named parts. Parts of the interface that is shared among several layouts (like navigation bar, footer, header) can be stored in snippents . Using snippets, layouts and page parts helps the site creators to elegantly build and maintain their website. Some features that is beyond a CMS, like having a page that sends emails or a form that stores data somewhere, can be obtained through radiant extensions . let's start a new radiant project: first you need to install the radiant gem gem install radiant --include-dependencies then create a new radiant project specifying the database engine used. radiant --database m...

Introducing BDD with RSpec

Behavior Driven Development (BDD) is an approach for software development combining the advantages of Test Driven Development and Domain Driven Design . It helps the team of the project focus on the exact requirements of the client in a verifiable manner. In TDD, we had acceptance tests that verify the correctness and completeness of the feature once they pass. Those tests are written by the developers at the beginning of an iteration. A weak point though is that those tests were written in a programming language (java, ruby, ..) nothing that the customer can understand. BDD introduces a common vocabulary among all people, that is simple text, something that even the customer can understand and write. RSpec is a ruby framework that helps with the implementation of BDD. It is really an interesting project. RSpec started with what they call now the "spec framework", this framework describes pieces of the application model through by specifying characteristics and actions th...

Posting Messages Using Jaiku API through Ruby console

Jaiku is considered a nice communication method among a group of friends or colleagues in a small company or so. One major strength of jaiku is that it has a lot of notification methods about updates. users can receive notifications through sms, IM or throught jaiku website. I wanted to take a look at jaiku API . so i can use it in any application to send notifications to the rest of my colleagues. the user uses his username and API key to authenticate operations through the API Jaiku provides two interfaces that can be used to read/write jaikus. the XML-RPC and the JSON interface. xmlrpc behaved little strangly always responding with "XML-RPC server accepts POST requests only." even when i'm sending POST requests. i managed to use the json interface though just send a post request to api.jaiku.com/json with the parameters(username, api key, method, message) throught Ruby's irb i can send a note by typing: irb(main)> require 'net/http' irb(main)> da...

Overriding input components in active scaffold

One of the wonderful facts about Rails is that most stuff you need is already created for you, keeping you free to customize as you want. ActiveScaffold is one of the most powerful and widely used plugins in rails projects because it simply provide you with a complete CRUD for your model with minimum coding. The default view of the active scaffold is adequate for some applications, but not the most pretty. so is the input types used for the model attributes. Active Scaffold team helps us by providing and easy way to customize by overriding active scaffold defaults . In my application i had a boolean attribute "admin" in my model "user". that was showed as a drop down list having the values of true & false. Pretty ugly. I used partial form overrides to make it the more logical check box by adding app/views/users/_admin_form_column.rhtml with the following content:         is admin ?            'record[admin]'%> ...