Category Archives: Ruby on Rails

>Rails3, Rack and "Where did my Metal go?"


Our Rails3 (beta4) application had one route mapped in config/routes to a Sinatra app, by means of the following route:

   match '/foo', :to => EndPointApp, :as => :endpoint

The route was being defined to run as a Sinatra Application

require 'sinatra'
class EndPointApp < Sinatra::Application
  post '/foo' do

This was working mostly fine, but it was returning Set-Cookie header with the standard Rails sessions cookie, which in this case was preventing the client of this endpoint from successfully interpreting the result. As I could do nothing about the client side, I had to remove Set-Cookie from the headers, but only for this end-point and obviously not from the entire app. This proved to be somewhat more complicated than I had hoped, so let me share the solution here in hopes it might save someone else an hour or two.

First, I ran “rake middleware” and observed the following Rack stack:

use ActionDispatch::Static
use Rack::Lock
use ActiveSupport::Cache::Strategy::LocalCache
use Rack::Runtime
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::RemoteIp
use Rack::Sendfile
use ActionDispatch::Callbacks
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
use Rack::MethodOverride
use ActionDispatch::Head
run Kigster::Application.routes

As can be immediately seen from here, the routes execute very last after Session::CookieStore already wrapped the request. OK, so looks like I need to bypass the routes somehow, and so I started to look at Rails::Metal, which is supposed to run before all other processing.

Once I started to look for Rails::Metal, I realized pretty quickly that I am missing metal generator:

> rails g metal
Could not find generator metal.

After a few more rounds of digging around, it turns out that in Rails3 Beta4 Rails::Metal has been completely removed, because it is no longer needed in a Rack environment.

So I had convert my Sinatra module to a Rack module, and insert it into the Rack middleware stack before the Cookie/Sessions:

require File.expand_path('../../../config/environment',  __FILE__) unless defined?(Rails)

module Kigster
  class EndPoint
    def initialize(app)
      @app = app
    def call(env)
      if env["PATH_INFO"] =~ /^foo/

    def process_request(env) 
       req =
       params = req.params
       # do stuff
       [ 200, 
         { "Content-Type"   => "text/html", 
           "Content-Length" => "0" }, 

I had add the following to my config/application.rb to enable this Rack module, and have it run before the ActionDispatch::Session::CookieStore:

# config/application.rb
# require the file directly
require File.join(File.dirname(__FILE__), '../app/metal/kigster_endpoint')
module Kigster
  class Application < Rails::Application
    config.middleware.insert_after Rails::Rack::Logger, 

Now my handler executes before the session, and the result does not include Set-Cookie header.

Any other suggestions on how to make this any simpler, or more correct are as always welcome!

1 Comment

Posted by on July 26, 2010 in Ruby on Rails, Technology


>Rails3 and The Inevitable Fragmentation


I remember one of the early talks at the Canada On Rails in 2006 had a slide showing how many books one needs to read to be able to write web applications in Rails, versus Java.

Of course Java side had about 10 books: Java SE, Java EE, Hibernate, Struts/Tiles/JSF, WebServices, Ant, Maven, Eclipse, JUnit, etc, etc.

The Rails slide proudly showed the now hopelessly outdated “Agile Web Development With Ruby on Rails”, 1st edition.

Those were the times. Back then, during my work for myself and three other engineers managed to learn ruby, rails and build a fully functional e-commerce site in about 3 months. I was blown away by the productivity gains compared to Java, where months could be spent laying out the project, and creating all necessary infrastructure for builds, deployment, automated testing with or without the database, etc.

Fast-forward to 2010. We are on a brink of Rails3 release, and oh boy, has the landscape changed since back then. I would argue that in some ways, you may be better off with Java than with Rails today for a couple of reasons:

  • Rails moves very fast. Books published in 2009 are already outdated. That pretty much leaves blog posts and online documentation as the main source of information.
  • Blog posts are not written as well as books are, they are not edited and are often heavily biased. They are also often outdated, and they are also often hard to find.
  • Rails now supports swapping out view renderers (from Erb, to Haml for example), Javascript libraries (from Prototype to jQuery, etc), ORM layers.
  • Testing frameworks are now (I think) approaching on a dozen. Forget Test::Unit, now it’s all about RSpec, RSpec-Rails, Shoulda, Cucumber, WebRat, Selenium, TDD, BDD, ShmoDD. Hot Damn.
  • Finally, to make the matters “worse”, it’s become very trendy to replace RDBMS with a document-based databases such as MongoDB, CouchDB, or even a step further — with distributed data stores like Cassandra or Riak. As with any trend, people are doing this regardless of whether or not they actually need it. Although this part clearly has nothing to do with Rails.

As someone who is trying to “quickly” catch up on all the recent changes that happened in the last 18 months during which I did not do any major rails development, it feels like I have to learn a lot of things from scratch, and unlearn a lot of things too. Even though I had three-four years of production Rails experience building and That makes me wonder, how the newbies feel now joining the “new” Rails ecosystem. I am very curious to find out. I am guessing there is a lot of frustration and a steep learning curve required to master all the frameworks in isolation, and then bring them all together into the project. And that brings us back to where Java was exactly four years ago, and still is today.

I am not at all advocating for you all to go back to coding Java or COBOL :=) And I am absolutely not against Rails. But it’s about time we pull the curtain of naiveté and realize that RoR has become the complex multifaceted enterprise framework it was claiming to replace back in 2006, and to become proficient in it may take just as long, if not longer, then with Java EE.

Ironic? I’ll let you decide.


Posted by on July 8, 2010 in java, Ruby on Rails, Technology


>Integer Division with Modulus in Ruby, using Linear and Binary Search


I was recently chatting with someone about algorithms, and we were talking about efficient algorithm for implementing integer division with modulus, and how to make it efficient for large integers.

The following code snippet shows a class that implements two division methods, linear and binary. I wonder if there is a more elegant way to implement binary, please feel free to post to comments if there are. Also, any other faster methods are welcome.

# divide.rb
# Integer Divider Class that implements two algorithms for finding the 
# division result and modulus of two integers.
class IntegerDivider
  def self.linear n, d
     raise 'Cant divide by zero!' if (d == 0)
     multiplier = n * d = n)
     i -= 1 if (i*d > n)
     return multiplier * i, n - i*d, i

  def self.binary n, d
     raise 'Cant divide by zero!' if (d == 0) 
     multiplier = n * d = n) 
     return multiplier * i, 0 if (i*d == n) 
     i /= 2; j = i; cnt = 0
       j /= 2; cnt += 1
       sign = ((i + j)*d > n) ? 0 : 1
       i = i + sign * j 
     end until (i*d  n) 
     return multiplier * i, n - i*d, cnt
  def self.divide(how, numerator, denominator)
    before =
    (result, remainder, iterations) = self.send(how, numerator, denominator)
    after =
    puts "#{sprintf('%8.3f',(after - before)*1000)}ms #{how}" + 
         " (#{sprintf '%10d', iterations} iterations):  #{numerator} / " +
         " #{denominator} = #{result}, mod #{remainder}"
    return [result, remainder]

[:linear, :binary].each do |method|
  ARGV.each do |numerator|
    IntegerDivider.divide(method, numerator.to_i, 3)    

And some results of running it. Of course for large number like 100000000, binary search takes 24 iterations to get the answer, while linear … well 100000000. The total speed difference at such large number is big: 1524ms/0.012ms = 127,000.

> ruby divide.rb 10 100 1000 20000 100000000
   0.006ms linear (         3 iterations):  10 /  3 = 3, mod 1
   0.003ms binary (         1 iterations):  10 /  3 = 3, mod 1
   0.003ms linear (        33 iterations):  100 /  3 = 33, mod 1
   0.003ms binary (         5 iterations):  100 /  3 = 33, mod 1
   0.017ms linear (       333 iterations):  1000 /  3 = 333, mod 1
   0.004ms binary (         8 iterations):  1000 /  3 = 333, mod 1
   0.411ms linear (      6666 iterations):  20000 /  3 = 6666, mod 2
   0.006ms binary (        11 iterations):  20000 /  3 = 6666, mod 2
1524.712ms linear (  33333333 iterations):  100000000 /  3 = 33333333, mod 1
   0.012ms binary (        24 iterations):  100000000 /  3 = 33333333, mod 1
Leave a comment

Posted by on June 26, 2010 in Ruby on Rails, Technology


>Techtarget’s Java ServerSide Symposium 2009 Impressions


Just got back from Vegas where between Wednesday and Friday a small-ish java conference was taking place. This was my second one, the first being five years ago in 2004.

Of course it’s hard not to compare, and I find myself doing it anyway… I can’t help but feel that the excitement has left java server software. Remembering one of the very first java conferences in Sydney 1995, when it was still almost academic and less of an industry conference, I feel like we’ve come to an end of an era.

The tedious reality of maintaining enormous enterprise systems built over the the last decade has sinked in, and unfortunately there is nothing exciting about it, but everything difficult and complex. Those less fortune whose systems took advantage of EJB1 and EJB2s will suffer the most, as those are dying technologies and are rapidly being replaced by simpler more component friendly software.

The first set of simplification came with frameworks over the last five years – Spring and Hibernate being the most notable. Now the simplifications are being pushed out across language boundaries, because of the need to stay competitive against exploding Ruby on Rails community, and even smaller but still disproportionally more productive frameworks like Django, when compared to java.

Several talks focused on jRuby, and I think this is where the future power lies. Combining the two platforms, Ruby on Rails for web development, and server side java for multi-threaded, asynchronous, transactional behavior seems like a fantastic opportunity.

However nobody is yet talking about how this all works together in production. What does it mean to run a multi-app server distributed java application, with a RoR application hosted inside JVM and interacting with the service layer? What if service layer mixes ActiveRecord and Hibernate? Questions like this, while entirely logical in early evaluations of emerging technologies, were simply beyond the depth of TSSJS09.

But for what it’s worth, there was a decent overview of a multitude of scripting languages: javascript, ruby and scala, and a very impressive talk on Ruby meta programming.

There were several exciting news for me personally, the first having to do with Flex and BlazeDS integration in Spring 3.0. Basically what this means is that it’s now possible to build a typically modular and well understood server-side backend architecture in Spring, the client side in Flex, and have them directly converse over binary AMF protocol, which is highly compressed and optimized to send data back and force. I believe the entire stack is free, except Flex Builder Eclipse-based tool that’s not free. My exposure to Flex is minimal, but I love the ability to build beautiful application UIs that run consistently within the browser, and expose your backend in a way of clearly defined REST/XML api. And the load time in demos appeared significantly faster compared to java RMI applications I’ve had experience working with.

I’ll add part II in a couple of days.

1 Comment

Posted by on March 22, 2009 in Ruby on Rails, Technology


>Aptana – Please Don’t Suck Any Harder


I rarely rant about software. Reliable software is hard to make, and I know this because that’s what I do for living myself. But once in a while I come across such ignorance that a rant is really all I have left.

I’ve been coding in Ruby on Rails for over two years now, and have been using RadRails standalone, Eclipse with RadRails plugin, TextMate, IntelliJ IDEA and just good old plain Vim. But for the most part, I found myself very comfortable with RadRails because I liked the integrated environment for automated testing, outline views, project views, and all the goodies that are so nice in Eclipse, or IntelliJ IDEA if you work with Java.

Well, sometime back RadRails was abandoned by it’s young developers, who received a comfortable package from IBM, and the whole RadRails thingy somehow was inherited by Aptana, of which at that point nobody I talked to ever heard of.

What the heck is Aptana trying to do now, I still don’t quite truly understand, but I went along with the plan and switched. Instead of Eclipse, I had Aptana Studio, and for some time (while I assume Aptana’s contribution was merely the new name) things went well, and we all got along.

Well not anymore.

Aptana stopped being useful altogether with their most recent release, but things have been slowly creeping in even before that. The software now routinely spins at 100% cpu, the log file shows nothing useful, and a couple of versions back they broke Apple-Shift-R (although a later update fixed it), the command to pull up a resource by name after selecting a resource the whole thing would just crash.

So today I was like, “heck, let me reinstall the whole thing, maybe it’s my problem”? Huh. Not so fast.

Sure, I can download and install Aptana OK, but none of their bundled sweet plugins install at all. And what meaningful error message do I get when I try to install SubClipse? “Problem with your configuration”. And this is on a brand spanking new downloaded DMG. Sweet! Useful as a brick.

I am sorry, but the ignorance of Aptana Corp, who are now a proper company in San Mateo, trying to sell “Pro Version” as a worthwhile add-on while they can’t get their s**t together with the free community edition, just stinks to me of the worst kind of amateurism.

Thanks for ruining RadRails for me, Aptana Corp. At least it took a while to add enough of YOUR code to make things really break.

I wrote this post after hours of frustration, trying to fix my broken environment, and losing valuable time on a project that was falling behind.

I now realize that the post was overly emotional, and probably not entirely fair to the Aptana team. I’ll post updates here as I work through the issues to get my RadRails working again.


Posted by on April 22, 2008 in Ruby on Rails, Technology


>Ruby on Rails Hosting: From HostingRails to RailsMachine in a shake of a tail


Rails hosting is a hot subject, and with everyone asking everyone else about their experience, I thought its only fair to share my own experience, even though it is relatively limited.


I started with a shared “professional” hosting plan from HostingRails. It was around $30/month, and included non-root SSH access to a shared server, and additional 150Mb of RAM for total of 200Mb (although that’s actually quite misleading, see below). I stayed on this plan for about 3-4 months, and then decided to switch to a virtual hosting plan from RailsMachine – their single server plan, for about $100/month (that includes dedicated 384Mb of RAM and a root access to my virtual server). This post describes the reasons behind switching, and compares pros and cons of each hosting plan. Our needs included the following setup:

  • One application running in two instances (one production, and one test)
  • Two-mongrel instances per application (so total of 4 mongrels)
  • Capistrano based deployment / upgrades / restarts of the servers
  • Apache 2+
  • PostgreSQL 8.2
  • Trac (+ MySQL) served over https
  • Subversion repository served over https
  • Subversion post-commit hook linked to a build environment, for continuous integration
  • Automated remote daily backup of the entire environment

To be fair, the plans described here compare sort of like apples and oranges, so the review has to be taken with a grain of salt. Main differences are, of course, in the fact that one is a shared plan and the other one virtual hosting. People on smaller budget and without tight performance requirements will probably prefer the shared plan, while those with a bit more room in the budget and some UNIX know-how will most likely be much happier with virtual hosting. My hope is that perhaps this review will help someone make the right call for their environment based on their needs, budget and experience.

Detailed Comparison

1. HostingRails

  • Pros
    • Cheap, only $30/mo for 4 mongrel instances (200Mb)
    • Easy Trac/SVN install
    • Rudimentary backup can be run from web UI
    • Friendly support staff
    • Timely support, usually within an hour or two
    • Lots of info on forums
  • Cons
    • [Update: please see comments section for HostingRails response]. Slow, slow, and slow. We were sharing a server with 4Gb of RAM with another 50+ mongrel instances run by as many users. The server used over 1Gb of swap space and often showed load averages over 30. We were promised numerous upgrades, which did not materialize while we were using the service. Our sites and Trac at times took over 30 seconds to load the first page, probably while the corresponding process was getting un-swapped.
    • Have to email support for any changes to top-level apache configuration, such as adding domain aliases. This applies to setting up Trac, svn and mongrel apps.
    • Provided backup facility does not backup PostgreSQL/mysql DB, had to write our own script (but forums had a good starting point)
    • Our mongrels clearly were not allocated any amount of “reserved” RAM. Looks like buying extra 150Mb in reality means you can run three more mongrel instances, but has nothing to do with how much RAM you actually get, as was witnessed by swap usage stats.
    • As we decided to move because of performance issues, HostingRails refused to refund us the unused portion of the yearly fee we paid ahead as we were past first 30 days.
    • Locked in their choice of Ruby version, gems, PostgreSQL, MySQL, Trac – can not upgrade these individually, as each is shared among many clients.

Overall, I think that HostingRails has to fix performance issues and not pack as many clients on a single server if they want to be a viable solution for any business. Until they fix performance issues I would NOT recommend this service to anyone. If the performance is fixed, I would recommend this plan to less experienced engineers, who may not know how to use root on a UNIX system, or setup Apache, but have some basic understanding of Rails deployment. I would also recommend this plan on those with a really tight budget.


RailsMachine provides virtual hosting, meaning you get your own dedicated server with root access. The server, OS and pre-installed software details can be found on RailsMachine website. Because you are sort of expected to use root access, some basic UNIX system administration skills are necessary to take advantage of this plan. However, the flexibility and power that come with this solution by far outweigh the additional $60/month we are paying for our own box. Note that we could pay only $75/month for 256Mb of RAM, but considering the list of applications we wanted to run, I chose to upgrade our plan to at least 384Mb.

  • Pros
    • Much, much, much, faster. When using command line, sometimes you see server “hanging” momentarily while presumably other virtual machines are being processed, but the overall performance improvements are quite dramatic. Pages (trac/mongrel) load within 1-2 seconds consistently.
    • Fantastic provided Apache configuration, comes with plenty of dynamically compiled modules, template config files and modular structure. Our single apache server is providing umbrella access to both mongrel apps, SVN over https and Trac over https (using mod_wsgi, not CGI).
    • RailsMachine gem allows seamless initial capistrano deployment and subsequent installations
    • Apparently each virtual server is backed up automatically (but we do our remote backups anyway)
    • CentOS Linux provides convenient yum utility for installing pre-built packages. Sometimes it takes a few minutes to find the right package using “yum search” but once found, installation is a breeze.
    • Root access allows installing what you need for your environment, eg – latest PostgreSQL, latest Trac, etc. Was able to install mod_wsgi module to enable much faster Trac access than using traditional CGI access.
    • Our entire setup described above takes up 180Mb of RAM, with another 180Mb left for file system caching. Pre-installed MySQL and Apache are built with multi-threading enabled, so the processes manage their shared RAM very effectively. This means we have room to add another 2-3 mongrel instances to the setup without affecting pricing of our plan.
    • Responsive, knowledgeable support, although just the nature of the setup means you have to ask a lot LESS questions if you know what you are doing, since you can get most of the things installed yourself without bugging them.
  • Cons
    • [Update: this has been fixed, see comments section] The server came installed with broken permissions on /etc/resolv.conf and /etc/hosts file. This broke host/domain name resolution from the host itself, until the permissions were set to allow read access to the above files.
    • Slightly more expensive.
    • Occasionally (but mostly rarely), shell access has a latency that appears to be CPU bound by the physical server and not the network.

Overall, I would absolutely recommend RailsMachine to a technically savvy engineers, who want freedom of their own box at a very affordable price. Ability to grow the size of the virtual box dynamically is also great – it’s very nice to know that when you need extra 1Gb of RAM, it’s there waiting for you (and your wallet).

Install Notes

A quick note about SVN/Apache configuration with authorization turned on. This has been mentioned on many SVN forums, but if you are setting it up, please be aware that mod_dav_svn contains memory leak that makes apache seg-fault during checkouts of a large repository tree (we are using authorization as well as authentication). I had to add the following clause to apache config for SVN directory to resolve to issue: SVNPathAuthz off This is what our SVN configuraiton looks like in case someone is looking for a complete config:

<VirtualHost *:443>

 SSLEngine On
 SSLCertificateFile /etc/httpd/sslcert/server.crt
 SSLCertificateKeyFile /etc/httpd/sslcert/server.key

 <Location />
       DAV svn
       SVNPath /var/lib/subversion
       AuthzSVNAccessFile /var/lib/subversion/conf/authz
       SVNPathAuthz off

       AuthType Basic
       AuthName "Authorization Realm"
       AuthUserFile /var/lib/subversion/conf/passwd
       Require valid-user


  1. Memory Leak in mod_dav_svn

Closing Notes

Here are the responses I got from HostingRails and RailsMachine – thanks guys…

Hi Konstantin, The issue with broken permissions on hosts/resolv/others has been fixed. It was due to a small (and short-lived) bug in our provisioning system. Thanks for mentioning us! -Rob at Rails Machine

Hi Konstantin, there’s a couple things I’d like to point out that I hope you’d be willing to correct in your review. I understand that you had a bad experience with us and respect your right to voice it.

  1. Running a cluster of 4 Mongrels will only cost $22/mo on our professional plan, and $26, $32/mo on our business and platinum plans, respectively.
  2. On our site we outline that we’re selling (physical + virtual) memory in blocks of 50MB on shared servers — when Mongrels or Static FastCGI instances are fired up they consume (’reserve’) these resources persistently.

Overall, and I suppose you’d have to take my word for it, your server ran into an unfortunate resource situation with a number of users who are now either suspended due to malicious behavior or upgraded to dedicated environments due to extraordinary growth of their apps. Most of our clients are having good hosting experiences with us and we’re working hard to maintain fast and reliable shared servers for Rails deployment at the lowest possible price. All the best, ~William at HostingRails

— William, thank you for your corrections and I appreciate that it must not be easy to maintain quality service at such a competitive price. I’ve updated the pricing I mention and added a reference to your comment. I am willing to believe that our server may have been exception rather than a rule, and I hope that in the future you have a way to move clients off loaded machines quickly.


Posted by on October 16, 2007 in Ruby on Rails, Technology


Ruby on Rails Hosting: From HostingRails to RailsMachine in a shake of a tail

This posting has moved:

Ruby on Rails Hosting: From HostingRails to RailsMachine in a shake of a tail


Posted by on October 16, 2007 in Reviews, Ruby on Rails, Technology