HomeHome ArchiveArchive

what fields does this OpenStruct instance have?

OpenStruct is a nice tool to work with. However…

Let’s say you do this:

user    = OpenStruct.new( :name => "Franca Botanica", :uid => "777" )
address = OpenStruct.new( :user => user, :country => "Paraguay" )

some_stuff = []
some_stuff << user
some_stuff << address

and now you want to iterate over the some\_stuff collection and want to dump all those “containers” you created. But how do you find out which fields those OpenStruct instances have?

You could consult the documentation and be tempted to inspect them:

some_stuff.each { |c| c.inspect }

Let’s try it:

p address.inspect

"#<OpenStruct country=\"Paraguay\", user=#<OpenStruct ...>>"

Not terribly useful, is it? Instead of parsing that stuff, we can do some white box engineering and do:

class OpenStruct
  def fields
    @table.keys
  end
end

Now we can instead do:

p address.fields

… and be sure, that our code will break once OpenStruct will be re-engineerd. Let’s see what ruby’s gatekeepers think of this