recursive-open-struct icon indicating copy to clipboard operation
recursive-open-struct copied to clipboard

Get Defined Properties/Keys

Open trevorh opened this issue 1 year ago • 1 comments

Hi,

I just came across your gem as a replacement for Hashie::Mash w/ StrictKeyAccess enabled. I've been having some odd issues that others have had as well.

ROS seems like almost a perfect fit, but I have no way to easily introspect the properties/keys of an object. When I have raise_on_missing: enabled, I really would like to be able check for the presence of a key without resorting to respond_to?.

Specifically, I'm using this with Faraday and am trying out my own middleware based on the Mashify middleware but renamed to Rosify obviously :) . Essentially, it converts any response body to a ROS object when possible.

To get the list of keys I've added a refinement to use when I need it.

  refine RecursiveOpenStruct do
    def _struct_keys
      @table.keys
    end
  end

Is there anything I'm missing or why I shouldn't do something like this?

Thanks!

trevorh avatar Jun 24 '24 23:06 trevorh

The refinement seems to work for me (when run as a ruby file) with Ruby 3.3.1:

require 'recursive-open-struct'

module M
  refine RecursiveOpenStruct do
    def _struct_keys
      @table.keys
    end
  end
end

using M

r = RecursiveOpenStruct.new({a: :b, c: :d}, raise_on_missing: true)

puts r._struct_keys
# a
# c

If you want to inspect the current state (eg, of the table), would RecursiveOpenStruct#to_h meet your needs? (eg, r.to_h.keys)

aetherknight avatar Jun 25 '24 03:06 aetherknight