Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #75 from andymorris/proc_default

Support property default values returned by Procs
  • Loading branch information...
commit 2ea6f666e67dc1d1f5cf80f740ee5eb18d045aa6 2 parents e08ad14 + d727d5a
@langalex authored
View
1  README.md
@@ -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.
View
6 lib/couch_potato/persistence/simple_property.rb
@@ -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
View
6 spec/default_property_spec.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.