Below is an example problem that necessitates research of Rails code. An appropriate answer should provide any resources you used to discover the answer as well as a written explanation of the cause and a possible patch.
Setup a test app with the basic dependencies: rails 2.3.4 -m http://gist.github.com/raw/241424/e5a2c6750ea5f2f8e798acfcdb5ba76d77f99c41/template.rb fdl_question
You have a rails 2.3.4 application where you have an expensive web service call. You decide to use write-through caching using memcached and a job queue (in this case Delayed::Job) to speed up the responsiveness for the user. Assume you have an update action that calls save on an ActiveResource object. In the save action you write the current object into the cache then send a job into the queue to actually perform the save (i.e. send_later :save). Below might be an example of how you would execute this write through pattern.
def save_with_write_caching
if valid?
Rails.cache.write(self.cache_key, self)
self.send_later :save_without_write_caching
end
end
alias_method_chain :save, :write_caching
But before you add the code to throw the save into the queue you begin testing a simpler method to be able to test the write through aspect of your code.
def save_with_write_caching
if valid?
Rails.cache.write(self.cache_key, self)
self.save_without_write_caching
end
end
alias_method_chain :save, :write_caching
However,you quickly run into a problem where after you write the object to the cache you are unable to modify/save the object. You receive an error that states "Can't modify a frozen object" at the point of the save call.
This is an actual problem we ran into on a production site. Please research and answer the questions below.
- Pinpoint the exact line in the rails code that causes this issue.
- Explain the call stack from Rails.cache.write to the point at which the object is frozen
- Why was this decision made by the core team.
- How would you patch this and why?
- There will be follow up questions about the Rails caching code so ensure you understand how it works.