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

3 tips to write better Rails URL helpers

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 PostsHelper module_function def post_path_with_date(post, **options) Rails.application.routes.url_helpers.post_path( permalink: post.permalink, year: post.published_on.strftime('%Y'), month: post.published_on.strftime('%m'), day: post.published_on.strftime('%d'), **options ) end end 1234567891011 module PostsHelper   module_function def post_path_with_date(post, **options)     Rails.application.routes.url_helpers.post_path(       permalink: post.permalink,       year: post.published_on.strftime('%Y'),       month: post.published_on.strftime('%m'),       day: post.published_on.strftime('%d'),       **options     )   end end # 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: Post.all.map { |p| PostsHelper.post_path_with_date(p, only_path: false, host: 'https://blog.7sheep.net' )} 1234 Post.all.map { |p| PostsHelper.post_path_with_date(p,   only_path: false,   host: 'https://blog.7sheep.net' )} Really neat,...