Skip to content

Instantly share code, notes, and snippets.

@hattwj
Created May 27, 2015 15:11
Show Gist options
  • Select an option

  • Save hattwj/e3368e1edb2aa802f93f to your computer and use it in GitHub Desktop.

Select an option

Save hattwj/e3368e1edb2aa802f93f to your computer and use it in GitHub Desktop.

Revisions

  1. hattwj created this gist May 27, 2015.
    46 changes: 46 additions & 0 deletions rails_cache_effects.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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.