Skip to content

Commit

Permalink
allow attribute accessors to be overwritten and use super
Browse files Browse the repository at this point in the history
  • Loading branch information
langalex committed Sep 18, 2009
1 parent 9202bd3 commit 30e90b0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 27 deletions.
69 changes: 42 additions & 27 deletions lib/couch_potato/persistence/simple_property.rb
Expand Up @@ -6,7 +6,48 @@ class SimpleProperty #:nodoc:
def initialize(owner_clazz, name, options = {})
self.name = name
self.type = options[:type]
owner_clazz.class_eval do

define_accessors accessors_module_for(owner_clazz), name, options
end

def build(object, json)
value = json[name.to_s] || json[name.to_sym]
typecasted_value = if type
type.json_create value
else
value
end
object.send "#{name}=", typecasted_value
end

def dirty?(object)
object.send("#{name}_changed?")
end

def save(object)

end

def destroy(object)

end

def serialize(json, object)
json[name] = object.send name
end

private

def accessors_module_for(clazz)
unless clazz.const_defined?('AccessorMethods')
accessors_module = clazz.const_set('AccessorMethods', Module.new)
clazz.send(:include, accessors_module)
end
clazz.const_get('AccessorMethods')
end

def define_accessors(base, name, options)
base.class_eval do
attr_reader "#{name}_was"

def initialize(attributes = {})
Expand Down Expand Up @@ -49,32 +90,6 @@ def assign_attribute_copies_for_dirty_tracking
end
end
end

def build(object, json)
value = json[name.to_s] || json[name.to_sym]
typecasted_value = if type
type.json_create value
else
value
end
object.send "#{name}=", typecasted_value
end

def dirty?(object)
object.send("#{name}_changed?")
end

def save(object)

end

def destroy(object)

end

def serialize(json, object)
json[name] = object.send name
end
end
end
end
18 changes: 18 additions & 0 deletions spec/property_spec.rb
Expand Up @@ -6,6 +6,16 @@ class Watch
include CouchPotato::Persistence

property :time, :type => Time
property :overwritten_read
property :overwritten_write

def overwritten_read
super.to_s
end

def overwritten_write=(value)
super value.to_s
end
end


Expand All @@ -14,6 +24,14 @@ class Watch
recreate_db
end

it "should allow me to overwrite read accessor and call super" do
Watch.new(:overwritten_read => 1).overwritten_read.should == '1'
end

it "should allow me to overwrite write accessor and call super" do
Watch.new(:overwritten_write => 1).overwritten_write.should == '1'
end

it "should return the property names" do
Comment.property_names.should == [:created_at, :updated_at, :title, :commenter]
end
Expand Down

0 comments on commit 30e90b0

Please sign in to comment.