What is OpenStruct used for?

I have come accross OpenStruct quite a lot recently as I venture into other peoples code on GitHub or watching a few conferences online.

Can somebody please explain what is is and why you use it?

I have seen Struct also, could someone explain what this is too and also what the difference between OpenStruct and Struct are ?

I saw this recently in a conference @benorenstein did last year at Rocky Mountain Ruby some of the code was this:

class DateRange < Struct.new(:start_date, :end_date)
end

class Order < OpenStruct
  def placed_between?(date_range)
    placed_at >= date_range.start_date &&
      place_at <= date_range.end_date
  end
end

Thanks

1 Like

So I believe they are both just convenient ways to bundle a bunch of attributes into a object. The difference between the two is in their initialization, a Struct takes position order arguments while OpenStruct will take a hash and derive attributes from it.

Both are used when a class is too heavy handed but you still need to represent something as an object. It seems like a good practice to use them to represent data over things like arrays of hashes because later on, when/if the code needs to change it is simple enough to swap out the structs for new, more complex objects.

@deviousduck is right. If you’re building lots of small, non-ActiveRecord classes, and you find yourself setting up a objects where the #initialize method just sets the arguments to instance variables, and then you’re referencing those same variables through attr_reader, your class might be a good candidate for a Struct. I often don’t use it because by the time I realize I need it I’ve already done all that work, but it’s a nice pattern for simple classes.

1 Like