Permalink
Browse files

Merge pull request #75 from andymorris/proc_default

Support property default values returned by Procs
  • Loading branch information...
2 parents e08ad14 + d727d5a commit 2ea6f666e67dc1d1f5cf80f740ee5eb18d045aa6 @langalex committed Dec 11, 2012
Showing with 12 additions and 1 deletion.
  1. +1 −0 README.md
  2. +5 −1 lib/couch_potato/persistence/simple_property.rb
  3. +6 −0 spec/default_property_spec.rb
View
@@ -154,6 +154,7 @@ Properties can have a default value:
include CouchPotato::Persistence
property :active, :default => true
+ property :signed_up, :default => Proc.new { Time.now }
end
Now you can save your objects. All database operations are encapsulated in the CouchPotato::Database class. This separates your domain logic from the database access logic which makes it easier to write tests and also keeps you models smaller and cleaner.
@@ -56,7 +56,11 @@ def define_accessors(base, name, options)
load_attribute_from_document(name) unless instance_variable_defined?("@#{name}")
value = instance_variable_get("@#{name}")
if value.nil? && !options[:default].nil?
- default = clone_attribute(options[:default])
+ default = if options[:default].respond_to?(:call)
+ options[:default].call
+ else
+ clone_attribute(options[:default])
+ end
self.instance_variable_set("@#{name}", default)
default
else
@@ -6,6 +6,7 @@ class Test
property :test, :default => 'Test value'
property :complex, :default => [1, 2, 3]
property :false_value, :default => false
+ property :proc, :default => Proc.new { 1 + 2 }
end
describe 'default properties' do
@@ -41,4 +42,9 @@ class Test
t = Test.new
t.false_value.should == false
end
+
+ it "uses the return value of a Proc given as the default" do
+ t = Test.new
+ t.proc.should == 3
+ end
end

0 comments on commit 2ea6f66

Please sign in to comment.