At one point a while back, I had a config file outside a rails app and what I wanted was something like this:
Given this mappping definition
/order/:meal/:cheese
How can I turn these strings into parsed hashes?/order/hotdog/cheddar -> {meal:'hotdog', cheese:'cheddar'}
I knew that something in Rails was doing this. I just didn’t know what. I also didn’t know what assumptions or abstraction level it was working at.
Journey into Journey
The gem that handles parsing the routes file and creating a tree is journey.
Journey used to be (years ago) a separate gem but is not integrated into
action_dispatch
which itself is a part of actionpack
. So to install it you
need to gem install actionpack
(or use bundler) but to include it in your
program you need to require 'action_dispatch/journey'
. If you have
any rails 4+ gem installed on your system, you don’t need to install
anything. Action pack comes with rails.
We have to have hashify_match
reorganize our objects because this is what
pattern.match
returns:
So we have to turn these ordered matches into a hash.
We could also zip the results together but we wouldn’t have symbolized keys.
You could symbolize them easily within a rails app or by including active support.