Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support property default values returned by Procs #75

Merged
merged 1 commit into from
Dec 11, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion lib/couch_potato/persistence/simple_property.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions spec/default_property_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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