Skip to content

Commit

Permalink
Rails plugin, refactoring duplicated code
Browse files Browse the repository at this point in the history
  • Loading branch information
kaievns committed Jan 19, 2012
1 parent f933b83 commit 5fbe765
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions src/rails/ujs.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ function try_link_submit(event, link) {
var url = link.get('href'),
method = link.get('data-method'),
remote = link.get('data-remote'),
param = $$('meta[name=csrf-param]')[0],
token = $$('meta[name=csrf-token]')[0];

param = param && param.get('content');
token = token && token.get('content');
token = get_csrf_token();

if (user_cancels(event, link)) { return; }
if (method || remote) { event.stop(); }
Expand All @@ -72,14 +68,14 @@ function try_link_submit(event, link) {
Xhr.load(url, add_xhr_events(link, {
method: method || 'get',
spinner: link.get('data-spinner'),
params: new Function('return {"'+ param +'": "'+ token +'"}')()
params: new Function('return {"'+ token[0] +'": "'+ token[1] +'"}')()
}));

} else if (method) {
var form = $E('form', {action: url, method: 'post'});

if (param && token) {
form.insert('<input type="hidden" name="'+param+'" value="'+token+'" />');
if (token) {
form.insert('<input type="hidden" name="'+token[0]+'" value="'+token[1]+'" />');
}

form.insert('<input type="hidden" name="_method" value="'+method+'"/>')
Expand All @@ -89,25 +85,34 @@ function try_link_submit(event, link) {
}
}

function get_csrf_token() {
var param, token;

param = $$('meta[name=csrf-param]')[0];
token = $$('meta[name=csrf-token]')[0];

param = param && param.get('content');
token = token && token.get('content');

if (param && token) {
return [param, token];
}
}

// global events listeners
$(document).on({
ready: function() {
var param, token, xhr, modules, i;

param = $$('meta[name=csrf-param]')[0];
token = $$('meta[name=csrf-token]')[0];

param = param && param.get('content');
token = token && token.get('content');
var token = get_csrf_token(), i = 0, xhr,
modules = ['InEdit', 'Rater', 'Sortable'];

if (param && token) {
for (modules = ['InEdit', 'Rater', 'Sortable'], i=0; i < modules.length; i++) {
if (token) {
for (; i < modules.length; i++) {
if (modules[i] in RightJS) {
xhr = RightJS[modules[i]].Options.Xhr;

if (RightJS.isHash(xhr)) {
xhr.params = Object.merge(xhr.params, {});
xhr.params[param] = token;
xhr.params[token[0]] = token[1];
}
}
}
Expand Down

0 comments on commit 5fbe765

Please sign in to comment.