Created
May 20, 2014 15:07
-
-
Save madrobby/2aeb77781b0ed3140ec5 to your computer and use it in GitHub Desktop.
Monkey-patch that fixes Rails 2.3's `link_to` helper with method "delete" and fragment caching (just put the file in `config/initializers`)
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
# Monkey-patch link_to (when called with method "delete") to use the authenticity token | |
# from the current page (in the #authenticity_token element), as opposed to hard-coding it. | |
# Rails' hard-coding breaks the app when using fragment caching because users get authenticity | |
# tokens that are old and/or not their own. | |
# | |
# To make the JavaScript less complicated, assumes that you have an element (like a DIV) | |
# on the page with id="authenticity_token" that contains the authenticity token. | |
# It could also be adapted to use the authenticity token from the the csrf-token meta tag. | |
# | |
# See https://github.com/cheerful/freckle/issues/743 | |
module ActionView | |
module Helpers #:nodoc: | |
module UrlHelper | |
private | |
def method_javascript_function(method, url = '', href = nil) | |
action = (href && url.size > 0) ? "'#{url}'" : 'this.href' | |
submit_function = | |
"var f = document.createElement('form'); f.style.display = 'none'; " + | |
"this.parentNode.appendChild(f); f.method = 'POST'; f.action = #{action};" | |
unless method == :post | |
submit_function << "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); " | |
submit_function << "m.setAttribute('name', '_method'); m.setAttribute('value', '#{method}'); f.appendChild(m);" | |
end | |
if protect_against_forgery? | |
submit_function << "var s = document.createElement('input'); s.setAttribute('type', 'hidden'); " | |
submit_function << "s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', document.getElementById('authenticity_token').innerHTML); f.appendChild(s);" | |
end | |
submit_function << "f.submit();" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment