[ruby/ostruct] Add access to public instance methods in case they are overriden

This commit is contained in:
Marc-Andre Lafortune 2020-09-08 17:13:29 -04:00
parent 12a13eef49
commit 12a2e32d43
2 changed files with 37 additions and 2 deletions

View File

@ -62,8 +62,7 @@
# first_pet # => #<OpenStruct name="Rowdy">
# first_pet == second_pet # => true
#
#
# == Implementation
# == Caveats
#
# An OpenStruct utilizes Ruby's method lookup structure to find and define the
# necessary methods for properties. This is accomplished through the methods
@ -72,10 +71,41 @@
# This should be a consideration if there is a concern about the performance of
# the objects that are created, as there is much more overhead in the setting
# of these properties compared to using a Hash or a Struct.
# Creating an open struct from a small Hash and accessing a few of the
# entries can be 200 times slower than accessing the hash directly.
#
# This may also be the source of incompatibilities between Ruby versions:
#
# o = OpenStruct.new
# o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6
#
# Builtin methods may be overwritten this way, which may be a source of bugs
# or security issues:
#
# o = OpenStruct.new
# o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, ...
# o.methods = [:foo, :bar]
# o.methods # => [:foo, :bar]
#
# To help remedy clashes, OpenStruct uses only protected/private methods ending with `!`
# and defines aliases for builtin public methods by adding a `!`:
#
# o = OpenStruct.new(make: 'Bentley', class: :luxury)
# o.class # => :luxury
# o.class! # => OpenStruct
#
# It is recommended (but not enforced) to not use fields ending in `!`.
#
# For all these reasons, consider not using OpenStruct at all.
#
class OpenStruct
VERSION = "0.2.0"
instance_methods.each do |method|
new_name = "#{method}!"
alias_method new_name, method
end
#
# Creates a new OpenStruct object. By default, the resulting OpenStruct
# object will have no attributes.

View File

@ -241,4 +241,9 @@ class TC_OpenStruct < Test::Unit::TestCase
assert_equal(:foo, os.method)
assert_equal(:bar, os.class)
end
def test_access_original_methods
os = OpenStruct.new(method: :foo)
assert_equal(os.object_id, os.method!(:object_id).call)
end
end