Archive for the 'Rails' Category

Rails Tip #12: Easy HTML Input Validation

Thursday, 19 June 2008

Not really a Rails-specific tip this one, more of a Ruby tip presented in a Rails’ context. Let’s imagine that your application accepts user input and you’re using HTML whitelisting to allow through a limited number of HTML elements, such as <a>, <strong>, <em> etc. This is fine, but you’ll also want to ensure that the user can’t enter badly-formed markup because that can seriously affect the rest of your page. Somehow you need to check that any markup entered is well-formed and inform the user if it isn’t.

It turns out this is easy to do using Ruby’s REXML module, which performs XML processing. For example, to validate a field named lyrics in a Track ActiveRecord model, you could add the following to the Track model class:


protected
def validate
  begin
    REXML::Document.new("<lyrics>#{self.lyrics}</lyrics>")
  rescue REXML::ParseException => exception
    errors.add(:lyrics, 'are not valid HTML.')
  end
end

—Note that the <lyrics> element in the REXML::Document constructor can be anything you like because it’s just there to provide a bit of an XML structure around the user’s input. Sending the message message to the rescued exception object will return more detailed information about why the parsing failed if you require that.

AssetsGraphed Hits 200 Days Uptime

Friday, 28 December 2007

I’m pleased to report that my AssetsGraphed Ruby on Rails application has been running continuously for over two hundred days now, as the screenshot below taken from my installation of monit shows. Okay, so AssetsGraphed isn’t exactly getting hammered like Facebook, but this level of reliability supports my decision to choose Rails Machine for hosting my Rails applications. Their choice of running Xen-based VPSs on Linux would appear to be a wise one and I know that 37signals themselves are moving in this direction.

A screenshot of the monit system management page for AssetsGraphed, showing 201 days uptime

The next milestone will be a year’s continuous uptime—let’s hope that posting this isn’t the kiss of death that takes AssetsGraphed offline! Happy New Year everyone.

Rails Tip #11: Add Plugin Repositories

Monday, 17 December 2007

It’s something of a secret that you can configure the source code repositories the Rails plugin manager searches when you instruct it to install a plugin. This can be handy if you’re installing several plugins from the same author. Such as this one. Or this one.

To add a repository to the plugin manager:

./script/plugin source http://svn.techno-weenie.net/projects/plugins/

To remove a repository from the plugin manager:

./script/plugin unsource http://svn.techno-weenie.net/projects/plugins/

To list repositories registered with the plugin manager:

./script/plugin sources

To discover and list repositories without adding them:

./script/plugin discover -l

One Small Step…

Friday, 25 May 2007

I just got a skeletal Ruby on Rails application running on a Java Virtual Machine using JRuby:

A picture of the Ruby on Rails welcome screen that shows the Ruby version as 1.8.5 (java)

—This is running on Windows XP which is running in a Parallels VM which is running on my Mac. To recap: it’s Ruby on Java on Windows on Mac OS X. Who could have predicted that a few years ago! Next steps: hook up a database and try to deploy a Rails application to a servlet engine. I think this could be very useful in future!

So True

Monday, 21 May 2007

I absolutely love this spoof commercial from the Rails Envy guys, so I make no apologies for embedding it here in case you haven’t seen it yet!

Deal Of The Century

Monday, 5 March 2007

That got your attention, didn’t it? Maybe not deal of the century, but if you’re a UK-based Rails developer then you owe it to yourself to check out the PeepCode subscription packs. Given the current weak state of the dollar it would be rude not to. I’ve just bought a ten-pack which cost the princely sum of £36.69. That’s over ten hours of properly produced video with Geoffrey Grosenbach teaching you Ruby on Rails. It’s a little known fact that over 85% of the Web is now comprised of Rails sites that Geoffrey has developed.† This boy knows his beans!

To put it into perspective, £36.69 is about the price of a decent dinner for two at ASK/Zizzi/Pizza Express/Strada/your favourite authentic Italian restaurant chain. That’s shockingly good value for money. Don’t you think it’s time you put down that Fettucine and did some Test-Driven Development?

The PeepCode videos are also available for video iPods, so whilst all the losers on the bus are filling their empty heads with County & Western songs about a man named Clint whose dog left him for another woman, you can be sitting pretty on the back seat learning all the Rails ninja moves like REST, Capistrano and RJS. If that doesn’t get you the girls then you’re on your own, squire. Please note that I’m not affiliated with PeepCode in any way, I just call it how it is.

Rails Envy

Thursday, 1 March 2007

Gregg Pollack and Jason Seifer have just started a great new Ruby on Rails blog named Rails Envy. They’ve got off to a flying start with tutorials on the Rails page caching mechanism and using the Ferret text search engine from within a Rails app. One to watch!

Installing Mint On A Rails Machine

Friday, 12 January 2007

I recently added Shaun Inman’s superb Mint statistics package to my AssetGraphed Rails Machine installation. As the installation wasn’t particularly straightforward, I thought I’d write this little guide for others who may be struggling. I should point out that the real credit for the information here goes to Bradley Taylor from Rails Machine who was extremely helpful and persistent.

First of all, I should point out that these instructions cover installing Mint under your /public directory i.e. yoursite.tld/mint/ rather than the subdomain installation method (mint.yoursite.tld). Also note that → indicates that the line has a break in it in the instructions, but in reality it should all be on one line. With that out of the way, here’s what you need to do:

  1. Install PHP on your Rails Machine using these instructions. You should have no problems with them if you follow them exactly.
  2. Log in to your Rails Machine as your deploy user then become root by using su - root and entering your root password.
  3. Edit /etc/httpd/conf/httpd.conf and search for DirectoryIndex index.html. Add index.php to the end if it’s not present as shown below and save the file:

    DirectoryIndex index.html index.php
  4. Edit /etc/httpd/conf/apps/yourapp.conf and add the following immediately after the RewriteEngine On line:

    RewriteRule ^/mint/$ /mint/index.php [QSA]
  5. Now find the three lines shown below:

    # Redirect all non-static requests to cluster
    RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
    RewriteRule ^/(.*)$→
    balancer://yourapp_cluster%{REQUEST_URI} [P,QSA,L]
    —And add the following line immediately before them:

    # Don't redirect requests to /mint
    RewriteCond %{REQUEST_URI} !^/mint/(.*)$

  6. The full rewrite rules should look like this:

    RewriteEngine On
    RewriteRule ^/mint/?$ /mint/index.php [QSA]
    # Prevent access to .svn directories
    RewriteRule ^(.*/)?\.svn/ - [F,L]
    ErrorDocument 403 "Access Forbidden"

    # Check for maintenance file and redirect all requests
    RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
    RewriteCond %{SCRIPT_FILENAME} !maintenance.html
    RewriteRule ^.*$ /system/maintenance.html [L]

    # Rewrite index to check for static
    RewriteRule ^/$ /index.html [QSA]

    # Rewrite to check for Rails cached page
    RewriteRule ^([^.]+)$ $1.html [QSA]

    # Don't redirect requests to /mint
    RewriteCond %{REQUEST_URI} !^/mint/(.*)$

    # Redirect all non-static requests to cluster
    RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
    RewriteRule ^/(.*)$→
    balancer://yourapp_cluster%{REQUEST_URI} [P,QSA,L]

  7. Save the file. It’s probably read-only. If you edited it using vi then you can save it even though it’s read-only by using :wq!
  8. Finally, restart Apache by using /sbin/service httpd reload and log out completely from your Rails Machine.

You can now install Mint itself by adding it to your working copy directory under /public and adding it to your Subversion repository using svn add ./public/mint. Once you’ve deployed to your Rails Machine you’ll be able to complete the Mint installation by visiting http://yoursite.tld/mint/ and following the instructions.

P.S. I have spent the past several hours wrestling with WordPress trying to get the markup in this post to validate, but I have conceded defeat!

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.