Skip to content
Browse files

Refine and add specs

  • Loading branch information...
1 parent db68a37 commit 257fd45930af0ab0d198545a80baa038225ebb46 @jfirebaugh jfirebaugh committed
Showing with 54 additions and 1 deletion.
  1. +2 −0 Gemfile
  2. +2 −0 cache_column.gemspec
  3. +1 −1 lib/cache_column.rb
  4. +44 −0 spec/cache_column_spec.rb
  5. +5 −0 spec/schema.rb
View
2 Gemfile
@@ -1,2 +1,4 @@
source 'https://rubygems.org'
gemspec
+
+gem "activerecord-nulldb-adapter", :git => "git://github.com/nulldb/nulldb.git"
View
2 cache_column.gemspec
@@ -15,4 +15,6 @@ Gem::Specification.new do |gem|
gem.version = "0.1"
gem.add_dependency "activerecord", "~> 3.0"
+ gem.add_development_dependency "rspec"
+ gem.add_development_dependency "activerecord-nulldb-adapter"
end
View
2 lib/cache_column.rb
@@ -16,7 +16,7 @@ def before_save(record)
class ActiveRecord::Base
def self.cache_column(column, options = {})
- before_save CacheColumn.new(column, instance_method(column), options)
+ before_save CacheColumn.new(column, instance_method(options[:method] || column), options)
define_method_attribute(column.to_s)
end
end
View
44 spec/cache_column_spec.rb
@@ -0,0 +1,44 @@
+require 'cache_column'
+require 'nulldb'
+
+ActiveRecord::Base.establish_connection :adapter => :nulldb,
+ :schema => File.expand_path("../schema.rb", __FILE__)
+
+describe CacheColumn do
+ let :model do
+ Class.new(ActiveRecord::Base) do
+ self.table_name = 'test'
+
+ def cached_column(value = 42)
+ value
+ end
+
+ def calculating_method
+ 43
+ end
+ end
+ end
+
+ describe "when saving" do
+ it "sets the attribute value to the result of the method of the same name" do
+ model.cache_column :cached_column
+ instance = model.new
+ instance.save
+ instance[:cached_column].should == 42
+ end
+
+ it "sets the attribute value to the result of the specified method" do
+ model.cache_column :cached_column, :method => :calculating_method
+ instance = model.new
+ instance.save
+ instance[:cached_column].should == 43
+ end
+
+ it "allows the original method to be called" do
+ model.cache_column :cached_column
+ instance = model.new
+ instance.save
+ instance.cached_column(44).should == 44
+ end
+ end
+end
View
5 spec/schema.rb
@@ -0,0 +1,5 @@
+ActiveRecord::Schema.define(:version => 20120611163936) do
+ create_table "test", :force => true do |t|
+ t.integer "cached_column"
+ end
+end

0 comments on commit 257fd45

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