Archive for the 'Rails' Category

AssetsGraphed At The Rails Way

Tuesday, 9 January 2007

You may recall that a while ago I mentioned The Rails Way, which is a site where Rails core team members Jamis Buck and Michael Koziarski review code submissions and illustrate Rails best practices. Well, the big news is that they’ve started reviewing my code! I submitted a subset of the code from the AssetsGraphed application and the first article about it was posted yesterday. Incidentally, in case you’re wondering what I didn’t submit, it’s the code for the Reports feature and for the hidden administration interface that I use to manage users and currencies within the system etc.

The first part of the series is about removing a lot of duplicated code around the incomings and outgoings that each asset has. I always knew that having so much identical code was totally evil, but I wasn’t quite sure how to go about removing it. As is often the way with these things, it does seem kind of obvious now! I have to admit that it’s quite nerve-wracking having my early fumblings with Ruby and Rails subjected to public scrutiny, but it’s also a great way to learn, which is why I’m doing it. I intend to implement all of the improvements featured, although some of them may be more challenging to do than meets the eye because I have the added problem of having to preserve the existing data. I don’t know how many articles are going to be in the series, but there’s certainly lots of areas that I know could be done better.

I’ve also just launched the AssetsGraphed Forums where you can post any feature requests or bug reports or just generally hang out. I’m using Josh Goebel’s and Rick Olson’s Beast forum software. Go take a look!

AssetsGraphed On Rails Machine

Wednesday, 3 January 2007

I’ve just finished moving AssetsGraphed over to Rails Machine. The application was originally hosted by TextDrive, on the same server as this site. I don’t have any complaints about TextDrive but it was clear that I needed something more substantial for AssetsGraphed. I have lifetime hosting with TextDrive which is fine for websites but problematic for Ruby on Rails applications, as you’re limited to 48 MB resident memory and 80 MB virtual memory. If your application exceeds those limits—which are pretty generous for a shared hosting environment—then your Ruby process gets terminated without warning and it’s goodnight to your app. This was proving to be a problem for AssetsGraphed, which is fairly memory intensive due to the image processing required for the graphs.

I did consider TextDrive’s other plans, in particular their Accelerator Hosting plans whereby you get a proportion of a Solaris box and root access. It sounded great but a bit too DIY for me. I don’t mind the odd bit of system administration but I’d rather be writing code with my developer’s hat on. Enter Rails Machine. I’d read good things about them and watched the demo movie on their site. The thing that appealed to me was that they make it really very easy to set everything up and deploy your application, leaving you free to spend your brain power on development. You use their Rails Machine RubyGem and custom Capistrano recipe and it all just works, as if by magic.

I went for a three VPS set up, as shown below. One virtual server is given over entirely to the AssetsGraphed Rails application, a second one will host the forthcoming AssetsGraphed forum and blog and the third is the MySQL database server that all the applications use. It’s a nice, tidy set up:

A diagram showing the configuration of my three Rails Machine virtual private servers

One of the things that I didn’t appreciate from the Rails Machine site is that the don’t provide any DNS services, so you have to bring your own. I signed up for the cheapest account from DNS Made Easy and all I had to do was go into my GoDaddy domain control panel and enter the names of the nameservers that DNS Made Easy provided me with. Then, in the DNS Made Easy control panel I set up the records for the assetsgraphed.com domain so that they pointed to the IP addresses of my Rails Machine virtual servers.

Because I went for a multiple VPS arrangement, I did have a few configuration problems where my set up deviated from the instructions on the Rails Machine site, which assumes a single VPS per app. For example, something that caught me out was that when I initially set up the Rails Machine for AssetsGraphed, the assetsgraphed.com domain was still pointing to TextDrive, so I set the domain variable in the Capistrano recipe (deploy.rb) to the non-friendly server address assigned to me by Rails Machine. When I did switch the domain over and accessed the application, all I saw was a Welcome to Rails Machine! holding page. That was fixed by setting the domain variable to assetsgraphed.com and then running:

cap setup_web
cap reload_web

—To configure Apache correctly. I should stress that I got excellent help with this and the other issues that I had by dropping in to the Rails Machine Campfire chat and talking directly to Bradley Taylor, who has always been friendly and quick to help, no matter what else he was occupied with at the time!

If you come to Rails Machine from other hosting providers like I did, then you may find it a bit bare-bones at first. As well as no DNS service, there’s no Web-based control panel. It’s all driven through Capistrano and the command line. However, don’t let that put you off because once you wrap your brain around it then it all works extremely well. What you do get for your money is a high performance Rails hosting solution, with the emphasis being on solution. All the hard work of setting up a Subversion repository, importing your code into it and deploying and running your application has been done for you. Highly recommended.

Introducing AssetsGraphed

Tuesday, 12 December 2006

I’ve just put my first Ruby on Rails application online. It’s called AssetsGraphed. It’s a free asset tracking application that also graphs your data. I created it as a vehicle for learning Rails and also because I needed a better handle on where my money goes!

AssetsGraphed lets you create assets and give them a starting balance. An asset can be anything financial that you want to track over time. For example, that dream holiday that you’re saving up for, a bank account, a retirement fund or even your pocket money. You enter incomings or outgoings against each asset and each incoming or outgoing is assigned a category, which might be something like Deposit for an incoming or Electricity Bill for an outgoing. You have complete control over your own categories. Oh, you can select which currency you want to do all this in too. There are eight to choose from, although it’s easy for me to add more. I made it default to the U.S. Dollar because that’s the nearest we have to a global currency. Don’t be offended if it’s not your currency, just select your own on the Settings screen.

An extract from the screenshots on the AssetsGraphed home page

The main AssetsGraphed screen gives an overview of all your assets and you can click them to drill down into the detail. Sparkline graphs plot the trends in the incomings, outgoings and overall balance for the asset. You can view or share asset activity by subscribing to its Atom feed. Yesterday I added a Reports page that for now just contains one report. It’s a pretty useful one though as it gives a breakdown of income or expenditure by category, either for all your assets or individual ones. So you can see the movement of your money very easily.

It’s important to understand that because AssetsGraphed is a learning exercise, it’s not a bulletproof web application. That means that it might crash, although I’ve been eating my own dog food on AssetsGraphed for just over a month now and it seems pretty solid. If it does crash on you then I’ll automatically get an e-mail about it and will investigate. You might find it a bit slow too. That’s because it’s actually running on the same shared server as this blog. I’m currently weighing up various options for moving it to a much more powerful hosting environment. I might even add SSL support too.

AssetsGraphed is just the first step on my journey to learn Ruby and Rails. There are lots of bits under the covers that I know could be done in better ways. I shall keep improving it as I learn more. There’s a really great community around Rails. I’d like to thank the Rails Weenie folks for patiently answering my questions and also Khoi Vinh for inspiring me with his Boxes and Arrows colour palette and letting me re-use it on AssetsGraphed.

Now that you’ve learned about AssetsGraphed and you’ve read the disclaimers, why not give it a try and let me know what you think?

Rails Tip #10: Listing Model Associations

Friday, 8 December 2006

You can use the built-in Rails console script to ask any model class for its associations:

Model.reflections.keys

—For example, let’s say we have a simple iTunes-like application in which a user can have one music library that contains many tracks:

class User < ActiveRecord::Base
has_one :music_library
.
.
end

class MusicLibrary < ActiveRecord::Base
belongs_to :user
has_many :tracks
.
.
end

class Track < ActiveRecord::Base
belongs_to :music_library
.
.
end

Now, firing up the Rails console and listing the associations produces the following output:

./script/console
>> User.reflections.keys
=> [:music_library]
>> MusicLibrary.reflections.keys
=> [:user, :tracks]
>> Track.reflections.keys
=> [:music_library]

Rails Tip #9: Don’t Load What You Don’t Need

Wednesday, 29 November 2006

If you’ve frozen a version of Rails into the vendor/rails directory then you can configure your application so that it doesn’t load frameworks that you aren’t using. All you have to do is uncomment the line below in your config/environment.rb file:

config.frameworks -= [:action_web_service]

—This example is instructing Rails not to load the Action Web Service framework, which is going to shave approximately a third off your application’s memory usage.

The Best Way

Thursday, 2 November 2006

One of the difficulties of learning a new programming language, framework or technology is that of knowing whether you’re doing things in the best way. Tutorials and books can only take you so far, then after that you’re flying solo staring at a terrifying blank screen in your editor or IDE. Of course practice makes perfect and hopefully if you care about your craft then you will acquire knowledge of best practice with experience. But what to do in the meantime; how do you ensure that you’re not setting off on completely the wrong footing?

Ruby on Rails is one of the kinder frameworks that I’ve come across in this regard, in the sense that it puts a lot of infrastructure in place to guide you on your way. For example, the project directory structure is pre-canned and there’s a nice testing framework in place, which leaves you free to just write the actual tests. There are also lots of smart people writing blog posts stuffed full of really useful information. You’ll find links for a lot of the best ones over there on the right. Also highly recommended is PeepCode, where in return for a small amount of money you get about an hour of video with the amazingly productive Geoffrey Grosenbach teaching you one-on-one about various aspects of Rails.

It’s not all perfect though. Like many people, the first Rails book I bought was the first one that came out: Agile Web Development with Rails. Unfortunately Rails is such a fast-moving target at the moment that much has changed since the book was published. Which means that the copy of the book sat on my bookshelf is full of code examples illustrating approaches that are out of date, or in the worse case, deprecated or just plain dangerous! That’s hardly the authors’ fault, it’s just a natural corollary of the growing pains that Rails is experiencing as it matures. And a completely revised second edition is on the way.

Recently I’ve been thinking that it would be great if I could somehow get a Rails expert to perform a code review of my Rails code because I know there are areas where I could do things in a smarter way, or where I have a gut feeling that I’m using an old technique. By amazing coincidence two members of the Rails core team have just announced a site that will do exactly that. The Rails Way is a new creation from Jamis Buck and Michael Koziarski where they’ll review code submissions and publish how and why they’d have done it. I’m really looking forward to seeing how this one goes—I think it’s going to be a big hit. Thanks guys!

Talking of Rails, I’ve recently been writing lots of tests and learning how to do that properly. The first thing I did was to download and install autotest, which automatically runs the appropriate tests every time you save a changed file. That way you get instant feedback on whether your change was successful or not. I also installed a Ruby code coverage tool named rcov by following these instructions. That gives me a nice HTML report which shows how much of my application code is being exercised by my test code. This is the first time I’ve really followed TDD techniques so vigourously and it’s paying off handsomely by giving me a much greater confidence in the correctness of my code.

Rails Tip #8: Learn From Existing Code

Sunday, 3 September 2006

Not really a Rails-specific tip this one, but worth mentioning because high quality open-source Ruby on Rails projects are starting to appear that you can learn from by studying their code.

  • Geoffrey Grosenbach’s Gullery is a photo gallery application built using Rails.
  • Rails Day 2006 was a 24 hour Rails development contest that was held back in June. Unfortunately the judging’s turned into a bit of a fiasco (no winners have been named yet), but you can grab the code from each team that entered straight out of the Subversion repository.
  • My current favourite is Beast, which is a brand new Rails’ project where the aim was to create a fully-functional discussion forum in about 500 lines of code.

One of the things that I love about Rails is the fact that every application has the same folder structure, so if you do decide to look at someone else’s code then you can immediately find your way around, which saves time.

Rails Tip #7: Listing Rake Tasks

Tuesday, 15 August 2006

Rake is Ruby’s equivalent of the UNIX make build tool. You can list all of the Rake tasks available from within Rails using:

rake -T

—Note the uppercase “T”.

Rails Tip #6: Resetting The Session

Tuesday, 4 July 2006

Rails makes it dead easy to clean up objects in the HTTP session. No need for anything as complicated as iterating over them and setting them to nil. Simply use:

reset_session

—within a controller.

Rails Tip #5: Clean Up Using Rake

Sunday, 25 June 2006

Rails comes with a number of Rake tasks for cleaning up various temporary files that get generated when you run your application.

  • rake tmp:clear Clear all files in tmp/
  • rake tmp:cache:clear Clear all files and directories in tmp/cache
  • rake tmp:sessions:clear Clear all files in tmp/sessions
  • rake tmp:sockets:clear Clear all files in tmp/sockets

—Rake can also clear the sessions table if you’re using one:

rake db:sessions:clear