Matt Allen asked an interesting question on the Ruby on Rails Aus mailing list today:
I’m porting an existing app that has over 190 tables in it and my models directory is getting huge.
Is there a way to organise your models into sub directories? It’s possible I’ve missed something obvious.
These days I like to arrange my STI-based models in subdirectories. For example in one app I have a Payment model with various subclasses. I store the subclasses in a directory of their own:
/app/models/payment.rb /app/models/payments/offline_payment.rb /app/models/payments/paypal_payment.rb
So how do you arrange your models like this without littering require’s everywhere? Just add them to the load_paths config array in environment.rb:
config.load_paths += %w( #{RAILS_ROOT}/app/models/payments )
Now we can just refer to the payment subclasses and rails will automatically find the classes, require them and autoload them as neccessary:
class OfflinePaymentsController < ApplicationController
def new
@payment = OfflinePayment.new
end
end
As an aside, I’ve just added Dan Webb‘s Javascript CodeHighlighter with Justin Palmer’s VibrantInk TextMate bundle colours.
Looks purty sweet eh (time to hop out of your feed reader)!
I wonder if I can add a user script and customise the styles in NetNewsWire to get the same affect for all blog posts following this convention.
The only change I made was concatting CodeHighlighter into one file to reduce the page load by 4 HTTP requests.
Archived comments
Comments were previously allowed on articles. Though no new comments are being accepted you can see the old comments below.
-
Now if you’d just change the default code colour to something different to post text life would be sweet ;)
I like it, actually. Glad I got out of the feed reader!
-
That better?
-
You made me get out of Google Reader for that!?
Bastard.
-
How about this?
-
Another great tip from the toolman. I just started moving some of my sti models into subdirectories and noticed a small issue with your example:
config.load_paths += %w( #{RAILS_ROOT}/app/models/payments )… should use the
%W( ... )(capital W) syntax if you want interpolation.Also this:
config.load_paths += Dir["#{RAILS_ROOT}/app/models/*"].find_all { |f| File.stat(f).directory? }… will include all first level subdirectories without having to explicitly name them.
Two comments in one day. Next thing you know I might actually start blogging.
-
Damn it. I put class=“ruby” in my
codetags and your comment system (or maybe redcloth?) ate them.Your fancy javascript highlighting code too good for my snippets? … maybe I’ll just take my little nuggets of wisdom elsewhere.
-
Reverse engineering my code highlighting now Myles? hah! That’ll teach you.
Yeah over these hols I’m going to boost up this site a bit… I’ll make sure people can preview, as well as post pretty code snippets and be updated to follow-up comments.
-
Nice one on that snippet btw. Sooner or later we could tumblelog this stuff.