Created
March 11, 2012 00:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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