Browse files

support for overloading property getters/setters

  • Loading branch information...
1 parent b082f58 commit fd37f387e37d56161b2631525bf1e86ca1cbcd9d @mislav committed Aug 10, 2011
Showing with 14 additions and 2 deletions.
  1. +4 −2 lib/mingo/properties.rb
  2. +10 −0 spec/mingo_spec.rb
View
6 lib/mingo/properties.rb
@@ -11,12 +11,13 @@ module Properties
module ClassMethods
attr_reader :properties
- def property(name, options = {})
+ def property(name, options = nil)
self.properties << name.to_sym
setter_name = "#{name}="
unless method_defined?(setter_name)
- class_eval <<-RUBY, __FILE__, __LINE__
+ methods = Module.new
+ methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{name}(&block)
self.[](#{name.to_s.inspect}, &block)
end
@@ -25,6 +26,7 @@ def #{setter_name}(value)
self.[]=(#{name.to_s.inspect}, value)
end
RUBY
+ include methods
end
if defined? @subclasses
View
10 spec/mingo_spec.rb
@@ -6,6 +6,10 @@
class User < Mingo
property :name
property :age
+
+ def age=(value)
+ super(value.nil? ? nil : value.to_i)
+ end
end
describe User do
@@ -76,6 +80,12 @@ class User < Mingo
doc.should have_key('name')
end
end
+
+ it "supports overloading the setter method" do
+ user = build
+ user.age = '12'
+ user.age.should == 12
+ end
context "existing doc" do
before do

0 comments on commit fd37f38

Please sign in to comment.