Rails 2.2.2

Updated to Rails 2.2.2.
Added a couple more Ruby 1.9 fixes, but that's pretty much at a standstill,
until one gets Maruku and HTML5lib working right under Ruby 1.9.
This commit is contained in:
Jacques Distler 2008-11-24 15:53:39 -06:00
parent 1b69b148de
commit 2e81ca2d30
716 changed files with 8009 additions and 113047 deletions

View file

@ -52,7 +52,7 @@
<% end %>
</h1>
<%= render 'navigation' unless @web.nil? || @hide_navigation %>
<%= render(:file => 'navigation') unless @web.nil? || @hide_navigation %>
<% if flash[:info] %>
<div class="info"><%= escape_preserving_linefeeds flash[:info] %></div>

View file

@ -5,8 +5,8 @@
%>
<div id="MarkupHelp">
<%= render("#{@web.markup}_help") %>
<%= render 'wiki_words_help' %>
<%= render(:file => "#{@web.markup}_help") %>
<%= render(:file => 'wiki_words_help') %>
</div>
<% form_tag({ :action => 'save', :web => @web.address, :id => @page.name },

View file

@ -5,8 +5,8 @@
%>
<div id="MarkupHelp">
<%= render("#{@web.markup}_help") %>
<%= render 'wiki_words_help' %>
<%= render(:file => "#{@web.markup}_help") %>
<%= render(:file => 'wiki_words_help') %>
</div>
<div id="editForm">

View file

@ -7,8 +7,8 @@
<%= "<p style='color:red'>Please correct the error that caused this error in rendering:<br/><small>#{params["msg"]}</small></p>" if params["msg"] %>
<div id="MarkupHelp">
<%= render("#{@web.markup}_help") %>
<%= render 'wiki_words_help' %>
<%= render(:file => "#{@web.markup}_help") %>
<%= render(:file => 'wiki_words_help') %>
</div>
<% form_tag({:web => @web.address, :action => 'save', :id => @page.name},

View file

@ -74,7 +74,8 @@ class URIChunk < Chunk::Abstract
SUSPICIOUS_PRECEDING_CHARACTER = '(!|\"\:|\"|\\\'|\]\()?' # any of !, ":, ", ', ](
INTERNET_URI_REGEXP =
Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + INTERNET_URI, Regexp::EXTENDED, 'N')
# Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + INTERNET_URI, Regexp::EXTENDED, 'N')
Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + INTERNET_URI, Regexp::EXTENDED)
end
@ -172,7 +173,8 @@ class LocalURIChunk < URIChunk
'(?=\.?(?:\s|\)|\z))' # ends only with optional dot + space or ")"
# or end of the string
LOCAL_URI_REGEXP = Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + LOCAL_URI, Regexp::EXTENDED, 'N')
# LOCAL_URI_REGEXP = Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + LOCAL_URI, Regexp::EXTENDED, 'N')
LOCAL_URI_REGEXP = Regexp.new(SUSPICIOUS_PRECEDING_CHARACTER + LOCAL_URI, Regexp::EXTENDED)
end
def LocalURIChunk.pattern

View file

@ -153,7 +153,7 @@ class String
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*\Z/x;
)*\Z/nx;
end
#++

View file

@ -33,7 +33,7 @@ class String
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*\Z/x;
)*\Z/nx;
end
#++
@ -2220,7 +2220,7 @@ class String
end
def unescapeHTML
self.gsub(/&(.*?);/n) do
self.gsub(/&(.*?);/) do
match = $1.dup
case match
when /\Aamp\z/ni then '&'

View file

@ -1,7 +1,7 @@
#coding: utf-8
# Contains all the methods for finding and replacing wiki words
module WikiWords
# In order of appearance: Latin, greek, cyrillian, armenian
# In order of appearance: Latin, greek, cyrillic, armenian
I18N_HIGHER_CASE_LETTERS =
"ÀÁÂÃÄÅĀĄĂÆÇĆČĈĊĎĐÈÉÊËĒĘĚĔĖĜĞĠĢĤĦÌÍÎÏĪĨĬĮİIJĴĶŁĽĹĻĿÑŃŇŅŊÒÓÔÕÖØŌŐŎŒŔŘŖŚŠŞŜȘŤŢŦȚÙÚÛÜŪŮŰŬŨŲŴŶŸȲÝŹŽŻ" +
"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ" +

View file

@ -1,6 +1,6 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
@ -37,10 +37,10 @@
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { }
var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element)
element = $(element);
this.element = element;
this.update = $(update);
this.hasFocus = false;
@ -209,13 +209,13 @@ Autocompleter.Base = Class.create({
},
markPrevious: function() {
if(this.index > 0) this.index--
if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++
if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
@ -457,7 +457,7 @@ Autocompleter.Local = Class.create(Autocompleter.Base, {
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
@ -474,7 +474,7 @@ Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
}
};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
@ -604,7 +604,7 @@ Ajax.InPlaceEditor = Class.create({
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML;
return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
@ -780,7 +780,7 @@ Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw 'Server returned an invalid collection representation.';
throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),

View file

@ -1,5 +1,5 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
@ -121,7 +121,7 @@ var Droppables = {
if(this.last_active)
this.deactivate(this.last_active);
}
}
};
var Draggables = {
drags: [],
@ -218,7 +218,7 @@ var Draggables = {
).length;
});
}
}
};
/*--------------------------------------------------------------------------*/
@ -331,8 +331,8 @@ var Draggable = Class.create({
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this.element._originallyAbsolute)
this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
@ -403,9 +403,9 @@ var Draggable = Class.create({
}
if(this.options.ghosting) {
if (!this.element._originallyAbsolute)
if (!this._originallyAbsolute)
Position.relativize(this.element);
delete this.element._originallyAbsolute;
delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
@ -478,10 +478,10 @@ var Draggable = Class.create({
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this))
return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
@ -560,7 +560,7 @@ var Draggable = Class.create({
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight
H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
@ -608,7 +608,8 @@ var Sortable = {
},
destroy: function(element){
var s = Sortable.options(element);
element = $(element);
var s = Sortable.sortables[element.id];
if(s) {
Draggables.removeObserver(s.element);
@ -689,14 +690,14 @@ var Sortable = {
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
}
};
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
}
};
// fix for gecko engine
Element.cleanWhitespace(element);
@ -851,11 +852,11 @@ var Sortable = {
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
}
};
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child)
this._tree(child.container, options, child);
parent.children.push (child);
}
@ -880,7 +881,7 @@ var Sortable = {
children: [],
container: element,
position: 0
}
};
return Sortable._tree(element, options, root);
},
@ -940,14 +941,14 @@ var Sortable = {
}).join('&');
}
}
}
};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
}
};
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
@ -965,8 +966,8 @@ Element.findChildren = function(element, only, recursive, tagName) {
});
return (elements.length>0 ? elements.flatten() : []);
}
};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}
};

View file

@ -70,25 +70,20 @@ var Effect = {
Transitions: {
linear: Prototype.K,
sinoidal: function(pos) {
return (-Math.cos(pos*Math.PI)/2) + 0.5;
return (-Math.cos(pos*Math.PI)/2) + .5;
},
reverse: function(pos) {
return 1-pos;
},
flicker: function(pos) {
var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
return pos > 1 ? 1 : pos;
},
wobble: function(pos) {
return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
},
pulse: function(pos, pulses) {
pulses = pulses || 5;
return (
((pos % (1/pulses)) * pulses).round() == 0 ?
((pos * pulses * 2) - (pos * pulses * 2).floor()) :
1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
);
return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
},
spring: function(pos) {
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
@ -249,18 +244,30 @@ Effect.Base = Class.create({
this.totalTime = this.finishOn-this.startOn;
this.totalFrames = this.options.fps*this.options.duration;
eval('this.render = function(pos){ '+
'if (this.state=="idle"){this.state="running";'+
codeForEvent(this.options,'beforeSetup')+
(this.setup ? 'this.setup();':'')+
codeForEvent(this.options,'afterSetup')+
'};if (this.state=="running"){'+
'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
'this.position=pos;'+
codeForEvent(this.options,'beforeUpdate')+
(this.update ? 'this.update(pos);':'')+
codeForEvent(this.options,'afterUpdate')+
'}}');
this.render = (function() {
function dispatch(effect, eventName) {
if (effect.options[eventName + 'Internal'])
effect.options[eventName + 'Internal'](effect);
if (effect.options[eventName])
effect.options[eventName](effect);
}
return function(pos) {
if (this.state === "idle") {
this.state = "running";
dispatch(this, 'beforeSetup');
if (this.setup) this.setup();
dispatch(this, 'afterSetup');
}
if (this.state === "running") {
pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
this.position = pos;
dispatch(this, 'beforeUpdate');
if (this.update) this.update(pos);
dispatch(this, 'afterUpdate');
}
};
})();
this.event('beforeStart');
if (!this.options.sync)
@ -508,16 +515,15 @@ Effect.Highlight = Class.create(Effect.Base, {
Effect.ScrollTo = function(element) {
var options = arguments[1] || { },
scrollOffsets = document.viewport.getScrollOffsets(),
elementOffsets = $(element).cumulativeOffset(),
max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();
elementOffsets = $(element).cumulativeOffset();
if (options.offset) elementOffsets[1] += options.offset;
return new Effect.Tween(null,
scrollOffsets.top,
elementOffsets[1] > max ? max : elementOffsets[1],
elementOffsets[1],
options,
function(p){ scrollTo(scrollOffsets.left, p.round()) }
function(p){ scrollTo(scrollOffsets.left, p.round()); }
);
};
@ -568,7 +574,7 @@ Effect.Puff = function(element) {
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
Position.absolutize(effect.effects[0].element)
Position.absolutize(effect.effects[0].element);
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().setStyle(oldStyle); }
@ -625,7 +631,7 @@ Effect.SwitchOff = function(element) {
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
});
}
}, arguments[1] || { }));
};
@ -674,7 +680,7 @@ Effect.Shake = function(element) {
new Effect.Move(effect.element,
{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
effect.element.undoPositioned().setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
}}); }}); }}); }}); }}); }});
};
Effect.SlideDown = function(element) {
@ -816,7 +822,7 @@ Effect.Grow = function(element) {
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
)
);
}
});
};
@ -877,11 +883,13 @@ Effect.Shrink = function(element) {
Effect.Pulsate = function(element) {
element = $(element);
var options = arguments[1] || { };
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
reverser.bind(transition);
var options = arguments[1] || { },
oldOpacity = element.getInlineOpacity(),
transition = options.transition || Effect.Transitions.linear,
reverser = function(pos){
return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
};
return new Effect.Opacity(element,
Object.extend(Object.extend({ duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
@ -934,7 +942,7 @@ Effect.Morph = Class.create(Effect.Base, {
effect.transforms.each(function(transform) {
effect.element.style[transform.style] = '';
});
}
};
}
}
this.start(options);
@ -945,7 +953,7 @@ Effect.Morph = Class.create(Effect.Base, {
if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
color = color.parseColor();
return $R(0,2).map(function(i){
return parseInt( color.slice(i*2+1,i*2+3), 16 )
return parseInt( color.slice(i*2+1,i*2+3), 16 );
});
}
this.transforms = this.style.map(function(pair){
@ -978,7 +986,7 @@ Effect.Morph = Class.create(Effect.Base, {
transform.unit != 'color' &&
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
)
)
);
});
},
update: function(position) {
@ -1074,14 +1082,14 @@ if (document.defaultView && document.defaultView.getComputedStyle) {
Element.getStyles = function(element) {
element = $(element);
var css = element.currentStyle, styles;
styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
hash.set(property, css[property]);
return hash;
styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
results[property] = css[property];
return results;
});
if (!styles.opacity) styles.set('opacity', element.getOpacity());
if (!styles.opacity) styles.opacity = element.getOpacity();
return styles;
};
};
}
Effect.Methods = {
morph: function(element, style) {
@ -1090,7 +1098,7 @@ Effect.Methods = {
return element;
},
visualEffect: function(element, effect, options) {
element = $(element)
element = $(element);
var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[klass](element, options);
return element;
@ -1109,7 +1117,7 @@ $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
element = $(element);
Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
return element;
}
};
}
);

View file

@ -1,4 +1,4 @@
/* Prototype JavaScript framework, version 1.6.0.2
/* Prototype JavaScript framework, version 1.6.0.3
* (c) 2005-2008 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
@ -7,23 +7,26 @@
*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.6.0.2',
Version: '1.6.0.3',
Browser: {
IE: !!(window.attachEvent && !window.opera),
Opera: !!window.opera,
IE: !!(window.attachEvent &&
navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
SelectorsAPI: !!document.querySelector,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div').__proto__ &&
document.createElement('div').__proto__ !==
document.createElement('form').__proto__
document.createElement('div')['__proto__'] &&
document.createElement('div')['__proto__'] !==
document.createElement('form')['__proto__']
},
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
@ -83,12 +86,13 @@ Class.Methods = {
var property = properties[i], value = source[property];
if (ancestor && Object.isFunction(value) &&
value.argumentNames().first() == "$super") {
var method = value, value = Object.extend((function(m) {
var method = value;
value = (function(m) {
return function() { return ancestor[m].apply(this, arguments) };
})(property).wrap(method), {
valueOf: function() { return method },
toString: function() { return method.toString() }
});
})(property).wrap(method);
value.valueOf = method.valueOf.bind(method);
value.toString = method.toString.bind(method);
}
this.prototype[property] = value;
}
@ -167,7 +171,7 @@ Object.extend(Object, {
},
isElement: function(object) {
return object && object.nodeType == 1;
return !!(object && object.nodeType == 1);
},
isArray: function(object) {
@ -198,7 +202,8 @@ Object.extend(Object, {
Object.extend(Function.prototype, {
argumentNames: function() {
var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
.replace(/\s+/g, '').split(',');
return names.length == 1 && !names[0] ? [] : names;
},
@ -232,6 +237,11 @@ Object.extend(Function.prototype, {
}, timeout);
},
defer: function() {
var args = [0.01].concat($A(arguments));
return this.delay.apply(this, args);
},
wrap: function(wrapper) {
var __method = this;
return function() {
@ -248,8 +258,6 @@ Object.extend(Function.prototype, {
}
});
Function.prototype.defer = Function.prototype.delay.curry(0.01);
Date.prototype.toJSON = function() {
return '"' + this.getUTCFullYear() + '-' +
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
@ -530,7 +538,7 @@ if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.proto
return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
},
unescapeHTML: function() {
return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
return this.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
}
});
@ -547,7 +555,7 @@ Object.extend(String.prototype.escapeHTML, {
text: document.createTextNode('')
});
with (String.prototype.escapeHTML) div.appendChild(text);
String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
var Template = Class.create({
initialize: function(template, pattern) {
@ -589,10 +597,9 @@ var $break = { };
var Enumerable = {
each: function(iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function(value) {
iterator(value, index++);
iterator.call(context, value, index++);
});
} catch (e) {
if (e != $break) throw e;
@ -601,47 +608,46 @@ var Enumerable = {
},
eachSlice: function(number, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var index = -number, slices = [], array = this.toArray();
if (number < 1) return array;
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.collect(iterator, context);
},
all: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var result = true;
this.each(function(value, index) {
result = result && !!iterator(value, index);
result = result && !!iterator.call(context, value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator(value, index))
if (result = !!iterator.call(context, value, index))
throw $break;
});
return result;
},
collect: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
results.push(iterator.call(context, value, index));
});
return results;
},
detect: function(iterator, context) {
iterator = iterator.bind(context);
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
if (iterator.call(context, value, index)) {
result = value;
throw $break;
}
@ -650,17 +656,16 @@ var Enumerable = {
},
findAll: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
if (iterator.call(context, value, index))
results.push(value);
});
return results;
},
grep: function(filter, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var results = [];
if (Object.isString(filter))
@ -668,7 +673,7 @@ var Enumerable = {
this.each(function(value, index) {
if (filter.match(value))
results.push(iterator(value, index));
results.push(iterator.call(context, value, index));
});
return results;
},
@ -696,9 +701,8 @@ var Enumerable = {
},
inject: function(memo, iterator, context) {
iterator = iterator.bind(context);
this.each(function(value, index) {
memo = iterator(memo, value, index);
memo = iterator.call(context, memo, value, index);
});
return memo;
},
@ -711,10 +715,10 @@ var Enumerable = {
},
max: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
value = iterator.call(context, value, index);
if (result == null || value >= result)
result = value;
});
@ -722,10 +726,10 @@ var Enumerable = {
},
min: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
value = iterator.call(context, value, index);
if (result == null || value < result)
result = value;
});
@ -733,10 +737,10 @@ var Enumerable = {
},
partition: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
iterator = iterator || Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
(iterator(value, index) ?
(iterator.call(context, value, index) ?
trues : falses).push(value);
});
return [trues, falses];
@ -751,19 +755,20 @@ var Enumerable = {
},
reject: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
if (!iterator.call(context, value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator, context) {
iterator = iterator.bind(context);
return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
return {
value: value,
criteria: iterator.call(context, value, index)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
@ -815,8 +820,12 @@ function $A(iterable) {
if (Prototype.Browser.WebKit) {
$A = function(iterable) {
if (!iterable) return [];
if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
iterable.toArray) return iterable.toArray();
// In Safari, only use the `toArray` method if it's not a NodeList.
// A NodeList is a function, has an function `item` property, and a numeric
// `length` property. Adapted from Google Doctype.
if (!(typeof iterable === 'function' && typeof iterable.length ===
'number' && typeof iterable.item === 'function') && iterable.toArray)
return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
@ -963,8 +972,8 @@ Object.extend(Number.prototype, {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
times: function(iterator, context) {
$R(0, this, true).each(iterator, context);
return this;
},
@ -1011,6 +1020,8 @@ var Hash = Class.create(Enumerable, (function() {
},
get: function(key) {
// simulating poorly supported hasOwnProperty
if (this._object[key] !== Object.prototype[key])
return this._object[key];
},
@ -1051,14 +1062,14 @@ var Hash = Class.create(Enumerable, (function() {
},
toQueryString: function() {
return this.map(function(pair) {
return this.inject([], function(results, pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return values.map(toQueryPair.curry(key)).join('&');
}
return toQueryPair(key, values);
return results.concat(values.map(toQueryPair.curry(key)));
} else results.push(toQueryPair(key, values));
return results;
}).join('&');
},
@ -1558,6 +1569,7 @@ if (!Node.ELEMENT_NODE) {
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
};
Object.extend(this.Element, element || { });
if (element) this.Element.prototype = element.prototype;
}).call(window);
Element.cache = { };
@ -1574,12 +1586,14 @@ Element.Methods = {
},
hide: function(element) {
$(element).style.display = 'none';
element = $(element);
element.style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
element = $(element);
element.style.display = '';
return element;
},
@ -1733,7 +1747,7 @@ Element.Methods = {
element = $(element);
if (arguments.length == 1) return element.firstDescendant();
return Object.isNumber(expression) ? element.descendants()[expression] :
element.select(expression)[index || 0];
Element.select(element, expression)[index || 0];
},
previous: function(element, expression, index) {
@ -1863,24 +1877,16 @@ Element.Methods = {
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
var originalAncestor = ancestor;
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (element.sourceIndex && !Prototype.Browser.Opera) {
var e = element.sourceIndex, a = ancestor.sourceIndex,
nextAncestor = ancestor.nextSibling;
if (!nextAncestor) {
do { ancestor = ancestor.parentNode; }
while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
}
if (nextAncestor && nextAncestor.sourceIndex)
return (e > a && e < nextAncestor.sourceIndex);
}
if (ancestor.contains)
return ancestor.contains(element) && ancestor !== element;
while (element = element.parentNode)
if (element == originalAncestor) return true;
if (element == ancestor) return true;
return false;
},
@ -1895,7 +1901,7 @@ Element.Methods = {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value) {
if (!value || value == 'auto') {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
@ -1934,7 +1940,7 @@ Element.Methods = {
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
var display = element.getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
@ -1963,7 +1969,7 @@ Element.Methods = {
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (window.opera) {
if (Prototype.Browser.Opera) {
element.style.top = 0;
element.style.left = 0;
}
@ -2018,7 +2024,7 @@ Element.Methods = {
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (element.tagName == 'BODY') break;
if (element.tagName.toUpperCase() == 'BODY') break;
var p = Element.getStyle(element, 'position');
if (p !== 'static') break;
}
@ -2028,7 +2034,7 @@ Element.Methods = {
absolutize: function(element) {
element = $(element);
if (element.getStyle('position') == 'absolute') return;
if (element.getStyle('position') == 'absolute') return element;
// Position.prepare(); // To be done manually by Scripty when it needs it.
var offsets = element.positionedOffset();
@ -2052,7 +2058,7 @@ Element.Methods = {
relativize: function(element) {
element = $(element);
if (element.getStyle('position') == 'relative') return;
if (element.getStyle('position') == 'relative') return element;
// Position.prepare(); // To be done manually by Scripty when it needs it.
element.style.position = 'relative';
@ -2103,7 +2109,7 @@ Element.Methods = {
element = forElement;
do {
if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
}
@ -2218,6 +2224,9 @@ else if (Prototype.Browser.IE) {
Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
function(proceed, element) {
element = $(element);
// IE throws an error if element is not in document
try { element.offsetParent }
catch(e) { return $(document.body) }
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
element.setStyle({ position: 'relative' });
@ -2231,6 +2240,8 @@ else if (Prototype.Browser.IE) {
Element.Methods[method] = Element.Methods[method].wrap(
function(proceed, element) {
element = $(element);
try { element.offsetParent }
catch(e) { return Element._returnOffset(0,0) }
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
// Trigger hasLayout on the offset parent so that IE6 reports
@ -2246,6 +2257,14 @@ else if (Prototype.Browser.IE) {
);
});
Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap(
function(proceed, element) {
try { element.offsetParent }
catch(e) { return Element._returnOffset(0,0) }
return proceed(element);
}
);
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
@ -2337,7 +2356,7 @@ else if (Prototype.Browser.IE) {
Element._attributeTranslations.has = {};
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
'encType maxLength readOnly longDesc').each(function(attr) {
'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
});
@ -2390,7 +2409,7 @@ else if (Prototype.Browser.WebKit) {
(value < 0.00001) ? 0 : value;
if (value == 1)
if(element.tagName == 'IMG' && element.width) {
if(element.tagName.toUpperCase() == 'IMG' && element.width) {
element.width++; element.width--;
} else try {
var n = document.createTextNode(' ');
@ -2521,7 +2540,7 @@ Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
attribute = Element._attributeTranslations.has[attribute] || attribute;
var node = $(element).getAttributeNode(attribute);
return node && node.specified;
return !!(node && node.specified);
}
};
@ -2530,9 +2549,9 @@ Element.Methods.ByTag = { };
Object.extend(Element, Element.Methods);
if (!Prototype.BrowserFeatures.ElementExtensions &&
document.createElement('div').__proto__) {
document.createElement('div')['__proto__']) {
window.HTMLElement = { };
window.HTMLElement.prototype = document.createElement('div').__proto__;
window.HTMLElement.prototype = document.createElement('div')['__proto__'];
Prototype.BrowserFeatures.ElementExtensions = true;
}
@ -2547,7 +2566,7 @@ Element.extend = (function() {
element.nodeType != 1 || element == window) return element;
var methods = Object.clone(Methods),
tagName = element.tagName, property, value;
tagName = element.tagName.toUpperCase(), property, value;
// extend methods for specific tags
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
@ -2643,7 +2662,7 @@ Element.addMethods = function(methods) {
if (window[klass]) return window[klass];
window[klass] = { };
window[klass].prototype = document.createElement(tagName).__proto__;
window[klass].prototype = document.createElement(tagName)['__proto__'];
return window[klass];
}
@ -2669,12 +2688,18 @@ Element.addMethods = function(methods) {
document.viewport = {
getDimensions: function() {
var dimensions = { };
var B = Prototype.Browser;
var dimensions = { }, B = Prototype.Browser;
$w('width height').each(function(d) {
var D = d.capitalize();
dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
(B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
if (B.WebKit && !document.evaluate) {
// Safari <3.0 needs self.innerWidth/Height
dimensions[d] = self['inner' + D];
} else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
// Opera <9.5 needs document.body.clientWidth/Height
dimensions[d] = document.body['client' + D]
} else {
dimensions[d] = document.documentElement['client' + D];
}
});
return dimensions;
},
@ -2693,14 +2718,24 @@ document.viewport = {
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
}
};
/* Portions of the Selector class are derived from Jack Slocumâs DomQuery,
/* Portions of the Selector class are derived from Jack Slocum's DomQuery,
* part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
* license. Please see http://www.yui-ext.com/ for more information. */
var Selector = Class.create({
initialize: function(expression) {
this.expression = expression.strip();
if (this.shouldUseSelectorsAPI()) {
this.mode = 'selectorsAPI';
} else if (this.shouldUseXPath()) {
this.mode = 'xpath';
this.compileXPathMatcher();
} else {
this.mode = "normal";
this.compileMatcher();
}
},
shouldUseXPath: function() {
@ -2715,16 +2750,29 @@ var Selector = Class.create({
// XPath can't do namespaced attributes, nor can it read
// the "checked" property from DOM nodes
if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
if ((/(\[[\w-]*?:|:checked)/).test(e))
return false;
return true;
},
compileMatcher: function() {
if (this.shouldUseXPath())
return this.compileXPathMatcher();
shouldUseSelectorsAPI: function() {
if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
if (!Selector._div) Selector._div = new Element('div');
// Make sure the browser treats the selector as valid. Test on an
// isolated element to minimize cost of this check.
try {
Selector._div.querySelector(this.expression);
} catch(e) {
return false;
}
return true;
},
compileMatcher: function() {
var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
c = Selector.criteria, le, p, m;
@ -2781,8 +2829,27 @@ var Selector = Class.create({
findElements: function(root) {
root = root || document;
if (this.xpath) return document._getElementsByXPath(this.xpath, root);
var e = this.expression, results;
switch (this.mode) {
case 'selectorsAPI':
// querySelectorAll queries document-wide, then filters to descendants
// of the context element. That's not what we want.
// Add an explicit context to the selector if necessary.
if (root !== document) {
var oldId = root.id, id = $(root).identify();
e = "#" + id + " " + e;
}
results = $A(root.querySelectorAll(e)).map(Element.extend);
root.id = oldId;
return results;
case 'xpath':
return document._getElementsByXPath(this.xpath, root);
default:
return this.matcher(root);
}
},
match: function(element) {
@ -2873,10 +2940,10 @@ Object.extend(Selector, {
'first-child': '[not(preceding-sibling::*)]',
'last-child': '[not(following-sibling::*)]',
'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
'empty': "[count(*) = 0 and (count(text()) = 0)]",
'checked': "[@checked]",
'disabled': "[@disabled]",
'enabled': "[not(@disabled)]",
'disabled': "[(@disabled) and (@type!='hidden')]",
'enabled': "[not(@disabled) and (@type!='hidden')]",
'not': function(m) {
var e = m[6], p = Selector.patterns,
x = Selector.xpath, le, v;
@ -2968,7 +3035,7 @@ Object.extend(Selector, {
className: /^\.([\w\-\*]+)(\b|$)/,
pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
attrPresence: /^\[([\w]+)\]/,
attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/,
attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
},
@ -3270,7 +3337,7 @@ Object.extend(Selector, {
'empty': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
// IE treats comments as element nodes
if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
if (node.tagName == '!' || node.firstChild) continue;
results.push(node);
}
return results;
@ -3288,7 +3355,8 @@ Object.extend(Selector, {
'enabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node.disabled) results.push(node);
if (!node.disabled && (!node.type || node.type !== 'hidden'))
results.push(node);
return results;
},
@ -3308,11 +3376,14 @@ Object.extend(Selector, {
operators: {
'=': function(nv, v) { return nv == v; },
'!=': function(nv, v) { return nv != v; },
'^=': function(nv, v) { return nv.startsWith(v); },
'^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); },
'$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); },
'*=': function(nv, v) { return nv == v || nv && nv.include(v); },
'$=': function(nv, v) { return nv.endsWith(v); },
'*=': function(nv, v) { return nv.include(v); },
'~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
'|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
'|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() +
'-').include('-' + (v || "").toUpperCase() + '-'); }
},
split: function(expression) {
@ -3386,7 +3457,7 @@ var Form = {
var data = elements.inject({ }, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && (element.type != 'submit' || (!submitted &&
if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
if (key in result) {
// a key is already present; construct an array of values
@ -3547,7 +3618,6 @@ Form.Element.Methods = {
disable: function(element) {
element = $(element);
element.blur();
element.disabled = true;
return element;
},
@ -3587,22 +3657,22 @@ Form.Element.Serializers = {
else element.value = value;
},
select: function(element, index) {
if (Object.isUndefined(index))
select: function(element, value) {
if (Object.isUndefined(value))
return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
else {
var opt, value, single = !Object.isArray(index);
var opt, currentValue, single = !Object.isArray(value);
for (var i = 0, length = element.length; i < length; i++) {
opt = element.options[i];
value = this.optionValue(opt);
currentValue = this.optionValue(opt);
if (single) {
if (value == index) {
if (currentValue == value) {
opt.selected = true;
return;
}
}
else opt.selected = index.include(value);
else opt.selected = value.include(currentValue);
}
}
},
@ -3773,8 +3843,23 @@ Event.Methods = (function() {
isRightClick: function(event) { return isButton(event, 2) },
element: function(event) {
var node = Event.extend(event).target;
return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
event = Event.extend(event);
var node = event.target,
type = event.type,
currentTarget = event.currentTarget;
if (currentTarget && currentTarget.tagName) {
// Firefox screws up the "click" event when moving between radio buttons
// via arrow keys. It also screws up the "load" and "error" events on images,
// reporting the document as the target instead of the original image.
if (type === 'load' || type === 'error' ||
(type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
&& currentTarget.type === 'radio'))
node = currentTarget;
}
if (node.nodeType == Node.TEXT_NODE) node = node.parentNode;
return Element.extend(node);
},
findElement: function(event, expression) {
@ -3785,11 +3870,15 @@ Event.Methods = (function() {
},
pointer: function(event) {
var docElement = document.documentElement,
body = document.body || { scrollLeft: 0, scrollTop: 0 };
return {
x: event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft)),
(docElement.scrollLeft || body.scrollLeft) -
(docElement.clientLeft || 0)),
y: event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop))
(docElement.scrollTop || body.scrollTop) -
(docElement.clientTop || 0))
};
},
@ -3834,7 +3923,7 @@ Event.extend = (function() {
};
} else {
Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__'];
Object.extend(Event.prototype, methods);
return Prototype.K;
}
@ -3899,10 +3988,20 @@ Object.extend(Event, (function() {
cache[id][eventName] = null;
}
// Internet Explorer needs to remove event handlers on page unload
// in order to avoid memory leaks.
if (window.attachEvent) {
window.attachEvent("onunload", destroyCache);
}
// Safari has a dummy event handler on page unload so that it won't
// use its bfcache. Safari <= 3.1 has an issue with restoring the "document"
// object when page is returned to via the back button using its bfcache.
if (Prototype.Browser.WebKit) {
window.addEventListener('unload', Prototype.emptyFunction, false);
}
return {
observe: function(element, eventName, handler) {
element = $(element);

View file

@ -1,4 +1,5 @@
#!/usr/bin/env ruby
#coding: ascii-8bit
require File.expand_path(File.join(File.dirname(__FILE__), '/../test_helper'))
require 'sanitizer'

View file

@ -1,4 +1,6 @@
*2.2.0 [RC1] (October 24th, 2008)*
*2.2 (November 21st, 2008)*
* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth]
* Add layout functionality to mailers [Pratik]

0
vendor/rails/actionmailer/README vendored Executable file → Normal file
View file

2
vendor/rails/actionmailer/Rakefile vendored Executable file → Normal file
View file

@ -55,7 +55,7 @@ spec = Gem::Specification.new do |s|
s.rubyforge_project = "actionmailer"
s.homepage = "http://www.rubyonrails.org"
s.add_dependency('actionpack', '= 2.2.0' + PKG_BUILD)
s.add_dependency('actionpack', '= 2.2.2' + PKG_BUILD)
s.has_rdoc = true
s.requirements << 'none'

0
vendor/rails/actionmailer/lib/action_mailer.rb vendored Executable file → Normal file
View file

View file

@ -386,13 +386,16 @@ module ActionMailer #:nodoc:
end
def method_missing(method_symbol, *parameters) #:nodoc:
match = matches_dynamic_method?(method_symbol)
if match = matches_dynamic_method?(method_symbol)
case match[1]
when 'create' then new(match[2], *parameters).mail
when 'deliver' then new(match[2], *parameters).deliver!
when 'new' then nil
else super
end
else
super
end
end
# Receives a raw email, parses it into an email object, decodes it,
@ -440,7 +443,7 @@ module ActionMailer #:nodoc:
private
def matches_dynamic_method?(method_name) #:nodoc:
method_name = method_name.to_s
/(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
/^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
end
end
@ -546,7 +549,12 @@ module ActionMailer #:nodoc:
end
def render_message(method_name, body)
if method_name.respond_to?(:content_type)
@current_template_content_type = method_name.content_type
end
render :file => method_name, :body => body
ensure
@current_template_content_type = nil
end
def render(opts)
@ -565,8 +573,12 @@ module ActionMailer #:nodoc:
end
def default_template_format
if @current_template_content_type
Mime::Type.lookup(@current_template_content_type).to_sym
else
:html
end
end
def candidate_for_layout?(options)
!@template.send(:_exempt_from_layout?, default_template_name)
@ -585,7 +597,9 @@ module ActionMailer #:nodoc:
end
def initialize_template_class(assigns)
ActionView::Base.new(view_paths, assigns, self)
template = ActionView::Base.new(view_paths, assigns, self)
template.template_format = default_template_format
template
end
def sort_parts(parts, order = [])
@ -663,8 +677,10 @@ module ActionMailer #:nodoc:
mail.ready_to_send
sender = mail['return-path'] || mail.from
Net::SMTP.start(smtp_settings[:address], smtp_settings[:port], smtp_settings[:domain],
smtp_settings[:user_name], smtp_settings[:password], smtp_settings[:authentication]) do |smtp|
smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto)
smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
smtp_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, sender, destinations)
end
end

View file

@ -2,7 +2,7 @@ module ActionMailer
module VERSION #:nodoc:
MAJOR = 2
MINOR = 2
TINY = 0
TINY = 2
STRING = [MAJOR, MINOR, TINY].join('.')
end

View file

@ -24,11 +24,15 @@ class MockSMTP
def sendmail(mail, from, to)
@@deliveries << [mail, from, to]
end
def start(*args)
yield self
end
end
class Net::SMTP
def self.start(*args)
yield MockSMTP.new
def self.new(*args)
MockSMTP.new
end
end

View file

@ -1,3 +0,0 @@
Hello there,
Mr. <%= @recipient %>

View file

@ -20,6 +20,12 @@ class AutoLayoutMailer < ActionMailer::Base
from "tester@example.com"
body render(:inline => "Hello, <%= @world %>", :layout => false, :body => { :world => "Earth" })
end
def multipart(recipient)
recipients recipient
subject "You have a mail"
from "tester@example.com"
end
end
class ExplicitLayoutMailer < ActionMailer::Base
@ -56,6 +62,17 @@ class LayoutMailerTest < Test::Unit::TestCase
assert_equal "Hello from layout Inside", mail.body.strip
end
def test_should_pickup_multipart_layout
mail = AutoLayoutMailer.create_multipart(@recipient)
assert_equal 2, mail.parts.size
assert_equal 'text/plain', mail.parts.first.content_type
assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body
assert_equal 'text/html', mail.parts.last.content_type
assert_equal "Hello from layout text/html multipart", mail.parts.last.body
end
def test_should_pickup_layout_given_to_render
mail = AutoLayoutMailer.create_spam(@recipient)
assert_equal "Spammer layout Hello, Earth", mail.body.strip

26
vendor/rails/actionmailer/test/mail_service_test.rb vendored Executable file → Normal file
View file

@ -938,6 +938,20 @@ EOF
mail = TestMailer.create_body_ivar(@recipient)
assert_equal "body: foo\nbar: baz", mail.body
end
def test_starttls_is_enabled_if_supported
MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(true)
MockSMTP.any_instance.expects(:enable_starttls_auto)
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_signed_up(@recipient)
end
def test_starttls_is_disabled_if_not_supported
MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(false)
MockSMTP.any_instance.expects(:enable_starttls_auto).never
ActionMailer::Base.delivery_method = :smtp
TestMailer.deliver_signed_up(@recipient)
end
end
end # uses_mocha
@ -1031,4 +1045,16 @@ class RespondToTest < Test::Unit::TestCase
def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit
assert !RespondToMailer.respond_to?(:deliver_1_template)
end
def test_should_not_respond_to_method_where_deliver_is_not_a_suffix
assert !RespondToMailer.respond_to?(:foo_deliver_template)
end
def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method
error = assert_raises NoMethodError do
RespondToMailer.not_a_method
end
assert_match /undefined method.*not_a_method/, error.message
end
end

View file

@ -1,4 +1,34 @@
*2.2.0 [RC1] (October 24th, 2008)*
*2.2 (November 21st, 2008)*
* Deprecated the :file default for ActionView#render to prepare for 2.3's new :partial default [DHH]
* Restore backwards compatible functionality for setting relative_url_root. Include deprecation
* Switched the CSRF module to use the request content type to decide if the request is forgeable. #1145 [Jeff Cohen]
* Added :only and :except to map.resources to let people cut down on the number of redundant routes in an application. Typically only useful for huge routesets. #1215 [Tom Stuart]
map.resources :products, :only => :show do |product|
product.resources :images, :except => :destroy
end
* Added render :js for people who want to render inline JavaScript replies without using RJS [DHH]
* Fixed that polymorphic_url should compact given array #1317 [hiroshi]
* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 [antonmos/Ryan McGeary]
* Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 [Vladimir Dobriakov]
* Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 [Bernardo Padua/Tor Erik]
* Simplified the logging format for parameters (don't include controller, action, and format as duplicates) [DHH]
* Remove the logging of the Session ID when the session store is CookieStore [DHH]
* Fixed regex in redirect_to to fully support URI schemes #1247 [Seth Fitzsimmons]
* Fixed bug with asset timestamping when using relative_url_root #1265 [Joe Goldwasser]
* Fix incorrect closing CDATA delimiter and that HTML::Node.parse would blow up on unclosed CDATA sections [packagethief]

View file

@ -80,7 +80,7 @@ spec = Gem::Specification.new do |s|
s.has_rdoc = true
s.requirements << 'none'
s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD)
s.add_dependency('activesupport', '= 2.2.2' + PKG_BUILD)
s.require_path = 'lib'
s.autorequire = 'action_controller'

0
vendor/rails/actionpack/lib/action_controller.rb vendored Executable file → Normal file
View file

78
vendor/rails/actionpack/lib/action_controller/base.rb vendored Executable file → Normal file
View file

@ -278,12 +278,6 @@ module ActionController #:nodoc:
@@consider_all_requests_local = true
cattr_accessor :consider_all_requests_local
# Enable or disable the collection of failure information for RoutingErrors.
# This information can be extremely useful when tweaking custom routes, but is
# pointless once routes have been tested and verified.
@@debug_routes = true
cattr_accessor :debug_routes
# Indicates whether to allow concurrent action processing. Your
# controller actions and any other code they call must also behave well
# when called from concurrent threads. Turned off by default.
@ -364,11 +358,8 @@ module ActionController #:nodoc:
# If you are deploying to a subdirectory, you will need to set
# <tt>config.action_controller.relative_url_root</tt>
# This defaults to ENV['RAILS_RELATIVE_URL_ROOT']
cattr_writer :relative_url_root
def self.relative_url_root
@@relative_url_root || ENV['RAILS_RELATIVE_URL_ROOT']
end
cattr_accessor :relative_url_root
self.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
# Holds the request object that's primarily used to get environment variables through access like
# <tt>request.env["REQUEST_URI"]</tt>.
@ -801,6 +792,19 @@ module ActionController #:nodoc:
# # Renders "Hello from code!"
# render :text => proc { |response, output| output.write("Hello from code!") }
#
# === Rendering XML
#
# Rendering XML sets the content type to application/xml.
#
# # Renders '<name>David</name>'
# render :xml => {:name => "David"}.to_xml
#
# It's not necessary to call <tt>to_xml</tt> on the object you want to render, since <tt>render</tt> will
# automatically do that for you:
#
# # Also renders '<name>David</name>'
# render :xml => {:name => "David"}
#
# === Rendering JSON
#
# Rendering JSON sets the content type to application/json and optionally wraps the JSON in a callback. It is expected
@ -846,8 +850,14 @@ module ActionController #:nodoc:
# page.visual_effect :highlight, 'user_list'
# end
#
# === Rendering with status and location headers
# === Rendering vanilla JavaScript
#
# In addition to using RJS with render :update, you can also just render vanilla JavaScript with :js.
#
# # Renders "alert('hello')" and sets the mime type to text/javascript
# render :js => "alert('hello')"
#
# === Rendering with status and location headers
# All renders take the <tt>:status</tt> and <tt>:location</tt> options and turn them into headers. They can even be used together:
#
# render :xml => post.to_xml, :status => :created, :location => post_url(post)
@ -898,6 +908,10 @@ module ActionController #:nodoc:
response.content_type ||= Mime::XML
render_for_text(xml.respond_to?(:to_xml) ? xml.to_xml : xml, options[:status])
elsif js = options[:js]
response.content_type ||= Mime::JS
render_for_text(js, options[:status])
elsif json = options[:json]
json = json.to_json unless json.is_a?(String)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
@ -933,6 +947,7 @@ module ActionController #:nodoc:
def render_to_string(options = nil, &block) #:doc:
render(options, &block)
ensure
response.content_type = nil
erase_render_results
reset_variables_added_to_assigns
end
@ -1014,10 +1029,10 @@ module ActionController #:nodoc:
#
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
# * <tt>String starting with protocol:// (like http://)</tt> - Is passed straight through as the target for redirection.
# * <tt>String not containing a protocol</tt> - The current protocol and host is prepended to the string.
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) - Is passed straight through as the target for redirection.
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
# Short-hand for redirect_to(request.env["HTTP_REFERER"])
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
#
# Examples:
# redirect_to :action => "show", :id => 5
@ -1053,7 +1068,10 @@ module ActionController #:nodoc:
logger.info("Redirected to #{options}") if logger && logger.info?
case options
when %r{^\w+://.*}
# The scheme name consist of a letter followed by any combination of
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
# characters; and is terminated by a colon (":").
when %r{^\w[\w\d+.-]*:.*}
redirect_to_full_url(options, status)
when String
redirect_to_full_url(request.protocol + request.host_with_port + options, status)
@ -1198,12 +1216,34 @@ module ActionController #:nodoc:
def log_processing
if logger && logger.info?
logger.info "\n\nProcessing #{self.class.name}\##{action_name} (for #{request_origin}) [#{request.method.to_s.upcase}]"
logger.info " Session ID: #{@_session.session_id}" if @_session and @_session.respond_to?(:session_id)
logger.info " Parameters: #{respond_to?(:filter_parameters) ? filter_parameters(params).inspect : params.inspect}"
log_processing_for_request_id
log_processing_for_session_id
log_processing_for_parameters
end
end
def log_processing_for_request_id
request_id = "\n\nProcessing #{self.class.name}\##{action_name} "
request_id << "to #{params[:format]} " if params[:format]
request_id << "(for #{request_origin}) [#{request.method.to_s.upcase}]"
logger.info(request_id)
end
def log_processing_for_session_id
if @_session && @_session.respond_to?(:session_id) && @_session.respond_to?(:dbman) &&
!@_session.dbman.is_a?(CGI::Session::CookieStore)
logger.info " Session ID: #{@_session.session_id}"
end
end
def log_processing_for_parameters
parameters = respond_to?(:filter_parameters) ? filter_parameters(params) : params.dup
parameters = parameters.except!(:controller, :action, :format, :_method)
logger.info " Parameters: #{parameters.inspect}" unless parameters.empty?
end
def default_render #:nodoc:
render
end

View file

@ -23,11 +23,14 @@ module ActionController
if defined?(ActiveRecord)
after_dispatch :checkin_connections
before_dispatch { ActiveRecord::Base.verify_active_connections! }
to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers }
end
after_dispatch :flush_logger if Base.logger && Base.logger.respond_to?(:flush)
to_prepare do
I18n.reload!
end
end
# Backward-compatible class method takes CGI-specific args. Deprecated

View file

@ -20,8 +20,20 @@ module Mime
# end
class Type
@@html_types = Set.new [:html, :all]
cattr_reader :html_types
# These are the content types which browsers can generate without using ajax, flash, etc
# i.e. following a link, getting an image or posting a form. CSRF protection
# only needs to protect against these types.
@@browser_generated_types = Set.new [:html, :url_encoded_form, :multipart_form, :text]
cattr_reader :browser_generated_types
@@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml]
cattr_reader :html_types, :unverifiable_types
def self.unverifiable_types
ActiveSupport::Deprecation.warn("unverifiable_types is deprecated and has no effect", caller)
@@unverifiable_types
end
# A simple helper class used in parsing the accept header
class AcceptItem #:nodoc:
@ -165,15 +177,19 @@ module Mime
end
# Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See
# ActionController::RequestForgerProtection.
# ActionController::RequestForgeryProtection.
def verify_request?
!@@unverifiable_types.include?(to_sym)
browser_generated?
end
def html?
@@html_types.include?(to_sym) || @string =~ /html/
end
def browser_generated?
@@browser_generated_types.include?(to_sym)
end
private
def method_missing(method, *args)
if method.to_s =~ /(\w+)\?$/

View file

@ -73,7 +73,8 @@ module ActionController
#
def polymorphic_url(record_or_hash_or_array, options = {})
if record_or_hash_or_array.kind_of?(Array)
record_or_hash_or_array = record_or_hash_or_array.dup
record_or_hash_or_array = record_or_hash_or_array.compact
record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
end
record = extract_record(record_or_hash_or_array)

View file

@ -9,10 +9,11 @@ module ActionController
class AbstractRequest
extend ActiveSupport::Memoizable
def self.relative_url_root=(*args)
def self.relative_url_root=(relative_url_root)
ActiveSupport::Deprecation.warn(
"ActionController::AbstractRequest.relative_url_root= has been renamed." +
"You can now set it with config.action_controller.relative_url_root=", caller)
ActionController::Base.relative_url_root=relative_url_root
end
HTTP_METHODS = %w(get head put post delete options)

View file

@ -99,7 +99,7 @@ module ActionController #:nodoc:
end
def verifiable_request_format?
request.content_type.nil? || request.content_type.verify_request?
!request.content_type.nil? && request.content_type.verify_request?
end
# Sets the token value for the current session. Pass a <tt>:secret</tt> option

0
vendor/rails/actionpack/lib/action_controller/request_profiler.rb vendored Executable file → Normal file
View file

View file

@ -42,7 +42,11 @@ module ActionController
#
# Read more about REST at http://en.wikipedia.org/wiki/Representational_State_Transfer
module Resources
INHERITABLE_OPTIONS = :namespace, :shallow, :actions
class Resource #:nodoc:
DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy
attr_reader :collection_methods, :member_methods, :new_methods
attr_reader :path_prefix, :name_prefix, :path_segment
attr_reader :plural, :singular
@ -57,6 +61,7 @@ module ActionController
arrange_actions
add_default_actions
set_allowed_actions
set_prefixes
end
@ -113,6 +118,10 @@ module ActionController
@singular.to_s == @plural.to_s
end
def has_action?(action)
!DEFAULT_ACTIONS.include?(action) || @options[:actions].nil? || @options[:actions].include?(action)
end
protected
def arrange_actions
@collection_methods = arrange_actions_by_methods(options.delete(:collection))
@ -125,6 +134,25 @@ module ActionController
add_default_action(new_methods, :get, :new)
end
def set_allowed_actions
only = @options.delete(:only)
except = @options.delete(:except)
if only && except
raise ArgumentError, 'Please supply either :only or :except, not both.'
elsif only == :all || except == :none
options[:actions] = DEFAULT_ACTIONS
elsif only == :none || except == :all
options[:actions] = []
elsif only
options[:actions] = DEFAULT_ACTIONS & Array(only).map(&:to_sym)
elsif except
options[:actions] = DEFAULT_ACTIONS - Array(except).map(&:to_sym)
else
# leave options[:actions] alone
end
end
def set_prefixes
@path_prefix = options.delete(:path_prefix)
@name_prefix = options.delete(:name_prefix)
@ -353,6 +381,25 @@ module ActionController
#
# map.resources :users, :has_many => { :posts => :comments }, :shallow => true
#
# * <tt>:only</tt> and <tt>:except</tt> - Specify which of the seven default actions should be routed to.
#
# <tt>:only</tt> and <tt>:except</tt> may be set to <tt>:all</tt>, <tt>:none</tt>, an action name or a
# list of action names. By default, routes are generated for all seven actions.
#
# For example:
#
# map.resources :posts, :only => [:index, :show] do |post|
# post.resources :comments, :except => [:update, :destroy]
# end
# # --> GET /posts (maps to the PostsController#index action)
# # --> POST /posts (fails)
# # --> GET /posts/1 (maps to the PostsController#show action)
# # --> DELETE /posts/1 (fails)
# # --> POST /posts/1/comments (maps to the CommentsController#create action)
# # --> PUT /posts/1/comments/1 (fails)
#
# The <tt>:only</tt> and <tt>:except</tt> options are inherited by any nested resource(s).
#
# If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied.
#
# Examples:
@ -478,7 +525,7 @@ module ActionController
map_associations(resource, options)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
end
end
end
@ -495,7 +542,7 @@ module ActionController
map_associations(resource, options)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
end
end
end
@ -507,7 +554,7 @@ module ActionController
name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
Array(options[:has_one]).each do |association|
resource(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace], :shallow => options[:shallow])
resource(association, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => path_prefix, :name_prefix => name_prefix))
end
end
@ -522,7 +569,7 @@ module ActionController
map_has_many_associations(resource, association, options)
end
when Symbol, String
resources(associations, :path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], :has_many => options[:has_many])
resources(associations, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :has_many => options[:has_many]))
else
end
end
@ -531,41 +578,39 @@ module ActionController
resource.collection_methods.each do |method, actions|
actions.each do |action|
[method].flatten.each do |m|
action_options = action_options_for(action, resource, m)
map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options)
map_resource_routes(map, resource, action, "#{resource.path}#{resource.action_separator}#{action}", "#{action}_#{resource.name_prefix}#{resource.plural}", m)
end
end
end
end
def map_default_collection_actions(map, resource)
index_action_options = action_options_for("index", resource)
index_route_name = "#{resource.name_prefix}#{resource.plural}"
if resource.uncountable?
index_route_name << "_index"
end
map_named_routes(map, index_route_name, resource.path, index_action_options)
create_action_options = action_options_for("create", resource)
map_unnamed_routes(map, resource.path, create_action_options)
map_resource_routes(map, resource, :index, resource.path, index_route_name)
map_resource_routes(map, resource, :create, resource.path, index_route_name)
end
def map_default_singleton_actions(map, resource)
create_action_options = action_options_for("create", resource)
map_unnamed_routes(map, resource.path, create_action_options)
map_resource_routes(map, resource, :create, resource.path, "#{resource.shallow_name_prefix}#{resource.singular}")
end
def map_new_actions(map, resource)
resource.new_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if action == :new
map_named_routes(map, "new_#{resource.name_prefix}#{resource.singular}", resource.new_path, action_options)
else
map_named_routes(map, "#{action}_new_#{resource.name_prefix}#{resource.singular}", "#{resource.new_path}#{resource.action_separator}#{action}", action_options)
route_path = resource.new_path
route_name = "new_#{resource.name_prefix}#{resource.singular}"
unless action == :new
route_path = "#{route_path}#{resource.action_separator}#{action}"
route_name = "#{action}_#{route_name}"
end
map_resource_routes(map, resource, action, route_path, route_name, method)
end
end
end
@ -574,34 +619,33 @@ module ActionController
resource.member_methods.each do |method, actions|
actions.each do |action|
[method].flatten.each do |m|
action_options = action_options_for(action, resource, m)
action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash)
action_path ||= Base.resources_path_names[action] || action
map_named_routes(map, "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options)
map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m)
end
end
end
show_action_options = action_options_for("show", resource)
map_named_routes(map, "#{resource.shallow_name_prefix}#{resource.singular}", resource.member_path, show_action_options)
update_action_options = action_options_for("update", resource)
map_unnamed_routes(map, resource.member_path, update_action_options)
destroy_action_options = action_options_for("destroy", resource)
map_unnamed_routes(map, resource.member_path, destroy_action_options)
route_path = "#{resource.shallow_name_prefix}#{resource.singular}"
map_resource_routes(map, resource, :show, resource.member_path, route_path)
map_resource_routes(map, resource, :update, resource.member_path, route_path)
map_resource_routes(map, resource, :destroy, resource.member_path, route_path)
end
def map_unnamed_routes(map, path_without_format, options)
map.connect(path_without_format, options)
map.connect("#{path_without_format}.:format", options)
end
def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil)
if resource.has_action?(action)
action_options = action_options_for(action, resource, method)
formatted_route_path = "#{route_path}.:format"
def map_named_routes(map, name, path_without_format, options)
map.named_route(name, path_without_format, options)
map.named_route("formatted_#{name}", "#{path_without_format}.:format", options)
if route_name && @set.named_routes[route_name.to_sym].nil?
map.named_route(route_name, route_path, action_options)
map.named_route("formatted_#{route_name}", formatted_route_path, action_options)
else
map.connect(route_path, action_options)
map.connect(formatted_route_path, action_options)
end
end
end
def add_conditions_for(conditions, method)

0
vendor/rails/actionpack/lib/action_controller/response.rb vendored Executable file → Normal file
View file

View file

@ -1,23 +1,16 @@
module ActionController
module Routing
class RouteBuilder #:nodoc:
attr_accessor :separators, :optional_separators
attr_reader :separators, :optional_separators
attr_reader :separator_regexp, :nonseparator_regexp, :interval_regexp
def initialize
self.separators = Routing::SEPARATORS
self.optional_separators = %w( / )
end
@separators = Routing::SEPARATORS
@optional_separators = %w( / )
def separator_pattern(inverted = false)
"[#{'^' if inverted}#{Regexp.escape(separators.join)}]"
end
def interval_regexp
Regexp.new "(.*?)(#{separators.source}|$)"
end
def multiline_regexp?(expression)
expression.options & Regexp::MULTILINE == Regexp::MULTILINE
@separator_regexp = /[#{Regexp.escape(separators.join)}]/
@nonseparator_regexp = /\A([^#{Regexp.escape(separators.join)}]+)/
@interval_regexp = /(.*?)(#{separator_regexp}|$)/
end
# Accepts a "route path" (a string defining a route), and returns the array
@ -30,7 +23,7 @@ module ActionController
rest, segments = path, []
until rest.empty?
segment, rest = segment_for rest
segment, rest = segment_for(rest)
segments << segment
end
segments
@ -39,19 +32,19 @@ module ActionController
# A factory method that returns a new segment instance appropriate for the
# format of the given string.
def segment_for(string)
segment = case string
segment =
case string
when /\A:(\w+)/
key = $1.to_sym
case key
when :controller then ControllerSegment.new(key)
else DynamicSegment.new key
end
when /\A\*(\w+)/ then PathSegment.new($1.to_sym, :optional => true)
key == :controller ? ControllerSegment.new(key) : DynamicSegment.new(key)
when /\A\*(\w+)/
PathSegment.new($1.to_sym, :optional => true)
when /\A\?(.*?)\?/
StaticSegment.new($1, :optional => true)
when /\A(#{separator_pattern(:inverted)}+)/ then StaticSegment.new($1)
when Regexp.new(separator_pattern) then
DividerSegment.new($&, :optional => (optional_separators.include? $&))
when nonseparator_regexp
StaticSegment.new($1)
when separator_regexp
DividerSegment.new($&, :optional => optional_separators.include?($&))
end
[segment, $~.post_match]
end
@ -98,7 +91,7 @@ module ActionController
if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
end
if multiline_regexp?(requirement)
if requirement.multiline?
raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
end
segment.regexp = requirement

View file

@ -20,14 +20,20 @@ module ActionController
class Optimiser
attr_reader :route, :kind
GLOBAL_GUARD_CONDITIONS = [
"(!defined?(default_url_options) || default_url_options.blank?)",
"(!defined?(controller.default_url_options) || controller.default_url_options.blank?)",
"defined?(request)",
"request"
]
def initialize(route, kind)
@route = route
@kind = kind
end
def guard_condition
'false'
def guard_conditions
["false"]
end
def generation_code
@ -36,6 +42,7 @@ module ActionController
def source_code
if applicable?
guard_condition = (GLOBAL_GUARD_CONDITIONS + guard_conditions).join(" && ")
"return #{generation_code} if #{guard_condition}\n"
else
"\n"
@ -57,14 +64,14 @@ module ActionController
# return a string like "/people/#{@person.to_param}"
# rather than triggering the expensive logic in +url_for+.
class PositionalArguments < Optimiser
def guard_condition
def guard_conditions
number_of_arguments = route.segment_keys.size
# if they're using foo_url(:id=>2) it's one
# argument, but we don't want to generate /foos/id2
if number_of_arguments == 1
"(!defined?(default_url_options) || default_url_options.blank?) && defined?(request) && request && args.size == 1 && !args.first.is_a?(Hash)"
["args.size == 1", "!args.first.is_a?(Hash)"]
else
"(!defined?(default_url_options) || default_url_options.blank?) && defined?(request) && request && args.size == #{number_of_arguments}"
["args.size == #{number_of_arguments}"]
end
end
@ -98,8 +105,9 @@ module ActionController
# above, but it supports additional query parameters as the last
# argument
class PositionalArgumentsWithAdditionalParams < PositionalArguments
def guard_condition
"(!defined?(default_url_options) || default_url_options.blank?) && defined?(request) && request && args.size == #{route.segment_keys.size + 1} && !args.last.has_key?(:anchor) && !args.last.has_key?(:port) && !args.last.has_key?(:host)"
def guard_conditions
["args.size == #{route.segment_keys.size + 1}"] +
UrlRewriter::RESERVED_OPTIONS.collect{ |key| "!args.last.has_key?(:#{key})" }
end
# This case uses almost the same code as positional arguments,

View file

@ -148,18 +148,12 @@ module ActionController
end
nil
end
}, __FILE__, __LINE__
}, '(recognize_optimized)', 1
end
def clear_recognize_optimized!
remove_recognize_optimized!
class << self
def recognize_optimized(path, environment)
write_recognize_optimized!
recognize_optimized(path, environment)
end
end
end
def remove_recognize_optimized!

View file

@ -219,7 +219,7 @@ module ActionController
next_capture = 1
extraction = segments.collect do |segment|
x = segment.match_extraction(next_capture)
next_capture += Regexp.new(segment.regexp_chunk).number_of_captures
next_capture += segment.number_of_captures
x
end
extraction.compact

View file

@ -168,6 +168,7 @@ module ActionController
#
@module.module_eval <<-end_eval # We use module_eval to avoid leaks
def #{selector}(*args)
#{generate_optimisation_block(route, kind)}
opts = if args.empty? || Hash === args.first

View file

@ -27,6 +27,10 @@ class Regexp #:nodoc:
Regexp.new("|#{source}").match('').captures.length
end
def multiline?
options & MULTILINE == MULTILINE
end
class << self
def optionalize(pattern)
case unoptionalize(pattern)

View file

@ -13,6 +13,10 @@ module ActionController
@is_optional = false
end
def number_of_captures
Regexp.new(regexp_chunk).number_of_captures
end
def extraction_code
nil
end
@ -84,6 +88,10 @@ module ActionController
optional? ? Regexp.optionalize(chunk) : chunk
end
def number_of_captures
0
end
def build_pattern(pattern)
escaped = Regexp.escape(value)
if optional? && ! pattern.empty?
@ -194,10 +202,16 @@ module ActionController
end
end
def number_of_captures
if regexp
regexp.number_of_captures + 1
else
1
end
end
def build_pattern(pattern)
chunk = regexp_chunk
chunk = "(#{chunk})" if Regexp.new(chunk).number_of_captures == 0
pattern = "#{chunk}#{pattern}"
pattern = "#{regexp_chunk}#{pattern}"
optional? ? Regexp.optionalize(pattern) : pattern
end
@ -230,6 +244,10 @@ module ActionController
"(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))"
end
def number_of_captures
1
end
# Don't URI.escape the controller name since it may contain slashes.
def interpolation_chunk(value_code = local_name)
"\#{#{value_code}.to_s}"
@ -275,6 +293,10 @@ module ActionController
regexp || "(.*)"
end
def number_of_captures
regexp ? regexp.number_of_captures : 1
end
def optionality_implied?
true
end

0
vendor/rails/actionpack/lib/action_controller/session/drb_server.rb vendored Normal file → Executable file
View file

View file

@ -218,7 +218,7 @@ module ActionController #:nodoc:
# Returns the template of the file which was used to
# render this response (or nil)
def rendered_template
template.send(:_first_render)
template.instance_variable_get(:@_first_render)
end
# A shortcut to the flash. Returns an empty hash if no session flash exists.
@ -395,6 +395,7 @@ module ActionController #:nodoc:
@html_document = nil
@request.env['REQUEST_METHOD'] ||= "GET"
@request.action = action.to_s
parameters ||= {}

View file

@ -160,7 +160,7 @@ module HTML
if !options[:attributes].include?(attr_name) || contains_bad_protocols?(attr_name, value)
node.attributes.delete(attr_name)
else
node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(value)
node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(CGI::unescapeHTML(value))
end
end
end

View file

@ -2,7 +2,7 @@ module ActionPack #:nodoc:
module VERSION #:nodoc:
MAJOR = 2
MINOR = 2
TINY = 0
TINY = 2
STRING = [MAJOR, MINOR, TINY].join('.')
end

View file

@ -43,7 +43,7 @@ require 'action_view/base'
require 'action_view/partials'
require 'action_view/template_error'
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en-US.yml"
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
require 'action_view/helpers'

View file

@ -222,6 +222,7 @@ module ActionView #:nodoc:
def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
@assigns = assigns_for_first_render
@assigns_added = nil
@_render_stack = []
@controller = controller
@helpers = ProxyModule.new(self)
self.view_paths = view_paths
@ -239,6 +240,11 @@ module ActionView #:nodoc:
local_assigns ||= {}
if options.is_a?(String)
ActiveSupport::Deprecation.warn(
"Calling render with a string will render a partial from Rails 2.3. " +
"Change this call to render(:file => '#{options}', :locals => locals_hash)."
)
render(:file => options, :locals => local_assigns)
elsif options == :update
update_page(&block)
@ -271,9 +277,13 @@ module ActionView #:nodoc:
end
end
private
attr_accessor :_first_render, :_last_render
# Access the current template being rendered.
# Returns a ActionView::Template object.
def template
@_render_stack.last
end
private
# Evaluates the local assigns and controller ivars, pushes them to the view.
def _evaluate_assigns_and_ivars #:nodoc:
unless @assigns_added
@ -312,7 +322,8 @@ module ActionView #:nodoc:
template
elsif template = self.view_paths[template_file_name]
template
elsif _first_render && template = self.view_paths["#{template_file_name}.#{_first_render.format_and_extension}"]
elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension) &&
(template = self.view_paths["#{template_file_name}.#{first_render.format_and_extension}"])
template
elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"]
@template_format = :html

View file

@ -151,7 +151,7 @@ module ActionView
# javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js
# javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
def javascript_path(source)
JavaScriptTag.create(self, @controller, source).public_path
JavaScriptTag.new(self, @controller, source).public_path
end
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
@ -314,7 +314,7 @@ module ActionView
# stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css
# stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css
def stylesheet_path(source)
StylesheetTag.create(self, @controller, source).public_path
StylesheetTag.new(self, @controller, source).public_path
end
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
@ -411,7 +411,7 @@ module ActionView
# image_path("/icons/edit.png") # => /icons/edit.png
# image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png
def image_path(source)
ImageTag.create(self, @controller, source).public_path
ImageTag.new(self, @controller, source).public_path
end
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
@ -527,20 +527,6 @@ module ActionView
Cache = {}
CacheGuard = Mutex.new
def self.create(template, controller, source, include_host = true)
CacheGuard.synchronize do
key = if controller.respond_to?(:request)
[self, controller.request.protocol,
ActionController::Base.asset_host,
ActionController::Base.relative_url_root,
source, include_host]
else
[self, ActionController::Base.asset_host, source, include_host]
end
Cache[key] ||= new(template, controller, source, include_host).freeze
end
end
ProtocolRegexp = %r{^[-a-z]+://}.freeze
def initialize(template, controller, source, include_host = true)
@ -551,6 +537,14 @@ module ActionView
@controller = controller
@source = source
@include_host = include_host
@cache_key = if controller.respond_to?(:request)
[self.class.name,controller.request.protocol,
ActionController::Base.asset_host,
ActionController::Base.relative_url_root,
source, include_host]
else
[self.class.name,ActionController::Base.asset_host, source, include_host]
end
end
def public_path
@ -585,18 +579,30 @@ module ActionView
# roots. Rewrite the asset path for cache-busting asset ids. Include
# asset host, if configured, with the correct request protocol.
def compute_public_path(source)
if source =~ ProtocolRegexp
source += ".#{extension}" if missing_extension?(source)
unless source =~ ProtocolRegexp
source = prepend_asset_host(source)
source
else
CacheGuard.synchronize do
Cache[@cache_key] ||= begin
source += ".#{extension}" if missing_extension?(source) || file_exists_with_extension?(source)
source = "/#{directory}/#{source}" unless source[0] == ?/
source = prepend_relative_url_root(source)
source = rewrite_asset_path(source)
end
source = prepend_relative_url_root(source)
source = prepend_asset_host(source)
source
end
end
end
end
def missing_extension?(source)
extension && (File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}")))
extension && File.extname(source).blank?
end
def file_exists_with_extension?(source)
extension && File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}"))
end
def prepend_relative_url_root(source)
@ -735,7 +741,7 @@ module ActionView
end
def tag_sources
expand_sources.collect { |source| tag_class.create(@template, @controller, source, false) }
expand_sources.collect { |source| tag_class.new(@template, @controller, source, false) }
end
def joined_contents

View file

@ -1,3 +1,5 @@
require 'set'
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERb or any other
# template languages).
module ActionView
@ -121,6 +123,8 @@ module ActionView
end
class AtomBuilder
XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
def initialize(xml)
@xml = xml
end
@ -145,9 +149,10 @@ module ActionView
# in the Atom spec as potentially containing XHTML content and
# if :type => 'xhtml' is, in fact, specified.
def xhtml_block?(method, arguments)
%w( content rights title subtitle summary ).include?(method.to_s) &&
arguments.last.respond_to?(:[]) &&
arguments.last[:type].to_s == 'xhtml'
if XHTML_TAG_NAMES.include?(method.to_s)
last = arguments.last
last.is_a?(Hash) && last[:type].to_s == 'xhtml'
end
end
end

6
vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb vendored Executable file → Normal file
View file

@ -131,7 +131,7 @@ module ActionView
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> do
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
# the respective locale (e.g. [:year, :month, :day] in the en-US locale that ships with Rails).
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
# dates.
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
@ -539,7 +539,7 @@ module ActionView
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @options[:discard_day] && !@options[:discard_month]
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
@ -567,7 +567,7 @@ module ActionView
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @options[:discard_day] && !@options[:discard_month]
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
end

View file

@ -78,7 +78,7 @@ module ActionView
# # <option>Paris</option><option>Rome</option></select>
def select_tag(name, option_tags = nil, options = {})
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
content_tag :select, option_tags, { "name" => html_name, "id" => name }.update(options.stringify_keys)
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
end
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
@ -112,7 +112,7 @@ module ActionView
# text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input"
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
def text_field_tag(name, value = nil, options = {})
tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys)
tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
end
# Creates a label field
@ -130,7 +130,7 @@ module ActionView
# label_tag 'name', nil, :class => 'small_label'
# # => <label for="name" class="small_label">Name</label>
def label_tag(name, text = nil, options = {})
content_tag :label, text || name.to_s.humanize, { "for" => name }.update(options.stringify_keys)
content_tag :label, text || name.to_s.humanize, { "for" => sanitize_to_id(name) }.update(options.stringify_keys)
end
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
@ -282,7 +282,7 @@ module ActionView
# check_box_tag 'eula', 'accepted', false, :disabled => true
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
def check_box_tag(name, value = "1", checked = false, options = {})
html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys)
html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
html_options["checked"] = "checked" if checked
tag :input, html_options
end
@ -470,6 +470,12 @@ module ActionView
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
end
end
# see http://www.w3.org/TR/html4/types.html#type-name
def sanitize_to_id(name)
name.to_s.gsub(']','').gsub(/[^-a-zA-Z0-9:.]/, "_")
end
end
end
end

View file

@ -31,9 +31,6 @@ module ActionView
# to use all basic AJAX functionality. For the Scriptaculous-based
# JavaScript helpers, like visual effects, autocompletion, drag and drop
# and so on, you should use the method described above.
# * Use <tt><%= define_javascript_functions %></tt>: this will copy all the
# JavaScript support functions within a single script block. Not
# recommended.
#
# For documentation on +javascript_include_tag+ see
# ActionView::Helpers::AssetTagHelper.

View file

@ -1,963 +0,0 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { }
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element)
this.element = element;
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
}
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML;
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
// Can't use triggerCallback due to backward compatibility: requires
// binding + direct element
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw 'Server returned an invalid collection representation.';
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only exists for a while, in order to let ****
//**** users adapt to the new API. Read up on the new ****
//**** API and convert your code to it ASAP! ****
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3, // Use when multi-line w/ rows == 1
cancelControl: 'link', // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null, // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate', // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null, // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button', // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1, // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
// For backward compatibility, this one is bound to the IPE, and passes
// the element directly. It was too often customized, so we don't break it.
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});

View file

@ -1,972 +0,0 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || { });
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if(Object.isArray(containment)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if (drop != this.last_active) Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
}
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
}
/*--------------------------------------------------------------------------*/
var Draggable = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this.element._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
if (!this.element._originallyAbsolute)
Position.relativize(this.element);
delete this.element._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this))
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight
}
}
return { top: T, left: L, width: W, height: H };
}
});
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create({
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
});
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: { },
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
var s = Sortable.options(element);
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
}
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
}
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.id] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
}
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child)
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
}
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
}
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
}
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
}
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -9,7 +9,7 @@ module ActionView
module TagHelper
include ERB::Util
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple).to_set
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked).to_set
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym))
# Returns an empty HTML tag of type +name+ which by default is XHTML
@ -133,10 +133,12 @@ module ActionView
unless options.blank?
attrs = []
if escape
options.each do |key, value|
next unless value
value = BOOLEAN_ATTRIBUTES.include?(key) ? key : escape_once(value)
attrs << %(#{key}="#{value}")
options.each_pair do |key, value|
if BOOLEAN_ATTRIBUTES.include?(key)
attrs << %(#{key}="#{key}") if value
else
attrs << %(#{key}="#{escape_once(value)}") if !value.nil?
end
end
else
attrs = options.map { |key, value| %(#{key}="#{value}") }

View file

@ -344,9 +344,9 @@ module ActionView
text << "</p>"
end
# Turns all URLs and e-mail addresses into clickable links. The +link+ parameter
# Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option
# will limit what should be linked. You can add HTML attributes to the links using
# +href_options+. Options for +link+ are <tt>:all</tt> (default),
# <tt>:href_options</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default),
# <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and
# e-mail address is yielded and the result is used as the link text.
#
@ -355,15 +355,15 @@ module ActionView
# # => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
# # say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
#
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :urls)
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls)
# # => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a>
# # or e-mail david@loudthinking.com"
#
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :email_addresses)
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :email_addresses)
# # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
#
# post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com."
# auto_link(post_body, :all, :target => '_blank') do |text|
# auto_link(post_body, :href_options => { :target => '_blank' }) do |text|
# truncate(text, 15)
# end
# # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>.
@ -559,7 +559,7 @@ module ActionView
(?:\.[-\w]+)* # remaining subdomains or domain
(?::\d+)? # port
(?:/(?:[~\w\+@%=\(\)-]|(?:[,.;:'][^\s$]))*)* # path
(?:\?[\w\+@%&=.;-]+)? # query string
(?:\?[\w\+@%&=.;:-]+)? # query string
(?:\#[\w\-]*)? # trailing anchor
)
([[:punct:]]|<|$|) # trailing text

View file

@ -3,12 +3,11 @@ require 'action_view/helpers/tag_helper'
module ActionView
module Helpers
module TranslationHelper
def translate(*args)
args << args.extract_options!.merge(:raise => true)
I18n.translate *args
def translate(key, options = {})
options[:raise] = true
I18n.translate(key, options)
rescue I18n::MissingTranslationData => e
keys = I18n.send :normalize_translation_keys, e.locale, e.key, e.options[:scope]
keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope])
content_tag('span', keys.join(', '), :class => 'translation_missing')
end
alias :t :translate

View file

@ -499,7 +499,7 @@ module ActionView
# True if the current request URI was generated by the given +options+.
#
# ==== Examples
# Let's say we're in the <tt>/shop/checkout</tt> action.
# Let's say we're in the <tt>/shop/checkout?order=desc</tt> action.
#
# current_page?(:action => 'process')
# # => false
@ -507,6 +507,9 @@ module ActionView
# current_page?(:controller => 'shop', :action => 'checkout')
# # => true
#
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc)
# # => false
#
# current_page?(:action => 'checkout')
# # => true
#
@ -515,10 +518,18 @@ module ActionView
def current_page?(options)
url_string = CGI.escapeHTML(url_for(options))
request = @controller.request
if url_string =~ /^\w+:\/\//
url_string == "#{request.protocol}#{request.host_with_port}#{request.request_uri}"
# We ignore any extra parameters in the request_uri if the
# submitted url doesn't have any either. This lets the function
# work with things like ?order=asc
if url_string.index("?")
request_uri = request.request_uri
else
url_string == request.request_uri
request_uri = request.request_uri.split('?').first
end
if url_string =~ /^\w+:\/\//
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
else
url_string == request_uri
end
end

View file

@ -1,91 +0,0 @@
"en-US":
number:
# Used in number_with_delimiter()
# These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
format:
# Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
separator: "."
# Delimets thousands (e.g. 1,000,000 is a million) (always in groups of three)
delimiter: ","
# Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
precision: 3
# Used in number_to_currency()
currency:
format:
# Where is the currency sign? %u is the currency unit, %n the number (default: $5.00)
format: "%u%n"
unit: "$"
# These three are to override number.format and are optional
separator: "."
delimiter: ","
precision: 2
# Used in number_to_percentage()
percentage:
format:
# These three are to override number.format and are optional
# separator:
delimiter: ""
# precision:
# Used in number_to_precision()
precision:
format:
# These three are to override number.format and are optional
# separator:
delimiter: ""
# precision:
# Used in number_to_human_size()
human:
format:
# These three are to override number.format and are optional
# separator:
delimiter: ""
precision: 1
# Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
datetime:
distance_in_words:
half_a_minute: "half a minute"
less_than_x_seconds:
one: "less than 1 second"
other: "less than {{count}} seconds"
x_seconds:
one: "1 second"
other: "{{count}} seconds"
less_than_x_minutes:
one: "less than a minute"
other: "less than {{count}} minutes"
x_minutes:
one: "1 minute"
other: "{{count}} minutes"
about_x_hours:
one: "about 1 hour"
other: "about {{count}} hours"
x_days:
one: "1 day"
other: "{{count}} days"
about_x_months:
one: "about 1 month"
other: "about {{count}} months"
x_months:
one: "1 month"
other: "{{count}} months"
about_x_years:
one: "about 1 year"
other: "about {{count}} years"
over_x_years:
one: "over 1 year"
other: "over {{count}} years"
activerecord:
errors:
template:
header:
one: "1 error prohibited this {{model}} from being saved"
other: "{{count}} errors prohibited this {{model}} from being saved"
# The variable :count is also available
body: "There were problems with the following fields:"

View file

@ -1,70 +0,0 @@
module ActionView #:nodoc:
class PartialTemplate < Template #:nodoc:
attr_reader :variable_name, :object
def initialize(view, partial_path, object = nil, locals = {})
@path, @variable_name = extract_partial_name_and_path(view, partial_path)
super(view, @path, true, locals)
add_object_to_local_assigns!(object)
# This is needed here in order to compile template with knowledge of 'counter'
initialize_counter
# Prepare early. This is a performance optimization for partial collections
prepare!
end
def render
ActionController::Base.benchmark("Rendered #{@path}", Logger::DEBUG, false) do
@handler.render(self)
end
end
def render_member(object)
@locals[:object] = @locals[@variable_name] = object
template = render_template
@locals[@counter_name] += 1
@locals.delete(@variable_name)
@locals.delete(:object)
template
end
def counter=(num)
@locals[@counter_name] = num
end
private
def add_object_to_local_assigns!(object)
@locals[:object] ||=
@locals[@variable_name] ||=
if object.is_a?(ActionView::Base::ObjectWrapper)
object.value
else
object
end || @view.controller.instance_variable_get("@#{variable_name}")
end
def extract_partial_name_and_path(view, partial_path)
path, partial_name = partial_pieces(view, partial_path)
[File.join(path, "_#{partial_name}"), partial_name.split('/').last.split('.').first.to_sym]
end
def partial_pieces(view, partial_path)
if partial_path.include?('/')
return File.dirname(partial_path), File.basename(partial_path)
else
return view.controller.class.controller_path, partial_path
end
end
def initialize_counter
@counter_name ||= "#{@variable_name}_counter".to_sym
@locals[@counter_name] = 0
end
end
end

View file

@ -181,7 +181,7 @@ module ActionView
ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path)
template = _pick_partial_template(_partial_path)
local_assigns[template.counter_name] = index
result = template.render_partial(self, object, local_assigns, as)
result = template.render_partial(self, object, local_assigns.dup, as)
index += 1
result
end.join(spacer)

View file

@ -25,20 +25,28 @@ module ActionView
def render(view, local_assigns = {})
compile(local_assigns)
view.send(:_first_render=, self) unless view.send(:_first_render)
view.send(:_last_render=, self)
stack = view.instance_variable_get(:@_render_stack)
stack.push(self)
# This is only used for TestResponse to set rendered_template
unless is_a?(InlineTemplate) || view.instance_variable_get(:@_first_render)
view.instance_variable_set(:@_first_render, self)
end
view.send(:_evaluate_assigns_and_ivars)
view.send(:_set_controller_content_type, mime_type) if respond_to?(:mime_type)
view.send(method_name(local_assigns), local_assigns) do |*names|
result = view.send(method_name(local_assigns), local_assigns) do |*names|
ivar = :@_proc_for_layout
if view.instance_variable_defined?(ivar) and proc = view.instance_variable_get(ivar)
if !view.instance_variable_defined?(:"@content_for_#{names.first}") && view.instance_variable_defined?(ivar) && (proc = view.instance_variable_get(ivar))
view.capture(*names, &proc)
elsif view.instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}")
view.instance_variable_get(ivar)
end
end
stack.pop
result
end
def method_name(local_assigns)

View file

@ -1,177 +0,0 @@
module ActionView #:nodoc:
class TemplateFinder #:nodoc:
class InvalidViewPath < StandardError #:nodoc:
attr_reader :unprocessed_path
def initialize(path)
@unprocessed_path = path
super("Unprocessed view path found: #{@unprocessed_path.inspect}. Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=.")
end
end
cattr_reader :processed_view_paths
@@processed_view_paths = Hash.new {|hash, key| hash[key] = []}
cattr_reader :file_extension_cache
@@file_extension_cache = Hash.new {|hash, key|
hash[key] = Hash.new {|hash, key| hash[key] = []}
}
class << self #:nodoc:
# This method is not thread safe. Mutex should be used whenever this is accessed from an instance method
def process_view_paths(*view_paths)
view_paths.flatten.compact.each do |dir|
next if @@processed_view_paths.has_key?(dir)
@@processed_view_paths[dir] = []
#
# Dir.glob("#{dir}/**/*/**") reads all the directories in view path and templates inside those directories
# Dir.glob("#{dir}/**") reads templates residing at top level of view path
#
(Dir.glob("#{dir}/**/*/**") | Dir.glob("#{dir}/**")).each do |file|
unless File.directory?(file)
@@processed_view_paths[dir] << file.split(dir).last.sub(/^\//, '')
# Build extension cache
extension = file.split(".").last
if template_handler_extensions.include?(extension)
key = file.split(dir).last.sub(/^\//, '').sub(/\.(\w+)$/, '')
@@file_extension_cache[dir][key] << extension
end
end
end
end
end
def update_extension_cache_for(extension)
@@processed_view_paths.keys.each do |dir|
Dir.glob("#{dir}/**/*.#{extension}").each do |file|
key = file.split(dir).last.sub(/^\//, '').sub(/\.(\w+)$/, '')
@@file_extension_cache[dir][key] << extension
end
end
end
def template_handler_extensions
ActionView::Template.template_handler_extensions
end
def reload!
view_paths = @@processed_view_paths.keys
@@processed_view_paths = Hash.new {|hash, key| hash[key] = []}
@@file_extension_cache = Hash.new {|hash, key|
hash[key] = Hash.new {|hash, key| hash[key] = []}
}
process_view_paths(view_paths)
end
end
attr_accessor :view_paths
def initialize(*args)
@template = args.shift
@view_paths = args.flatten
@view_paths = @view_paths.respond_to?(:find) ? @view_paths.dup : [*@view_paths].compact
check_view_paths(@view_paths)
end
def prepend_view_path(path)
@view_paths.unshift(*path)
self.class.process_view_paths(path)
end
def append_view_path(path)
@view_paths.push(*path)
self.class.process_view_paths(path)
end
def view_paths=(path)
@view_paths = path
self.class.process_view_paths(path)
end
def pick_template(template_path, extension)
file_name = "#{template_path}.#{extension}"
base_path = find_base_path_for(file_name)
base_path.blank? ? false : "#{base_path}/#{file_name}"
end
alias_method :template_exists?, :pick_template
def file_exists?(template_path)
# Clear the forward slash in the beginning if exists
template_path = template_path.sub(/^\//, '')
template_file_name, template_file_extension = path_and_extension(template_path)
if template_file_extension
template_exists?(template_file_name, template_file_extension)
else
template_exists?(template_file_name, pick_template_extension(template_path))
end
end
def find_base_path_for(template_file_name)
@view_paths.find { |path| @@processed_view_paths[path].include?(template_file_name) }
end
# Returns the view path that the full path resides in.
def extract_base_path_from(full_path)
@view_paths.find { |p| full_path[0..p.size - 1] == p }
end
# Gets the extension for an existing template with the given template_path.
# Returns the format with the extension if that template exists.
#
# pick_template_extension('users/show')
# # => 'html.erb'
#
# pick_template_extension('users/legacy')
# # => "rhtml"
#
def pick_template_extension(template_path)
if extension = find_template_extension_from_handler(template_path, @template.template_format) || find_template_extension_from_first_render
extension
elsif @template.template_format == :js && extension = find_template_extension_from_handler(template_path, :html)
@template.template_format = :html
extension
end
end
def find_template_extension_from_handler(template_path, template_format = @template.template_format)
formatted_template_path = "#{template_path}.#{template_format}"
view_paths.each do |path|
if (extensions = @@file_extension_cache[path][formatted_template_path]).any?
return "#{template_format}.#{extensions.first}"
elsif (extensions = @@file_extension_cache[path][template_path]).any?
return extensions.first.to_s
end
end
nil
end
# Splits the path and extension from the given template_path and returns as an array.
def path_and_extension(template_path)
template_path_without_extension = template_path.sub(/\.(\w+)$/, '')
[ template_path_without_extension, $1 ]
end
# Determine the template extension from the <tt>@first_render</tt> filename
def find_template_extension_from_first_render
File.basename(@template.first_render.to_s)[/^[^.]+\.(.+)$/, 1]
end
private
def check_view_paths(view_paths)
view_paths.each do |path|
raise InvalidViewPath.new(path) unless @@processed_view_paths.has_key?(path)
end
end
end
end

View file

@ -1,128 +0,0 @@
module ActionView
module TemplateHandlers
module Compilable
def self.included(base)
base.extend ClassMethod
# Map method names to their compile time
base.cattr_accessor :compile_time
base.compile_time = {}
# Map method names to the names passed in local assigns so far
base.cattr_accessor :template_args
base.template_args = {}
# Count the number of inline templates
base.cattr_accessor :inline_template_count
base.inline_template_count = 0
end
module ClassMethod
# If a handler is mixin this module, set compilable to true
def compilable?
true
end
end
def render(template)
@view.send :execute, template
end
# Compile and evaluate the template's code
def compile_template(template)
return unless compile_template?(template)
render_symbol = assign_method_name(template)
render_source = create_template_source(template, render_symbol)
line_offset = self.template_args[render_symbol].size + self.line_offset
begin
file_name = template.filename || 'compiled-template'
ActionView::Base::CompiledTemplates.module_eval(render_source, file_name, -line_offset)
rescue Exception => e # errors from template code
if @view.logger
@view.logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}"
@view.logger.debug "Function body: #{render_source}"
@view.logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
raise ActionView::TemplateError.new(template, @view.assigns, e)
end
self.compile_time[render_symbol] = Time.now
# logger.debug "Compiled template #{file_name || template}\n ==> #{render_symbol}" if logger
end
private
# Method to check whether template compilation is necessary.
# The template will be compiled if the inline template or file has not been compiled yet,
# if local_assigns has a new key, which isn't supported by the compiled code yet,
# or if the file has changed on disk and checking file mods hasn't been disabled.
def compile_template?(template)
method_key = template.method_key
render_symbol = @view.method_names[method_key]
compile_time = self.compile_time[render_symbol]
if compile_time && supports_local_assigns?(render_symbol, template.locals)
if template.filename && !@view.cache_template_loading
template_changed_since?(template.filename, compile_time)
end
else
true
end
end
def assign_method_name(template)
@view.method_names[template.method_key] ||= compiled_method_name(template)
end
def compiled_method_name(template)
['_run', self.class.to_s.demodulize.underscore, compiled_method_name_file_path_segment(template.filename)].compact.join('_').to_sym
end
def compiled_method_name_file_path_segment(file_name)
if file_name
s = File.expand_path(file_name)
s.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}/, '') if defined?(RAILS_ROOT)
s.gsub!(/([^a-zA-Z0-9_])/) { $1.ord }
s
else
(self.inline_template_count += 1).to_s
end
end
# Method to create the source code for a given template.
def create_template_source(template, render_symbol)
body = compile(template)
self.template_args[render_symbol] ||= {}
locals_keys = self.template_args[render_symbol].keys | template.locals.keys
self.template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h }
locals_code = ""
locals_keys.each do |key|
locals_code << "#{key} = local_assigns[:#{key}]\n"
end
"def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend"
end
# Return true if the given template was compiled for a superset of the keys in local_assigns
def supports_local_assigns?(render_symbol, local_assigns)
local_assigns.empty? ||
((args = self.template_args[render_symbol]) && local_assigns.all? { |k,_| args.has_key?(k) })
end
# Method to handle checking a whether a template has changed since last compile; isolated so that templates
# not stored on the file system can hook and extend appropriately.
def template_changed_since?(file_name, compile_time)
lstat = File.lstat(file_name)
compile_time < lstat.mtime ||
(lstat.symlink? && compile_time < File.stat(file_name).mtime)
end
end
end
end

View file

@ -291,12 +291,14 @@ class ActionCacheTest < Test::Unit::TestCase
ActionController::Base.use_accept_header = old_use_accept_header
end
uses_mocha 'test action cache' do
def test_action_cache_with_store_options
MockTime.expects(:now).returns(12345).once
@controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
@controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once
get :index
end
end
def test_action_cache_with_custom_cache_path
get :show

3
vendor/rails/actionpack/test/controller/cgi_test.rb vendored Executable file → Normal file
View file

@ -48,7 +48,8 @@ class BaseCgiTest < Test::Unit::TestCase
# some developers have grown accustomed to using comma in cookie values.
@alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"}
@cgi = CGI.new
@cgi.stubs(:env_table).returns(@request_hash)
class << @cgi; attr_accessor :env_table end
@cgi.env_table = @request_hash
@request = ActionController::CgiRequest.new(@cgi)
end

View file

@ -1,45 +0,0 @@
require 'abstract_unit'
class CustomHandler < ActionView::TemplateHandler
def initialize( view )
@view = view
end
def render( template )
[ template.source,
template.locals,
@view ]
end
end
class CustomHandlerTest < Test::Unit::TestCase
def setup
ActionView::Template.register_template_handler "foo", CustomHandler
ActionView::Template.register_template_handler :foo2, CustomHandler
@view = ActionView::Base.new
end
def test_custom_render
template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "foo")
result = @view.render_template(template)
assert_equal(
[ "hello <%= one %>", { :one => "two" }, @view ],
result )
end
def test_custom_render2
template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "foo2")
result = @view.render_template(template)
assert_equal(
[ "hello <%= one %>", { :one => "two" }, @view ],
result )
end
def test_unhandled_extension
# uses the ERb handler by default if the extension isn't recognized
template = ActionView::InlineTemplate.new(@view, "hello <%= one %>", { :one => "two" }, "bar")
result = @view.render_template(template)
assert_equal "hello two", result
end
end

View file

@ -253,6 +253,10 @@ class SanitizerTest < Test::Unit::TestCase
assert_sanitized "<![CDATA[<span>neverending...", "&lt;![CDATA[&lt;span>neverending...]]>"
end
def test_should_not_mangle_urls_with_ampersand
assert_sanitized %{<a href=\"http://www.domain.com?var1=1&amp;var2=2\">my link</a>}
end
protected
def assert_sanitized(input, expected = nil)
@sanitizer ||= HTML::WhiteListSanitizer.new

View file

@ -61,7 +61,9 @@ class MimeTypeTest < Test::Unit::TestCase
types.each do |type|
mime = Mime.const_get(type.to_s.upcase)
assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
(types - [type]).each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
invalid_types = types - [type]
invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
end
end
@ -71,14 +73,12 @@ class MimeTypeTest < Test::Unit::TestCase
end
def test_verifiable_mime_types
unverified_types = Mime::Type.unverifiable_types
all_types = Mime::SET.to_a.map(&:to_sym)
all_types.uniq!
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
unverified, verified = all_types.partition { |type| Mime::Type.unverifiable_types.include? type }
assert verified.all? { |type| Mime.const_get(type.to_s.upcase).verify_request? }, "Not all Mime Types are verified: #{verified.inspect}"
assert unverified.all? { |type| !Mime.const_get(type.to_s.upcase).verify_request? }, "Some Mime Types are verified: #{unverified.inspect}"
verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type }
assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
end

View file

@ -1,945 +0,0 @@
require 'abstract_unit'
require 'controller/fake_models'
class CustomersController < ActionController::Base
end
module Fun
class GamesController < ActionController::Base
def hello_world
end
end
end
module NewRenderTestHelper
def rjs_helper_method_from_module
page.visual_effect :highlight
end
end
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
end
class NewRenderTestController < ActionController::Base
layout :determine_layout
def self.controller_name; "test"; end
def self.controller_path; "test"; end
def hello_world
end
def render_hello_world
render :template => "test/hello_world"
end
def render_hello_world_from_variable
@person = "david"
render :text => "hello #{@person}"
end
def render_action_hello_world
render :action => "hello_world"
end
def render_action_hello_world_as_symbol
render :action => :hello_world
end
def render_text_hello_world
render :text => "hello world"
end
def render_text_hello_world_with_layout
@variable_for_layout = ", I'm here!"
render :text => "hello world", :layout => true
end
def hello_world_with_layout_false
render :layout => false
end
def render_custom_code
render :text => "hello world", :status => "404 Moved"
end
def render_file_with_instance_variables
@secret = 'in the sauce'
path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')
render :file => path
end
def render_file_from_template
@secret = 'in the sauce'
@path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb'))
end
def render_file_with_locals
path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')
render :file => path, :locals => {:secret => 'in the sauce'}
end
def render_file_not_using_full_path
@secret = 'in the sauce'
render :file => 'test/render_file_with_ivar', :use_full_path => true
end
def render_file_not_using_full_path_with_dot_in_path
@secret = 'in the sauce'
render :file => 'test/dot.directory/render_file_with_ivar', :use_full_path => true
end
def render_xml_hello
@name = "David"
render :template => "test/hello"
end
def greeting
# let's just rely on the template
end
def layout_test
render :action => "hello_world"
end
def layout_test_with_different_layout
render :action => "hello_world", :layout => "standard"
end
def rendering_without_layout
render :action => "hello_world", :layout => false
end
def layout_overriding_layout
render :action => "hello_world", :layout => "standard"
end
def rendering_nothing_on_layout
render :nothing => true
end
def builder_layout_test
render :action => "hello"
end
def partials_list
@test_unchanged = 'hello'
@customers = [ Customer.new("david"), Customer.new("mary") ]
render :action => "list"
end
def partial_only
render :partial => true
end
def partial_only_with_layout
render :partial => "partial_only", :layout => true
end
def partial_with_locals
render :partial => "customer", :locals => { :customer => Customer.new("david") }
end
def partial_with_form_builder
render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, @template, {}, Proc.new {})
end
def partial_with_form_builder_subclass
render :partial => LabellingFormBuilder.new(:post, nil, @template, {}, Proc.new {})
end
def partial_collection
render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_spacer
render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_counter
render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ]
end
def partial_collection_with_locals
render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" }
end
def partial_collection_shorthand_with_locals
render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" }
end
def partial_collection_shorthand_with_different_types_of_records
render :partial => [
BadCustomer.new("mark"),
GoodCustomer.new("craig"),
BadCustomer.new("john"),
GoodCustomer.new("zach"),
GoodCustomer.new("brandon"),
BadCustomer.new("dan") ],
:locals => { :greeting => "Bonjour" }
end
def partial_collection_shorthand_with_different_types_of_records_with_counter
partial_collection_shorthand_with_different_types_of_records
end
def empty_partial_collection
render :partial => "customer", :collection => []
end
def partial_with_hash_object
render :partial => "hash_object", :object => {:first_name => "Sam"}
end
def partial_hash_collection
render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ]
end
def partial_hash_collection_with_locals
render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" }
end
def partial_with_implicit_local_assignment
@customer = Customer.new("Marcel")
render :partial => "customer"
end
def missing_partial
render :partial => 'thisFileIsntHere'
end
def hello_in_a_string
@customers = [ Customer.new("david"), Customer.new("mary") ]
render :text => "How's there? " << render_to_string(:template => "test/list")
end
def render_to_string_with_assigns
@before = "i'm before the render"
render_to_string :text => "foo"
@after = "i'm after the render"
render :action => "test/hello_world"
end
def render_to_string_with_partial
@partial_only = render_to_string :partial => "partial_only"
@partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") }
render :action => "test/hello_world"
end
def render_to_string_with_exception
render_to_string :file => "exception that will not be caught - this will certainly not work", :use_full_path => true
end
def render_to_string_with_caught_exception
@before = "i'm before the render"
begin
render_to_string :file => "exception that will be caught- hope my future instance vars still work!", :use_full_path => true
rescue
end
@after = "i'm after the render"
render :action => "test/hello_world"
end
def accessing_params_in_template
render :inline => "Hello: <%= params[:name] %>"
end
def accessing_request_in_template
render :inline => "Hello: <%= request.host %>"
end
def accessing_logger_in_template
render :inline => "<%= logger.class %>"
end
def accessing_action_name_in_template
render :inline => "<%= action_name %>"
end
def accessing_params_in_template_with_layout
render :layout => nil, :inline => "Hello: <%= params[:name] %>"
end
def render_with_explicit_template
render :template => "test/hello_world"
end
def render_with_explicit_template_with_locals
render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' }
end
def double_render
render :text => "hello"
render :text => "world"
end
def double_redirect
redirect_to :action => "double_render"
redirect_to :action => "double_render"
end
def render_and_redirect
render :text => "hello"
redirect_to :action => "double_render"
end
def render_to_string_and_render
@stuff = render_to_string :text => "here is some cached stuff"
render :text => "Hi web users! #{@stuff}"
end
def rendering_with_conflicting_local_vars
@name = "David"
def @template.name() nil end
render :action => "potential_conflicts"
end
def hello_world_from_rxml_using_action
render :action => "hello_world_from_rxml.builder"
end
def hello_world_from_rxml_using_template
render :template => "test/hello_world_from_rxml.builder"
end
def head_with_location_header
head :location => "/foo"
end
def head_with_symbolic_status
head :status => params[:status].intern
end
def head_with_integer_status
head :status => params[:status].to_i
end
def head_with_string_status
head :status => params[:status]
end
def head_with_custom_header
head :x_custom_header => "something"
end
def head_with_status_code_first
head :forbidden, :x_custom_header => "something"
end
def render_with_location
render :xml => "<hello/>", :location => "http://example.com", :status => 201
end
def render_with_object_location
customer = Customer.new("Some guy", 1)
render :xml => "<customer/>", :location => customer_url(customer), :status => :created
end
def render_with_to_xml
to_xmlable = Class.new do
def to_xml
"<i-am-xml/>"
end
end.new
render :xml => to_xmlable
end
helper NewRenderTestHelper
helper do
def rjs_helper_method(value)
page.visual_effect :highlight, value
end
end
def enum_rjs_test
render :update do |page|
page.select('.product').each do |value|
page.rjs_helper_method_from_module
page.rjs_helper_method(value)
page.sortable(value, :url => { :action => "order" })
page.draggable(value)
end
end
end
def delete_with_js
@project_id = 4
end
def render_js_with_explicit_template
@project_id = 4
render :template => 'test/delete_with_js'
end
def render_js_with_explicit_action_template
@project_id = 4
render :action => 'delete_with_js'
end
def update_page
render :update do |page|
page.replace_html 'balance', '$37,000,000.00'
page.visual_effect :highlight, 'balance'
end
end
def update_page_with_instance_variables
@money = '$37,000,000.00'
@div_id = 'balance'
render :update do |page|
page.replace_html @div_id, @money
page.visual_effect :highlight, @div_id
end
end
def action_talk_to_layout
# Action template sets variable that's picked up by layout
end
def render_text_with_assigns
@hello = "world"
render :text => "foo"
end
def yield_content_for
render :action => "content_for", :layout => "yield"
end
def render_content_type_from_body
response.content_type = Mime::RSS
render :text => "hello world!"
end
def render_call_to_partial_with_layout
render :action => "calling_partial_with_layout"
end
def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
render :action => "calling_partial_with_layout"
end
def render_using_layout_around_block
render :action => "using_layout_around_block"
end
def render_using_layout_around_block_in_main_layout_and_within_content_for_layout
render :action => "using_layout_around_block"
end
def rescue_action(e) raise end
private
def determine_layout
case action_name
when "hello_world", "layout_test", "rendering_without_layout",
"rendering_nothing_on_layout", "render_text_hello_world",
"render_text_hello_world_with_layout",
"hello_world_with_layout_false",
"partial_only", "partial_only_with_layout",
"accessing_params_in_template",
"accessing_params_in_template_with_layout",
"render_with_explicit_template",
"render_js_with_explicit_template",
"render_js_with_explicit_action_template",
"delete_with_js", "update_page", "update_page_with_instance_variables"
"layouts/standard"
when "builder_layout_test"
"layouts/builder"
when "action_talk_to_layout", "layout_overriding_layout"
"layouts/talk_from_action"
when "render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout"
"layouts/partial_with_layout"
when "render_using_layout_around_block_in_main_layout_and_within_content_for_layout"
"layouts/block_with_layout"
end
end
end
NewRenderTestController.view_paths = [ File.dirname(__FILE__) + "/../fixtures/" ]
Fun::GamesController.view_paths = [ File.dirname(__FILE__) + "/../fixtures/" ]
class NewRenderTest < Test::Unit::TestCase
def setup
@controller = NewRenderTestController.new
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
@controller.logger = Logger.new(nil)
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.host = "www.nextangle.com"
end
def test_simple_show
get :hello_world
assert_response :success
assert_template "test/hello_world"
assert_equal "<html>Hello world!</html>", @response.body
end
def test_do_with_render
get :render_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_from_variable
get :render_hello_world_from_variable
assert_equal "hello david", @response.body
end
def test_do_with_render_action
get :render_action_hello_world
assert_template "test/hello_world"
end
def test_do_with_render_action_as_symbol
get :render_action_hello_world_as_symbol
assert_template "test/hello_world"
end
def test_do_with_render_text
get :render_text_hello_world
assert_equal "hello world", @response.body
end
def test_do_with_render_text_and_layout
get :render_text_hello_world_with_layout
assert_equal "<html>hello world, I'm here!</html>", @response.body
end
def test_do_with_render_action_and_layout_false
get :hello_world_with_layout_false
assert_equal 'Hello world!', @response.body
end
def test_do_with_render_custom_code
get :render_custom_code
assert_response :missing
end
def test_render_file_with_instance_variables
get :render_file_with_instance_variables
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_not_using_full_path
get :render_file_not_using_full_path
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_not_using_full_path_with_dot_in_path
get :render_file_not_using_full_path_with_dot_in_path
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_with_locals
get :render_file_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
def test_render_file_from_template
get :render_file_from_template
assert_equal "The secret is in the sauce\n", @response.body
end
def test_attempt_to_access_object_method
assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
end
def test_private_methods
assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout }
end
def test_access_to_request_in_view
get :accessing_request_in_template
assert_equal "Hello: www.nextangle.com", @response.body
end
def test_access_to_logger_in_view
get :accessing_logger_in_template
assert_equal "Logger", @response.body
end
def test_access_to_action_name_in_view
get :accessing_action_name_in_template
assert_equal "accessing_action_name_in_template", @response.body
end
def test_render_xml
get :render_xml_hello
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
end
def test_enum_rjs_test
get :enum_rjs_test
assert_equal <<-EOS.strip, @response.body
$$(".product").each(function(value, index) {
new Effect.Highlight(element,{});
new Effect.Highlight(value,{});
Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}});
new Draggable(value, {});
});
EOS
end
def test_render_xml_with_default
get :greeting
assert_equal "<p>This is grand!</p>\n", @response.body
end
def test_render_with_default_from_accept_header
@request.env["HTTP_ACCEPT"] = "text/javascript"
get :greeting
assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body
end
def test_render_rjs_with_default
get :delete_with_js
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_render_rjs_template_explicitly
get :render_js_with_explicit_template
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_rendering_rjs_action_explicitly
get :render_js_with_explicit_action_template
assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
end
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
end
def test_layout_test_with_different_layout
get :layout_test_with_different_layout
assert_equal "<html>Hello world!</html>", @response.body
end
def test_rendering_without_layout
get :rendering_without_layout
assert_equal "Hello world!", @response.body
end
def test_layout_overriding_layout
get :layout_overriding_layout
assert_no_match %r{<title>}, @response.body
end
def test_rendering_nothing_on_layout
get :rendering_nothing_on_layout
assert_equal " ", @response.body
end
def test_render_xml_with_layouts
get :builder_layout_test
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
end
def test_partial_only
get :partial_only
assert_equal "only partial", @response.body
end
def test_partial_only_with_layout
get :partial_only_with_layout
assert_equal "<html>only partial</html>", @response.body
end
def test_render_to_string
assert_not_deprecated { get :hello_in_a_string }
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_render_to_string_doesnt_break_assigns
get :render_to_string_with_assigns
assert_equal "i'm before the render", assigns(:before)
assert_equal "i'm after the render", assigns(:after)
end
def test_render_to_string_partial
get :render_to_string_with_partial
assert_equal "only partial", assigns(:partial_only)
assert_equal "Hello: david", assigns(:partial_with_locals)
end
def test_bad_render_to_string_still_throws_exception
assert_raises(ActionView::MissingTemplate) { get :render_to_string_with_exception }
end
def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns
assert_nothing_raised { get :render_to_string_with_caught_exception }
assert_equal "i'm before the render", assigns(:before)
assert_equal "i'm after the render", assigns(:after)
end
def test_nested_rendering
get :hello_world
assert_equal "Living in a nested world", Fun::GamesController.process(@request, @response).body
end
def test_accessing_params_in_template
get :accessing_params_in_template, :name => "David"
assert_equal "Hello: David", @response.body
end
def test_accessing_params_in_template_with_layout
get :accessing_params_in_template_with_layout, :name => "David"
assert_equal "<html>Hello: David</html>", @response.body
end
def test_render_with_explicit_template
get :render_with_explicit_template
assert_response :success
end
def test_double_render
assert_raises(ActionController::DoubleRenderError) { get :double_render }
end
def test_double_redirect
assert_raises(ActionController::DoubleRenderError) { get :double_redirect }
end
def test_render_and_redirect
assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect }
end
# specify the one exception to double render rule - render_to_string followed by render
def test_render_to_string_and_render
get :render_to_string_and_render
assert_equal("Hi web users! here is some cached stuff", @response.body)
end
def test_rendering_with_conflicting_local_vars
get :rendering_with_conflicting_local_vars
assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body)
end
def test_action_talk_to_layout
get :action_talk_to_layout
assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body
end
def test_partials_list
get :partials_list
assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body
end
def test_partial_with_locals
get :partial_with_locals
assert_equal "Hello: david", @response.body
end
def test_partial_with_form_builder
get :partial_with_form_builder
assert_match(/<label/, @response.body)
assert_template('test/_form')
end
def test_partial_with_form_builder_subclass
get :partial_with_form_builder_subclass
assert_match(/<label/, @response.body)
assert_template('test/_labelling_form')
end
def test_partial_collection
get :partial_collection
assert_equal "Hello: davidHello: mary", @response.body
end
def test_partial_collection_with_counter
get :partial_collection_with_counter
assert_equal "david0mary1", @response.body
end
def test_partial_collection_with_locals
get :partial_collection_with_locals
assert_equal "Bonjour: davidBonjour: mary", @response.body
end
def test_partial_collection_with_spacer
get :partial_collection_with_spacer
assert_equal "Hello: davidonly partialHello: mary", @response.body
end
def test_partial_collection_shorthand_with_locals
get :partial_collection_shorthand_with_locals
assert_equal "Bonjour: davidBonjour: mary", @response.body
end
def test_partial_collection_shorthand_with_different_types_of_records
get :partial_collection_shorthand_with_different_types_of_records
assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body
end
def test_empty_partial_collection
get :empty_partial_collection
assert_equal " ", @response.body
end
def test_partial_with_hash_object
get :partial_with_hash_object
assert_equal "Sam\nmaS\n", @response.body
end
def test_hash_partial_collection
get :partial_hash_collection
assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body
end
def test_partial_hash_collection_with_locals
get :partial_hash_collection_with_locals
assert_equal "Hola: PratikHola: Amy", @response.body
end
def test_partial_with_implicit_local_assignment
get :partial_with_implicit_local_assignment
assert_equal "Hello: Marcel", @response.body
end
def test_render_missing_partial_template
assert_raises(ActionView::MissingTemplate) do
get :missing_partial
end
end
def test_render_text_with_assigns
get :render_text_with_assigns
assert_equal "world", assigns["hello"]
end
def test_template_with_locals
get :render_with_explicit_template_with_locals
assert_equal "The secret is area51\n", @response.body
end
def test_update_page
get :update_page
assert_template nil
assert_equal 'text/javascript; charset=utf-8', @response.headers['type']
assert_equal 2, @response.body.split($/).length
end
def test_update_page_with_instance_variables
get :update_page_with_instance_variables
assert_template nil
assert_equal 'text/javascript; charset=utf-8', @response.headers['type']
assert_match /balance/, @response.body
assert_match /\$37/, @response.body
end
def test_yield_content_for
assert_not_deprecated { get :yield_content_for }
assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body
end
def test_overwritting_rendering_relative_file_with_extension
get :hello_world_from_rxml_using_template
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
get :hello_world_from_rxml_using_action
assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
end
def test_head_with_location_header
get :head_with_location_header
assert @response.body.blank?
assert_equal "/foo", @response.headers["Location"]
assert_response :ok
end
def test_head_with_custom_header
get :head_with_custom_header
assert @response.body.blank?
assert_equal "something", @response.headers["X-Custom-Header"]
assert_response :ok
end
def test_head_with_symbolic_status
get :head_with_symbolic_status, :status => "ok"
assert_equal "200 OK", @response.headers["Status"]
assert_response :ok
get :head_with_symbolic_status, :status => "not_found"
assert_equal "404 Not Found", @response.headers["Status"]
assert_response :not_found
ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code|
get :head_with_symbolic_status, :status => status.to_s
assert_equal code, @response.response_code
assert_response status
end
end
def test_head_with_integer_status
ActionController::StatusCodes::STATUS_CODES.each do |code, message|
get :head_with_integer_status, :status => code.to_s
assert_equal message, @response.message
end
end
def test_head_with_string_status
get :head_with_string_status, :status => "404 Eat Dirt"
assert_equal 404, @response.response_code
assert_equal "Eat Dirt", @response.message
assert_response :not_found
end
def test_head_with_status_code_first
get :head_with_status_code_first
assert_equal 403, @response.response_code
assert_equal "Forbidden", @response.message
assert_equal "something", @response.headers["X-Custom-Header"]
assert_response :forbidden
end
def test_rendering_with_location_should_set_header
get :render_with_location
assert_equal "http://example.com", @response.headers["Location"]
end
def test_rendering_xml_should_call_to_xml_if_possible
get :render_with_to_xml
assert_equal "<i-am-xml/>", @response.body
end
def test_rendering_with_object_location_should_set_header_with_url_for
ActionController::Routing::Routes.draw do |map|
map.resources :customers
map.connect ':controller/:action/:id'
end
get :render_with_object_location
assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
end
def test_render_call_to_partial_with_layout
get :render_call_to_partial_with_layout
assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body
end
def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body
end
def test_using_layout_around_block
get :render_using_layout_around_block
assert_equal "Before (David)\nInside from block\nAfter", @response.body
end
def test_using_layout_around_block_in_main_layout_and_within_content_for_layout
get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout
assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body
end
end

View file

@ -169,6 +169,23 @@ uses_mocha 'polymorphic URL helpers' do
polymorphic_url([@article, :response, @tag], :format => :pdf)
end
def test_nesting_with_array_containing_nil
expects(:article_response_url).with(@article)
polymorphic_url([@article, nil, :response])
end
def test_with_array_containing_single_object
@article.save
expects(:article_url).with(@article)
polymorphic_url([nil, @article])
end
def test_with_array_containing_single_name
@article.save
expects(:articles_url)
polymorphic_url([:articles])
end
# TODO: Needs to be updated to correctly know about whether the object is in a hash or not
def xtest_with_hash
expects(:article_url).with(@article)

10
vendor/rails/actionpack/test/controller/redirect_test.rb vendored Executable file → Normal file
View file

@ -73,6 +73,10 @@ class RedirectController < ActionController::Base
redirect_to "http://dev.rubyonrails.org/query?status=new"
end
def redirect_to_url_with_complex_scheme
redirect_to "x-test+scheme.complex:redirect"
end
def redirect_to_back
redirect_to :back
end
@ -198,6 +202,12 @@ class RedirectTest < Test::Unit::TestCase
assert_redirected_to "http://dev.rubyonrails.org/query?status=new"
end
def test_redirect_to_url_with_complex_scheme
get :redirect_to_url_with_complex_scheme
assert_response :redirect
assert_equal "x-test+scheme.complex:redirect", redirect_to_url
end
def test_redirect_to_back
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
get :redirect_to_back

View file

@ -154,6 +154,10 @@ class TestController < ActionController::Base
render :json => {:hello => 'world'}.to_json
end
def render_json_with_render_to_string
render :json => {:hello => render_to_string(:partial => 'partial')}
end
def render_custom_code
render :text => "hello world", :status => 404
end
@ -180,6 +184,10 @@ class TestController < ActionController::Base
render("test/hello")
end
def render_vanilla_js_hello
render :js => "alert('hello')"
end
def render_xml_hello
@name = "David"
render :template => "test/hello"
@ -238,6 +246,15 @@ class TestController < ActionController::Base
:locals => { :local_name => name }
end
def helper_method_to_render_to_string(*args)
render_to_string(*args)
end
helper_method :helper_method_to_render_to_string
def render_html_only_partial_within_inline
render :inline => "Hello world <%= helper_method_to_render_to_string :partial => 'test/partial_with_only_html_version' %>"
end
def formatted_html_erb
end
@ -329,6 +346,11 @@ class TestController < ActionController::Base
render :text => "Hi web users! #{@stuff}"
end
def render_to_string_with_inline_and_render
render_to_string :inline => "<%= 'dlrow olleh'.reverse %>"
render :template => "test/hello_world"
end
def rendering_with_conflicting_local_vars
@name = "David"
def @template.name() nil end
@ -772,6 +794,12 @@ class RenderTest < Test::Unit::TestCase
assert_equal 'application/json', @response.content_type
end
def test_render_json_with_render_to_string
get :render_json_with_render_to_string
assert_equal '{"hello": "partial html"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_render_custom_code
get :render_custom_code
assert_response 404
@ -834,8 +862,17 @@ class RenderTest < Test::Unit::TestCase
assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller.
end
def test_render_vanilla_js
get :render_vanilla_js_hello
assert_equal "alert('hello')", @response.body
assert_equal "text/javascript", @response.content_type
end
def test_render_xml
assert_deprecated do
get :render_xml_hello
end
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
assert_equal "application/xml", @response.content_type
end
@ -869,7 +906,10 @@ class RenderTest < Test::Unit::TestCase
end
def test_render_xml_with_layouts
assert_deprecated do
get :builder_layout_test
end
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
end
@ -888,6 +928,11 @@ class RenderTest < Test::Unit::TestCase
assert_equal "The value of foo is: ::this is a test::\n", @response.body
end
def test_render_to_string_inline
get :render_to_string_with_inline_and_render
assert_template "test/hello_world"
end
def test_nested_rendering
@controller = Fun::GamesController.new
get :hello_world
@ -904,6 +949,11 @@ class RenderTest < Test::Unit::TestCase
assert_equal "Goodbye, Local David", @response.body
end
def test_rendering_html_only_partial_within_inline_with_js
get :render_html_only_partial_within_inline, :format => :js
assert_equal "Hello world partial with only html version", @response.body
end
def test_should_render_formatted_template
get :formatted_html_erb
assert_equal 'formatted html erb', @response.body
@ -1383,7 +1433,10 @@ class EtagRenderTest < Test::Unit::TestCase
end
def test_etag_should_govern_renders_with_layouts_too
assert_deprecated do
get :builder_layout_test
end
assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
assert_equal etag_for("<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n"), @response.headers['ETag']
end

View file

@ -77,6 +77,7 @@ module RequestForgeryProtectionTests
ActionController::Base.request_forgery_protection_token = nil
end
def test_should_render_form_with_token_tag
get :index
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
@ -102,32 +103,35 @@ module RequestForgeryProtectionTests
assert_response :success
end
def test_should_not_allow_post_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { post :index }
def test_should_not_allow_html_post_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raises(ActionController::InvalidAuthenticityToken) { post :index, :format => :html }
end
def test_should_not_allow_put_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { put :index }
def test_should_not_allow_html_put_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raises(ActionController::InvalidAuthenticityToken) { put :index, :format => :html }
end
def test_should_not_allow_delete_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { delete :index }
def test_should_not_allow_html_delete_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raises(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html }
end
def test_should_not_allow_api_formatted_post_without_token
assert_raises(ActionController::InvalidAuthenticityToken) do
def test_should_allow_api_formatted_post_without_token
assert_nothing_raised do
post :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_put_without_token
assert_raises(ActionController::InvalidAuthenticityToken) do
assert_nothing_raised do
put :index, :format => 'xml'
end
end
def test_should_not_allow_api_formatted_delete_without_token
assert_raises(ActionController::InvalidAuthenticityToken) do
def test_should_allow_api_formatted_delete_without_token
assert_nothing_raised do
delete :index, :format => 'xml'
end
end
@ -174,16 +178,20 @@ module RequestForgeryProtectionTests
end
end
def test_should_not_allow_xhr_post_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { xhr :post, :index }
def test_should_allow_xhr_post_without_token
assert_nothing_raised { xhr :post, :index }
end
def test_should_not_allow_xhr_post_with_html_without_token
@request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
assert_raise(ActionController::InvalidAuthenticityToken) { xhr :post, :index }
end
def test_should_not_allow_xhr_put_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { xhr :put, :index }
def test_should_allow_xhr_put_without_token
assert_nothing_raised { xhr :put, :index }
end
def test_should_not_allow_xhr_delete_without_token
assert_raises(ActionController::InvalidAuthenticityToken) { xhr :delete, :index }
def test_should_allow_xhr_delete_without_token
assert_nothing_raised { xhr :delete, :index }
end
def test_should_allow_post_with_token
@ -227,6 +235,7 @@ class RequestForgeryProtectionControllerTest < Test::Unit::TestCase
def setup
@controller = RequestForgeryProtectionController.new
@request = ActionController::TestRequest.new
@request.format = :html
@response = ActionController::TestResponse.new
class << @request.session
def session_id() '123' end
@ -248,11 +257,11 @@ class RequestForgeryProtectionWithoutSecretControllerTest < Test::Unit::TestCase
ActionController::Base.request_forgery_protection_token = :authenticity_token
end
def test_should_raise_error_without_secret
assert_raises ActionController::InvalidAuthenticityToken do
get :index
end
end
# def test_should_raise_error_without_secret
# assert_raises ActionController::InvalidAuthenticityToken do
# get :index
# end
# end
end
class CsrfCookieMonsterControllerTest < Test::Unit::TestCase
@ -304,10 +313,15 @@ class SessionOffControllerTest < Test::Unit::TestCase
@token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123')
end
def test_should_raise_correct_exception
@request.session = {} # session(:off) doesn't appear to work with controller tests
assert_raises(ActionController::InvalidAuthenticityToken) do
post :index, :authenticity_token => @token
end
end
# TODO: Rewrite this test.
# This test was passing but for the wrong reason.
# Sessions aren't really being turned off, so an exception was raised
# because sessions weren't on - not because the token didn't match.
#
# def test_should_raise_correct_exception
# @request.session = {} # session(:off) doesn't appear to work with controller tests
# assert_raises(ActionController::InvalidAuthenticityToken) do
# post :index, :authenticity_token => @token, :format => :html
# end
# end
end

View file

@ -735,11 +735,7 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
file = params['file']
foo = params['foo']
if RUBY_VERSION > '1.9'
assert_kind_of File, file
else
assert_kind_of Tempfile, file
end
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
@ -753,11 +749,9 @@ class MultipartRequestParameterParsingTest < Test::Unit::TestCase
assert_equal 'bar', params['foo']
file = params['file']
if RUBY_VERSION > '1.9'
assert_kind_of File, file
else
assert_kind_of Tempfile, file
end
assert_equal 'file.txt', file.original_filename
assert_equal "text/plain", file.content_type
assert ('a' * 20480) == file.read

View file

@ -14,6 +14,8 @@ class LogosController < ResourcesController; end
class AccountsController < ResourcesController; end
class AdminController < ResourcesController; end
class ProductsController < ResourcesController; end
class ImagesController < ResourcesController; end
module Backoffice
class ProductsController < ResourcesController; end
@ -776,6 +778,225 @@ class ResourcesTest < Test::Unit::TestCase
end
end
def test_resource_has_only_show_action
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :show
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
end
end
def test_singleton_resource_has_only_show_action
with_routing do |set|
set.draw do |map|
map.resource :account, :only => :show
end
assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy])
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :show, [:index, :new, :create, :edit, :update, :destroy])
end
end
def test_resource_does_not_have_destroy_action
with_routing do |set|
set.draw do |map|
map.resources :products, :except => :destroy
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
end
end
def test_singleton_resource_does_not_have_destroy_action
with_routing do |set|
set.draw do |map|
map.resource :account, :except => :destroy
end
assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy)
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [:new, :create, :show, :edit, :update], :destroy)
end
end
def test_resource_has_only_create_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :create
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
assert_not_nil set.named_routes[:products]
end
end
def test_resource_has_only_update_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :update
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
assert_not_nil set.named_routes[:product]
end
end
def test_resource_has_only_destroy_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :destroy
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
assert_not_nil set.named_routes[:product]
end
end
def test_singleton_resource_has_only_create_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resource :account, :only => :create
end
assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy])
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :create, [:new, :show, :edit, :update, :destroy])
assert_not_nil set.named_routes[:account]
end
end
def test_singleton_resource_has_only_update_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resource :account, :only => :update
end
assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy])
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :update, [:new, :create, :show, :edit, :destroy])
assert_not_nil set.named_routes[:account]
end
end
def test_singleton_resource_has_only_destroy_action_and_named_route
with_routing do |set|
set.draw do |map|
map.resource :account, :only => :destroy
end
assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update])
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :destroy, [:new, :create, :show, :edit, :update])
assert_not_nil set.named_routes[:account]
end
end
def test_resource_has_only_collection_action
with_routing do |set|
set.draw do |map|
map.resources :products, :except => :all, :collection => { :sale => :get }
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
assert_recognizes({ :controller => 'products', :action => 'sale' }, :path => 'products/sale', :method => :get)
assert_recognizes({ :controller => 'products', :action => 'sale', :format => 'xml' }, :path => 'products/sale.xml', :method => :get)
end
end
def test_resource_has_only_member_action
with_routing do |set|
set.draw do |map|
map.resources :products, :except => :all, :member => { :preview => :get }
end
assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1' }, :path => 'products/1/preview', :method => :get)
assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1', :format => 'xml' }, :path => 'products/1/preview.xml', :method => :get)
end
end
def test_singleton_resource_has_only_member_action
with_routing do |set|
set.draw do |map|
map.resource :account, :except => :all, :member => { :signup => :get }
end
assert_singleton_resource_allowed_routes('accounts', {}, [], [:new, :create, :show, :edit, :update, :destroy])
assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [], [:new, :create, :show, :edit, :update, :destroy])
assert_recognizes({ :controller => 'accounts', :action => 'signup' }, :path => 'account/signup', :method => :get)
assert_recognizes({ :controller => 'accounts', :action => 'signup', :format => 'xml' }, :path => 'account/signup.xml', :method => :get)
end
end
def test_nested_resource_inherits_only_show_action
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :show do |product|
product.resources :images
end
end
assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
end
end
def test_nested_resource_has_only_show_and_member_action
with_routing do |set|
set.draw do |map|
map.resources :products, :only => [:index, :show] do |product|
product.resources :images, :member => { :thumbnail => :get }, :only => :show
end
end
assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2' }, :path => 'products/1/images/2/thumbnail', :method => :get)
assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2', :format => 'jpg' }, :path => 'products/1/images/2/thumbnail.jpg', :method => :get)
end
end
def test_nested_resource_ignores_only_option
with_routing do |set|
set.draw do |map|
map.resources :products, :only => :show do |product|
product.resources :images, :except => :destroy
end
end
assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
end
end
def test_nested_resource_ignores_except_option
with_routing do |set|
set.draw do |map|
map.resources :products, :except => :show do |product|
product.resources :images, :only => :destroy
end
end
assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
end
end
protected
def with_restful_routing(*args)
with_routing do |set|
@ -979,6 +1200,51 @@ class ResourcesTest < Test::Unit::TestCase
end
end
def assert_resource_allowed_routes(controller, options, shallow_options, allowed, not_allowed, path = controller)
shallow_path = "#{path}/#{shallow_options[:id]}"
format = options[:format] && ".#{options[:format]}"
options.merge!(:controller => controller)
shallow_options.merge!(options)
assert_whether_allowed(allowed, not_allowed, options, 'index', "#{path}#{format}", :get)
assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
assert_whether_allowed(allowed, not_allowed, shallow_options, 'show', "#{shallow_path}#{format}", :get)
assert_whether_allowed(allowed, not_allowed, shallow_options, 'edit', "#{shallow_path}/edit#{format}", :get)
assert_whether_allowed(allowed, not_allowed, shallow_options, 'update', "#{shallow_path}#{format}", :put)
assert_whether_allowed(allowed, not_allowed, shallow_options, 'destroy', "#{shallow_path}#{format}", :delete)
end
def assert_singleton_resource_allowed_routes(controller, options, allowed, not_allowed, path = controller.singularize)
format = options[:format] && ".#{options[:format]}"
options.merge!(:controller => controller)
assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
assert_whether_allowed(allowed, not_allowed, options, 'show', "#{path}#{format}", :get)
assert_whether_allowed(allowed, not_allowed, options, 'edit', "#{path}/edit#{format}", :get)
assert_whether_allowed(allowed, not_allowed, options, 'update', "#{path}#{format}", :put)
assert_whether_allowed(allowed, not_allowed, options, 'destroy', "#{path}#{format}", :delete)
end
def assert_whether_allowed(allowed, not_allowed, options, action, path, method)
action = action.to_sym
options = options.merge(:action => action.to_s)
path_options = { :path => path, :method => method }
if Array(allowed).include?(action)
assert_recognizes options, path_options
elsif Array(not_allowed).include?(action)
assert_not_recognizes options, path_options
end
end
def assert_not_recognizes(expected_options, path)
assert_raise ActionController::RoutingError, ActionController::MethodNotAllowed, Test::Unit::AssertionFailedError do
assert_recognizes(expected_options, path)
end
end
def distinct_routes? (r1, r2)
if r1.conditions == r2.conditions and r1.requirements == r2.requirements then
if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then

View file

@ -706,12 +706,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
port = options.delete(:port) || 80
port_string = port == 80 ? '' : ":#{port}"
protocol = options.delete(:protocol) || "http"
host = options.delete(:host) || "named.route.test"
anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
path = routes.generate(options)
only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}"
only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
end
def request
@ -1726,6 +1727,11 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
end
def test_named_route_url_method_with_protocol
controller = setup_named_route_test
assert_equal "https://named.route.test/people/5", controller.send(:show_url, 5, :protocol => "https")
end
def test_named_route_url_method_with_ordered_parameters
controller = setup_named_route_test
assert_equal "http://named.route.test/people/go/7/hello/joe/5",

View file

@ -266,6 +266,7 @@ class CookieStoreTest < Test::Unit::TestCase
@options = self.class.default_session_options.merge(options)
session = CGI::Session.new(cgi, @options)
ObjectSpace.undefine_finalizer(session)
assert_nil cgi.output_hidden, "Output hidden params should be empty: #{cgi.output_hidden.inspect}"
assert_nil cgi.output_cookies, "Output cookies should be empty: #{cgi.output_cookies.inspect}"

View file

@ -606,7 +606,7 @@ class CleanBacktraceTest < Test::Unit::TestCase
def test_should_reraise_the_same_object
exception = Test::Unit::AssertionFailedError.new('message')
clean_backtrace { raise exception }
rescue => caught
rescue Exception => caught
assert_equal exception.object_id, caught.object_id
assert_equal exception.message, caught.message
end
@ -616,7 +616,7 @@ class CleanBacktraceTest < Test::Unit::TestCase
exception = Test::Unit::AssertionFailedError.new('message')
exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
clean_backtrace { raise exception }
rescue => caught
rescue Exception => caught
assert_equal ["#{path}/abc"], caught.backtrace
end

View file

@ -1 +1 @@
Hello: <%= customer.name %>
Hello: <%= customer.name rescue "Anonymous" %>

View file

@ -1,2 +0,0 @@
<% block_content_for :title do 'Putting stuff in the title!' end %>
Great stuff!

View file

@ -1,2 +0,0 @@
<% erb_content_for :title do %>Putting stuff in the title!<% end %>
Great stuff!

View file

@ -10,37 +10,37 @@ class ActiveRecordHelperI18nTest < Test::Unit::TestCase
@object_name = 'book'
stubs(:content_tag).returns 'content_tag'
I18n.stubs(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
I18n.stubs(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved"
I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
end
def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message
I18n.expects(:translate).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en-US')
I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never
error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en')
end
def test_error_messages_for_given_no_header_option_it_translates_header_message
I18n.expects(:t).with(:'header', :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
error_messages_for(:object => @object, :locale => 'en-US')
error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_a_message_option_it_does_not_translate_message
I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).never
I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
error_messages_for(:object => @object, :message => 'message', :locale => 'en-US')
error_messages_for(:object => @object, :message => 'message', :locale => 'en')
end
def test_error_messages_for_given_no_message_option_it_translates_message
I18n.expects(:t).with(:'body', :locale => 'en-US', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:'
I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns ''
error_messages_for(:object => @object, :locale => 'en-US')
error_messages_for(:object => @object, :locale => 'en')
end
def test_error_messages_for_given_object_name_it_translates_object_name
I18n.expects(:t).with(:header, :locale => 'en-US', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved"
I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name
error_messages_for(:object => @object, :locale => 'en-US', :object_name => @object_name)
error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name)
end
end
end

View file

@ -239,7 +239,11 @@ class AssetTagHelperTest < ActionView::TestCase
File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true)
assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png')
ensure
if old_asset_id
ENV["RAILS_ASSET_ID"] = old_asset_id
else
ENV.delete("RAILS_ASSET_ID")
end
end
end
@ -248,6 +252,14 @@ class AssetTagHelperTest < ActionView::TestCase
assert_equal %(<img alt="Rails" src="/images/rails.png?#{expected_time}" />), image_tag("rails.png")
end
def test_timebased_asset_id_with_relative_url_root
ActionController::Base.relative_url_root = "/collaboration/hieraki"
expected_time = File.stat(File.expand_path(File.dirname(__FILE__) + "/../fixtures/public/images/rails.png")).mtime.to_i.to_s
assert_equal %(<img alt="Rails" src="#{ActionController::Base.relative_url_root}/images/rails.png?#{expected_time}" />), image_tag("rails.png")
ensure
ActionController::Base.relative_url_root = ""
end
def test_should_skip_asset_id_on_complete_url
assert_equal %(<img alt="Rails" src="http://www.example.com/rails.png" />), image_tag("http://www.example.com/rails.png")
end
@ -636,4 +648,10 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
ensure
ActionController::Base.asset_host = nil
end
def test_assert_css_and_js_of_the_same_name_return_correct_extension
assert_dom_equal(%(/collaboration/hieraki/javascripts/foo.js), javascript_path("foo"))
assert_dom_equal(%(/collaboration/hieraki/stylesheets/foo.css), stylesheet_path("foo"))
end
end

View file

@ -255,7 +255,8 @@ class AtomFeedTest < Test::Unit::TestCase
def test_feed_xml_processing_instructions
with_restful_routing(:scrolls) do
get :index, :id => 'feed_with_xml_processing_instructions'
assert_match %r{<\?xml-stylesheet type="text/css" href="t.css"\?>}, @response.body
assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body
assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body
end
end

View file

@ -12,30 +12,42 @@ uses_mocha 'TestTemplateRecompilation' do
def test_template_gets_compiled
assert_equal 0, @compiled_templates.instance_methods.size
assert_deprecated do
assert_equal "Hello world!", render("test/hello_world.erb")
end
assert_equal 1, @compiled_templates.instance_methods.size
end
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
assert_deprecated do
assert_equal "Hello world!", render("test/hello_world.erb")
assert_equal "Hello world!", render("test/hello_world.erb", {:foo => "bar"})
end
assert_equal 2, @compiled_templates.instance_methods.size
end
def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
assert_equal 0, @compiled_templates.instance_methods.size
assert_deprecated do
assert_equal "Hello world!", render("test/hello_world.erb")
ActionView::Template.any_instance.expects(:compile!).never
assert_equal "Hello world!", render("test/hello_world.erb")
end
end
def test_compiled_template_will_always_be_recompiled_when_eager_loaded_templates_is_off
ActionView::PathSet::Path.expects(:eager_load_templates?).times(4).returns(false)
assert_equal 0, @compiled_templates.instance_methods.size
assert_deprecated do
assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
end
ActionView::Template.any_instance.expects(:compile!).times(3)
assert_deprecated do
3.times { assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
end
assert_equal 1, @compiled_templates.instance_methods.size
end

View file

@ -41,11 +41,11 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase
key, count = *expected
to = @from + diff
options = {:locale => 'en-US', :scope => :'datetime.distance_in_words'}
options = {:locale => 'en', :scope => :'datetime.distance_in_words'}
options[:count] = count if count
I18n.expects(:t).with(key, options)
distance_of_time_in_words(@from, to, include_seconds, :locale => 'en-US')
distance_of_time_in_words(@from, to, include_seconds, :locale => 'en')
end
def test_distance_of_time_pluralizations
@ -78,36 +78,36 @@ class DateHelperSelectTagsI18nTests < Test::Unit::TestCase
uses_mocha 'date_helper_select_tags_i18n_tests' do
def setup
I18n.stubs(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
end
# select_month
def test_select_month_given_use_month_names_option_does_not_translate_monthnames
I18n.expects(:translate).never
select_month(8, :locale => 'en-US', :use_month_names => Date::MONTHNAMES)
select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
end
def test_select_month_translates_monthnames
I18n.expects(:translate).with(:'date.month_names', :locale => 'en-US').returns Date::MONTHNAMES
select_month(8, :locale => 'en-US')
I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
select_month(8, :locale => 'en')
end
def test_select_month_given_use_short_month_option_translates_abbr_monthnames
I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en-US').returns Date::ABBR_MONTHNAMES
select_month(8, :locale => 'en-US', :use_short_month => true)
I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
select_month(8, :locale => 'en', :use_short_month => true)
end
# date_or_time_select
def test_date_or_time_select_given_an_order_options_does_not_translate_order
I18n.expects(:translate).never
datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en-US')
datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
end
def test_date_or_time_select_given_no_order_options_translates_order
I18n.expects(:translate).with(:'date.order', :locale => 'en-US').returns [:year, :month, :day]
datetime_select('post', 'updated_at', :locale => 'en-US')
I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day]
datetime_select('post', 'updated_at', :locale => 'en')
end
end
end

40
vendor/rails/actionpack/test/template/date_helper_test.rb vendored Executable file → Normal file
View file

@ -1150,6 +1150,46 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, date_select("post", "written_on", :include_blank => true)
end
def test_date_select_with_nil_and_blank_and_order
@post = Post.new
start_year = Time.now.year-5
end_year = Time.now.year+5
expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
expected << "<option value=\"\"></option>\n"
start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
expected << "</select>\n"
expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
expected << "<option value=\"\"></option>\n"
1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
expected << "</select>\n"
assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
end
def test_date_select_with_nil_and_blank_and_order
@post = Post.new
start_year = Time.now.year-5
end_year = Time.now.year+5
expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i"/>' + "\n"
expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
expected << "<option value=\"\"></option>\n"
start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
expected << "</select>\n"
expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
expected << "<option value=\"\"></option>\n"
1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
expected << "</select>\n"
assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
end
def test_date_select_cant_override_discard_hour
@post = Post.new
@post.written_on = Date.new(2004, 6, 15)

View file

@ -1,9 +0,0 @@
require 'abstract_unit'
class DeprecatedErbVariableTest < ActionView::TestCase
def test_setting_erb_variable_warns
assert_deprecated 'erb_variable' do
ActionView::Base.erb_variable = '_erbout'
end
end
end

View file

@ -12,12 +12,19 @@ class FormTagHelperTest < ActionView::TestCase
@controller = @controller.new
end
VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name
def test_check_box_tag
actual = check_box_tag "admin"
expected = %(<input id="admin" name="admin" type="checkbox" value="1" />)
assert_dom_equal expected, actual
end
def test_check_box_tag_id_sanitized
label_elem = root_elem(check_box_tag("project[2][admin]"))
assert_match VALID_HTML_ID, label_elem['id']
end
def test_form_tag
actual = form_tag
expected = %(<form action="http://www.example.com" method="post">)
@ -64,6 +71,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
def test_hidden_field_tag_id_sanitized
input_elem = root_elem(hidden_field_tag("item[][title]"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_file_field_tag
assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
end
@ -118,6 +130,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
def test_select_tag_id_sanitized
input_elem = root_elem(select_tag("project[1]people", "<option>david</option>"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_text_area_tag_size_string
actual = text_area_tag "body", "hello world", "size" => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>)
@ -184,6 +201,11 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
def test_text_field_tag_id_sanitized
input_elem = root_elem(text_field_tag("item[][title]"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_label_tag_without_text
actual = label_tag "title"
expected = %(<label for="title">Title</label>)
@ -208,11 +230,17 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
def test_boolean_optios
def test_label_tag_id_sanitized
label_elem = root_elem(label_tag("item[title]"))
assert_match VALID_HTML_ID, label_elem['for']
end
def test_boolean_options
assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => true)
assert_dom_equal %(<select id="people[]" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => nil)
end
@ -283,4 +311,10 @@ class FormTagHelperTest < ActionView::TestCase
def protect_against_forgery?
false
end
private
def root_elem(rendered_content)
HTML::Document.new(rendered_content).root.children[0]
end
end

View file

@ -13,42 +13,42 @@ class NumberHelperI18nTests < Test::Unit::TestCase
@percentage_defaults = { :delimiter => '' }
@precision_defaults = { :delimiter => '' }
I18n.backend.store_translations 'en-US', :number => { :format => @number_defaults,
I18n.backend.store_translations 'en', :number => { :format => @number_defaults,
:currency => { :format => @currency_defaults }, :human => @human_defaults }
end
def test_number_to_currency_translates_currency_formats
I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.currency.format', :locale => 'en-US',
I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.currency.format', :locale => 'en',
:raise => true).returns(@currency_defaults)
number_to_currency(1, :locale => 'en-US')
number_to_currency(1, :locale => 'en')
end
def test_number_with_precision_translates_number_formats
I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.precision.format', :locale => 'en-US',
I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.precision.format', :locale => 'en',
:raise => true).returns(@precision_defaults)
number_with_precision(1, :locale => 'en-US')
number_with_precision(1, :locale => 'en')
end
def test_number_with_delimiter_translates_number_formats
I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
number_with_delimiter(1, :locale => 'en-US')
I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
number_with_delimiter(1, :locale => 'en')
end
def test_number_to_percentage_translates_number_formats
I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en-US',
I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en',
:raise => true).returns(@percentage_defaults)
number_to_percentage(1, :locale => 'en-US')
number_to_percentage(1, :locale => 'en')
end
def test_number_to_human_size_translates_human_formats
I18n.expects(:translate).with(:'number.format', :locale => 'en-US', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.human.format', :locale => 'en-US',
I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults)
I18n.expects(:translate).with(:'number.human.format', :locale => 'en',
:raise => true).returns(@human_defaults)
# can't be called with 1 because this directly returns without calling I18n.translate
number_to_human_size(1025, :locale => 'en-US')
number_to_human_size(1025, :locale => 'en')
end
end
end

View file

@ -8,20 +8,26 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file
assert_deprecated do
assert_equal "Hello world!", @view.render("test/hello_world.erb")
end
end
def test_render_file_not_using_full_path
assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
end
def test_render_file_without_specific_extension
assert_deprecated do
assert_equal "Hello world!", @view.render("test/hello_world")
end
end
def test_render_file_at_top_level
assert_deprecated do
assert_equal 'Elastica', @view.render('/shared')
end
end
def test_render_file_with_full_path
template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world.erb')
@ -29,17 +35,29 @@ class ViewRenderTest < Test::Unit::TestCase
end
def test_render_file_with_instance_variables
assert_deprecated do
assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_ivar.erb")
end
end
def test_render_file_with_locals
locals = { :secret => 'in the sauce' }
assert_deprecated do
assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_locals.erb", locals)
end
end
def test_render_file_not_using_full_path_with_dot_in_path
assert_deprecated do
assert_equal "The secret is in the sauce\n", @view.render("test/dot.directory/render_file_with_ivar")
end
end
def test_render_has_access_current_template
assert_deprecated do
assert_equal "test/template.erb", @view.render("test/template.erb")
end
end
def test_render_update
# TODO: You should not have to stub out template because template is self!
@ -111,6 +129,10 @@ class ViewRenderTest < Test::Unit::TestCase
assert_nil @view.render(:partial => "test/customer", :collection => nil)
end
def test_render_partial_with_nil_values_in_collection
assert_equal "Hello: davidHello: Anonymous", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), nil ])
end
def test_render_partial_with_empty_array_should_return_nil
assert_nil @view.render(:partial => [])
end
@ -158,4 +180,14 @@ class ViewRenderTest < Test::Unit::TestCase
ActionView::Template.register_template_handler :foo, CustomHandler
assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
end
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
end
def test_render_with_nested_layout
assert_equal %(<title>title</title>\n<div id="column">column</div>\n<div id="content">content</div>\n),
@view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
end
end

View file

@ -19,6 +19,10 @@ class TagHelperTest < ActionView::TestCase
assert_equal "<p />", tag("p", :ignored => nil)
end
def test_tag_options_accepts_false_option
assert_equal "<p value=\"false\" />", tag("p", :value => false)
end
def test_tag_options_accepts_blank_option
assert_equal "<p included=\"\" />", tag("p", :included => '')
end

View file

@ -1,73 +0,0 @@
require 'abstract_unit'
class TemplateFinderTest < Test::Unit::TestCase
LOAD_PATH_ROOT = File.join(File.dirname(__FILE__), '..', 'fixtures')
def setup
ActionView::TemplateFinder.process_view_paths(LOAD_PATH_ROOT)
ActionView::Template::register_template_handler :mab, Class.new(ActionView::TemplateHandler)
@template = ActionView::Base.new
@finder = ActionView::TemplateFinder.new(@template, LOAD_PATH_ROOT)
end
def test_should_raise_exception_for_unprocessed_view_path
assert_raises ActionView::TemplateFinder::InvalidViewPath do
ActionView::TemplateFinder.new(@template, File.dirname(__FILE__))
end
end
def test_should_cache_file_extension_properly
assert_equal ["builder", "erb", "rhtml", "rjs", "rxml", "mab"].sort,
ActionView::TemplateFinder.file_extension_cache[LOAD_PATH_ROOT].values.flatten.uniq.sort
assert_equal (Dir.glob("#{LOAD_PATH_ROOT}/**/*/*.{erb,rjs,rhtml,builder,rxml,mab}") |
Dir.glob("#{LOAD_PATH_ROOT}/**.{erb,rjs,rhtml,builder,rxml,mab}")).size,
ActionView::TemplateFinder.file_extension_cache[LOAD_PATH_ROOT].keys.size
end
def test_should_cache_dir_content_properly
assert ActionView::TemplateFinder.processed_view_paths[LOAD_PATH_ROOT]
assert_equal (Dir.glob("#{LOAD_PATH_ROOT}/**/*/**") | Dir.glob("#{LOAD_PATH_ROOT}/**")).find_all {|f| !File.directory?(f) }.size,
ActionView::TemplateFinder.processed_view_paths[LOAD_PATH_ROOT].size
end
def test_find_template_extension_from_first_render
assert_nil @finder.send(:find_template_extension_from_first_render)
{
nil => nil,
'' => nil,
'foo' => nil,
'/foo' => nil,
'foo.rb' => 'rb',
'foo.bar.rb' => 'bar.rb',
'baz/foo.rb' => 'rb',
'baz/foo.bar.rb' => 'bar.rb',
'baz/foo.o/foo.rb' => 'rb',
'baz/foo.o/foo.bar.rb' => 'bar.rb',
}.each do |input,expectation|
@template.instance_variable_set('@first_render', input)
assert_equal expectation, @finder.send(:find_template_extension_from_first_render)
end
end
def test_should_report_file_exists_correctly
assert_nil @finder.send(:find_template_extension_from_first_render)
assert_equal false, @finder.send(:file_exists?, 'test.rhtml')
assert_equal false, @finder.send(:file_exists?, 'test.rb')
@template.instance_variable_set('@first_render', 'foo.rb')
assert_equal 'rb', @finder.send(:find_template_extension_from_first_render)
assert_equal false, @finder.send(:file_exists?, 'baz')
assert_equal false, @finder.send(:file_exists?, 'baz.rb')
end
uses_mocha 'Template finder tests' do
def test_should_update_extension_cache_when_template_handler_is_registered
ActionView::TemplateFinder.expects(:update_extension_cache_for).with("funky")
ActionView::Template::register_template_handler :funky, Class.new(ActionView::TemplateHandler)
end
end
end

View file

@ -1,95 +0,0 @@
require 'abstract_unit'
class TemplateObjectTest < Test::Unit::TestCase
LOAD_PATH_ROOT = File.join(File.dirname(__FILE__), '..', 'fixtures')
ActionView::TemplateFinder.process_view_paths(LOAD_PATH_ROOT)
class TemplateTest < Test::Unit::TestCase
def setup
@view = ActionView::Base.new(LOAD_PATH_ROOT)
@path = "test/hello_world.erb"
end
def test_should_create_valid_template
template = ActionView::Template.new(@view, @path, true)
assert_kind_of ActionView::TemplateHandlers::ERB, template.handler
assert_equal "test/hello_world.erb", template.path
assert_nil template.instance_variable_get(:"@source")
assert_equal "erb", template.extension
end
uses_mocha 'Template preparation tests' do
def test_should_prepare_template_properly
template = ActionView::Template.new(@view, @path, true)
view = template.instance_variable_get(:"@view")
view.expects(:evaluate_assigns)
template.handler.expects(:compile_template).with(template)
view.expects(:method_names).returns({})
template.prepare!
end
end
end
class PartialTemplateTest < Test::Unit::TestCase
def setup
@view = ActionView::Base.new(LOAD_PATH_ROOT)
@path = "test/partial_only"
end
def test_should_create_valid_partial_template
template = ActionView::PartialTemplate.new(@view, @path, nil)
assert_equal "test/_partial_only", template.path
assert_equal :partial_only, template.variable_name
assert template.locals.has_key?(:object)
assert template.locals.has_key?(:partial_only)
end
def test_partial_with_errors
template = ActionView::PartialTemplate.new(@view, 'test/raise', nil)
assert_raise(ActionView::TemplateError) { template.render_template }
end
uses_mocha 'Partial template preparation tests' do
def test_should_prepare_on_initialization
ActionView::PartialTemplate.any_instance.expects(:prepare!)
template = ActionView::PartialTemplate.new(@view, @path, 1)
end
end
end
class PartialTemplateFallbackTest < Test::Unit::TestCase
def setup
@view = ActionView::Base.new(LOAD_PATH_ROOT)
@path = 'test/layout_for_partial'
end
def test_default
template = ActionView::PartialTemplate.new(@view, @path, nil)
assert_equal 'test/_layout_for_partial', template.path
assert_equal 'erb', template.extension
assert_equal :html, @view.template_format
end
def test_js
@view.template_format = :js
template = ActionView::PartialTemplate.new(@view, @path, nil)
assert_equal 'test/_layout_for_partial', template.path
assert_equal 'erb', template.extension
assert_equal :html, @view.template_format
end
def test_xml
@view.template_format = :xml
assert_raise ActionView::MissingTemplate do
ActionView::PartialTemplate.new(@view, @path, nil)
end
end
end
end

View file

@ -221,6 +221,7 @@ class TextHelperTest < ActionView::TestCase
http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1
http://en.wikipedia.org/wiki/Sprite_(computer_graphics)
http://en.wikipedia.org/wiki/Texas_hold'em
https://www.google.com/doku.php?id=gps:resource:scs:start
)
urls.each do |url|

View file

@ -10,12 +10,12 @@ class TranslationHelperTest < Test::Unit::TestCase
end
def test_delegates_to_i18n_setting_the_raise_option
I18n.expects(:translate).with(:foo, 'en-US', :raise => true)
translate :foo, 'en-US'
I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true)
translate :foo, :locale => 'en'
end
def test_returns_missing_translation_message_wrapped_into_span
expected = '<span class="translation_missing">en-US, foo</span>'
expected = '<span class="translation_missing">en, foo</span>'
assert_equal expected, translate(:foo)
end

Some files were not shown because too many files have changed in this diff Show more