•April 5, 2008 • Leave a Comment

Well this is damned annoying!!! Grrrrr…….

Whenever I add a block of code to one of my posts WordPress seems to screw it up. It might be that I’m doing something stupid myself of course.

I think this issue will be seen by anyone who reads these posts which is even more frustrating. If I view a page containing a code block, navigate away from that page to a different post and then back to the original the code block seems to have magically added blank lines between each line of code. I can only assume that this is a WordPress bug of some kind; I did a Google search some weeks ago about this problem but didn’t find any actual solution. I thought that I’d solved it by adding <pre></pre> markup but it would seem not.

Oh, I’ve also changed the theme as I was sick of having my lines of code cut-off due to having a very small column width.

Maybe one day I’ll get my blog hosted and write my own blog platform!


Login Routine: A 1st Attempt

•April 5, 2008 • 2 Comments

So I have started to convert my PHP-based issue tracker application to a Rails-based version. When the users of the issue tracker access the site the first thing that they must do is login. This is achieved with a simple form where they supply their username and their password. I was looking at my copy of Agile Web Development with Rails to see how to handle the user login routine. The snippets of code that follow have either been taken directly from this book or have been very heavily influenced by it. Oh, by the way, I’ve tried most of this code but some of it hasn’t been (the user registration bit in particular) so beware. I have asked myself the question, “Why am I spending my time writing this blog entry when I only seem to be copying an example from a book?”. I think the answer is that it has helped me to understand how this user login routine works and it’s helped me come to terms with some of the Ruby / Rails concepts, such as the use of virtual attributes and the use of hash algorithms. I’m only really reproducing snippets of code from the book and not swathes of the actual text (the book is obviously far, far better than explaining than I am!) and the code has been changed my myself a little. Right, back to the code.

I had defined all of the models for the issue tracker app. a little while ago and my User model already had a password field but I wanted to change this to a field named hashed_password, so I created a migration to achieve this. I also created another migration to create a field named salt. Yes they could have been combined into just one migration to achieve this but it just didn’t happen that way.

OK, I’m not 100% sure of what a ‘salt’ is and to be honest I don’t think that I need to know the full story. It seems to simply be a random bit pattern that can be combined with a plain text password to create a more secure password. You can perhaps, if you would like, take a look at the Wikipedia entry for a salt to get further information.

The plain text password can be combined with this salt and then passed through a Secure Hash Algorithm (SHA) to produce a 160-bit hash. This hashed password can then be stored in the database (stored in the string-type attribute named hashed_password); along with the salt value so that we can use it to recreate the hashed version of the password from the password that a user submits when they attempt to login to the site. The SHA that I’ve used is the Rails method named (Digest::SHA1::)hexdigest.

I’ll firstly talk about the code that is used to register a new user first before going on to look at the login procedure.

When our theoretical user first uses the site they will be asked to register as a new user. We will assume that this simply requires them to supply a username and a password. We won’t worry about details such as ensuring that the username is unique in this simplistic example. The password that the user supplies will need to be stored somewhere temporarily while the unencrypted password is given the hash treatment. To achieve this I added a virtual attribute to my existing model. A virtual attribute is basically a model attribute which is not stored in the database. I added this with the following code where getter and setter methods were defined in my model:

# The getter:
def password
# The setter:
def password=(pwd)
 @password = pwd (#1)
 return if pwd.blank?
 create_salt (#2)
 self.hashed_password = User.encrypt_password(pwd, self.salt) (#3)

The setter is used by my account controller when the user registers. The code belonging to my registration action that sits within this controller follows:

# Create a new user object:
@user = User.new(params[:user])

# Has post been made and user saved?
if request.post? and @user.save
 flash.now[:notice] = 'You have registered successfully'
 redirect_to :controller => :issues, :action => :list

The HTML from my registration view is as follows:

<% form_for :user do |form| %>
  <label for="user_name">Enter a username:</label>
  <%= form.text_field :name %>
  <label for="user_password">Enter a password:</label>
  <%= form.password_field :password %>
 <%= image_submit_tag('register.gif', :alt => 'Register') %>
<% end %>

Ok, so I’m still learning but I think that the setter method for my password attribute is probably called when the new User object is created (with the line @user = User.new(params[:user]) in the controller), as the data in the params hash would be used to initialise the User object data. However, being a little new to all of this, I’m not completely sure of this. If I am correct then, once the registration form has been submitted, the password setter function will be called and the plain-text password that the user entered will be passed to it. This password is assigned to an instance variable (#1 in the setter code seen above) and, provided that the password is not completely blank, the create_salt method is called to create a salt for us (#2) and finally the salt is passed to the encrypt_password method along with the plain-text version of the password and the resulting encrypted password is then assigned to the hashed_password model attribute that is finally saved in the database.

Here’s the code for the create_salt method which I added to my User model as a private method:

def create_salt
 self.salt = self.object_id.to_s + rand.to_s

Essentially this method takes the id of our user object, converts it to a string, creates a random number, converts this to a string and then joins the two strings before assigning the new string to the salt attribute. The use of the keyword self ensures that the attributes belonging to the current object are used. If self was omitted I believe that the variables would simply be treated as local variables (local to the create_salt method that is). I’ve pretty much taken this method verbatim from the book.

Next is the encrypt_password method which actually takes the plain-text password and the salt that was defined by the create_salt method, concatenates them together along with a bit of extra text and passes them to the hexdigest method:

def self.encrypt_password(password, salt)
 # Join the unencrypted password and the salt:
 value_to_hash = password + 'addtomakemoretricky' + salt

 # Run through the SHA1 digest and return:

This method was also defined in my User model as a private method.


Once our user has successfully registered with the site they will need to login when they visit the site in the future. After the user has registered they would ideally be sent an email which gives them a link that will take them to a special first time login page. Once they have logged in for the first time the system would then fully activate the account for that user. This might help to prevent malicious scripts from registering invalid users. I have yet to write the Rails code to achieve however I have done something similar in PHP.

Anyway, on to the login process. Here’s a snippet of code from my view that I used to present the login form to the user:

<% form_tag do %>
  <label for="name">Username:</label>
  <%= text_field_tag :name, params[:name] %>
  <label for="password">Password:</label>
  <%= password_field_tag :password, nil %>
 <%= image_submit_tag('login.gif', :alt => 'Login') %>
<% end %>

You can see here that the password_field_tag method is using the password attribute.

Once the user has keyed-in their password and hit the submit button the controller takes over. My controller had the following code:

# Has the form been posted yet?
if request.post?
 # Check if the user details are valid:
 user = User.authenticate(params[:name], params[:password])
 # Valid user object returned?
 if user
  # Store the user's id in a session variable:
  session[:user_id] = user.id
  # Redirect to the main page
  redirect_to :controller => :issues, :action => :list
  flash.now[:notice] = "Invalid username or password, please try again."

The first if statement checks that the form has been submitted (otherwise the block is skipped and the login view is shown). I then call my authenticate class method that belongs to my User class. If the authenticate method successfully returns a user object the id of this user is stored in a session and the user is redirected to my main page otherwise, if the authentication fails, the login page is shown again with a flash message.

Right, so the authenticate method takes the user’s username and plain-text password from our form’s params hash, but what happens then? Here’s the code from my model:

def self.authenticate(username, password)
 user = self.find_by_username(username) # (1)
 if user
  if user.salt
   desired_password = encrypt_password(password, user.salt) # (2)

  if user.hashed_password != desired_password # (3)
   user = nil
 # Return the user object

Essentially (1) we find the user in the database using the username that was entered at the form, if this username is found we then (2) encrypt the password that was entered at the form using the salt that was originally used for that user (during the registration process) and we then (3) compare the encrypted password that was derived from the login form with the encrypted password that was been stored in the database when the user registered. If they are the same we have not only found the user’s username but we also have the matching password and so we return the user object to the controller (which stores the user id in a session, etc.).

If you’ve read this post and actually found it to be useful in any way then please leave a comment letting me know. I’ve been quite surprised that this blog has had a small trickle of traffic, principally on my post about the use of the select helper.
It’s taken me quite some time to write this particular blog post and I’m a little worried that it contains numerous mistakes and bit of mis-information. I’m going to think twice before I decide to write a post in this level of detail again as I’ve literally taken about a week or so to write the entire post! Yes someone might be searching for help on a particular topic and find their way to this blog but there are going to be far better sites and forums to find more accurate information.

Possibly see a future post for a list of rails web resources that I find useful.

Using select Helper in Rails

•March 17, 2008 • 2 Comments

In my last post I wrote that I had produced a PHP application for the company that I currently work for. Well, now that I’m trying to learn Ruby on Rails I decided that I would convert that applicition from PHP to Rails. I’ve not really allocated very much time to the task at the moment but hope I can give it some more of my time soon.

One of the things that the PHP application had was a number of drop-down combo-boxes (or selection lists) on the main page. These were used to filter the displaying of problems that the system was tracking. The user could use these selection lists to get the app. to show only problems that they had raised for example, or to only show problems that related to a particular system. This app. was being used to track problems with a large piece of software that we had recently delivered to our customer. Without going into details, the software was focused on the training of ground-crew who maintain fast jets. This meant that problems tracked by the app. would relate to various aircraft system, engine, communications, navigation, etc.

Anyway, back to the selection lists. As I have a table in my database listing all of the aircraft systems I could have simply populated my selection list with the systems from that table/model quite simply:

In the controller:

@system_names =  System.find(:all, :order => 'description')

In the view:

<% form_tag do %>
      <label for="system_id">System Title to filter on:</label>
      <%= select_tag(:system_id,
         :id, :description) %>
   <%= submit_tag 'Filter Issues' %>
<% end %>

However I wanted to ensure that the option selected by the user would remain selected and I also wanted to add an option to the beginning of the list that could be used to switch the filter off. I thought at the beginning of the week that this would be a really easy task but I spent several days of frustration trying different options, looking at the online Rails Framework Documentation and searching a Rails Forum or two. I was about to give up and submit a post to one of the forums when I had a breakthrough.

I finally worked out what I needed to add to the options_from_collection_for_select helper method to get the previously selected option to appear selected if the form was submitted:

<%= select_tag(:system_id,
   :id, :description, params[:system_id].to_i) %>

It was some time before I realised that I needed to add to_i to convert the string stored in params to an integer. I guess that I had assumed that this conversion would take place automatically. This highlights one of my problems learning Rails and that’s the fact that I haven’t really got any experience using Ruby and I’m beginning to think that is a mistake.

As I write this post I’m realising that I don’t actually need to have the previously selected option selected in the selection list using this technique. Instead I’ll simply find out what the user had selected and store it in a session variable; the use of params will only work if the user is submitting a form that needs to be re-displayed because of an error in the form, for example.

Adding an option to the beginning of the selection list took me longer to achieve and I don’t know if I’ve done it the best or easiest way. I’m just glad that I got it worked out eventually! I dropped the options_from_collection_for_select helper method in favour of the options_for_select method:

<%= select_tag( :system_id,
   params[:system_id].to_i) ) %>

In the controller I was toying with the idea of using the find method in the same way, to grab all available systems, and then adding the new option to the beginning of the list. Again, I had a number of problems with this due to my limited knowledge of Ruby as well as my inexperience at using Rails. Eventually I came to the following solution, where I convert the array of objects that is returned by the find method to an array of arrays (using the map method) and then joining this to another array of arrays that contains my first option:

@system_names =  System.find(:all, :order => 'description')
@system_names = [ ["No Filter Selected", 0] ]
   + @system_names.map {|p| [ p.description, p.id ] }

It actually appears to work.

Blatant Self Promotion

•March 8, 2008 • Leave a Comment

I’ve been studying PHP, on and off, for a good year or so now and I had the opportunity recently to produce a PHP served site at work. I needed to produce this site quite quickly and I stumbled across the Code Igniter framework which seemed to offer me flexibility and a little structure (if that’s not a contradiction) in the guise of the Model-View-Controller (MVC) pattern.

For some time now I’ve had an idea for a web application in mind (in the Web 2.0 tradition) and I thought of using Code Igniter to build this application. However, I wanted a framework with a little more structure, more support and I felt that Code Igniter wasn’t the way forward. For a very short while I looked at the Zend Framework but had problems finding a decent resource from which to teach myself.

That’s when I began to take a closer look at Ruby on Rails. I had heard of RoR over a year ago and I’m trying to remember right now why I didn’t pursue it then. It may have been because there were only a small number of hosting companies available for RoR or, more likely, because the language looked a little too different and I was quite happy, at the time, with the C++ -like syntax of PHP.

Anyway that’s all history now. I haven’t ruled out PHP entirely and I’ve found it a little more difficult to learn RoR than I imagined I would, but I like what I’ve discovered so far. I decided to take a look at RoR for a week and see if I could take to it. After downloading a free Rails book from SitePoint (Sitepoint – an excellent resource, the book – “Build Your Own Ruby on Rails Applications” ) and InstantRails for Windows I was quite interested within a couple of hours. I then dived in and bought myself a copy of “Agile Web Development with Rails” and I’ve not really looked back. I’m not sure if this book is the best learning resource but I’m getting there, slowly.

I think that Ruby on Rails is probably a good language / framework to use if you are about to develop a brand new site or application. I have some concerns about scalability and speed of execution but I’ll leave that topic for a later blog post. I’m not sure though if RoR is such a good choice from a career choice standpoint.

At the current time I am wondering if I’m about to be made redundant. The company that I work for has recently been taken over by a very big Italian company and I have come across some information that leads me to believe that redundancies may be on the cards. Now, I could be utterly wrong, but what if I’m not? As soon as I made this discovery my first thought was to dust of the CV and to take a look around at what jobs, if any, there might be available. I’ve had a look and I’ve found a number of PHP jobs and a very small number of RoR jobs, a very small number indeed. Hmmm, I think, perhaps I should have carried on developing with PHP. At least that way I may be a little more attractive to a future employer.

I stated in my previous post that I currently program in C++, and this is true. Well kind of. Without naming technologies, companies or international customers, I am involved in writing software that models aircraft systems. That may sound incredibly complex and I suppose it is, to a degree. The hardcore code that deals with scheduling of events, handling of user interactions, etc., was developed by a team of proper programmers. I write code that interfaces with this software infrastructure and which is responsible for modelling the behaviour of aircraft systems. This essentially means that the code that I write in my day job uses C++ command structures such as ‘if’ statements, loops and functions but I don’t usually have the opportunity to write my own classes (for example) as the software tools that I use perform these tasks for me.

So here I am, maybe looking for another job in the near future. Perhaps I should start some self promotion going; well I guess that that was one of the reasons for starting this blog in the first place! The only fully functioning web site that I’ve produced is the one that I did for my current employer and I thought myself quite lucky to be given the chance to do that – web development is not in my job description. Now normally I wouldn’t dream of promoting myself by using examples of my work like this – in fact it would be quite unwise of me to do so. However! A) I did most of the work for this site at home in my own time, and B) I have removed all data and the company details from the demo that follows. I’ve put together a demo of the application and put it on Slideshare.net. It’s a bit too small to see with sufficient clarity on this site so it may be better viewed from the Slideshare site where it can be viewed full screen. Excuse the poor interface design and complete lack of site design. Hey, I was in a rush!

I’ve removed my company logo and part of the site’s title which is why is may look a little odd.

Designer or developer?

•March 5, 2008 • Leave a Comment

Recently I’ve begun to wonder if I’m taking the right approach to pursuing a web development / design career. Originally I had the notion that I could do development and also work on the design. I’ve read a number of comments on forums and blogs fairly recently about the role of web developer versus web designer. In a nutshell the issues are: what is the difference between the two roles and can a developer design and can a designer develop?

It seems that some companies / individuals believe that a designer produces the site mock-ups and then passes these to the developer who codes the site in (X)HTML and CSS, perhaps with some JavaScript on the side, while other companies believe that it’s the job of the designer to write the HTML and CSS.

The question of, “Can a developer design?”, is bothering me and it’s this question that’s making me reconsider my initial direction. Originally the move into web development appealed to me as I saw it as a way of moving away from my current role (let’s say for now that I program in C++, although more on that story a little later perhaps) and kind of stepping sideways into server-side and / or client-side development. Of course I then began to really look into the possibilities and discovered the amazing array of options and technologies. I thought that I could learn and practice them all; PHP, JavaScript, Ajax and ‘web design’ to name just a few. I also thought that perhaps web design would be good to learn and to become really good at, as a core skill so to speak. My thinking behind this was that design, and this includes interface design, would remain a relatively static field and one where I could learn the core principles and apply them to the current web design trends and equally well apply them to the web of the future (some virtual world environment like Second Life for instance). So I saw design as an option but was unsure whether or not I had the aptitude for it.

The phrase that came to mind quite a lot was, “Jack of all trades and master of none”. I could perhaps eventually produce some half-decent design work, after much practice, but my work wouldn’t be as good as it might if I had specialised in one particular area, be that design, server-side development or client-side development.

In recent days I’ve come a little closer to the conclusion that, if I am to follow the career of web developer, I should drop my design aspirations and concentrate solely on development. Not sure if that will be client-side or server-side yet, or a mixture of both, but the design stuff should remain purely as an interest and a hobby.

Starter for 10

•February 13, 2008 • Leave a Comment

So the first thing was to choose a title for my shiny new blog. The original purpose of this blog was to write about my discoveries in the world of web development / design. I’ve started learning Ruby, with a huge dash of Rails for good measure, and so I thought something hilarious such as, “Off the Rails”, would do the trick. But that sounds a little as though I’ve decided to leave Rails development behind to learn something else, like PHP for example, when the opposite (quite literally) is true. Where did “Keep Within the Lines” come from? Well it’s a combination of exchanging ‘rails’ with ‘lines’, trying to stay with Rails development and a joke with a work colleague who has the job title of media developer (amongst other things he produces 3D models in 3DS Max).

After the question of what to call the blog the next task was to give it a style, or theme, other than the default one.

I seriously have no idea how long I can keep myself interested in writing this blog. I hope that one day someone may read it; when I make it public which it’s not right now. I would like it to prove useful to one or two people who, like myself, are trying to get to grips with the whole web design arena and it may even help me finally fulfill a long ambition of mine. Well the ambition is to write a novel but at least I’m writing something.

I also want it to be somewhere that I can record what I’ve done so that, some time later, I can read my own blog and remember how I achieved certain things.

Well, after reading this post again I can’t quite believe that I’m going to publish this dross. There’s enough garbage out there already. Stop me someone please…..ah, too late. Engage!