Sunday, 18 April 2010

Rails observers and exception handling

I can't find much written about this, so here goes.

If you have  a Rails observer watching a model for a new account being created, and sending an email, that process could potentially generate errors, which you may wish to trap - say if the email address is user entered, and is undeliverable.  You could do that with begin..rescue..end, and that may be fine - it will prevent the user from just being presented with a 500.

However, what if you actually need to do something with the error - given that observers are essentially models, you can't even set a flash from them

After much experimentation, it seems to me that the best way to do this is to insert a rescue_from at the top of the controller concerned.  Something like:

    rescue_from Net::SMTPFatalError do
        flash[:error] = "Please check the email address."
        render 'show'
    end
Note that the render is essential - the server throws a rather bizarre 500 (can't convert array to string) otherwise.  No idea why.

Friday, 12 February 2010

Rails: NoMethodError if validation fails

This sometimes happens if you load objects in the edit method, but don't load the same objects in the update - if the validation fails, the view is generated by update, and the objects aren't there.

Sunday, 24 January 2010

Ruby on Rails: StartTLS

Using this feature in ActionMailer (for gmail, for example) requires ruby 1.8.7. If using any earlier, you will get an error similar to

Net::SMTPAuthenticationError (530 5.7.0 Must issue a STARTTLS command first. 14sm4080666ewy.11)

in your logs

Monday, 18 January 2010

Note to Self

If you want a rails model to accept nested attributes, it's really important to have
accepts_nested_attributes_for 
in your model definition.
Otherwise you get the rather cryptic error:
ActiveRecord::AssociationTypeMismatch in YourController#create    
YourDependentModel(#-615375688) expected, got Array(#-605176048)

Tuesday, 5 January 2010

Ruby Object Model

Dave Thomas's Lecture at Scotland on Rails 2009

  • Classes in Ruby are simply objects which hold tables of methods
  • IF it can't find a method call, it jumps to the parent
  • IF it gets to the top & doesn't find a method call, it goes back to the bottom & looks for a method called methodmissing
  • "Singleton Class" - a class any object has as soon as you add a method to it, it's invisible