Skip to content

Commit

Permalink
Merge pull request #37 from senny/make_attribute_methods_overridable
Browse files Browse the repository at this point in the history
allow to override attribute setters/getters
  • Loading branch information
solnic committed Nov 15, 2011
2 parents e8b817b + 9e63ab2 commit fbded4e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
40 changes: 40 additions & 0 deletions 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
9 changes: 6 additions & 3 deletions lib/virtus/class_methods.rb
Expand Up @@ -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
Expand Down

0 comments on commit fbded4e

Please sign in to comment.