ostruct
ostruct copied to clipboard
Recursively converting child hash attributes to OpenStruct.
This PR can enable something like this:
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.more_info = {interests: ['singing', 'dancing'], tech_skills: ['Ruby', 'C++']}
puts person.more_info.interests
puts person.more_info.tech_skills
Hi @hsbt , Did you get a chance to review this PR? What do you think about the changes?
Regards, Abhilash
No maintainer or someone to have decision, but before going forward I'd suggest two things:
- A set of benchmarking on this. How this will impact the current code.
- Tests
Additionally, as being a new feature this should be proposed via https://bugs.ruby-lang.org ticket, will be discussed there (if not rejected before).
It's fine to propose a feature/change without having tests, etc., as a way to first check if the feature is acceptable or not.
In this case I believe it isn't, for compatibility reasons. OpenStruct
doesn't respond to all the methods of Hash
, so if someone is already storing a hash in an attribute of an OpenStruct
, she is expecting that attribute to be a Hash
.
In the example above, person.more_info.transform_values{ ... }
would no longer work.
@marcandre Thanks for the response!! I completely agree with your feedback. But there are a lot of people out there expecting OpenStruct to recursively convert a child hash to another OpenStruct object. So, why not provide them with an option to recursively convert child hash objects to OpenStruct object? Maybe allowing users to pass additional options to constructor would help?
Like this:
def initialize(hash=nil, options={})
...
end
Adding a recursive: true
or similar option to the constructor seems to me like a much better idea :smile:
The official forum to get a new feature accepted is https://bugs.ruby-lang.org/ . Best thing at this point would be to make the feature request there to see if there are any objections.
If you'd like to work on the implementation, you can amend this PR too. You'll need tests, also I'd use respond_to? :to_hash
as a check.
@marcandre Thanks! Like you suggested I will create a feature request on https://bugs.ruby-lang.org/ 😃
+1 for the PR
Just FYI, A feature request has been created here https://bugs.ruby-lang.org/issues/15225
Hi there! Any news?
I updated https://bugs.ruby-lang.org/issues/15225