Skip to content

Commit

Permalink
define field methods in an included module
Browse files Browse the repository at this point in the history
replicates ActiveModel behaviour which allows you to override a field
method and still call super
  • Loading branch information
adzap committed Nov 4, 2010
1 parent 64d6dec commit ee64f1d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/mongoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,21 @@ def set_field(name, options = {})

# Create the field accessors.
def create_accessors(name, meth, options = {})
define_method(meth) { read_attribute(name) }
define_method("#{meth}=") { |value| write_attribute(name, value) }
define_method("#{meth}?") do
attr = read_attribute(name)
(options[:type] == Boolean) ? attr == true : attr.present?
generated_field_methods.module_eval do
define_method(meth) { read_attribute(name) }
define_method("#{meth}=") { |value| write_attribute(name, value) }
define_method("#{meth}?") do
attr = read_attribute(name)
(options[:type] == Boolean) ? attr == true : attr.present?
end
end
end

def generated_field_methods
@generated_field_methods ||= begin
mod = Module.new
include mod
mod
end
end
end
Expand Down
13 changes: 13 additions & 0 deletions spec/unit/mongoid/fields_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@
Person.new.testing?.should be_false
end

it "adds field methods in a module to allow overriding and preserve inheritance" do
Person.class_eval do
attr_reader :testing_override_called
def testing=(value)
@testing_override_called = true
super
end
end

@person = Person.new
@person.testing = 'Test'
@person.testing_override_called.should be_true
end
end

context "when the type is an object" do
Expand Down

0 comments on commit ee64f1d

Please sign in to comment.