lewstherin.com

Hi!
As you can probably guess from the domain name, I am a huge fan of the Wheel of Time Series and the fantasy genre in general. I am also a programmer and love the Ruby language and the RoR framework.

This is my personal blog. Say Hi by dropping me a mail at rATlewstherinD0Tc0m or on twitter @lttmorning.
Recent Tweets @

Dirk’s done, huh? He is on the way to a 50-40-90 season for the second time, a feat achieved before only by Larry Bird and Steve Nash!

Shot Chart for the season.

Awesome, just discovered this theme does not have styling for h2, h3 etc. The theme before this had conflicts with the styling of google code prettify.

Plus can there be anything more annoying than a tiny popup for you to write your text blog post? I don’t think this tumblr business is going to work out!

In Cadinsor, I defined a Custom Module which was used as a mixin to extend the functionality of the application controller and hence, all the controllers in the app. The key method, checks the incoming request for a valid signature and upon failure, redirects it to specific error response page.

As some of you may have had the misfortune of discovering, a redirect_to query doesn’t stop the processing in the controller action (unless encountered in the before_filter ) and might lead to a nasty double render error. For example, look at this controller action below:

# GET /temp_scaffs/new
# GET /temp_scaffs/new.json
def new
  @temp_scaff = TempScaff.new
  redirect_to action: :index

  respond_to do |format|
    format.html { render :new }
    format.json { render json: @temp_scaff }
  end
end

Now when you visit the action, you get the following error:

AbstractController::DoubleRenderError

Normally, you escape this by doing one of two things:

  1. Place the redirect_to statement at the very end of the action
  2. Return from the action after the redirect_to statement (as the exception message helpfully points out).

The second option works well until you try to do it from within another method. Now, when you say return - you don’t return from the action in the controller, but instead you just get out of your method. As far as I can see, the only way out of this problem is to break your control flow by - Raising an Exception. Needless to say, once we raise an exception, we also need to handle it sanely and present the right response to the user. Let’s see how to do that, shall we?

Let us cook some exceptions

First off, if you are totally new to Ruby Extensions, please go read this excellent post about Exceptions and Exception Handling in Ruby. Do pay attention to this comment.

Getting back to our problem, we need to raise an exception and handle it appropriately. We are better off defining our own exception class and raising it, because it is the easiest way of ensuring that we provide the right response. Rails 3 onwards, in order for Rails to auto-load your custom modules and classes, the should be placed according to the directory structure: lib/<module_name>/<class_name>.rb . So, if our exception class is CustomExceptions::RequestError, it is defined as a simple child of StandardError and placed as shown.

module CustomExceptions
  class RequestError < StandardError
  end
end

You must of course include your lib directory as part of your auto-load paths by adding the following line in your application.rb file:

config.autoload_paths += %W(#{config.root}/lib)

Exception Class

Raising the exception

So there we have it, our own custom exception defined and ready to roll. So let us try raising it with a message indicating the action it was raised from.

class TempScaffsController < ApplicationController

  def index
    raise CustomExceptions::RequestError "Raised from Action Index"

    respond_to do |format|
      format.html { render :new }
      format.json { render json: @temp_scaff }
    end
  end

  def new
    raise CustomExceptions::RequestError "Raised from Action New"
    respond_to do |format|
      format.html { render :new }
      format.json { render json: @temp_scaff }
    end
  end
  # ....

end

Upon visiting the index action, we get the following exception.

CustomExceptions::RequestError

This is one of the rare occasions where we get to go Yay! after an exception,so don’t miss out.

Recovering!

Great! Now how do we handle the exception? You can place a rescue block in each of your actions but thankfully Rails gives you a nicer way of handling this. Any exceptions that are raised in your actions are can be caught using a call to the rescue_from method in your controller. This method is pretty versatile and using :with option, you can ask a method or a Proc object to handle the exception. While the examples provided in the guide tell you how to handle the request, they do not capture any information about the exception object itself. Lets use a simple code-block (it is not necessary to explicitly define a Proc object) and see how to get this information.

class TempScaffsController < ApplicationController

  rescue_from CustomExceptions::RequestError do |exception|
    custom_exception_handler exception.message, exception.backtrace
  end
  # ....

  private

    def custom_exception_handler(message, backtrace)
      raise message.to_yaml
    end

end

As you can see, rescue_from conveniently makes you the exception object available to you as a block parameter. Thus not only do you know that the exception has been raised, but also where (through the backtrace) and any message that is passed along with the exception. Just to confirm, let’s take a look at the output when we visit the new action:

CustomExceptions::RequestError

Viola! Comments, feedback welcome.

I’ve made several attempts at blogging before and they have usually failed rather quite spectacularly. A big reason for this is that I don’t feel comfortable putting something out there that doesn’t add significantly to the material already covered by someone else. However, the primary aim of this blog is to share stuff that I learn and hence I should probably let the reader be the judge of the value of this content. Also, when people are straight away pulling sutff from the Rails Guides/ RDocs and putting it on their blogs or when they proudly claim Laravel (it might be for a number of reasons, I don’t know anythign about it or the latest happenings in PHP) is a better web framework than Rails because it is easier to install, I suppose it should be pretty safe to put my material out there. Also, it should save me from the embarrassment of searching for solutions to problems that I’ve already solved before. So, that’s settled then. Onward!*

"Muad’drin tia dar allende caba’drin rhiadem! Los Valdar Cuebiyari! Los! Carai an Caldazar! Al Caldazar! (Did I mention I am WoT Fan??)

This may seem like the poster child for "First World Problems Meme" in the programming world, but the Ruby/ Rails Community just moves too damned fast! I am away for 4 months on a non-programming job and once I get back, so much has changed. All of a sudden, all the nice little gems that fit so well together seemed to hate each other. I had to build a site real fast in order to obtain freedom from my job and I made some pretty horrid framework decisions along the way. While most of it was because I was in an awful hurry to finish the damned thing, some of it was really stupidity. Anyway, this is what I eventually went with:

  • Rails 3.2.16
  • twitter-bootswatch-rails (less based framework that supports bootswatch)
  • Simple Form
  • Rails Admin
  • font-awesome-rails

I initially chose Rails 3 because I found out client side validations was no longer supported in Rails 4. Turned out that it was a pretty bad decision as the Rails 3 branches are hardly receiving updates. Anyway, from then on started the nightmare of getting everything to fit together. Some of the problems I ended up facing are:

  • Twitter Bootswatch Rails had different versions of bootstrap and bootswatch. I ultimately ended up getting an older version of bootstrap and patching the variables.less file so that bootstrap and bootswatch played well together.
  • Simple form does not support bootstrap
  • After some googling, I ended up using a fork of Simple Form. I think the simple form initializer threw one error, but commenting out the offending line took care of things. My gem file entry is as below:

gem 'simple_form', github: 'wtfiwtz/simple_form_bootstrap3', branch: 'rails_3'
  • Rails Admin (branch 3.x) uses Font-Awesome 3.2 and font-awesome-rails was using font-awesome 4. While all my code was initially using FA-4 with the font-awesome-less gem, once I added Rails Admin my icons did not show up. My guess is that sprockets was including only one version and after one embarrassing demo where RailsAdmin stopped showing any icons, I ended up switching to font-awesome-rails and that too version 3.2.1.3. What was really odd was that I this happened only in production and I had no trouble in development. My guess is something happened during the asset precompile. Anyway, I decided that I had enough and I switched to font-awesome-rails and edited all my icon markup to match that of FA-3.2. I finally had icons working at the same time both on my app as well as rails_admin.

It was a frustrating exercise but it felt good to be coding again. I am going to stick to Rails 4 in the future though and although I haven’t used it yet, I am going to start using the rails_layout gem from now on!

A vote of thanks to the nice folks at the RailsApps Project whose articles were extremely helpful.