Sha256: cded6bade9499ad3cdf50eef079f48a9e7676fa5e182ac902f7c0280ef670d0a

Contents?: true

Size: 602 Bytes

Versions: 2

Compression:

Stored size: 602 Bytes

Contents

require 'active_record'

class CachedColumn
  attr_accessor :column, :options, :block

  def initialize(column, options = {}, &block)
    @column  = column
    @options = options
    @block   = block
  end

  def before_save(record)
    record.send("#{column}=", computed_value(record))
    true
  end

  def computed_value(record)
    if block
      record.instance_eval(&block)
    else
      record.send(options[:method] || column)
    end
  end
end

class ActiveRecord::Base
  def self.cached_column(column, options = {}, &block)
    before_save CachedColumn.new(column, options, &block)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cached_column-0.4 lib/cached_column.rb
cached_column-0.3 lib/cached_column.rb