Permalink
Browse files

Merge pull request #37 from senny/make_attribute_methods_overridable

allow to override attribute setters/getters
  • Loading branch information...
2 parents e8b817b + 9e63ab2 commit fbded4e9e359e0a19903f1154633ddbe9042f33b @solnic committed Nov 15, 2011
Showing with 46 additions and 3 deletions.
  1. +40 −0 examples/override_attribute_methods_spec.rb
  2. +6 −3 lib/virtus/class_methods.rb
View
40 examples/override_attribute_methods_spec.rb
@@ -0,0 +1,40 @@
+require './spec/spec_helper'
+
+class Article
+ include Virtus
+
+ attribute :author, String
+
+ def author
+ super || '<unknown>'
+ end
+
+ def author=(name)
+ super unless name == 'Brad'
+ end
+
+end
+
+describe Article, 'override' do
+
+ it 'Alice is an allowed author' do
+ Article.new(:author => 'Alice').author.should == 'Alice'
+ end
+
+ it 'Brad isn not an allowed author' do
+ Article.new(:author => 'Brad').author.should == '<unknown>'
+ end
+
+ context 'with author' do
+ subject { Article.new(:author => 'John') }
+
+ its(:author) { should == 'John' }
+ end
+
+ context 'without author' do
+ subject { Article.new }
+
+ its(:author) { should == '<unknown>' }
+ end
+
+end
View
9 lib/virtus/class_methods.rb
@@ -99,9 +99,12 @@ def const_missing(name)
#
# @api private
def virtus_define_attribute_methods(attribute)
- attribute.define_reader_method(self)
- attribute.define_writer_method(self)
- include self::AttributeMethods
+ module_with_methods = self::AttributeMethods
+
+ attribute.define_reader_method(module_with_methods)
+ attribute.define_writer_method(module_with_methods)
+
+ include module_with_methods
end
# Add the attribute to the class' and descendants' attributes

0 comments on commit fbded4e

Please sign in to comment.