lib/ostruct.rb in ostruct-0.3.3 vs lib/ostruct.rb in ostruct-0.4.0
- old
+ new
@@ -105,11 +105,11 @@
# ending with `!`.
#
# For all these reasons, consider not using OpenStruct at all.
#
class OpenStruct
- VERSION = "0.3.3"
+ VERSION = "0.4.0"
#
# Creates a new OpenStruct object. By default, the resulting OpenStruct
# object will have no attributes.
#
@@ -195,11 +195,11 @@
# require "ostruct"
# data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
# data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]]
#
def each_pair
- return to_enum(__method__) { @table.size } unless block_given?
+ return to_enum(__method__) { @table.size } unless block_given!
@table.each_pair{|p| yield p}
self
end
#
@@ -324,12 +324,14 @@
end
@table.dig(name, *names)
end
#
- # Removes the named field from the object. Returns the value that the field
- # contained if it was defined.
+ # Removes the named field from the object and returns the value the field
+ # contained if it was defined. You may optionally provide a block.
+ # If the field is not defined, the result of the block is returned,
+ # or a NameError is raised if no block was given.
#
# require "ostruct"
#
# person = OpenStruct.new(name: "John", age: 70, pension: 300)
#
@@ -339,17 +341,22 @@
# Setting the value to +nil+ will not remove the attribute:
#
# person.pension = nil
# person # => #<OpenStruct name="John", pension=nil>
#
+ # person.delete_field('number') # => NameError
+ #
+ # person.delete_field('number') { 8675_309 } # => 8675309
+ #
def delete_field(name)
sym = name.to_sym
begin
singleton_class.remove_method(sym, "#{sym}=")
rescue NameError
end
@table.delete(sym) do
+ return yield if block_given!
raise! NameError.new("no field `#{sym}' in #{self}", sym)
end
end
InspectKey = :__inspect_key__ # :nodoc:
@@ -444,7 +451,8 @@
new_name = "#{method}!"
alias_method new_name, method
end
# Other builtin private methods we use:
alias_method :raise!, :raise
- private :raise!
+ alias_method :block_given!, :block_given?
+ private :raise!, :block_given!
end