Wildcards In Rails Redirects

The captured wildcard in a Rails 3 route can be used in the redirect method:

match 'via/:source' => redirect('/?utm_source=%{source}')

This example is intended to improve metrics for customer acquisition campaigns. utm_source is for Google Analytics, which KISSMetrics logs as Ad Campaign Hits.

The URLs are now friendlier for sharing:

/via/email
/via/twitter
/via/search-ads
/via/blog-ads

When the user clicks them, they’ll be redirected to:

/?utm_source=email
/?utm_source=twitter
/?utm_source=search-ads
/?utm_source=blog-ads

The URLs are also encapsulated. If the Google Analytics params need to change, the developer can edit config/routes.rb and deploy. All past routes will still work.

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.