Skip to content
Browse files

Added proc defaults.

  • Loading branch information...
1 parent 04d7499 commit a17478a9abdc593dad707e81c64a49bfb39a5506 @jnunemaker committed Sep 9, 2010
Showing with 35 additions and 8 deletions.
  1. +4 −2 lib/toy/attribute.rb
  2. +1 −2 spec/spec.opts
  3. +30 −4 spec/toy/attribute_spec.rb
View
6 lib/toy/attribute.rb
@@ -19,11 +19,13 @@ def write(value)
end
def default
- options[:default]
+ if default?
+ options[:default].respond_to?(:call) ? options[:default].call : options[:default]
+ end
end
def default?
- default.present?
+ options.key?(:default)
end
# Stores reference to related embedded list
View
3 spec/spec.opts
@@ -1,4 +1,3 @@
--colour
--timeout
-20
---diff
+20
View
34 spec/toy/attribute_spec.rb
@@ -50,20 +50,46 @@
@attribute = Toy::Attribute.new(User, :brother_name, String, :default => 'Daryl')
end
- it "should return default when reading a nil value" do
+ it "returns default when reading a nil value" do
@attribute.read(nil).should == 'Daryl'
end
- it "should return value when reading a non-nil value" do
+ it "returns value when reading a non-nil value" do
@attribute.read('Larry').should == 'Larry'
end
- it "should return default when writing a nil value" do
+ it "returns default when writing a nil value" do
@attribute.write(nil).should == 'Daryl'
end
- it "should return value when writing a non-nil value" do
+ it "returns value when writing a non-nil value" do
@attribute.write('Larry').should == 'Larry'
end
end
+
+ describe "attribute with default that is proc" do
+ before do
+ @time = 4.days.ago
+ default = proc { @time }
+ @attribute = Toy::Attribute.new(User, :created_at, Time, :default => default)
+ end
+
+ it "returns default when reading a nil value" do
+ @attribute.read(nil).should == @time
+ end
+
+ it "returns value when reading a non-nil value" do
+ time = 3.days.ago
+ @attribute.read(time).should == time
+ end
+
+ it "returns default when writing a nil value" do
+ @attribute.write(nil).to_i.should == @time.to_i
+ end
+
+ it "returns value when writing a non-nil value" do
+ time = 2.days.ago
+ @attribute.write(time).to_i.should == time.to_i
+ end
+ end
end

0 comments on commit a17478a

Please sign in to comment.
Something went wrong with that request. Please try again.