Skip to content

Instantly share code, notes, and snippets.

@hattwj
Created May 27, 2015 15:11
Show Gist options
  • Save hattwj/e3368e1edb2aa802f93f to your computer and use it in GitHub Desktop.
Save hattwj/e3368e1edb2aa802f93f to your computer and use it in GitHub Desktop.
rails cache unexpected side effects.rb
def get_data_no_marshal
cache_key = 'Some random cache key'
result = Rails.cache.fetch(cache_key, race_condition_ttl: 10) do
# Load resource and pre-load associations
Survey.includes(:survey_meta,
:q_groups=>[
:q_questions=>[
:q_answers,
:q_attributes
]
]).where(:sid=>sid.to_i).first
end
end
result_1 = get_data_no_marshal()
result_2 = get_data_no_marshal()
puts result1.object_id
puts result2.object_id
# And there you have it. When I run this my objects will have the same object_id,
# which is unfortunate, because the plan is to alter them and have them return
# different results. The solution I came up with was Marshal!
def get_data_and_marshal
cache_key = 'Some random cache key'
result = Rails.cache.fetch(cache_key, race_condition_ttl: 10) do
# Load resource and pre-load associations
Survey.includes(:survey_meta,
:q_groups=>[
:q_questions=>[
:q_answers,
:q_attributes
]
]).where(:sid=>sid.to_i).first
end
result = Marshal.load(Marshal.dump(result))
end
result_1 = get_data_and_marshal()
result_2 = get_data_and_marshal()
puts result1.object_id
puts result2.object_id
#It adds a little bit of overhead, but it fixed the problem for me.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment