Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get Defined Properties/Keys #77

Open
trevorh opened this issue Jun 24, 2024 · 1 comment
Open

Get Defined Properties/Keys #77

trevorh opened this issue Jun 24, 2024 · 1 comment

Comments

@trevorh
Copy link

trevorh commented Jun 24, 2024

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!

@aetherknight
Copy link
Owner

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants