RAILS_DEFAULT_LOGGER

February 27, 2007

Just a simple problem

It all started when I wanted to add the Rails default logger to some code I was working on. The code sits in the lib directory and I wanted to use the same logger the controllers and models use. Without thinking I threw a call to logger.info(”whatever”) in my code. Obviously that’s not going to work as I quickly got an error. Fortunately a quick google search turned up this. Basically to use the logger in my code I simply needed to call the constant RAILS_DEFAULT_LOGGER. Ok, great. Problem solved. Time to move on. But something caught my curiosity. How is Rails setting this constant and making it available to my Class ?

The plot thickens

So I decide to dig in. Luckily I start by looking at the code in initializer.rb. Rails::Initializer is called when your app boots up. It does most of the heavy lifting configuring the environment for Rails. Right around line 258, I find the answer to the constant mystery:


  Object.const_set "RAILS_DEFAULT_LOGGER", logger

Great. Ok now I can move on…but what the heck is


  Object.const_set

An aha moment

As it turns out the method const_set allows you to set a constant on the given object. In our case we’re setting the constant on Object - the parent of all classes in Ruby. So let’s see how this works…fire-up IRB and follow along:

Let’s start by seeing what constants Object already has. Ruby makes that easy:


  > Object.constants

As you can see (in your IRB terminal) Object comes with a large list of constants already. Ok let’s add our own


  > Object.const_set("WHOS_THE_MAN", "DAVE_IS")
  > Object.constants

Wow, you just added a constant to the supreme Ruby Object. Next, let’s see how we can get to this in our own classes:


  class Test
    def whos_the_man?
      puts WHOS_THE_MAN
    end
  end
  t = Test.new
  t.whos_the_man => DAVE_IS

So there you have it. A clever way to add constants that are available throughout your Ruby app. Of course you’re not limited to just adding to Object. Your Class can have it’s own constants that are scoped to it and its subclasses. You gotta love this language!

Trackbacks

Unfortunately, due to spammers I've had to close both trackbacks and comments.

Comments

Comments are closed.