Posts

Showing posts with the label rails

Utilizing Page Caching while using query string parameters using Nginx

One of the common practices for ruby on rails developers is to wrap all parameters in the URI itself, so they can easily make use of page caching. Sometimes having a lot of parameters can start being confusing specially with the ordering of the parameters to match the defined routes. Let's elaborate with an example. Consider an API that provides a list of entries, with possible filters: http://api.example.com/feed.json This can simply be page cached, rails will place the proper feed.json file in the public directory. If we wanted to add use some supported filters like: date (in the format of 2012-03-25) order (by date, score or relevance) page (used to get the next pages of the feed) limit (or the page size.. the expected number of entries per response) type (some app related filter. let's assume the values can be: post, comment, announcement) If we used the simply form of http://api.example.com/feed.json?date=2012-03-25&page=2&limit=20&type=comment&order=score ...

Rails 3 "couldn't parse YAML" error suddenly showing up

I have been developing on the latest Rails 3, Ruby 1.9.2 for a while. and suddenly in 2 projects I started to get this YAML loading error when I try to start my server or run the tests. bundler./home/mahmoud/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/psych.rb:148:in `parse': couldn't parse YAML at line 55 column 12 (Psych::SyntaxError) from /home/mahmoud/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/psych.rb:148:in `parse_stream' from /home/mahmoud/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/psych.rb:119:in `parse' from /home/mahmoud/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/psych.rb:106:in `load' It turned out to be related to my recent upgrade of bundler to 1.0.10 After this update, my database.yml was not considered a valid YAML file. until I realized I have to put the special character values (for example: asd@#$asdf@$@) between double quotes. This fixed the problem for now I also came across another approach that basically will use a different YAML engine, This is wi...

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...

Presenting NeverBlcok in rubykaigi 2009

Mohammad Ali's presentation of NeverBlock .

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',        '/...

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'},         ...

REXML Error when running rcov

Rcov is one of the tools we use at eSpace to measure automated tests coverage for our rails applications. By rcov through gem install rcov , I had rcov(0.8.1.2.0) installed. After upgrading to the latest ubuntu 8.10, I realized that the installed rcov is not compatible with ruby 1.8.7 that i have. Rcov failed at generating the html reports with this stacktrace /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `[]': no implicit conversion from nil to integer (TypeError)     from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `wrap'     from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `wrap'     from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:90:in `write_text'     from /usr/lib/ruby/1.8/rexml/formatters/default.rb:50:in `write'     from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:75:in `write_element'     from /usr/lib/ruby/1.8/rexml/formatters/prett...

Creating Functional Tests for Restful Authencation based websites

At eSpace we stress on having automated tests to cover our code. If you are using Restful Authentication plugin in your rails application, You will have to bypass the authentication filter that is processed before your controller actions.Restful authentication helps you does that through the login_as() method of the AuthenticatedTestHelper module. Let me show you how. In your functional test, login before you send the request.    class PublicationsControllerTest        fixtures :users        def test_method           login_as (:user_one)           Your test code...        end    end That user is loaded from the users fixtures and will act as the current logged in user. The fixtures must have something like: user_one:     id: 1     login...

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...

Building interactive web pages using AJAX and RJS

When we talk about interactive web applications, AJAX is one of the most important technologies. Rails provides an easy way to use Ajax in your web site through RJS. RJS helps you make and ajax request and have several page elements updated correspondingly. Implementing Ajax requests using RJS is a simple matter of doing the following: Include the requried javascript files. Use the right rails tags to launch an ajax request. Declare that your action in the controller can respond to rjs. Define the rjs response (the changes to the DOM). Any rails application has the javascript files (prototype.js, effects.js, dragdrop.js, controls.js, application.js) by default. All you need to do is to include them in your layout file by adding: Rails provide 'remote' alternatives for its link and form tags link_to_remote vs link_to form_remote_for vs form_for and form_remote_tag vs form_tag. Using the remote alternative will cause the html tags generated to have a new AjaxRequest call; so whe...

Downloading Rails Casts

Rails casts is hosting Ruby on Rails video tutorials. It explains a lot of tips for development and how different rails components work. I highly recommend it for rails starters. I wanted to download all the previous episodes, that needed me to open the page of each episode, find the link for the mov file, and click save as. So i created a bash script to visit the links of the episodes and do the job automatically get_rails_casts.sh: #!/bin/bash for ((i=$1;i wget http://railscasts.com/episodes/$i -O- | grep -oi 'http://media.railscasts.com/videos/[a-z_0-9]*.mov' >> links done while read LINE ; do wget "$LINE" ; done Now the script can be used to download any range of episodes. below i'm calling it to download episodes from the episode #1 to episode #115 ./get_rails_casts.sh 1 115

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...

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]'%> ...