Loading custom code in Rails

This is a question I’ve seen asked (including by myself) in #rubyonrails on Freenode quite a few times, and I figured I’d settle it once and for all. There’s a few different ways to get custom code loaded into your Rails app. The first solution to this is understanding how code gets loaded with Ruby in the first place, which I usually get confused with. Let’s do a little recap about your different options that Ruby and Rails provides:

load: Loads and executes the Ruby program in the file filename.

require: Ruby tries to load the library, returning true if successful.

require_dependency: Reloads source files on each request when in development mode, so changes are reflected on the next request.

require_or_load: There doesn’t seem to be much documentation on this, but it doesn’t seem as safe and it may result in your code being loaded twice. Review the code here before you use it.

So, the most ideal keyword to use is require_dependency, since it will reload code during development mode when you make changes. Otherwise, you’ll have to constantly restart your development server/console, and that just sucks. Plus, it’ll work perfectly in production mode and only load the files once.

So, where’s the best place to put the files with your custom code? Well, there’s a few folders that are on the Rails load path in the first place: app, lib, vendor and mock paths (source)

If you need to add different folders to the load path, that’s more than possible. In your config/environment.rb, add whatever folder you want in the config.load_paths variable. For instance,
config.load_paths += %W( custom )

This will load the custom directory (RAILS_ROOT/custom) to the load path so you can use those files. The problem with files you put in these directories is that they may be in the load path, but you’ll have to require the custom files you want in each class that you’ll want to use them. The solution to this is to get the file required for the entire Rails environment, which is a lot easier than you’d think.

Let’s say we want to load some extensions to String for your app. Being a forward thinking developer, you’ve created a new folder in lib, called core_ext, where you can put other ruby files in the future if you need to. So in lib/core_ext/string.rb you’ve dumped for example:

class String
  def slugify
    self.gsub(/[^a-z0-9]+/i, '-').chomp('-')
  end
end

The folder config/initializers contains files that run once when your Rails environment is getting set up. Create a new file in that folder and this will run through your custom folder and make sure that the files are required properly.

module CoreExtensions
  def require_core_ext
    Dir["#{RAILS_ROOT}/lib/core_ext/*.rb"].each do |f|
      require_dependency f
    end
  end
end
Object.instance_eval { include CoreExtensions }

So now, you can call

require_core_ext

in whatever class you want, and it will reload all of your custom code if you’re in development mode or if you’re in production, it will only load your custom classes when the file is first loaded. Now you can call

String#slugify

all you want, and if you make changes to the method in lib/core_ext it will be reflected when you refresh the page.

If you’ve got any other examples of how you bring in custom code, let me know, as I’d love to find out.

Permalink · Rating: · Written on: 09-22-08 · No Comments »

Switching to Rails

For a while now I’ve been obsessed working with Ruby on Rails. Rails has caused me to switch from doing .NET/ASP.NET development on my desktop PC using Windows XP to owning a Mac Mini and putting Ubuntu on Dell laptop. Obviously, this is a huge change, and I’m going to explain why I’ve switched.

Rails is a combination of software engineering principles and web programming best practices.

In this respect Rails is a dream: Active Record. RESTful architecture. Built-in xml/json/etc web services. TDD/BDD practices. I could go on and on, but all that matters is writing Rails applications is an enjoyable and fun process. You’re not writing scripts for pages, not having to worry about the nuts and bolts of creating a site, or dealing with painful XML files. Convention over configuration is a real path to productivity, and it’s going to take the other competing systems a long time to catch up to the headway that Rails is making on a daily basis. Rails isn’t the solution to everything, and it certainly has had it share of growing pains, but it’s being proven again and again as the most efficient way to create data-driven web applications that are very reliable and follow web standards.

Tools on *nix based systems are a lot better for Rails development.

DHH puts it best:

The stigma of being a Web programmer still using Windows will increase.

For me, it’s not that much of a stigma, but more of a practical issue. The power of the Unix command line combined with tools like Textmate makes development on OSX and Linux machines for Rails a LOT easier. The tools on the Windows side are there, but they’re usually not as powerful and not as easy to set up. Cygwin is piss slow. Most of the non-Visual Studio text editors suck. The command line sucks, and I tried really hard to make it not suck. Even Ruby is slower! All of this pain goes away on OSX/Ubuntu. Rails would be a lot different if it started on Windows, and I wonder if it would really be the same platform. For now though, I’m loving the productivity boost that I’m experencing and trying out different operating systems, and it serves my needs well.

Bleak future of .NET development.

This one will probably get me flamed the most.  It’s not that I don’t like .NET, it’s just that I couldn’t see myself using it any more professionally. I’m really not a fan of VB.NET, especially compared to Ruby. It’s a cruft filled language that makes me feel like Mort when writing it. Great things are possible with the language, but the result is so unreadable and ugly that I don’t feel it’s worth it anymore to use, especially if I can choose not to. C# on the other hand I love and always will, especially over Java.

What scares me more about .NET is where’s it’s going: Silverlight and WPF. WPF is supposed to be an awesome new platform that makes it easier for both programmers and designers to collaborate and create great applications. Seriously though, where are the great WPF applications? Why haven’t we heard as much about them, as say, the newest iPhone apps? I could say the same for Silverlight. Oh wait, the Olympics. ooh, Yahoo Messenger! Whatever. Nothing is going to kill Flash’s market share.

I’m sure that things have changed since I was heavy into (bleeding edge) .NET development 6-9 months ago, but still there seems to be no killer app for WPF or Silverlight yet. Until that happens they’ll just suck like everything else. I’d love to be proven wrong on this point, so if you know of one please show me.

If you’ve switched away from Windows or even if you’ve become a Rubyist/Pythonista in recent times, let me know what your experiences have been. For now on my blog posts will hopefully be a bit more frequent, and will chronicle various quirks and fun things I’ve found during my Rails journeys.

Permalink · Rating: · Written on: 09-18-08 · 8 Comments »