Debug Rails View Helpers

Some common tasks in the development business are done no matter the programming language you use. Debugging is one of those tasks. While developing web applications I often need to debug the View layer and it is kind of a tedious job to write while loops to inspect variables values, for example.

Rails provides some interesting helper methods for your views:

  • debug
  • to_yaml

debug

This helper method will return the information about any object in YAML format, which is very human readable. To use this command, just type:

<%= debug @logged_user %>

and you will get something like this in a <pre> tag:

--- !ruby/object:User 
attributes: 
  salt: asa87d901284sa90s8ae515cd047a1a83aca9bee6bb
  updated_at: 2009-10-30 23:48:17
  activated_at: 2009-05-05 23:05:21
  crypted_password: klwq3223j2313laaa21aca7891cc1375cc824d8b
  deleted_at: 
  remember_token_expires_at: 2009-11-14 01:48:17
  activation_code: 
  role_id: "2"
  id: "2"
  remember_token: 805d2a2af102d1fdfc3f294bef662ad975874c54
  login: foo
  email: foo@gmail.com
  created_at: 2009-05-05 20:04:58
  state: active
attributes_cache: {}

groups: 
- !ruby/object:Group 
  attributes: 
    updated_at: 2009-05-05 20:05:44
    title: Accounts used by Foo user
    id: "1"
    created_at: 2009-05-05 20:05:44
  attributes_cache: {}

If you look closely you will notice that even the Group object instance which is a member of the User object gets printed and debugged.

Want to get nasty? Add this to your _bottom.rhtml page:

<%= debug request %>

to_yaml

This helper method combined with the simple_format method will produce the same output as the debug method. Just another way to do things.

<%= simple_format @logged_user.to_yaml %>

Read more about this subject on debugging in rails.

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options