summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog5
-rw-r--r--lib/ostruct.rb20
-rw-r--r--test/ostruct/test_ostruct.rb8
3 files changed, 25 insertions, 8 deletions
diff --git a/ChangeLog b/ChangeLog
index 411c50b..ae27a24 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+Sun Feb 15 21:43:44 2009 Nobuyoshi Nakada <nobu@ruby-lang.org>
+
+ * lib/ostruct.rb (OpenStruct#new_ostruct_member): checks if frozen.
+ [ruby-talk:328195], [ruby-core:22142]
+
Sun Feb 15 21:22:48 2009 Nobuyoshi Nakada <nobu@ruby-lang.org>
* lib/test/unit/assertions.rb (Test::Unit::Assertions): aliases
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 35a14b4..45ebb80 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -67,29 +67,33 @@ class OpenStruct
@table.each_key{|key| new_ostruct_member(key)}
end
+ def modifiable
+ if self.frozen?
+ raise TypeError, "can't modify frozen #{self.class}", caller(2)
+ end
+ @table
+ end
+ protected :modifiable
+
def new_ostruct_member(name)
name = name.to_sym
unless self.respond_to?(name)
class << self; self; end.class_eval do
define_method(name) { @table[name] }
- define_method(:"#{name}=") { |x| @table[name] = x }
+ define_method("#{name}=") { |x| modifiable[name] = x }
end
end
+ name
end
def method_missing(mid, *args) # :nodoc:
mname = mid.id2name
len = args.length
- if mname =~ /=$/
+ if mname.chomp!('=')
if len != 1
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
- if self.frozen?
- raise TypeError, "can't modify frozen #{self.class}", caller(1)
- end
- mname.chop!
- self.new_ostruct_member(mname)
- @table[mname.intern] = args[0]
+ modifiable[new_ostruct_member(mname)] = args[0]
elsif len == 0
@table[mid]
else
diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb
index 79662c6..37b7cd1 100644
--- a/test/ostruct/test_ostruct.rb
+++ b/test/ostruct/test_ostruct.rb
@@ -34,4 +34,12 @@ class TC_OpenStruct < Test::Unit::TestCase
foo.bar.foo = foo
assert_equal('#<OpenStruct bar=#<OpenStruct foo=#<OpenStruct ...>>>', foo.inspect)
end
+
+ def test_frozen
+ o = OpenStruct.new
+ o.a = 'a'
+ o.freeze
+ assert_raise(TypeError) {o.b = 'b'}
+ assert_not_respond_to(o, :b)
+ end
end