Skip to content

Instantly share code, notes, and snippets.

@alto
Created March 11, 2012 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alto/2014230 to your computer and use it in GitHub Desktop.
Save alto/2014230 to your computer and use it in GitHub Desktop.
Calculate a certain attribute only until the (active) record has been saved to the database.
module CalculateUntilSaved
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def calculate_until_saved(attribute_name)
attr_protected attribute_name
before_validation :on => :create do
self.send("#{attribute_name}=", send(attribute_name))
end
define_method("#{attribute_name}_with_reading_attribute") do
attribute = read_attribute(attribute_name)
return attribute if attribute
send("#{attribute_name}_without_reading_attribute")
end
alias_method_chain attribute_name, :reading_attribute
end
end
end
class Booking < ActiveRecord::Base
include CalculateUntilSaved
# has an attribute named price
def price
# some really expensive or slow calculation
end
calculate_until_saved :price
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment