June 25th, 2008 benhughes
I fairly often use the acts_as_tree plugin in my applications. While acts_as_nested_set (and superior variants..) is more powerful, often times a simple two-level deep hierarchy is all I need and acts_as_tree is simple. I’ve found the new named_scope functionality in Rails 2.1 to be very helpful when dealing with tree data structures.
Firstly, it’s somewhat rare that I have one single root node in the tree structure (which is apparently how it’s meant to be used). Instead I’ll have multiple “parent” nodes designated with a NULL parent_id and children beneath. In the past I’ve always done something like: find(:all, :conditions => {:parent_id => nil}) to grab the top entries. Instead with nested set you can do this:
named_scope :top, :conditions => {:parent_id => nil}
#Then:
Category.top
Another common task when dealing with hierarchical categories is to query on the base object (products for example) for members that are “part of” that category. Specifically, part of in a 2-level heirarchy simply means “where id = ? or parent_id = ?” on the joined categories table. Because this involves a join it was somewhat clunky to do before. Now with nested set, on the product model I can declare this:
named_scope :in_category, lambda {|c| {:include => [:category], :conditions => ["categories.id = ? OR categories.parent_id = ?", c, c]} }
# Then:
Product.in_category(3)
I would also highly encourage you all to check out RailsCasts Episode 112 “Anonymous Scopes” by Ryan Bates where he outlines a pattern for handling conditions elegantly with searches using named_scopes in Rails 2.1, something I’ve always found to be lacking from Rails core and always resorted to using plugins like criteria_query.
Posted in Rails General, Rails Techniques, Rails Tools | No Comments »
April 12th, 2008 benhughes
I had an opportunity to play around with Phusion Passenger (mod_rails) which was just released yesterday. Before yesterday all that was available was an introductory video showing Passenger being configured, and I was quite impressed by it’s ease. Clearly one of the problems with Rails as a major platform right now is it’s hosting situation. Currently the best solution is to proxy HTTP requests from Apache or Nginx to a cluster of mongrels, which is tricky to set up and somewhat tedious - certainly not as as easy as a mod_php in Apache where things “just work”. Phusion set out to overcome this problem and release a module for Apache that hosts Rails applications easily. Here is what took me from a clean Ubuntu 7.10 slice from SliceHost to a working server with Passenger:Starting OutTo start out, I used the following *excellent* SliceHost articles to get some of the basic packages installed such as Ruby and MySQL:Ubuntu Setup - Part 1Ubuntu Setup - Part 2MySQL and RailsApache and PHPApache Virtual HostsVirtual Hosts & PermissionsNote my permissions gotcha below - you may not want to strictly follow their permissions advice (where the global does not have read permission).I also installed sqlite3 as this is now the default database package used in Rails 2.0:
$ sudo aptitude install sqlite3$ sudo gem install sqlite3-ruby
Installing the Passenger Apache ModuleUsing the simple instructions on the Passenger website, I ran:
$ sudo gem install passenger$ passenger-install-apache2-module
The passenger-install-apache2-module binary walks you through the installation of the Passenger. On the first run, it told me I didn’t have some software that was required:
* GNU C++ compiler... found* Ruby development headers... found* OpenSSL support for Ruby... found* RubyGems... found* Rake... found at /usr/bin/rake* Apache 2... found at /usr/sbin/apache2* Apache 2 development headers... not found* Apache Portable Runtime (APR) development headers... not found* fastthread... foundSome required software is not installed.But don't worry, this installer will tell you how to install them....* To install Apache 2 development headers:Please run apt-get install apache2-prefork-dev as root.* To install Apache Portable Runtime (APR) development headers:Please run apt-get install libapr1-dev as root.
Clearly the installer detected I was running Debian-based Linux and told me exactly what to do. No compile errors or nasty dependency issues, just simple and clear instructions. After installing the requisite software the installer compiled the Apache module and spit out this:
The Apache 2 module was successfully installed.Please edit your Apache configuration file, and add these lines:LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-1.0.1/ext/apache2/mod_passenger.soRailsSpawnServer /usr/lib/ruby/gems/1.8/gems/passenger-1.0.1/bin/passenger-spawn-serverRailsRuby /usr/bin/ruby1.8After you restart Apache, you are ready to deploy any numberof Ruby on Rails applications on Apache, without any furtherRuby on Rails-specific configuration!
Note that it didn’t find or attempt to find where apache modules are installed as the actual compiled modules is kept within the Ruby gems directory, it just told me what lines to include in my Apache configuration file. The last part of the installation says:
Deploying a Ruby on Rails application: an example.Suppose you have a Ruby on Rails application in /somewhere.Add a virtual host to your Apache configuration file,and set its DocumentRoot to /somewhere/public, like this:<VirtualHost> ServerName www.yourhost.com DocumentRoot /somewhere/public</VirtualHost>And that's it!
Now this is pretty cool… Passenger doesn’t even require virtual hosts to configure themselves as Rails applications. It will automatically detect a Rails application (I’m unsure of the actual criteria here) based on the DocumentRoot that you provide.So I added the necessary lines specified above to /etc/apache2/apache2.conf to load the module. Note that some deployments of Apache have their own way of managing modules; in Ubuntu there is a mods-available directory with individual configuration files for each module. You could split up the above commands to follow the convention for your system of choice, but for my purposes I just dumped the three lines into apache2.conf.Then I created a new Rails application and pointed DocumentRoot to the Rails public directory. Restart apache, and the site should then immediately work with no further configuration.Permissions Gotcha - Important!If you get:
RAILS_ROOT is not a directory.
The first time I got to this point I was running into an extremely obscure problem - Rails was reporting that RAILS_ROOT wasn’t a directory. After some debugging which involved hacking up the gem source code of both Rails and Passenger, I realized it was a permissions issue (what do you know). Passenger reports that it will run your Rails application as whatever user owns environment.rb. However, it will set the effective group to that user’s primary UNIX group, NOT the group that environment.rb is owned by. In my case, I set the group of all of the web files to www-data and no read or execute permissions whatsoever for other. I figured this would be sufficient since Apache runs as www-data. But in my case when Passenger got spawned, it got spawned running as bhughes:bhughes NOT bhughes:www-data, so it effectively couldn’t find the RAILS_ROOT directory and didn’t think it existed. You can design your permissions scheme however you want, but make sure you keep this in mind. I have an enhancement in Passenger’s ticketing system for fixing this and allowing you to manually set the effective group (you already can explicitly set the effective user through the RailsUser option).More Passenger ConfigurationThe Passenger User’s Guide is pretty good and includes some more specific configuration options you can choose, but the default appears to work fine. The Rails environment is by default set to “production” though this can be changed (sadly, only server-wide, not on a virtual-host basis - but there is an enhancement in the issue tracker for this feature).Restarting Your AppRestarting a Rails app hosted by Passenger is easy - simply touch a file called tmp/restart.txt within the Rails application root:
$ touch tmp/restart.txt
CapistranoBrian Ketelsen pointed out this Capistrano configuration which uses the touch tmp/restart.txt approach to restart and removes the .htaccess file which can cause issues:
namespace :deploy do task :start, :roles => :app do end task :stop, :roles => :app do end task :restart, :roles => :app do run "touch #{release_path}/tmp/restart.txt" end task :after_update_code, :roles => :app do run "rm -rf #{release_path}/public/.htaccess" endend
Diagnosing ProblemsOne of the absolutely wonderful things about Passenger is that problem diagnostics (regarding starting your Rails app) is fairly easy because Passenger includes its own nice error pages:Database Error ExampleFramework Initialization ExampleMemory ManagementOne of the issues with mongrel or thin is that they are constantly running and sucking up memory, even for sites that get very little traffic. This leads to a situation where hosting very low-traffic sites is very inefficient from a system resources perspective. This isn’t the case with PHP where memory usage spikes during traffic but is otherwise unused, allowing multiple sites to leverage the on and offs and maintain a pretty efficient hosting platform as far as memory is concerned. One of the great feature of Passenger is that you can configure it to automatically shut down your Rails application if it is idle for a certain period of time. Doing this obviously exerts a cost then on the next hit, but this may be an acceptable tradeoff for a server hosting many low-traffic sites. The configuration option is RailsPoolIdleTime and there is more information on this in the user guide.ConclusionObviously my introduction here doesn’t go in-depth into performance and ability of Passenger to scale. Time will tell as people begin using this whether it is a viable solution for Rails hosting, but for me installing this and getting it to work was dirt simple, at least compared to the mod_proxy_balancer setup with mongrel clusters I have used in the past. I’m not quite ready to actually host my sites using this but I’ll definitely be keeping my eye on this - it could be a major step forward in the proliferation of Rails hosting.
Posted in Rails General, Rails Tools | 17 Comments »
December 28th, 2007 benhughes
This Christmas my parents got me an Apple giftcard which I promptly used to buy a new 2.2Ghz MacBook. With next day shipping, I had it in my hands at 10:30 yesterday morning (27th) – pretty fast!
All day yesterday I was setting stuff up (and to some extent today) and I think I’ve finally got everything moved over. I also invested in 4 gigs of memory from Newegg for only $110. Because of the small screen, I’ve found Leopard Spaces invaluable. I still have quite a bit to learn, but I’m glad I made the switch. I can finally start developing with TextMate.

Posted in Personal, Rails Tools | No Comments »