Archive

Archive for the ‘Rails’ Category

Extreme named_scope?

March 14th, 2009

By now, we all know that named_scope is one of the most useful Rails features ever. It’s the kind of thing that makes me wonder how I ever lived without it. I’m currently refactoring some old code and finding that using named_scope can make for some really long chains sometimes. They almost seem…too long.

For instance, I have an Update model which contains both news items (short blurbs) and articles (longer updates). Some articles are also for internal eyes only (via admin pages). When someone is viewing a news item, the 5 latest updates appear in the sidebar, but I can’t be listing the one they’re currently viewing!

In the tradition of small view / huge model, I’ve attempted to move all the logic into the model.

Model / update.rb

1
2
3
4
5
  named_scope :public, :conditions => "internal_only = 0", :order => 'updated_at desc'
  named_scope :news, :conditions => "update_type = 'news'"
  named_scope :articles, :conditions => "update_type = 'article'"
  named_scope :limit_to, lambda { |l| { :limit => l } }
  named_scope :except, lambda { |i| { :conditions => [ "id != ?", i ] } }

In a view or helper method (object = currently displayed item)

1
2
  news = Update.public.news.limit_to(5).except(object.id)
  articles = Update.public.articles.limit_to(5).except(object.id)

Now, this works great, but that’s getting to be a mighty long scoping chain. So, the burning question - can this chain ever get too long?

Rails, Ruby

Efficient TextMate Project Panels

January 23rd, 2009

I ran into an issue with TextMate recently: the Find in Project function (command-shift-F) was taking over a minute to run and consuming huge amounts of memory in the process.

Before you scold me, know that I’m already using the time-honored tradition of excluding bloated directories like vendor/rails, log, doc, etc. using a bash alias.

This time, the culprit turned out to be my public/uploads folder which apparently included some documents that TextMate didn’t like to search.

Solution
Exclude the entire public directory from my alias and only include the javascripts and stylesheets directories. This has the added benefit of making my TextMate project panel easier to work with. After a little more thought, I decided I could do without the apps directory as well. The new look:

My TextMate Project Panel

My TextMate Project Panel

The alias:
alias rtm=’mate app/controllers app/helpers app/models app/views config lib db public/javascripts public/stylesheets spec stories vendor/plugins &’

And, when I want to have access to the excluded directories:
alias rtma=’mate . &’

TextMate colored labels provided by the ProjectPlus plugin.

Rails, TextMate