I recently ran into a Rubocop error that was complaining about my use of OpenStruct in a project. Okay, I don’t like linter errors, so time to fix it.
At the time I was converting a ruby Hash object to an OpenStruct. The use case was more or less as a presenter object in a view. For things like that, an object can be nicer to work with than a hash. But, the linter didn’t like my use of OpenStruct.
The answer in my case was to use a Struct instead of OpenStruct. But, I wanted the nice freedom of being able to just turn whatever is in my Hash object into a Struct. I’m going to do this more than once so I don’t want to define a new Struct every time.
So here is the code I came up with:
The input is a Hash object. The output is a Struct with same set of key/value pairs as the Hash. So in practice if you had a Hash that looked like this:
{ foo: 1, bar: ’wat’}
You could access the values as you would a normal object. For example:
So this approach works well enough for simple data structures, but falls down a bit on nested data structures. It doesn’t recursively create child Structs for each node in the Hash, so if you have nested Hash objects, it’s not going to be ideal.
In places where you have simple Hash objects that don’t do a lot of nesting, this is a nice approach and might save you the headache of defining the fields for each Struct when you just want to do a simple as-is conversion. Any more complexity and you would need to modify the above code (or just realize you’ll have nested Hashes which is fine too).
That’s it for this Ruby tutorial. See you later!
-Brian