cached_column 0.1 → 0.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -12,7 +12,7 @@ Gem::Specification.new do |gem|
12
12
  gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
13
13
  gem.name = "cached_column"
14
14
  gem.require_paths = ["lib"]
15
- gem.version = "0.1"
15
+ gem.version = "0.2"
16
16
 
17
17
  gem.add_dependency "activerecord", "~> 3.0"
18
18
  gem.add_development_dependency "rspec"
data/lib/cached_column.rb CHANGED
@@ -1,22 +1,29 @@
1
1
  require 'active_record'
2
2
 
3
3
  class CachedColumn
4
- attr_accessor :column, :options, :instance_method
4
+ attr_accessor :column, :options, :block
5
5
 
6
- def initialize(column, instance_method, options = {})
7
- @column = column
8
- @options = options
9
- @instance_method = instance_method
6
+ def initialize(column, options = {}, &block)
7
+ @column = column
8
+ @options = options
9
+ @block = block
10
10
  end
11
11
 
12
12
  def before_save(record)
13
- record.send("#{column}=", instance_method.bind(record).call)
13
+ record.send("#{column}=", computed_value(record))
14
+ end
15
+
16
+ def computed_value(record)
17
+ if block
18
+ record.instance_eval(&block)
19
+ else
20
+ record.send(options[:method] || column)
21
+ end
14
22
  end
15
23
  end
16
24
 
17
25
  class ActiveRecord::Base
18
- def self.cached_column(column, options = {})
19
- before_save CachedColumn.new(column, instance_method(options[:method] || column), options)
20
- define_method_attribute(column.to_s)
26
+ def self.cached_column(column, options = {}, &block)
27
+ before_save CachedColumn.new(column, options, &block)
21
28
  end
22
29
  end
@@ -34,6 +34,13 @@ describe CachedColumn do
34
34
  instance[:cached_column].should == 43
35
35
  end
36
36
 
37
+ it "sets the attribute value to the result of instance evaluating the block" do
38
+ model.cached_column(:cached_column) { calculating_method }
39
+ instance = model.new
40
+ instance.save
41
+ instance[:cached_column].should == 43
42
+ end
43
+
37
44
  it "allows the original method to be called" do
38
45
  model.cached_column :cached_column
39
46
  instance = model.new
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cached_column
3
3
  version: !ruby/object:Gem::Version
4
- version: '0.1'
4
+ version: '0.2'
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-08-15 00:00:00.000000000 Z
12
+ date: 2012-10-03 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: activerecord