1 # frozen_string_literal: true
3 # = ostruct.rb: OpenStruct implementation
5 # Author:: Yukihiro Matsumoto
6 # Documentation:: Gavin Sinclair
8 # OpenStruct allows the creation of data objects with arbitrary attributes.
9 # See OpenStruct for an example.
13 # An OpenStruct is a data structure, similar to a Hash, that allows the
14 # definition of arbitrary attributes with their accompanying values. This is
15 # accomplished by using Ruby's metaprogramming to define methods on the class
22 # person = OpenStruct.new
23 # person.name = "John Smith"
26 # person.name # => "John Smith"
28 # person.address # => nil
30 # An OpenStruct employs a Hash internally to store the attributes and values
31 # and can even be initialized with one:
33 # australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
34 # # => #<OpenStruct country="Australia", capital="Canberra">
36 # Hash keys with spaces or characters that could normally not be used for
37 # method calls (e.g. <code>()[]*</code>) will not be immediately available
38 # on the OpenStruct object as a method for retrieval or assignment, but can
39 # still be reached through the Object#send method or using [].
41 # measurements = OpenStruct.new("length (in inches)" => 24)
42 # measurements[:"length (in inches)"] # => 24
43 # measurements.send("length (in inches)") # => 24
45 # message = OpenStruct.new(:queued? => true)
46 # message.queued? # => true
47 # message.send("queued?=", false)
48 # message.queued? # => false
50 # Removing the presence of an attribute requires the execution of the
51 # delete_field method as setting the property value to +nil+ will not
52 # remove the attribute.
54 # first_pet = OpenStruct.new(:name => "Rowdy", :owner => "John Smith")
55 # second_pet = OpenStruct.new(:name => "Rowdy")
57 # first_pet.owner = nil
58 # first_pet # => #<OpenStruct name="Rowdy", owner=nil>
59 # first_pet == second_pet # => false
61 # first_pet.delete_field(:owner)
62 # first_pet # => #<OpenStruct name="Rowdy">
63 # first_pet == second_pet # => true
65 # Ractor compatibility: A frozen OpenStruct with shareable values is itself shareable.
69 # An OpenStruct utilizes Ruby's method lookup structure to find and define the
70 # necessary methods for properties. This is accomplished through the methods
71 # method_missing and define_singleton_method.
73 # This should be a consideration if there is a concern about the performance of
74 # the objects that are created, as there is much more overhead in the setting
75 # of these properties compared to using a Hash or a Struct.
76 # Creating an open struct from a small Hash and accessing a few of the
77 # entries can be 200 times slower than accessing the hash directly.
79 # This is a potential security issue; building OpenStruct from untrusted user data
80 # (e.g. JSON web request) may be susceptible to a "symbol denial of service" attack
81 # since the keys create methods and names of methods are never garbage collected.
83 # This may also be the source of incompatibilities between Ruby versions:
86 # o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6
88 # Builtin methods may be overwritten this way, which may be a source of bugs
92 # o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, ...
93 # o.methods = [:foo, :bar]
94 # o.methods # => [:foo, :bar]
96 # To help remedy clashes, OpenStruct uses only protected/private methods ending with <code>!</code>
97 # and defines aliases for builtin public methods by adding a <code>!</code>:
99 # o = OpenStruct.new(make: 'Bentley', class: :luxury)
100 # o.class # => :luxury
101 # o.class! # => OpenStruct
103 # It is recommended (but not enforced) to not use fields ending in <code>!</code>;
104 # Note that a subclass' methods may not be overwritten, nor can OpenStruct's own methods
105 # ending with <code>!</code>.
107 # For all these reasons, consider not using OpenStruct at all.
112 HAS_PERFORMANCE_WARNINGS = begin
113 Warning[:performance]
115 rescue NoMethodError, ArgumentError
118 private_constant :HAS_PERFORMANCE_WARNINGS
121 # Creates a new OpenStruct object. By default, the resulting OpenStruct
122 # object will have no attributes.
124 # The optional +hash+, if given, will generate attributes and values
125 # (can be a Hash, an OpenStruct or a Struct).
129 # hash = { "country" => "Australia", :capital => "Canberra" }
130 # data = OpenStruct.new(hash)
132 # data # => #<OpenStruct country="Australia", capital="Canberra">
134 def initialize(hash=nil)
135 if HAS_PERFORMANCE_WARNINGS && Warning[:performance]
136 warn "OpenStruct use is discouraged for performance reasons", uplevel: 1, category: :performance
140 update_to_values!(hash)
146 # Duplicates an OpenStruct object's Hash table.
147 private def initialize_clone(orig) # :nodoc:
148 super # clones the singleton class for us
149 @table = @table.dup unless @table.frozen?
152 private def initialize_dup(orig) # :nodoc:
154 update_to_values!(@table)
157 private def update_to_values!(hash) # :nodoc:
159 hash.each_pair do |k, v|
160 set_ostruct_member_value!(k, v)
166 # ostruct.to_h -> hash
167 # ostruct.to_h {|name, value| block } -> hash
169 # Converts the OpenStruct to a hash with keys representing
170 # each attribute (as symbols) and their corresponding values.
172 # If a block is given, the results of the block on each pair of
173 # the receiver will be used as pairs.
176 # data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
177 # data.to_h # => {:country => "Australia", :capital => "Canberra" }
178 # data.to_h {|name, value| [name.to_s, value.upcase] }
179 # # => {"country" => "AUSTRALIA", "capital" => "CANBERRA" }
181 if {test: :to_h}.to_h{ [:works, true] }[:works] # RUBY_VERSION < 2.6 compatibility
192 @table.map(&block).to_h
201 # ostruct.each_pair {|name, value| block } -> ostruct
202 # ostruct.each_pair -> Enumerator
204 # Yields all attributes (as symbols) along with the corresponding values
205 # or returns an enumerator if no block is given.
208 # data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
209 # data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]]
212 return to_enum(__method__) { @table.size } unless defined?(yield)
213 @table.each_pair{|p| yield p}
218 # Provides marshalling support for use by the Marshal library.
220 def marshal_dump # :nodoc:
225 # Provides marshalling support for use by the Marshal library.
227 alias_method :marshal_load, :update_to_values! # :nodoc:
230 # Used internally to defined properties on the
231 # OpenStruct. It does this by using the metaprogramming function
232 # define_singleton_method for both the getter method and the setter method.
234 def new_ostruct_member!(name) # :nodoc:
235 unless @table.key?(name) || is_method_protected!(name)
236 if defined?(::Ractor)
237 getter_proc = nil.instance_eval{ Proc.new { @table[name] } }
238 setter_proc = nil.instance_eval{ Proc.new {|x| @table[name] = x} }
239 ::Ractor.make_shareable(getter_proc)
240 ::Ractor.make_shareable(setter_proc)
242 getter_proc = Proc.new { @table[name] }
243 setter_proc = Proc.new {|x| @table[name] = x}
245 define_singleton_method!(name, &getter_proc)
246 define_singleton_method!("#{name}=", &setter_proc)
249 private :new_ostruct_member!
251 private def is_method_protected!(name) # :nodoc:
252 if !respond_to?(name, true)
254 elsif name.match?(/!$/)
257 owner = method!(name).owner
258 if owner.class == ::Class
261 self.class!.ancestors.any? do |mod|
262 return false if mod == ::OpenStruct
274 private def method_missing(mid, *args) # :nodoc:
276 if mname = mid[/.*(?==\z)/m]
278 raise! ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1)
280 set_ostruct_member_value!(mname, args[0])
286 rescue NoMethodError => err
295 # ostruct[name] -> object
297 # Returns the value of an attribute, or +nil+ if there is no such attribute.
300 # person = OpenStruct.new("name" => "John Smith", "age" => 70)
301 # person[:age] # => 70, same as person.age
309 # ostruct[name] = obj -> obj
311 # Sets the value of an attribute.
314 # person = OpenStruct.new("name" => "John Smith", "age" => 70)
315 # person[:age] = 42 # equivalent to person.age = 42
320 new_ostruct_member!(name)
323 alias_method :set_ostruct_member_value!, :[]=
324 private :set_ostruct_member_value!
327 # ostruct.dig(name, *identifiers) -> object
329 # Finds and returns the object in nested objects
330 # that is specified by +name+ and +identifiers+.
331 # The nested objects may be instances of various classes.
332 # See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
336 # address = OpenStruct.new("city" => "Anytown NC", "zip" => 12345)
337 # person = OpenStruct.new("name" => "John Smith", "address" => address)
338 # person.dig(:address, "zip") # => 12345
339 # person.dig(:business_address, "zip") # => nil
340 def dig(name, *names)
344 raise! TypeError, "#{name} is not a symbol nor a string"
346 @table.dig(name, *names)
350 # Removes the named field from the object and returns the value the field
351 # contained if it was defined. You may optionally provide a block.
352 # If the field is not defined, the result of the block is returned,
353 # or a NameError is raised if no block was given.
357 # person = OpenStruct.new(name: "John", age: 70, pension: 300)
359 # person.delete_field!("age") # => 70
360 # person # => #<OpenStruct name="John", pension=300>
362 # Setting the value to +nil+ will not remove the attribute:
364 # person.pension = nil
365 # person # => #<OpenStruct name="John", pension=nil>
367 # person.delete_field('number') # => NameError
369 # person.delete_field('number') { 8675_309 } # => 8675309
371 def delete_field(name, &block)
374 singleton_class.remove_method(sym, "#{sym}=")
377 @table.delete(sym) do
378 return yield if block
379 raise! NameError.new("no field '#{sym}' in #{self}", sym)
383 InspectKey = :__inspect_key__ # :nodoc:
386 # Returns a string containing a detailed summary of the keys and values.
389 ids = (Thread.current[InspectKey] ||= [])
390 if ids.include?(object_id)
395 detail = @table.map do |key, value|
396 " #{key}=#{value.inspect}"
402 ['#<', self.class!, detail, '>'].join
406 attr_reader :table # :nodoc:
411 # Compares this object and +other+ for equality. An OpenStruct is equal to
412 # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
416 # first_pet = OpenStruct.new("name" => "Rowdy")
417 # second_pet = OpenStruct.new(:name => "Rowdy")
418 # third_pet = OpenStruct.new("name" => "Rowdy", :age => nil)
420 # first_pet == second_pet # => true
421 # first_pet == third_pet # => false
424 return false unless other.kind_of?(OpenStruct)
425 @table == other.table!
429 # Compares this object and +other+ for equality. An OpenStruct is eql? to
430 # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
434 return false unless other.kind_of?(OpenStruct)
435 @table.eql?(other.table!)
438 # Computes a hash code for this OpenStruct.
444 # Provides marshalling support for use by the YAML library.
446 def encode_with(coder) # :nodoc:
447 @table.each_pair do |key, value|
448 coder[key.to_s] = value
450 if @table.size == 1 && @table.key?(:table) # support for legacy format
451 # in the very unlikely case of a single entry called 'table'
452 coder['legacy_support!'] = true # add a bogus second entry
457 # Provides marshalling support for use by the YAML library.
459 def init_with(coder) # :nodoc:
461 if h.size == 1 # support for legacy format
470 # Make all public methods (builtin or our own) accessible with <code>!</code>:
471 give_access = instance_methods
472 # See https://github.com/ruby/ostruct/issues/30
473 give_access -= %i[instance_exec instance_eval eval] if RUBY_ENGINE == 'jruby'
474 give_access.each do |method|
475 next if method.match(/\W$/)
477 new_name = "#{method}!"
478 alias_method new_name, method
480 # Other builtin private methods we use:
481 alias_method :raise!, :raise
484 # See https://github.com/ruby/ostruct/issues/40
485 if RUBY_ENGINE != 'jruby'
486 alias_method :block_given!, :block_given?
487 private :block_given!