US +1 650 600 3955 | EU +43 720 115 215 office@7sheep.net

This is a typical Rails URL helper I write these days, and I encourage you to do the same. Why? Let me explain it here, but first the helper:

# module_function

By using Ruby’s module_function you can create a global helper which can be called like PostsHelper.post_path_with_date(post). This allows you to use this helper outside its typical context, but without breaking existing functionality. Your views will still work, and you can use your helper inside Rails console or any Rake task as well. Win-win!

# routes.url_helpers

Rails’ magic does a lot for you helping to write as little code as necessary. For example, it mixes all your url helpers into your view context. But once you step out of this context, a lot of the magic is gone. Be sure to always access your urls with Rails.application.routes.url_helpers to be safe from any unpleasant surprises.

# kwargs

or keyword arguments are my personal favourite of Ruby 2.0. And if you’re already using a recent version (and you really should so), don’t hesitate to use them already now. By passing the given kwargs to the route helper, you can easily customize your routes for your needs. For example, the other day I needed all blog post URLs including our domain:

Really neat, huh?