diff options
-rw-r--r-- | ChangeLog | 4 | ||||
-rw-r--r-- | lib/ostruct.rb | 65 |
2 files changed, 58 insertions, 11 deletions
@@ -1,3 +1,7 @@ +Thu Feb 19 22:39:00 2004 Gavin Sinclair <[email protected]> + + * lib/ostruct.rb: documented + Thu Feb 19 22:39:04 2004 NAKAMURA, Hiroshi <[email protected]> * test/rinda/test_rinda.rb: DRb.start_service only once in testsuites. diff --git a/lib/ostruct.rb b/lib/ostruct.rb index eea7132ca0..786bd4de20 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -1,14 +1,48 @@ -# ostruct.rb - Python Style Object -# just assign to create field -# -# s = OpenStruct.new -# s.foo = 25 -# p s.foo -# s.bar = 2 -# p s.bar -# p s +# +# = ostruct.rb: OpenStruct implementation +# +# Author:: Yukihiro Matsumoto +# Documentation:: Gavin Sinclair +# +# OpenStruct allows the creation of data objects with arbitrary attributes. +# See OpenStruct for an example. +# +# +# OpenStruct allows you to create data objects and set arbitrary attributes. +# For example: +# +# require 'ostruct' +# +# record = OpenStruct.new +# record.name = "John Smith" +# record.age = 70 +# record.pension = 300 +# +# puts record.name # -> "John Smith" +# puts record.address # -> nil +# +# It is like a hash with a different way to access the data. In fact, it is +# implemented with a hash, and you can initialize it with one. +# +# hash = { "country" => "Australia", :population => 20_000_000 } +# data = OpenStruct.new(hash) +# +# p data # -> <OpenStruct country="Australia" population=20000000> +# class OpenStruct + # + # Create a new OpenStruct object. The optional +hash+, if given, will + # generate attributes and values. For example. + # + # require 'ostruct' + # hash = { "country" => "Australia", :population => 20_000_000 } + # data = OpenStruct.new(hash) + # + # p data # -> <OpenStruct country="Australia" population=20000000> + # + # By default, the resulting OpenStruct object will have no attributes. + # def initialize(hash=nil) @table = {} if hash @@ -18,7 +52,7 @@ class OpenStruct end end - def method_missing(mid, *args) + def method_missing(mid, *args) # :nodoc: mname = mid.id2name len = args.length if mname =~ /=$/ @@ -37,10 +71,16 @@ class OpenStruct end end + # + # Remove the named field from the object. + # def delete_field(name) @table.delete name.to_sym end + # + # Returns a string containing a detailed summary of the keys and values. + # def inspect str = "<#{self.class}" for k,v in @table @@ -49,9 +89,12 @@ class OpenStruct str << ">" end - attr_reader :table + attr_reader :table # :nodoc: protected :table + # + # Compare this object and +other+ for equality. + # def ==(other) return false unless(other.kind_of?(OpenStruct)) return @table == other.table |