The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.
OpenStruct is a class from the Ruby Standard Library. Here’s how it’s described in the docs:
OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values.
Basically, it uses metaprogramming and the method_missing method to obtain some really cool functionality that allows you to dynamically set attributes and store values. Take a look at the example they provide:
When I first saw this, I though that there must be a ton of crazy stuff going on under the hood. I’m sure the actual class in the Standard Lib is pretty advanced and has to handle all sorts of edge cases, but it is pretty easy to roll your own simple version. Check it out:
Pretty simple, right? Lets walk through it:
Whenever a method that isn’t defined is called on an AwesomeStruct instance, the method_missing method is called. The name of the method is passed in along with the value if there was one. On line 8, we check to see if the method called was a setter method (i.e. anything=). If it is, we define the method name as the key in a hash and point it to the value that was sent in. If the method is not a setter method, we just return that value from the hash.
Make yourself useful.