Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Support property default values returned by Procs #75

Merged
merged 1 commit into from

2 participants

@andymorris

Title pretty much says it all. Allow Procs to be given as property default values, call the Proc to get the default value when needed.

@langalex
Owner

awesome, thanks.

@langalex langalex merged commit 2ea6f66 into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Dec 11, 2012
  1. @andymorris
This page is out of date. Refresh to see the latest.
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
Something went wrong with that request. Please try again.