Learning about OpenStruct in Ruby
Boutique Inventory Improvements
A precocious introduction
Working through this challenge was interesting because I had never heard of OpenStruct before! As a part of Ruby's Standard Library, I was genuinely curious because I hadn't seen obvious usages of OpenStruct in my time as a Rails developer.
What makes OpenStruct so cool?
Well once require
-ing it to a Ruby file, you can use it to create a data structure with ease to interact with getting/setting values.
class BoutiqueInventory
attr_reader :items
def initialize(items)
@items = items.map {|i| OpenStruct.new(i)}
end
end
Here I'm taking an array of items and creating an OpenStruct instance on each item.
When I initialize the class, my items
may look like this:
[#<OpenStruct price=30.0, name="Shoes", quantity_by_size={:s=>1, :xl=>4}>,
#<OpenStruct price=65.0, name="Coat", quantity_by_size={}>,
#<OpenStruct price=19.99, name="Handkerchief", quantity_by_size={}>]
I can easily access their item and name by going into a specific index on the array and using method notation to get and set values.
> foo.items[0].name
# get the item's name
=> "Shoes"
> foo.items[0].name = "Slippers"
# Set a new name for the item
=> "Slippers"
> foo.items[0].name
# Confirm that the name has been changed!
=> "Slippers"
What's the catch?
I stumbled upon this discussion of how OpenStruct holds potential security issues. Written by the Ruby docs, they say that it's not recommended to use OpenStruct. It's slower to access values in an OpenStruct class than a Hash. The security issue is that it can be susceptible to a "symbol denial of service" attack due to how OpenStruct can easily create methods, and these are never garbage collected.
So... is OpenStruct bad?
For production code that runs to serve something important... possibly yes. But for silly little Exercism classes like this boutique, I don't think so. It can come in useful if you need to draft up something quickly and will eventually be replaced by more robust code
Learning more about Ruby's metaprogramming should inspire a new adventure regarding OpenStruct's usages or alternatives. However, these writing about Exercism are simple musings as I complete each exercise.