Playing with exceptions

I’ve just been having a little play with exceptions, as a new colleague wanted to understand how different errors could be handled. There is a good description of how they work in the “Exceptions, Catch, and Throw” chapter of the origin Pickaxe book.

I created the following script to demonstrate how it works

module Play
  def self.do &er
    begin
      puts "\n"
      er.call
    rescue SyntaxError, KeyError => e
      puts "One of SyntaxError, KeyError"
      output(e)
    rescue RuntimeError => e
      puts "Another known error"
      output(e)
    rescue => e
      puts 'Unknown error'
      output(e)
    end
  end

  def self.output(error)
    puts "#{error.class}: #{error.message}"
  end
end

Play.do {raise SyntaxError}

Play.do {raise "Gor Blimey"}

Play.do {HeBeJeeBees}
Posted in Ruby | Comments Off on Playing with exceptions

TreeDecorator

On a couple of my projects, I’ve wanted a dynamic tree representation of a group of objects. acts_as_nested_set and it variants (such as awesome_nested_set) work well for creating the back-end structure. There are plenty of JavaScript libraries that will help you create a dynamic tree. I’ve used YUI 2 TreeView in the past, and this time I wanted to use Dynatree.

What I find takes time is pulling the two together. Specifically, I like to output the items in an unordered list and then used the JavaScript library to rebuild the list as a dynamic tree. That way the list degrades nicely if there is a JavaScript issue. However, getting an acts_as_nested_set group into an nested ordered list is tiresome.

So to prevent me having to reinvent the conversion of a nested set into a nested unordered list, I’ve created TreeDecorator. It is installed into a rails app with:

gem 'tree_decorator'

With that in place I could create this helper method (My nested set object is Event):

  def events_in_unorder_list(events)
    hanger = TreeDecorator::ObjectHanger.new(events)
   
    hanger.outer {|content| content_tag('ul', content.html_safe)}
    hanger.inner {|content| content_tag('li', content.html_safe)}
    hanger.element {|event| link_to(event.title.html_safe, event_path(event))}
   
    hanger.tree
  end

That then gives me my nested ordered list, and it is then trivial to make it dynamic:

<div class="events">
<%= events_in_unorder_list(@event_roots) %>
</div>

<%= javascript_tag('$(".events").dynatree({});') %>
Posted in Ruby | Comments Off on TreeDecorator

Rails database user

Another project, another database connection via root user with no password. This is so sloppy.

It is so easy to create a project specific user in any database. If this was done more often, I wouldn’t be for ever changing the password for my root user. I’d also be able to swap between projects more easily. It would also be easier to maintain a secure set up.

So please, don’t use root as the database user on your next Rails project.

Posted in Ruby | Comments Off on Rails database user

Comments in Gemfile

I wish people would take a little time to consider the best way to arrange and comment the gem insertions in Gemfile.

I am not a great fan of commenting. I believe you should code so that it is easily readable without comments. When I see comments, I tend to think “There’s a bit of code that the developer doesn’t think people will be able to understand”. Commented methods are usually the ones in prime need of refactoring.

However, there are times where you have little option but to use unintuitive code patterns and a short comment is then required.

One of the best examples of this, and one where I rarely see any comments is the Gemfile. All the team developed rails apps I have worked on, have a range of different gems. I sometimes wonder whether most rails developers measure their skill level on the number of gems they can add to the Gemfile. It’s certainly become an interview criteria!

Many gems have functionality that is not obvious from their name. For example, nokogiri (Japanese symbol for ‘saw’ I believe), is not a name that makes it obvious to me that it is an html parser. I do not think that is the fault of the gem developer. You have to come up with a unique name, and that is not easy. Especially if you want to make it memorable.

It is usually fairly easy to find the gem’s project in github and/or via a google search, and then to find out what it does. It is very rare for a commonly used gem not to have at least a basic description of its functionality in its README (polyamorous being one exception).

The problem is do you really want to have to look up every gem README when you are scanning through a Gemfile looking for where some functionality you don’t recognise, may be added. Some short comments can make this task so much easier.

I’m working on an application that uses Postgres, and the models are being queried with search_by_title_and_body, and I couldn’t see where the search_by functionality was coming in. It took me a few minutes looking through the Gemfile and look up READMEs, to find that ‘texticle’ was the source. This was far down in the Gemfile and amongst unrelated gems.

So I moved it to the ‘pg’ gem declaration and added a comment. I did the same for ‘activerecord-postgis-adapter’:

gem 'pg'
gem 'activerecord-postgis-adapter' # Adds postgres spatial querying to active record
gem 'texticle', '~&gt; 2.0', :require =&gt; 'texticle/rails' # Adds postgres search tools to active record

Now I hope the next developer who reads the Gemfile, will find it a little easier to identify the functionality being added by these gems.

Update

There is now a gem call grub, that will automatically add comments to you Gemfile. I’d highly recommend you have a look at it.

Posted in Ruby | Comments Off on Comments in Gemfile

Initialize: keep it simple

The more objects I build, the more I am realising that I need to keep my initialize methods simple. Not doing so, leads to problems later on.

The key is in the name: best practice is to keep the initialize method to just initially loading instance variables.

An example

Suppose I want to build a class to translate Spanish text into English.

The wrong way to do it

class Translator < String
  def initialize(text)
    super(to_english(text))
  end
.......  
  def to_english(text)
    EasyTranslate.translate(text, :to => :en)
  end
end

Translate.new('Este es texto')    ---->  'This is text'

So what is the problem

This solution works. However, it doesn’t scale.

What if I want to use Translator to translate Spanish to German, or English to Spanish? My initialize method assumes that I’ll only be translating to English. As well as adding code to do the new translation code, I’d also have to modify initialize to work with the new code.

This is not too much of a problem with such a simple class, but what if there were many methods and each of them relied on the initialize method’s modification of the text as a starting point. I’d have to modify all those methods too.

Also it is not easy to test any instance method without processing the to_english method. It then becomes difficult to isolate a method test to simply testing the actions of that method.

A better solution

class Translator
  def initialize(text)
    @text = text
  end
..............................
  def to_english
    EasyTranslate.translate(@text, :to => :en)
  end
end

Now if I want to add a method to translate to German, it is just a case of adding the new method.

The downside, is when I use the code, the input is now more verbose:

 Translate.new('Este es texto').to_english    ---->  'This is text'

However I can easily fix that with a class method:

  def self.to_english(text)
    new(text).to_english
  end

Personally, I might not keep the class and instance methods using the same name, but this demonstrates how easy it is to create more succinct usage:

 Translate.to_english('Este es texto')    ---->  'This is text'
Posted in Ruby | Comments Off on Initialize: keep it simple

Output table column names to a file

I’m working on tool to transfer data from one database to another. I wanted a list of column names in a file so that I had a list I could work through. After a hunt around the MySQL docs I found mysqlshow, which works a treat:

  mysqlshow -u username -p password database_name table_name > output.txt
Posted in SQL | Comments Off on Output table column names to a file

Do not put hyphens in engine names

I’m currently working on my first rails 3.1 engine and have just wasted a day or so because I put a hyphen in the engine name. The reason I did this was to be consistent with some other plug-ins I am using (e.g. noodall-core). The new plugin should provide polls for noodall sites. So noodall-poll would be consistent with other noodall plugins.

rails plugin new NoodallPoll --mountable

Created noodall_poll.

So instead I used:

rails plugin new noodall-poll --mountable

The result was lots of paths using noodall-poll, such as /app/helpers/noodall-poll/application_helper.rb. When I tried to run test, I got application_helper.rb not found errors. The system was looking for /app/helpers/noodall_poll/application_helper.rb.

Lesson learn: don’t play around with engine names. Use camelcase or underscored engine names.

An update:
This issue has raised its head again and following a google search and I came up with what I think should be the definitive answer:

If your gem lives in a parent name space, the name spaces should be separated with hyphens in the gem name. So Net::HTTP has a parent namespace of Net and a main namespace of HTTP, and so the gem name is net-http.

If your project name comprises multiple words, the words should be separated by underscores in the gem name. So a project with a namespace FooBar have the gem name foo_bar.

And to combine the two Net::FooBar should have the project name ‘net-foo_bar‘.

As for the folder structure in my original example: Noodall should have been the parent namespace, so the gem name would be noodall-poll, and the path to the helper should have been: /app/helpers/noodall/poll/application_helper.rb

Posted in Ruby | Comments Off on Do not put hyphens in engine names

Acts As Soft Delete By Field

I’ve had a bit of spare time recently, so I thought it was about time that I created a public gem. I thought about my code and decided that my soft delete system would be a good place to start. I’d created it about three years ago and it’s been used in a couple of corporate projects. It is also fairly simple and self contained.

It had been created in a somewhat pragmatic way, using the simplest way that I could find to implement it. That was to create the functionality in an ActiveRecord::Base abstract class, and then have all the models that needed this functionality, inherit this class. I’ve made the code available as SoftDeleteableBase.

This approach works fine and is very easy to implement. The problem is that it does not scale very well. That is, if you need to add additional functionality in the same way, the new abstact class has to inherit from the original.

A much better way to add functionality to a model is by mixing in via a module. Having recently read Elequent Ruby by Russ Olsen (my favourite Ruby author), and Metaprogramming Ruby by Paolo Perrotta (the two books complement each other very well), I felt I should rewrite SoftDeletableBase as an ‘Act as’ plugin.

The result was ActsAsSoftDeleteByField. A bit verbose, but as ActsAsSoftDeletable already existed I needed to differentiate my plugin from that. ActsAsSoftDeletable moves deleted items into another table, which was not been the functionality I wanted. My system uses a field in the model’s table to flag when a record is deleted. A simple solution, but ActsAsSoftDeletable maybe more suitable for many projects.

The two books gave me the knowledge I needed to understand how the methods used to create the mixin can be used. However, I found it very useful to look at other Acts As plugins such as acts_as_rateable, and acts_as_nested_set, to see how to arrange the code. The Ruby on Rails Guide was also useful.

Loading instance and class methods is actually fairly straight forward. Most of the work is done by this bit of code:

def self.included(base)
   base.send :extend, ClassMethods
 end

Getting the code to load properly was more difficult. It took me a little fiddling to get the init.rb file to work correctly. A lot of examples use class_eval here, but as I know the class names, I chose to use the simpler technique of monkey patching:

$:.unshift "#{File.dirname(__FILE__)}/lib"
require 'soft_delete_by_field'

class ActiveSupport::TestCase
  include ActsAsSoftDeleteByFieldAssertions
end

class ActiveRecord::Base
  include ActiveRecord::Acts::SoftDeleteByField
end

I used a set of assertions I’d used to test SoftDeleteableBase to test the new mixin, and included this code in the new plugin. That made it a lot easier to check the functionality. I created a new Rails app, and generated a Thing model. I then applied acts_as_soft_delete_by_field to thing, made sure it had a :deleted_at field, and ran the tests.

The next thing I did was to extend the functionality so that an alternative field could be used to store the deleted information. A few modifications and that was all working.

The last step was to create the gem. Russ Olsen’s book gave me the basics. The main thing that caused me problems was again initiating the script.

The main problem is that many of the examples on the web use the old system relying on /rails/init.rb, but I couldn’t get this to work. In the end, I realised that a file with the gem name was always loaded, and therefore that would be the place to put the hook script. So acts_as_soft_delete_by_field.rb was created and I put a hook script there. With that in place everything started working a treat.

The end result was the acts_as_soft_delete_by_field gem!

Posted in Ruby | Comments Off on Acts As Soft Delete By Field

A Geek’s take on dealing with stress

Being a CFR has put me in stressful situations. Trying to resusitate someone with kith and kin look on, is demanding.*

Last year I also started work carrying out bereavement support for a local hospice. The training involved in getting me up to speed in this work, has made me think a lot about how we behave in stressful situations such as bereavement.

Of course, I’m also a geek. Ruby programmer is my day job after all.

With all that in mind, here is my take on very stressful occurrences such as bereavement:

Bereavement: UDP and the unconcious mind

Your brain works very like a UDP stack, where the conscious mind sits at the application layer.

Most of the work is done within lower parts of the stack, and with everything working normally, stuff gets passed down into the unconscious brain and stuff pops back up without the top layer knowing or really caring about what happened lower down. You often think your conscious mind is doing all the work, but actually its all happening lower down.

Normally, the stack is able to handle problems and routes messages back and forth without any problem.

However, when something very stressful happens the stack gets disrupted. It gets information it doesn’t know how to handle. The result at the top layer is it doesn’t get any answers. Also as this is UDP, it doesn’t get any error messages either. So the net result is numb confusion.

With time the stack fixes itself. This can take hours or even days. Until then nothing computes properly. You can’t concentrate, you feel numb, and a little confused because you can’t figure out what is happening. These symptoms only go away once the stack fixes itself and normal conscious to sub-conscious communication returns.

This matches my experience:

Immediately after a very stressful situation I am left with a very numb, empty feeling where my brain just doesn’t work normally. The only thing that fixes this is time. I’ve learnt to recognise this feeling and the knowledge that time fixes it helps me deal with it. Trying to force my brain to fix the problem just makes the fix time longer.

Once the stack sorts itself out (for me, 2 to 12 hours is a common fix time), I can then start the rational process of sorting out the emotions and images that pop into my head.


* In fact, I find the reactions of relatives stick in my mind far longer than what actually happened to the patient or what I did. For example, the image of a wife crying at the bottom of the stairs is my main memory of a particular CPR attempt.

Posted in Bereavement support, Community First Responder | Comments Off on A Geek’s take on dealing with stress

Model inhertiance

I’m working on an application with some CMS features. One requirement is that new content is moderated before being published. To enable this, some users are allocated as moderators. To achieve this I have a moderator status column which can be either ‘some’ or ‘all’ (at the moment a ‘some’ moderator can only moderate content in some languages). Up until now it hasn’t be too cumbersome to have user methods associated with moderaters defined within the User class, but now I’m getting to the point where it would be good to split some of this functionality out into a separate class.

My problem was how to connect a new Moderator class to the User class.

A starting point is that I want Moderator class to inherit from User. That’s simple:

Moderator < User
end

The problem with this is if you do Moderator.find(:all) you get all users and not just those who are moderators.

In my last project, I overrode find, but that was a Rails 2 project and the same technique doesn’t work so well for this Rails 3 project. For example, Moderator.all still returns all users.

Another option would be to use ‘Single Table Inheritance’ (see ActiveRecord::Base api), but that would mean adding a new field and then limiting users to just one sub-class. For example, I think I will use the same technique with admins, and what if a moderator is both a moderator and an admin. Single Table Inheritance won’t let you do that.

In the end the solution was ridiculous simple. It is ‘default_scope’.

This works

class Moderator < User
  default_scope where("moderation_scope IN (?)", ['all', 'some'])
end

And this is what I ended up with:

class User < ActiveRecord::Base

  MODERATE_ALL_SCOPE = 'all'
  MODERATE_SOME_SCOPE = 'some'
  MODERATION_SCOPES = [MODERATE_ALL_SCOPE, MODERATE_SOME_SCOPE]

  def self.find_moderators
    where("moderation_scope IN (?)", MODERATION_SCOPES)
  end
end

class Moderator < User
  default_scope find_moderators
end

If I have special data entries that alter behaviour, I prefer to put them into constants and use the constants within the code. That way I can change the specific data entries at a later date without having to change every instance where it is used. Hence using MODERATION_SCOPES.

The final version also allows me to share the same code between User.find_moderators and Moderator.default_scope.

Posted in Ruby | Comments Off on Model inhertiance