views:

153

answers:

3

I want to print out some debug messages in my erb template when it is called in development mode, but not when it is called in production mode (i.e.)

<%= debug variable_name %>

However, this will be printed in any mode.

I found I can do

<% if logger.debug?
     debug variable_name
   end %>

which seems to work. Is this the proper way, or is there a more elegant solution?

+1  A: 

I'll look around for a better way but for now that could be a one liner:

<%= debug(variable) if logger.debug? %>

Edit: If you're going to have this type of code everywhere maybe a helper would do the trick.

def fancy_debuggin(f)
  debug(f) if logger.debug?
end

<%= fancy_debuggin(variable) %>
Andy Gaskell
+1  A: 

You don't need to call the logger.debug? function to test if logging is switched on you can place a direct call to logger.debug.

There is a performance hit, usually pretty marginal, with this approach as you have to evaluate the string passed to the logger.debug method even if the logger is not at debug level. This is only a problem where you have a relatively expensive string.

So your code would look something like this

<%= logger.debug(variable) %>
Steve Weet
That doesn't print out to the view though right?
Andy Gaskell
Well that depends. When the log level is set to debug it does. When it's set to a higher level e.g. info or warn then no it doesn't.
Steve Weet
+1  A: 

You probably want to do something like this:

<%= debug(variable) if RAILS_ENV == 'development %>

If you're doing this often, you might want to create a quick helper method to clean up the code a little more:

def my_debug(debug_variable)
debug_variable if RAILS_ENV == 'development'
end

Then you can do this in your erb template/view

my_debug(variable_here)
Carlos