Design Patterns In Ruby

Design Patterns In RubyDesign Patterns In Ruby

  • Russ Olsen
  • Programming

A few years ago I didn't know that design patterns existed when writing software. It was only when I started tinkering with Ruby, because of Rails, that I heard about a book called Design Patterns : Elements of Reusable Object-Oriented Software written by the mythical sounding "Gang of Four".

Whenever I've been writing Ruby code in the past I've always had the nagging feeling that I'm doing it wrong. There is obviously more than one way to tackle a problem but I never know if I've taken the correct path. Countless blog posts have been devoted taking a class, or a method, and re-factoring it, making it leaner and cleaner. I guess the only way to learn is to write it so that it works, then go back to it over time and re-factor it. Surprisingly, after reading this book, that's what I'm doing now to one of my little Ruby projects.

The book takes 14 of the classic patterns and considers them from the point of view of Ruby code. It covers the background and basic Ruby concepts and idioms in the first part before launching into patterns. The third part discusses patterns for Ruby and looks into the Rails code.

For a book that is so heavily code related it is surprisingly easy to read away from the keyboard. But to really understand how the code works you would need to run and tweak it to see what makes it tick. That's what I intend to do next.

A book to always keep near you for those times when you feel that someone must have dealt with this coding problem before.


Deploying Rails Applications

Deploying Rails ApplicationsDeploying Rails Applications

  • A Step-by-Step Guide
  • Ezra Zygmuntowicz, Bruce Tate and Clinton Begin
  • Programming

Before I even wrote a Rails application I wondered exactly how this would be run on a remote server. Especially a shared server that you didn't even have command line access to. The first Rails book that I read didn't really cover that aspect in any great depth as I recall. So, I constantly thought exactly how would this work. If I wrote a great application would I have to pay big bucks just to get it working.

Up until now I think I have spent much more time getting Rails to work on a remote server than doing any actual coding.

I tried getting getting Rails to work on Bluehost, which at the time, didn't work. Then I had a Mephisto site running on TextDrive using Lighttpd, which did work, but I really didn't know enough about what was involved as I had just blindly set it up using the instructions they provided. Now I've switched to SliceHost, I set-up the slice using the Deprec gem, then had trouble using Capistrano and Subversion to deploy an application. So I set-up another slice and transferred things over. Now I have an application, that only I use, which was running Apache2 and a Mongrel Cluster but is now running Apache2 and Phusion Passenger™ (a.k.a. mod_rails/mod_rack). It's no wonder that I've only just started to move about Rails development.

To be honest, it's all good fun. Except when things don't work the way you expect and you have no idea why. If you are developing Rails applications, even like me as more of a hobby, then you need to know about the environment that it's going to be running on.

This book covers it all from hosting, shared, virtual and dedicated, to Capistrano set-up, which you will certainly need to understand to remove deployment headaches. Then it covers Mongrels, Apache2 and nginx and even has a section on deploying to Windows, for those who like pain or simply don't have a choice. There are also chapters on clustering MySQL, database sharding and performance benchmarking.

Because the book was only released this year it doesn't cover mod_rails. From a recent Web 2.0 Show podcast that Ezra was on I can understand why the book had to be rewritten three times, just to keep up with the latest advances in hosting environments.

It is a book I wish I had either bought sooner, or that it had been released earlier. At least now I have a book that I can use as a guide. I still want to aim to have either a slice, or an S3 instance that is running nginx, mongrel cluster with monit and that's all.

Everything that you wanted to know about Rails deployment... but was afraid to ask.


Everyday Scripting with Ruby

Everyday Scripting with RubyEveryday Scripting with Ruby

  • for Teams, Testers and You
  • Brian Marick
  • Programming

After, what must have been, the third attempt I finally worked through this book.

You would have thought that with writing little Ruby scripts for myself, and for work, that zipping through it would have been a breeze.

The book is essentially similar to the pick-axe book, but less detailed obviously, and with more exercises. And it's these exercises that I had trouble with. If you are following along at home, which I and the book encourage you to do, you have to complete them all. This is because the work that you should have done in the previous chapter will be touched upon in the next chapter. Sometimes you think, "Yes, I can do this, I understand it, I don't need to code this", only to find that parts of the next exercise rely upon it. I think if each set was more self contained it would have worked better.

The chapters do cover the Ruby basics, with real-world examples and tasks, then the subjects get trickier as the book goes on. I don't think for a minute that I understood inheritance and superclasses but these are mentioned in the final chapters.

If you're, like me, still getting to grips with Ruby scripts and best practices this book is certainly worth reading to further your knowledge.


Well, that didn't take long...

Amazon Web ServicesAmazon Web Services

In my iPhoto application I now have over 6,000 photos. Some I've taken with my Canon digital camera, but the majority I've scanned from negatives and added to iPhoto. With over 120 rolls of 36 exposure film to scan that little task took quite a while. But that was back in 2004.

My backup drive is a LaCie firewire drive that’s partitioned. One section is for a full iMac backup using SuperDuper!, the other, at the moment just contains a Time Machine backup. Just as a little aside, I was thinking of getting a Drobo and having loads of backups across lots of discs, but I've since gone off the idea.

So, the worry has been “What if my Mac and backup drive are destroyed by fire, power surge or are stolen?” I don’t have an offsite backup. I did think of just burning the photos to a couple of DVDs and putting the discs either in the garage or in my Dad’s safe, but that isn’t exactly ‘hi-tech’ for this day and age.

Reading around the internet I decided to try Amazon S3 (that’s Simple Storage Service) a part of Amazon Web Services. You are basically charged a per GB fee for storage per month, per GB transfer in and out in a month and for PUT, LIST and GET requests. It sounds more complicated than it is but at the moment my bill for the month is running at $1.73. Which with the dollar/pound exchange rate is very little indeed. That is after uploading nearly 11 GB of photos. The actual transfer in fee took the most of the total at $1.08.

To get my photo folder to S3 I used a set of Ruby based programs called S3Sync. I have been using rsync to download backups from my web-server, so I knew what to expect. After setting up a web services account with Amazon I added S3 to my set of connections in Transmit. It was this I used to create my first ‘buckets’ (a folder by any other name) on S3. This was fine, copying files and folders just like normal FTP. The only snag being that Transmit won’t, at the moment, let you delete any buckets that you've created. It just doesn’t happen. It even struggles deleting folders. I sent Panic an email and haven’t heard back, so I presume they know about it and are working on a fix for the next release. The only way to delete buckets, that I've found, is to install the S3 Organizer for Firefox, this works like a charm.

The majority of the tinkering took place last Thursday. Since then my iMac has been awake, during the day at least, and securely transferring photos to S3. It’s worked so well that I've set-up another bucket to take backups from my web-server directly to S3. I used to use the rsync command that I mentioned to download them to my iMac but from now on I don’t think I’ll bother.

So far the whole Amazon Web Services and S3 experience has been quite enjoyable. I just have to think of other uses for it.


Redesign

RedesignRedesign

Yes, I felt that a little redesign was in order.

I wrote a little Ruby script the other weekend to scrape my Digg RSS feed so that recently Dugg links could be listed on my blog. All it does is read in the XML, cut-out the titles and links and writes them out to a dugg.php file as list items. The file is then included in the sidebar. This is done, more or less, every hour for the hours in the day that I'm awake and could be Digging. All done on the web-server with a cron job. Of course Digg have now released an API which I will no doubt tinker with at some time. For the moment this way works fine.

This is the first time that I've written the stylesheet from scratch. The last one was based on Kubrick, the Wordpress default and so had lots of elements that I didn’t need or use.

A sidebar has been added which either has a double or single column based on the content. That was to make it easier to navigate without scrolling down to the links in the footer.

Each theme is still generated by a little Ruby program that I wrote. The switching is done with a change to the Wordpress stylesheet selector which switches the theme based on the current week.

  • Posted on Tuesday, 24 April 2007
  • Tagged with web, ruby, rails

Colour Shade

I wanted to be able to generate the shades of a particular colour.

This site has many themes with one main colour for the links and lines. But I wanted to be able to input the hex colour, that I had picked from the banner photo, and find a lighter shade for the menu section at the bottom.

Eric Meyer has written a Color Blender and I thought that I could do something similar using Ruby.

The program just takes the colour in hex (e.g. #ff0000 or even #f00), the shade number that you want and a number for the scale. Positive shade numbers make the colour lighter, negative numbers darker. Scale tops out at 100 and defaults to 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def colour_shade(colour, shade, scale=10)
  # default the scale to 100 if it is greater...
  scale = 100 if scale > 100

  # if the shade is out of the range of scale then reset shade to scale...
  if shade > 0
    shade = scale if shade > scale
  else
    shade = scale * -1 if shade < scale * -1
  end

  colour = "##{colour[1,1]*2}#{colour[2,1]*2}#{colour[3,1]*2}" if colour.length == 4

  # Convert the colours to decimal...
  colour_split = [(eval "0x#{colour[1,2]}"), (eval "0x#{colour[3,2]}"), (eval "0x#{colour[5,2]}")]

  # Calculate the shade...
  new_colour = "#"
  colour_split.each do |c|
    case
    when shade <  0: colour_shade = (c - ((c / scale) * shade.abs))
    when shade == 0: colour_shade = (c)
    when shade >  0: colour_shade = (c + (((255 - c) / scale) * shade))
    end
    new_colour << sprintf("0%x", colour_shade.to_i).slice(-2..-1).upcase
  end
  new_colour
end

Hover the mouse over the bars below to see what parameters were used to create the shades.

                     

                     

                     

Download the source code.

  • Posted on Sunday, 23 July 2006
  • Tagged with ruby, rails

Agile Web Development with Rails

Agile Web Development with RailsAgile Web Development with Rails

  • Dave Thomas, David Heinemeier Hansson With Leon Breedt, Mike Clark, Thomas Fuchs and Andreas Schwarz
  • Web Programming

Yes, I've read it all, some sections more than once. It probably isn't a necessary thing to do, but I think that having some knowledge of everything gives you a better understanding of what is possible.

Of course it's been a bit of a struggle. I started working through the example application last December when I bought the book. I quickly found that I just didn't know what the code meant and how the functionality all links together. So, quite rightly, I bought the Programming Ruby book and I worked my way through that. I must just point out that I'm from a procedural programming background and not an object orientated one. That was probably why I found it difficult to get my head around some of the concepts. When I eventually came back to this book I did find it easier to understand how things worked.

Ruby and the Rails framework are just light years ahead of the programming language that I use a work. While reading the book I've often thought how great it would be if we had that kind of functionality in our application.

If you're interested in Rails then this book pretty much has it all. It starts with the development of a simple application, then moves on to describe the framework in more depth, then deals with AJAX, security and deployment. There is even an overview of the Ruby language in a section at the back.

I'll certainly be buying the next edition to see what else has been added to this elegant framework.


Out with the old...

Out with the oldOut with the old

My little web-site has had a quick re-design over the weekend.

The ads and badges have gone from the left sidebar and it’s been dropped to the bottom. The links sidebar on the right has disappeared altogether. It did seem to get out of hand, with every web-site that I thought was good getting a mention. The links are still in WordPress so they might reappear as a separate page, especially if there’s a link that I want. It’ll be interesting to see if my Google rank or my site hits per month drop off the chart.

The scrolling idea was pinched from poocs.net, oh you haven’t found it yet?

I did contemplate switching to a Ruby on Rails blog engine after looking at the code behind the quotes WordPress plugin. It’s all in PHP, obviously, and I couldn’t figure out how to just list 250 quotes on a page. At least I know more about Ruby and Rails now so I could write something in that instead. I looked at Typo again and downloaded a few of the themes. The Lucid theme really caught my eye by Jamie. I tried to get Typo working locally so that I could import my WordPress stuff but kept having trouble even connecting to the admin pages. I never have trouble with my own Rails applications I just run webrick in the directory and that’s it. I also had a look at Mephisto and couldn’t get that to work either. I'm way too busy with my own little Rails application to look into it further.

  • Posted on Tuesday, 04 July 2006
  • Tagged with web, ruby, rails

Programming Ruby

Programming RubyProgramming Ruby

  • Dave Thomas with Chad Fowler and Andy Hunt
  • Programming

In my professional capacity, as a programmer of long standing, I've used a few languages: Pascal, Cobol, Silicon Office, Focus and currently Informix 4gl/Four J's and ASP.NET. Some I've liked using, some I've hated with passion. Visual Basic I tinkered with for a while at home and I just thought it was vile. Having a little bit of code embedded in a field on a tab of a property of a button just did not appeal to me at all. I am a little 'old-school' in that regard. I like to be able to open the program in a text editor and know that the reason it isn't working is in the file somewhere. And the fact that I hate using a mouse to edit programs with doesn't help.

Last December I decided to learn Ruby on Rails and bought the Agile Web Development with Rails book. I worked through the first hundred pages or so but felt that I need to know more about Ruby as a language before I moved onto Rails. Some people have programmed Rails without the need to learn Ruby but I've come from a procedural development background instead of an object orientated one.

This book is the definitive guide to the Ruby language and is sometimes call the PickAxe after the cover photo. It deals with all facets of Ruby from the initial tutorial, for people new to the language like me, to the comprehensive reference section at the back detailing all the methods, classes and modules.

I must admit that I struggled a little at first. Not because of a problem with the book more a problem with trying to get my rapidly ageing brain cells to think in new and different ways. Having just a couple of hours in the evening didn't exactly help either. But I did manage to read everything up to the reference section, so that I knew what the language was capable of. The more I read the more depressed I became. Realising that one line of code in Ruby could take me hours to code using 4gl at work just to perform the same task. You really are spoilt rotten by what the language can do.

It's a book that you will always have to hand because of the reference section at the back. As a programmer, there is nothing better than flicking through a user manual and finding something new about the language that you thought you knew so well. In that regard this book will be invaluable.


Ruby on Rails...

Ruby on RailsRuby on Rails

I've been busy learning, or at least trying to learn, Ruby on Rails. For people who don’t know this is a new programming language/application which allows programmers, like myself, to create web applications really fast.

At work we have one of our applications written in ASP.NET and since the beginning of last year I have been the unfortunate soul who has to debug and maintain this piece of software. At first I did think that it was pretty good. Towards the end of last year I had an idea to write some web pages linking to a database so that we could store client information, contacts, which clients have what software, what platform they are using etc. Just, more or less, everything that we need to know, all in one place. I felt that this was a good idea so I started writing it. I set-up the database and the tables in SQL Server and started to code the pages having copied chunks of code from our web application. Of course it has never been finished.

Let me warn you that if you work for a software company and one of the managers, who we’ll call Scouse Boy No. 1, buys a Rolodex to store contact information then leave immediately. Just run as far and as fast as you can and don’t look back.

This year I've had to convert our ASP.NET application so that it works with the new version of our main software. Even after having ASP training last year it was a slow and tortuous task. The fact that one of the pages doesn’t render correctly in Firefox, that it’s all tied into Microshites® web server and probably doesn’t validate to any W3 standard makes me think that it’s not going to be a possible career path. Maybe if we had spent £500 on Visual Studio things may have been less painful.

So, Ruby on Rails, is just the kind of thing that I've been looking for. A development environment written by programmers to make life easier so that more time can be spent writing clean, well structured, code. I ordered the Agile Web Development with Rails book, downloaded the necessary software for Tiger and started to work through a great little Ruby tutorial by Chris Pine. When that was done I started on the book proper, reading through the first section before promptly coming to a grinding halt on page 57. This is when I had a MySQL database and tables created and was about to see the power of Rails for the first time. I must have spent at least 2 days, on and off, trying to figure out why the views of the table weren’t being created. I even un-installed the latest version of Xcode and and re-installed the old version from the Tiger DVD, all to no avail. It just wasn’t seeing the database for some reason. Last Saturday afternoon I found the solution. In the config/database.yml file specify the username, in the book ‘dave’, that you granted database access for. Then re-run the ruby script/generate scaffold Product admin and you should see app/views/admin pages being created. Since then I've been working through the Book Store application. Everything is so easy, well not exactly easy, but just a joy to use. The scaffold that is generated by Rails knows what the database table looks like so you don’t have to key in lines of HTML with the different types of input code embedded in it. You don’t have to give each field a name, as this is already done for you from the field names. Links for edit/list/show/delete are already created and all the pages behind them. With one Rails command I generated a set of table maintenance pages. This is something that would have taken me at least a few hours using ASP.NET. And all without writing SQL statements.

I think to get the most out of the book you do need to have your own application to work on yourself. It would be really easy to just blindly get the demonstration application working without understanding how the principles can be put into practice. It hasn’t all been plain sailing. Just last night none of the controllers for my application would display in Safari. I found that emptying the cache and deleting any localhost cookies did the trick.