Thursday, January 26, 2017

Nested send and hash/array access for Ruby Objects

I had to do some work where I needed to be able to perform nested calls to an object mixing both send 'sending' and accessing data from a hash/array in a single call. In this gist I've put together a method that can be added to the base Ruby Object that lets you perform complex nested calls. For example
value = obj.send_nested("data.foo['bar'].id")
and under the hood this will do something akin to
obj.send(data).send(foo)['bar'].send(id)
This also works with symbols in the attribute string
value = obj.send_nested('data.foo[:bar][0].id')
which will do something akin to
obj.send(data).send(foo)[:bar][0].send(id)
In the event that you want to use indifferent access you can add that as a parameter as well. E.g.
value = obj.send_nested('data.foo[:bar][0].id', with_indifferent_access: true)
Since it's a bit more involved, here is the link to the gist that you can use to add that method to the base Ruby Object. The gist also includes the relevant tests for your peace of mind.