aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides
diff options
context:
space:
mode:
Diffstat (limited to 'railties/guides')
-rwxr-xr-xrailties/guides/files/javascripts/code_highlighter.js376
-rwxr-xr-xrailties/guides/files/javascripts/guides.js16
-rw-r--r--railties/guides/files/javascripts/highlighters.js4
-rw-r--r--railties/guides/files/stylesheets/main.css24
-rwxr-xr-xrailties/guides/files/stylesheets/print.css104
-rwxr-xr-xrailties/guides/files/stylesheets/reset.css86
-rwxr-xr-xrailties/guides/files/stylesheets/style.css26
-rw-r--r--railties/guides/files/stylesheets/syntax.css4
-rw-r--r--railties/guides/rails_guides/indexer.rb2
-rw-r--r--railties/guides/source/2_2_release_notes.textile10
-rw-r--r--railties/guides/source/2_3_release_notes.textile84
-rw-r--r--railties/guides/source/action_controller_overview.textile6
-rw-r--r--railties/guides/source/action_mailer_basics.textile28
-rw-r--r--railties/guides/source/active_record_basics.textile8
-rw-r--r--railties/guides/source/activerecord_validations_callbacks.textile98
-rw-r--r--railties/guides/source/association_basics.textile66
-rw-r--r--railties/guides/source/caching_with_rails.textile24
-rw-r--r--railties/guides/source/command_line.textile22
-rw-r--r--railties/guides/source/debugging_rails_applications.textile16
-rw-r--r--railties/guides/source/form_helpers.textile16
-rw-r--r--railties/guides/source/getting_started.textile40
-rw-r--r--railties/guides/source/i18n.textile32
-rw-r--r--railties/guides/source/layout.html.erb6
-rw-r--r--railties/guides/source/layouts_and_rendering.textile20
-rw-r--r--railties/guides/source/migrations.textile22
-rw-r--r--railties/guides/source/performance_testing.textile12
-rw-r--r--railties/guides/source/plugins.textile76
-rw-r--r--railties/guides/source/rails_on_rack.textile4
-rw-r--r--railties/guides/source/routing.textile26
-rw-r--r--railties/guides/source/security.textile10
-rw-r--r--railties/guides/source/testing.textile72
31 files changed, 670 insertions, 670 deletions
diff --git a/railties/guides/files/javascripts/code_highlighter.js b/railties/guides/files/javascripts/code_highlighter.js
index 4ed72e1692..ce983dad52 100755
--- a/railties/guides/files/javascripts/code_highlighter.js
+++ b/railties/guides/files/javascripts/code_highlighter.js
@@ -1,188 +1,188 @@
-/* Unobtrustive Code Highlighter By Dan Webb 11/2005
- Version: 0.4
-
- Usage:
- Add a script tag for this script and any stylesets you need to use
- to the page in question, add correct class names to CODE elements,
- define CSS styles for elements. That's it!
-
- Known to work on:
- IE 5.5+ PC
- Firefox/Mozilla PC/Mac
- Opera 7.23 + PC
- Safari 2
-
- Known to degrade gracefully on:
- IE5.0 PC
-
- Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
- in older browsers use expressions that use lookahead in string format when defining stylesets.
-
- This script is inspired by star-light by entirely cunning Dean Edwards
- http://dean.edwards.name/star-light/.
-*/
-
-// replace callback support for safari.
-if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
- var default_replace = String.prototype.replace;
- String.prototype.replace = function(search,replace){
- // replace is not function
- if(typeof replace != "function"){
- return default_replace.apply(this,arguments)
- }
- var str = "" + this;
- var callback = replace;
- // search string is not RegExp
- if(!(search instanceof RegExp)){
- var idx = str.indexOf(search);
- return (
- idx == -1 ? str :
- default_replace.apply(str,[search,callback(search, idx, str)])
- )
- }
- var reg = search;
- var result = [];
- var lastidx = reg.lastIndex;
- var re;
- while((re = reg.exec(str)) != null){
- var idx = re.index;
- var args = re.concat(idx, str);
- result.push(
- str.slice(lastidx,idx),
- callback.apply(null,args).toString()
- );
- if(!reg.global){
- lastidx += RegExp.lastMatch.length;
- break
- }else{
- lastidx = reg.lastIndex;
- }
- }
- result.push(str.slice(lastidx));
- return result.join("")
- }
-})();
-
-var CodeHighlighter = { styleSets : new Array };
-
-CodeHighlighter.addStyle = function(name, rules) {
- // using push test to disallow older browsers from adding styleSets
- if ([].push) this.styleSets.push({
- name : name,
- rules : rules,
- ignoreCase : arguments[2] || false
- })
-
- function setEvent() {
- // set highlighter to run on load (use LowPro if present)
- if (typeof Event != 'undefined' && typeof Event.onReady == 'function')
- return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter));
-
- var old = window.onload;
-
- if (typeof window.onload != 'function') {
- window.onload = function() { CodeHighlighter.init() };
- } else {
- window.onload = function() {
- old();
- CodeHighlighter.init();
- }
- }
- }
-
- // only set the event when the first style is added
- if (this.styleSets.length==1) setEvent();
-}
-
-CodeHighlighter.init = function() {
- if (!document.getElementsByTagName) return;
- if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
- // throw out older browsers
-
- var codeEls = document.getElementsByTagName("CODE");
- // collect array of all pre elements
- codeEls.filter = function(f) {
- var a = new Array;
- for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
- return a;
- }
-
- var rules = new Array;
- rules.toString = function() {
- // joins regexes into one big parallel regex
- var exps = new Array;
- for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
- return exps.join("|");
- }
-
- function addRule(className, rule) {
- // add a replace rule
- var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
- // converts regex rules to strings and chops of the slashes
- rules.push({
- className : className,
- exp : "(" + exp + ")",
- length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
- replacement : rule.replacement || null
- });
- }
-
- function parse(text, ignoreCase) {
- // main text parsing and replacement
- return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
- var i = 0, j = 1, rule;
- while (rule = rules[i++]) {
- if (arguments[j]) {
- // if no custom replacement defined do the simple replacement
- if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
- else {
- // replace $0 with the className then do normal replaces
- var str = rule.replacement.replace("$0", rule.className);
- for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
- return str;
- }
- } else j+= rule.length;
- }
- });
- }
-
- function highlightCode(styleSet) {
- // clear rules array
- var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)");
- rules.length = 0;
-
- // get stylable elements by filtering out all code elements without the correct className
- var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) });
-
- // add style rules to parser
- for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
-
-
- // replace for all elements
- for (var i = 0; i < stylableEls.length; i++) {
- // EVIL hack to fix IE whitespace badness if it's inside a <pre>
- if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
- stylableEls[i] = stylableEls[i].parentNode;
-
- parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
- return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
- });
- parsed = parsed.replace(/\n( *)/g, function() {
- var spaces = "";
- for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
- return "\n" + spaces;
- });
- parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
- parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
-
- } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
-
- stylableEls[i].innerHTML = parsed;
- }
- }
-
- // run highlighter on all stylesets
- for (var i=0; i < this.styleSets.length; i++) {
- highlightCode(this.styleSets[i]);
- }
-} \ No newline at end of file
+/* Unobtrustive Code Highlighter By Dan Webb 11/2005
+ Version: 0.4
+
+ Usage:
+ Add a script tag for this script and any stylesets you need to use
+ to the page in question, add correct class names to CODE elements,
+ define CSS styles for elements. That's it!
+
+ Known to work on:
+ IE 5.5+ PC
+ Firefox/Mozilla PC/Mac
+ Opera 7.23 + PC
+ Safari 2
+
+ Known to degrade gracefully on:
+ IE5.0 PC
+
+ Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
+ in older browsers use expressions that use lookahead in string format when defining stylesets.
+
+ This script is inspired by star-light by entirely cunning Dean Edwards
+ http://dean.edwards.name/star-light/.
+*/
+
+// replace callback support for safari.
+if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
+ var default_replace = String.prototype.replace;
+ String.prototype.replace = function(search,replace){
+ // replace is not function
+ if(typeof replace != "function"){
+ return default_replace.apply(this,arguments)
+ }
+ var str = "" + this;
+ var callback = replace;
+ // search string is not RegExp
+ if(!(search instanceof RegExp)){
+ var idx = str.indexOf(search);
+ return (
+ idx == -1 ? str :
+ default_replace.apply(str,[search,callback(search, idx, str)])
+ )
+ }
+ var reg = search;
+ var result = [];
+ var lastidx = reg.lastIndex;
+ var re;
+ while((re = reg.exec(str)) != null){
+ var idx = re.index;
+ var args = re.concat(idx, str);
+ result.push(
+ str.slice(lastidx,idx),
+ callback.apply(null,args).toString()
+ );
+ if(!reg.global){
+ lastidx += RegExp.lastMatch.length;
+ break
+ }else{
+ lastidx = reg.lastIndex;
+ }
+ }
+ result.push(str.slice(lastidx));
+ return result.join("")
+ }
+})();
+
+var CodeHighlighter = { styleSets : new Array };
+
+CodeHighlighter.addStyle = function(name, rules) {
+ // using push test to disallow older browsers from adding styleSets
+ if ([].push) this.styleSets.push({
+ name : name,
+ rules : rules,
+ ignoreCase : arguments[2] || false
+ })
+
+ function setEvent() {
+ // set highlighter to run on load (use LowPro if present)
+ if (typeof Event != 'undefined' && typeof Event.onReady == 'function')
+ return Event.onReady(CodeHighlighter.init.bind(CodeHighlighter));
+
+ var old = window.onload;
+
+ if (typeof window.onload != 'function') {
+ window.onload = function() { CodeHighlighter.init() };
+ } else {
+ window.onload = function() {
+ old();
+ CodeHighlighter.init();
+ }
+ }
+ }
+
+ // only set the event when the first style is added
+ if (this.styleSets.length==1) setEvent();
+}
+
+CodeHighlighter.init = function() {
+ if (!document.getElementsByTagName) return;
+ if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
+ // throw out older browsers
+
+ var codeEls = document.getElementsByTagName("CODE");
+ // collect array of all pre elements
+ codeEls.filter = function(f) {
+ var a = new Array;
+ for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
+ return a;
+ }
+
+ var rules = new Array;
+ rules.toString = function() {
+ // joins regexes into one big parallel regex
+ var exps = new Array;
+ for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
+ return exps.join("|");
+ }
+
+ function addRule(className, rule) {
+ // add a replace rule
+ var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
+ // converts regex rules to strings and chops of the slashes
+ rules.push({
+ className : className,
+ exp : "(" + exp + ")",
+ length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
+ replacement : rule.replacement || null
+ });
+ }
+
+ function parse(text, ignoreCase) {
+ // main text parsing and replacement
+ return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
+ var i = 0, j = 1, rule;
+ while (rule = rules[i++]) {
+ if (arguments[j]) {
+ // if no custom replacement defined do the simple replacement
+ if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
+ else {
+ // replace $0 with the className then do normal replaces
+ var str = rule.replacement.replace("$0", rule.className);
+ for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
+ return str;
+ }
+ } else j+= rule.length;
+ }
+ });
+ }
+
+ function highlightCode(styleSet) {
+ // clear rules array
+ var parsed, clsRx = new RegExp("(\\s|^)" + styleSet.name + "(\\s|$)");
+ rules.length = 0;
+
+ // get stylable elements by filtering out all code elements without the correct className
+ var stylableEls = codeEls.filter(function(item) { return clsRx.test(item.className) });
+
+ // add style rules to parser
+ for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
+
+
+ // replace for all elements
+ for (var i = 0; i < stylableEls.length; i++) {
+ // EVIL hack to fix IE whitespace badness if it's inside a <pre>
+ if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
+ stylableEls[i] = stylableEls[i].parentNode;
+
+ parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
+ return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
+ });
+ parsed = parsed.replace(/\n( *)/g, function() {
+ var spaces = "";
+ for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
+ return "\n" + spaces;
+ });
+ parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
+ parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
+
+ } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
+
+ stylableEls[i].innerHTML = parsed;
+ }
+ }
+
+ // run highlighter on all stylesets
+ for (var i=0; i < this.styleSets.length; i++) {
+ highlightCode(this.styleSets[i]);
+ }
+}
diff --git a/railties/guides/files/javascripts/guides.js b/railties/guides/files/javascripts/guides.js
index 63c127d04a..81fc07e799 100755
--- a/railties/guides/files/javascripts/guides.js
+++ b/railties/guides/files/javascripts/guides.js
@@ -1,8 +1,8 @@
-function guideMenu(){
-
- if (document.getElementById('guides').style.display == "none") {
- document.getElementById('guides').style.display = "block";
- } else {
- document.getElementById('guides').style.display = "none";
- }
-}
+function guideMenu(){
+
+ if (document.getElementById('guides').style.display == "none") {
+ document.getElementById('guides').style.display = "block";
+ } else {
+ document.getElementById('guides').style.display = "none";
+ }
+}
diff --git a/railties/guides/files/javascripts/highlighters.js b/railties/guides/files/javascripts/highlighters.js
index bf46367dfe..4f5f0779d7 100644
--- a/railties/guides/files/javascripts/highlighters.js
+++ b/railties/guides/files/javascripts/highlighters.js
@@ -47,14 +47,14 @@ CodeHighlighter.addStyle("html", {
exp: /&lt;!\s*(--([^-]|[\r\n]|-[^-])*--\s*)&gt;/
},
tag : {
- exp: /(&lt;\/?)([a-zA-Z1-9]+\s?)/,
+ exp: /(&lt;\/?)([a-zA-Z1-9]+\s?)/,
replacement: "$1<span class=\"$0\">$2</span>"
},
string : {
exp : /'[^']*'|"[^"]*"/
},
attribute : {
- exp: /\b([a-zA-Z-:]+)(=)/,
+ exp: /\b([a-zA-Z-:]+)(=)/,
replacement: "<span class=\"$0\">$1</span>$2"
},
doctype : {
diff --git a/railties/guides/files/stylesheets/main.css b/railties/guides/files/stylesheets/main.css
index 9c9ef5151b..64243be945 100644
--- a/railties/guides/files/stylesheets/main.css
+++ b/railties/guides/files/stylesheets/main.css
@@ -22,7 +22,7 @@ ol { list-style-type: decimal; }
dl { margin: 0 0 1.5em 0; }
dl dt { font-weight: bold; }
dd { margin-left: 1.5em;}
-
+
pre,code { margin: 1.5em 0; white-space: pre; }
pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; }
@@ -86,7 +86,7 @@ body {
font-family: Helvetica, Arial, sans-serif;
font-size: 87.5%;
line-height: 1.5em;
- background: #222;
+ background: #222;
color: #999;
}
@@ -124,7 +124,7 @@ body {
#mainCol {
width: 45em;
margin-left: 2em;
- }
+ }
#subCol {
position: absolute;
@@ -137,7 +137,7 @@ body {
font-size: 0.9285em;
line-height: 1.3846em;
}
-
+
#extraCol {display: none;}
#footer {
@@ -190,7 +190,7 @@ a, a:link, a:visited {
#header .nav .index a {
background: #980905 url(../../images/nav_arrow.gif) no-repeat right top;
- padding-right: 1em;
+ padding-right: 1em;
position: relative;
z-index: 15;
padding-bottom: 0.125em;
@@ -256,7 +256,7 @@ h3 {
margin: 0.875em 0 0.2916em;
font-weight: bold;
}
-
+
h4 {
font-size: 1.2857em;
line-height: 1.2em;
@@ -271,7 +271,7 @@ h5 {
font-weight: bold;
}
-h6 {
+h6 {
font-size: 1em;
line-height: 1.5em;
margin: 1em 0 .5em;
@@ -418,15 +418,15 @@ em.highlight {
padding-left: 1em;
margin-left: 0;
}
-
+
/* Clearing
--------------------------------------- */
.clearfix:after {
- content: ".";
- display: block;
- height: 0;
- clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
visibility: hidden;
}
diff --git a/railties/guides/files/stylesheets/print.css b/railties/guides/files/stylesheets/print.css
index 6aa1662c0b..628da105d4 100755
--- a/railties/guides/files/stylesheets/print.css
+++ b/railties/guides/files/stylesheets/print.css
@@ -1,52 +1,52 @@
-/* Guides.rubyonrails.org */
-/* Print.css */
-/* Created January 30, 2009 */
-/* Modified January 31, 2009
---------------------------------------- */
-
-body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
-
-body {
- background: #FFF;
- font-size: 10pt !important;
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
- line-height: 1.5;
- color: #000;
- padding: 0 3%;
- }
-
-.hide, .nav {
- display: none !important;
- }
-
-a:link, a:visited {
- background: transparent;
- font-weight: bold;
- text-decoration: underline;
- }
-
-hr {
- background:#ccc;
- color:#ccc;
- width:100%;
- height:2px;
- margin:2em 0;
- padding:0;
- border:none;
-}
-
-h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
-code { font:.9em "Courier New", Monaco, Courier, monospace; }
-
-img { float:left; margin:1.5em 1.5em 1.5em 0; }
-a img { border:none; }
-
-blockquote {
- margin:1.5em;
- padding:1em;
- font-style:italic;
- font-size:.9em;
-}
-
-.small { font-size: .9em; }
-.large { font-size: 1.1em; } \ No newline at end of file
+/* Guides.rubyonrails.org */
+/* Print.css */
+/* Created January 30, 2009 */
+/* Modified January 31, 2009
+--------------------------------------- */
+
+body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
+
+body {
+ background: #FFF;
+ font-size: 10pt !important;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ line-height: 1.5;
+ color: #000;
+ padding: 0 3%;
+ }
+
+.hide, .nav {
+ display: none !important;
+ }
+
+a:link, a:visited {
+ background: transparent;
+ font-weight: bold;
+ text-decoration: underline;
+ }
+
+hr {
+ background:#ccc;
+ color:#ccc;
+ width:100%;
+ height:2px;
+ margin:2em 0;
+ padding:0;
+ border:none;
+}
+
+h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
+code { font:.9em "Courier New", Monaco, Courier, monospace; }
+
+img { float:left; margin:1.5em 1.5em 1.5em 0; }
+a img { border:none; }
+
+blockquote {
+ margin:1.5em;
+ padding:1em;
+ font-style:italic;
+ font-size:.9em;
+}
+
+.small { font-size: .9em; }
+.large { font-size: 1.1em; }
diff --git a/railties/guides/files/stylesheets/reset.css b/railties/guides/files/stylesheets/reset.css
index 48c2451cb3..cb14fbcc55 100755
--- a/railties/guides/files/stylesheets/reset.css
+++ b/railties/guides/files/stylesheets/reset.css
@@ -1,43 +1,43 @@
-/* Guides.rubyonrails.org */
-/* Reset.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-html, body, div, span, applet, object, iframe,
-h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-a, abbr, acronym, address, big, cite, code,
-del, dfn, em, font, img, ins, kbd, q, s, samp,
-small, strike, strong, sub, sup, tt, var,
-b, u, i, center,
-dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend,
-table, caption, tbody, tfoot, thead, tr, th, td {
- margin: 0;
- padding: 0;
- border: 0;
- outline: 0;
- font-size: 100%;
- background: transparent;
-}
-
-body {line-height: 1; color: black; background: white;}
-a img {border:none;}
-ins {text-decoration: none;}
-del {text-decoration: line-through;}
-
-:focus {
- -moz-outline:0;
- outline:0;
- outline-offset:0;
-}
-
-/* tables still need 'cellspacing="0"' in the markup */
-table {border-collapse: collapse; border-spacing: 0;}
-caption, th, td {text-align: left; font-weight: normal;}
-
-blockquote, q {quotes: none;}
-blockquote:before, blockquote:after,
-q:before, q:after {
- content: '';
- content: none;
-} \ No newline at end of file
+/* Guides.rubyonrails.org */
+/* Reset.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, font, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ background: transparent;
+}
+
+body {line-height: 1; color: black; background: white;}
+a img {border:none;}
+ins {text-decoration: none;}
+del {text-decoration: line-through;}
+
+:focus {
+ -moz-outline:0;
+ outline:0;
+ outline-offset:0;
+}
+
+/* tables still need 'cellspacing="0"' in the markup */
+table {border-collapse: collapse; border-spacing: 0;}
+caption, th, td {text-align: left; font-weight: normal;}
+
+blockquote, q {quotes: none;}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
diff --git a/railties/guides/files/stylesheets/style.css b/railties/guides/files/stylesheets/style.css
index 0249c77e85..89b2ab885a 100755
--- a/railties/guides/files/stylesheets/style.css
+++ b/railties/guides/files/stylesheets/style.css
@@ -1,13 +1,13 @@
-/* Guides.rubyonrails.org */
-/* Style.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-/*
----------------------------------------
-Import advanced style sheet
----------------------------------------
-*/
-
-@import url("reset.css");
-@import url("main.css");
+/* Guides.rubyonrails.org */
+/* Style.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+/*
+---------------------------------------
+Import advanced style sheet
+---------------------------------------
+*/
+
+@import url("reset.css");
+@import url("main.css");
diff --git a/railties/guides/files/stylesheets/syntax.css b/railties/guides/files/stylesheets/syntax.css
index 7e5b4bd8c7..55fc5b209f 100644
--- a/railties/guides/files/stylesheets/syntax.css
+++ b/railties/guides/files/stylesheets/syntax.css
@@ -27,5 +27,5 @@
}
.ruby .symbol {
- color: green;
-} \ No newline at end of file
+ color: green;
+}
diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb
index 7f1c55a980..52809829e2 100644
--- a/railties/guides/rails_guides/indexer.rb
+++ b/railties/guides/rails_guides/indexer.rb
@@ -43,7 +43,7 @@ module RailsGuides
counters << last + 1
end
end
- s.getch
+ s.getch
end
level_hash
end
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
index f88cd7c5b0..6f882f6d7d 100644
--- a/railties/guides/source/2_2_release_notes.textile
+++ b/railties/guides/source/2_2_release_notes.textile
@@ -137,7 +137,7 @@ development:
</ruby>
* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/
-* More information:
+* More information:
** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools
h4. Hashes for Join Table Conditions
@@ -175,7 +175,7 @@ User.find_last_by_city('London')
* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua
-h5. +find_by_<attribute>!+
+h5. +find_by_<attribute>!+
The new bang! version of +find_by_<attribute>!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match.
@@ -197,7 +197,7 @@ Active Record association proxies now respect the scope of methods on the proxie
h4. Other ActiveRecord Changes
* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo
-* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
+* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer.
* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names
@@ -207,7 +207,7 @@ On the controller side, there are several changes that will help tidy up your ro
h4. Shallow Route Nesting
-Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
+Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
<ruby>
map.resources :publishers, :shallow => true do |publisher|
@@ -228,7 +228,7 @@ This will enable recognition of (among others) these routes:
</ruby>
* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/
-* More information:
+* More information:
** "Rails Routing from the Outside In":http://guides.rails.info/routing/routing_outside_in.html#_nested_resources
** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
index 235554f904..334416f3f6 100644
--- a/railties/guides/source/2_3_release_notes.textile
+++ b/railties/guides/source/2_3_release_notes.textile
@@ -38,7 +38,7 @@ Here's a summary of the rack-related changes:
* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+.
* +ActionController::Request+ inherits from +Rack::Request+
* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+
-* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it.
+* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it.
h4. Renewed Support for Rails Engines
@@ -68,7 +68,7 @@ end
</ruby>
Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).
-
+
* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/
* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
@@ -84,7 +84,7 @@ User.transaction do
raise ActiveRecord::Rollback
end
end
-
+
User.find(:all) # => Returns only Admin
</ruby>
@@ -98,7 +98,7 @@ You know about dynamic finders in Rails (which allow you to concoct methods like
<ruby>
Order.scoped_by_customer_id(12)
-Order.scoped_by_customer_id(12).find(:all,
+Order.scoped_by_customer_id(12).find(:all,
:conditions => "status = 'open'")
Order.scoped_by_customer_id(12).scoped_by_status("open")
</ruby>
@@ -110,7 +110,7 @@ There's nothing to define to use dynamic scopes: they just work.
h4. Default Scopes
-Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
+Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
* Lead Contributor: Paweł Kondzior
* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping
@@ -120,7 +120,7 @@ h4. Multiple Conditions for Callbacks
When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array:
<ruby>
-before_save :update_credit_rating, :if => :active,
+before_save :update_credit_rating, :if => :active,
:unless => [:admin, :cash_only]
</ruby>
* Lead Contributor: L. Caviola
@@ -130,7 +130,7 @@ h4. Find with having
Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:
<ruby>
-developers = Developer.find(:all, :group => "salary",
+developers = Developer.find(:all, :group => "salary",
:having => "sum(salary) > 10000", :select => "salary")
</ruby>
@@ -144,7 +144,7 @@ You can once again use a hash in conditions for a +has_many+ relationship:
has_many :orders, :conditions => {:status => 'confirmed'}
</ruby>
-That worked in Rails 2.1, fails in Rails 2.2, and will now work again in Rails 2.3 (if you're dealing with this issue in Rails 2.2, you can use a string rather than a hash to specify conditions).
+That worked in Rails 2.1, fails in Rails 2.2, and will now work again in Rails 2.3 (if you're dealing with this issue in Rails 2.2, you can use a string rather than a hash to specify conditions).
* Lead Contributor: "Frederick Cheung":http://www.spacevatican.org/
@@ -153,7 +153,7 @@ h4. Reconnecting MySQL Connections
MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change.
* Lead Contributor: "Dov Murik":http://twitter.com/dubek
-* More information:
+* More information:
** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4
@@ -162,7 +162,7 @@ h4. Other Active Record Changes
* An extra +AS+ was removed from the generated SQL for has_and_belongs_to_many preloading, making it work better for some databases.
* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record.
* A bug in quoting table names in some +has_many :through+ associations was fixed.
-* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+
+* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+
* Better error messages on failed +find_by_attribute!+ calls.
* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option.
* A bug in canceling callbacks from +before_update+ or +before_create_ was fixed.
@@ -195,10 +195,10 @@ Rails chooses between file, template, and action depending on whether there is a
h4. Application Controller Renamed
-If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process.
+If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process.
* More Information:
-** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/
+** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/
** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more
h4. HTTP Digest Authentication Support
@@ -211,12 +211,12 @@ class PostsController < ApplicationController
before_filter :authenticate
def secret
- render :text => "Password Required!"
+ render :text => "Password Required!"
end
private
def authenticate
- realm = "Application"
+ realm = "Application"
authenticate_or_request_with_http_digest(realm) do |name|
Users[name]
end
@@ -266,15 +266,15 @@ Rails now keeps a per-request local cache of requests, cutting down on unnecessa
h4. Localized Views
-Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project.
+Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project.
h4. Other Action Controller Changes
* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+.
-* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely.
-* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+.
-* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
-* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+.
+* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely.
+* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+.
+* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
+* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+.
* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources.
h3. Action View
@@ -327,7 +327,7 @@ You can write this view in Rails 2.3:
</erb>
* Lead Contributor: "Eloy Duran":http://www.superalloy.nl/blog/
-* More Information:
+* More Information:
** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
** "complex-form-examples":http://github.com/alloy/complex-form-examples/tree/nested_attributes
** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
@@ -337,11 +337,11 @@ h4. Smart Rendering of Partials
The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):
<ruby>
-# Equivalent of render :partial => 'articles/_article',
+# Equivalent of render :partial => 'articles/_article',
# :object => @article
-render @article
+render @article
-# Equivalent of render :partial => 'articles/_article',
+# Equivalent of render :partial => 'articles/_article',
# :collection => @articles
render @articles
</ruby>
@@ -357,9 +357,9 @@ select_datetime(DateTime.now, :prompt => true)
select_datetime(DateTime.now, :prompt => "Choose date and time")
-select_datetime(DateTime.now, :prompt =>
- {:day => 'Choose day', :month => 'Choose month',
- :year => 'Choose year', :hour => 'Choose hour',
+select_datetime(DateTime.now, :prompt =>
+ {:day => 'Choose day', :month => 'Choose month',
+ :year => 'Choose year', :hour => 'Choose hour',
:minute => 'Choose minute'})
</ruby>
@@ -380,7 +380,7 @@ h4. grouped_options_for_select Helper Method
Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example:
<ruby>
-grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
+grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
"Cowboy Hat", "Choose a product...")
</ruby>
@@ -396,9 +396,9 @@ returns
h4. Other Action View Changes
-* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs.
-* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links.
-* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive.
+* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs.
+* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links.
+* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive.
h3. Active Support
@@ -408,7 +408,7 @@ h4. Object#try
A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +<%= @person.try(:name) %>+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil.
-* More Information: "try()":http://ozmm.org/posts/try.html.
+* More Information: "try()":http://ozmm.org/posts/try.html.
h4. Object#tap Backport
@@ -432,10 +432,10 @@ If you look up the spec on the "json.org" site, you'll discover that all keys in
h4. Other Active Support Changes
* You can use +Enumerable#none?+ to check that none of the elements match the supplied block.
-* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil.
-* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+.
-* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies).
-* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
+* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil.
+* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+.
+* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies).
+* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
h3. Railties
@@ -443,7 +443,7 @@ In addition to the Rack changes covered above, Railties (the core code of Rails
h4. Rails Metal
-Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack.
+Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack.
* More Information:
** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal
@@ -470,7 +470,7 @@ Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/qu
h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload
-Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
+Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together.
@@ -479,16 +479,16 @@ h4. Other Railties Changes
* The instructions for updating a CI server to build Rails have been updated and expanded.
* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test.
* The default +environment.rb+ file has been decluttered.
-* The dbconsole script now lets you use an all-numeric password without crashing.
-* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+.
-* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+).
+* The dbconsole script now lets you use an all-numeric password without crashing.
+* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+.
+* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+).
h3. Deprecated
A few pieces of older code are deprecated in this release:
-* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin.
-* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master.
+* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin.
+* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master.
* Support for Rails components has been removed.
* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back.
* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index d51f2a9745..31a9c6819c 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -68,9 +68,9 @@ You will probably want to access data sent in by the user or other parameters in
<ruby>
class ClientsController < ActionController::Base
- # This action uses query string parameters because it gets run by a HTTP
- # GET request, but this does not make any difference to the way in which
- # the parameters are accessed. The URL for this action would look like this
+ # This action uses query string parameters because it gets run by a HTTP
+ # GET request, but this does not make any difference to the way in which
+ # the parameters are accessed. The URL for this action would look like this
# in order to list activated clients: /clients?status=activated
def index
if params[:status] = "activated"
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index 5157e62788..9c56691dc1 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -184,7 +184,7 @@ class UserMailer < ActionMailer::Base
sent_on Time.now
body {:user => user, :url => "http://example.com/login"}
content_type "text/html"
-
+
# change the default from welcome_email.[html, txt].erb
template "some_other_template" # this will be in app/views/user_mailer/some_other_template.[html, txt].erb
end
@@ -254,15 +254,15 @@ class UserMailer < ActionMailer::Base
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
-
+
part :content_type => "text/html",
:body => "<p>html content, can also be the name of an action that you call<p>"
-
+
part "text/plain" do |p|
p.body = "text content, can also be the name of an action that you call"
end
end
-
+
end
</ruby>
@@ -278,15 +278,15 @@ class UserMailer < ActionMailer::Base
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
-
+
attachment :content_type => "image/jpeg",
:body => File.read("an-image.jpg")
-
+
attachment "application/pdf" do |a|
a.body = generate_your_pdf_here()
end
end
-
+
end
</ruby>
@@ -307,21 +307,21 @@ class UserMailer < ActionMailer::Base
def receive(email)
page = Page.find_by_address(email.to.first)
page.emails.create(
- :subject => email.subject,
+ :subject => email.subject,
:body => email.body
)
if email.has_attachments?
for attachment in email.attachments
- page.attachments.create({
- :file => attachment,
+ page.attachments.create({
+ :file => attachment,
:description => email.subject
})
end
end
end
-
-
+
+
end
</ruby>
@@ -363,8 +363,8 @@ ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
-ActionMailer::Base.perform_deliveries = true
-ActionMailer::Base.raise_delivery_errors = true
+ActionMailer::Base.perform_deliveries = true
+ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "iso-8859-1"
</ruby>
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index 5446c5dd81..ab3e4c6e96 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -8,7 +8,7 @@ After reading this guide we hope that you'll be able to:
* Create basic Active Record models and map them with your database tables.
* Use your models to execute CRUD (Create, Read, Update and Delete) database operations.
* Follow the naming conventions used by Rails to make developing database applications easier and obvious.
-* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic.
+* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic.
* Use Active Record with legacy databases that do not follow the Rails naming conventions.
endprologue.
@@ -39,7 +39,7 @@ ActiveRecord gives us several mechanisms, being the most important ones the habi
* Validate models before they get recorded to the database.
* Perform database operations in an object-oriented fashion.
-It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
+It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
h3. Active Record inside the MVC model
@@ -54,7 +54,7 @@ h4. Naming Conventions
By default, ActiveRecord uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:
* Database Table - Plural with underscores separating words i.e. (book_clubs)
-* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
+* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
|_.Model / Class |_.Table / Schema |
|Post |posts|
@@ -109,7 +109,7 @@ puts p.name # "Some Book"
h3. Overriding the naming conventions
-What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
+What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
<ruby>
diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile
index c84b458a8c..28948eca77 100644
--- a/railties/guides/source/activerecord_validations_callbacks.textile
+++ b/railties/guides/source/activerecord_validations_callbacks.textile
@@ -23,7 +23,7 @@ Before you dive into the detail of validations in Rails, you should understand a
h4. Why Use ActiveRecord Validations?
-The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
+The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
There are several ways that you could validate the data that goes to the database, including native database constraints, client-side validations, and model-level validations. Each of these has pros and cons:
@@ -31,7 +31,7 @@ There are several ways that you could validate the data that goes to the databas
* Implementing validations only at the client side can be difficult in web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
* Using validation directly in your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the ability to easily create validations, providing built-in helpers for common validations while still allowing you to create your own validation methods.
-# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
+# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
# http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
h4. When Does Validation Happen?
@@ -58,7 +58,7 @@ We can see how it works by looking at some script/console output:
Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not trigger the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an object in the database that's invalid. You can choose to have specific validations run when an object is created, saved, or updated.
-CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
+CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
The following methods trigger validations, and will save the object to the database only if the object is valid. The bang versions (e.g. +save!+) will raise an exception if the record is invalid. The non-bang versions (e.g. +save+) simply return +false+.
@@ -100,7 +100,7 @@ Person.create(:name => "John Doe").valid? # => true
Person.create.valid? # => false
</ruby>
-When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.
+When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.
However, note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.
@@ -129,20 +129,20 @@ end
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>
-To verify whether or not a particular attribute of an object is valid, you can use the +invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +valid?+ method because it doesn't verify the validity of the object as a whole, but only if there are errors found on an individual attribute of the object.
+To verify whether or not a particular attribute of an object is valid, you can use the +invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +valid?+ method because it doesn't verify the validity of the object as a whole, but only if there are errors found on an individual attribute of the object.
<ruby>
class Person < ActiveRecord::Base
validates_presence_of :name
end
-
+
>> Person.new.errors.invalid?(:name) # => false
>> Person.create.errors.invalid?(:name) # => true
</ruby>
h3. Declarative Validation Helpers
-Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
+Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
Each helper accepts an arbitrary number of attributes identified by symbols, so with a single line of code you can add the same kind of validation to several attributes.
@@ -219,7 +219,7 @@ This helper validates that the attributes' values are not included in a given se
<ruby>
class MovieFile < ActiveRecord::Base
- validates_exclusion_of :format, :in => %w(mov avi),
+ validates_exclusion_of :format, :in => %w(mov avi),
:message => "Extension %s is not allowed"
end
</ruby>
@@ -234,7 +234,7 @@ This helper validates the attributes' values by testing whether they match a giv
<ruby>
class Product < ActiveRecord::Base
- validates_format_of :description, :with => /^[a-zA-Z]+$/,
+ validates_format_of :description, :with => /^[a-zA-Z]+$/,
:message => "Only letters allowed"
end
</ruby>
@@ -247,7 +247,7 @@ This helper validates that the attributes' values are included in a given set. I
<ruby>
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large),
+ validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size"
end
</ruby>
@@ -273,7 +273,7 @@ The possible length constraint options are:
* +:minimum+ - The attribute cannot have less than the specified length.
* +:maximum+ - The attribute cannot have more than the specified length.
-* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
* +:is+ - The attribute length must be equal to a given value.
The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
@@ -314,7 +314,7 @@ The default error message for +validates_numericality_of+ is "_is not a number_"
h4. validates_presence_of
-This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
+This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
<ruby>
class Person < ActiveRecord::Base
@@ -331,7 +331,7 @@ class LineItem < ActiveRecord::Base
end
</ruby>
-NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
+NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
The default error message for +validates_presence_of+ is "_can't be empty_".
@@ -351,7 +351,7 @@ There is a +:scope+ option that you can use to specify other attributes that are
<ruby>
class Holiday < ActiveRecord::Base
- validates_uniqueness_of :name, :scope => :year,
+ validates_uniqueness_of :name, :scope => :year,
:message => "Should happen once per year"
end
</ruby>
@@ -390,7 +390,7 @@ The +:allow_nil+ option skips the validation when the value being validated is +
<ruby>
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large),
+ validates_inclusion_of :size, :in => %w(small medium large),
:message => "%s is not a valid size", :allow_nil => true
end
</ruby>
@@ -419,13 +419,13 @@ The +:on+ option lets you specify when the validation should happen. The default
<ruby>
class Person < ActiveRecord::Base
# => it will be possible to update email with a duplicated value
- validates_uniqueness_of :email, :on => :create
-
+ validates_uniqueness_of :email, :on => :create
+
# => it will be possible to create the record with a 'non-numerical age'
- validates_numericality_of :age, :on => :update
-
+ validates_numericality_of :age, :on => :update
+
# => the default (validates on both create and update)
- validates_presence_of :name, :on => :save
+ validates_presence_of :name, :on => :save
end
</ruby>
@@ -440,7 +440,7 @@ You can associate the +:if+ and +:unless+ options with a symbol corresponding to
<ruby>
class Order < ActiveRecord::Base
validates_presence_of :card_number, :if => :paid_with_card?
-
+
def paid_with_card?
payment_type == "card"
end
@@ -463,7 +463,7 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object
<ruby>
class Account < ActiveRecord::Base
- validates_confirmation_of :password,
+ validates_confirmation_of :password,
:unless => Proc.new { |a| a.password.blank? }
end
</ruby>
@@ -474,16 +474,16 @@ When the built-in validation helpers are not enough for your needs, you can writ
<ruby>
class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past,
+ validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
- errors.add(:expiration_date, "can't be in the past") if
+ errors.add(:expiration_date, "can't be in the past") if
!expiration_date.blank? and expiration_date < Date.today
- end
-
+ end
+
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") unless
+ errors.add(:discount, "can't be greater than total value") unless
discount <= total_value
end
end
@@ -567,7 +567,7 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
-person.errors.on(:name)
+person.errors.on(:name)
# => "is too short (minimum is 3 characters)"
person = Person.new
@@ -586,11 +586,11 @@ end
person = Person.new
person.valid? # => false
-person.errors.on(:name)
+person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.clear
-person.errors.empty? # => true
+person.errors.empty? # => true
p.save # => false
p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
@@ -655,7 +655,7 @@ It's also possible to change the CSS classes used by the +error_messages+ helper
* +.fieldWithErrors+ - Style for the form fields with errors.
* +#errorExplanation+ - Style for the +div+ element with the error messages.
-* +#errorExplanation h2+ - Style for the header of the +div+ element.
+* +#errorExplanation h2+ - Style for the header of the +div+ element.
* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
* +#errorExplanation ul li+ - Style for the list of error messages.
@@ -679,7 +679,7 @@ This will result in something like the following content:
!images/validation_error_messages.png(Validation error messages)!
-The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:
+The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:
* A string with the HTML tag
* An object of the +ActionView::Helpers::InstanceTag+ class.
@@ -689,7 +689,7 @@ h3. Callbacks
Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.
# TODO discuss what does/doesn't trigger callbacks, like we did in the validations section (e.g. destroy versus delete).
-# Consider moving up to the (new) intro overview section, before getting into details.
+# Consider moving up to the (new) intro overview section, before getting into details.
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002220
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
@@ -700,15 +700,15 @@ In order to use the available callbacks, you need to register them. You can do t
<ruby>
class User < ActiveRecord::Base
validates_presence_of :login, :email
-
+
before_validation :ensure_login_has_a_value
-
+
protected
def ensure_login_has_a_value
if self.login.nil?
self.login = email unless email.blank?
end
- end
+ end
end
</ruby>
@@ -717,7 +717,7 @@ The macro-style class methods can also receive a block. Rails best practices say
<ruby>
class User < ActiveRecord::Base
validates_presence_of :login, :email
-
+
before_create {|user| user.name = user.login.capitalize if user.name.blank?}
end
</ruby>
@@ -756,7 +756,7 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object.
<ruby>
class Order < ActiveRecord::Base
- before_save :normalize_card_number,
+ before_save :normalize_card_number,
:if => Proc.new { |order| order.paid_with_card? }
end
</ruby>
@@ -767,14 +767,14 @@ When writing conditional callbacks, it's possible to mix both +:if+ and +:unless
<ruby>
class Comment < ActiveRecord::Base
- after_create :send_email_to_author, :if => :author_wants_emails?,
+ after_create :send_email_to_author, :if => :author_wants_emails?,
:unless => Proc.new { |comment| comment.post.ignore_comments? }
end
</ruby>
h3. Available callbacks
-# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
+# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.
@@ -783,16 +783,16 @@ h4. Callbacks called both when creating or updating a record.
# TODO consider just listing these in the possible lifecycle of an object, roughly as they do here:
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
-* +before_validation+
-* +after_validation+
-* +before_save+
+* +before_validation+
+* +after_validation+
+* +before_save+
* *INSERT OR UPDATE OPERATION*
-* +after_save+
+* +after_save+
h4. Callbacks called only when creating a new record.
-* +before_validation_on_create+
-* +after_validation_on_create+
+* +before_validation_on_create+
+* +after_validation_on_create+
* +before_create+
* *INSERT OPERATION*
* +after_create+
@@ -817,7 +817,7 @@ h4. after_initialize and after_find callbacks
The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
-The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
+The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
@@ -854,7 +854,7 @@ class PictureFileCallbacks
def self.after_destroy(picture_file)
File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
end
-end
+end
</ruby>
If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.
@@ -887,7 +887,7 @@ end
Like in callback classes, the observer's methods receive the observed model as a parameter.
-Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.
+Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.
<ruby>
class Auditor < ActiveRecord::Observer
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index b18bc47d80..43e81123e9 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -23,7 +23,7 @@ end
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
<ruby>
-@order = Order.create(:order_date => Time.now,
+@order = Order.create(:order_date => Time.now,
:customer_id => @customer.id)
</ruby>
@@ -268,7 +268,7 @@ class Part < ActiveRecord::Base
end
</ruby>
-The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
+The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
@@ -290,7 +290,7 @@ class Product < ActiveRecord::Base
end
</ruby>
-You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
+You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
Similarly, you can retrieve +@product.pictures+.
@@ -371,7 +371,7 @@ But what if you want to reload the cache, because data might have been changed b
<ruby>
customer.orders # retrieves orders from the database
customer.orders.size # uses the cached copy of orders
-customer.orders(true).empty? # discards the cached copy of orders
+customer.orders(true).empty? # discards the cached copy of orders
# and goes back to the database
</ruby>
@@ -400,8 +400,8 @@ class CreateOrders < ActiveRecord::Migration
def self.up
create_table :orders do |t|
t.datetime :order_date
- t.string :order_number
- t.integer :customer_id
+ t.string :order_number
+ t.integer :customer_id
end
end
@@ -415,7 +415,7 @@ If you create an association some time after you build the underlying model, you
h5. Creating Join Tables for has_and_belongs_to_many Associations
-If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
@@ -490,14 +490,14 @@ To associate a model with a model in a different scope, you must specify the com
module MyApplication
module Business
class Supplier < ActiveRecord::Base
- has_one :account,
+ has_one :account,
:class_name => "MyApplication::Billing::Account"
end
end
module Billing
class Account < ActiveRecord::Base
- belongs_to :supplier,
+ belongs_to :supplier,
:class_name => "MyApplication::Business::Supplier"
end
end
@@ -573,7 +573,7 @@ h6. build_<em>association</em>(attributes = {})
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
<ruby>
-@customer = @order.build_customer({:customer_number => 123,
+@customer = @order.build_customer({:customer_number => 123,
:customer_name => "John Doe"})
</ruby>
@@ -582,7 +582,7 @@ h6. create_<em>association</em>(attributes = {})
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
<ruby>
-@customer = @order.create_customer({:customer_number => 123,
+@customer = @order.create_customer({:customer_number => 123,
:customer_name => "John Doe"})
</ruby>
@@ -592,7 +592,7 @@ In many situations, you can use the default behavior of +belongs_to+ without any
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true,
+ belongs_to :customer, :counter_cache => true,
:conditions => "active = 1"
end
</ruby>
@@ -659,7 +659,7 @@ class Customer < ActiveRecord::Base
end
</ruby>
-With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
+With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
@@ -686,7 +686,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi
<ruby>
class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron",
+ belongs_to :customer, :class_name => "Patron",
:foreign_key => "patron_id"
end
</ruby>
@@ -1109,7 +1109,7 @@ h6. <em>collection</em>.build(attributes = {}, ...)
The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
<ruby>
-@order = @customer.orders.build({:order_date => Time.now,
+@order = @customer.orders.build({:order_date => Time.now,
:order_number => "A12345"})
</ruby>
@@ -1118,7 +1118,7 @@ h6. <em>collection</em>.create(attributes = {})
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
<ruby>
-@order = @customer.orders.create({:order_date => Time.now,
+@order = @customer.orders.create({:order_date => Time.now,
:order_number => "A12345"})
</ruby>
@@ -1181,7 +1181,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
<ruby>
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
+ has_many :confirmed_orders, :class_name => "Order",
:conditions => "confirmed = 1"
end
</ruby>
@@ -1190,7 +1190,7 @@ You can also set conditions via a hash:
<ruby>
class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
+ has_many :confirmed_orders, :class_name => "Order",
:conditions => { :confirmed => true }
end
</ruby>
@@ -1199,7 +1199,7 @@ If you use a hash-style +:conditions+ option, then record creation via this asso
h6. :counter_sql
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
@@ -1281,7 +1281,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f
<ruby>
class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => "Order",
+ has_many :recent_orders, :class_name => "Order",
:order => "order_date DESC", :limit => 100
end
</ruby>
@@ -1468,7 +1468,7 @@ h6. <em>collection</em>.find(...)
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.find(:all,
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
@@ -1500,7 +1500,7 @@ In many situations, you can use the default behavior for +has_and_belongs_to_man
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :uniq => true,
+ has_and_belongs_to_many :assemblies, :uniq => true,
:read_only => true
end
</ruby>
@@ -1536,8 +1536,8 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s
<ruby>
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
</ruby>
@@ -1562,7 +1562,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
+ has_and_belongs_to_many :assemblies,
:conditions => "factory = 'Seattle'"
end
</ruby>
@@ -1571,7 +1571,7 @@ You can also set conditions via a hash:
<ruby>
class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
+ has_and_belongs_to_many :assemblies,
:conditions => { :factory => 'Seattle' }
end
</ruby>
@@ -1580,7 +1580,7 @@ If you use a hash-style +:conditions+ option, then record creation via this asso
h6. :counter_sql
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
@@ -1602,8 +1602,8 @@ By convention, Rails guesses that the column in the join table used to hold the
<ruby>
class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
</ruby>
@@ -1620,7 +1620,7 @@ end
h6. :include
-You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
h6. :insert_sql
@@ -1710,7 +1710,7 @@ You can stack callbacks on a single event by passing them as an array:
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders,
+ has_many :orders,
:before_add => [:check_credit_limit, :calculate_shipping_charges]
def check_credit_limit(order)
@@ -1761,7 +1761,7 @@ To include more than one extension module in a single association, specify an ar
<ruby>
class Customer < ActiveRecord::Base
- has_many :orders,
+ has_many :orders,
:extend => [FindRecentExtension, FindActiveExtension]
end
</ruby>
@@ -1776,7 +1776,7 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11
-* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
+* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
* September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
index 456b0c48a7..940466ecb3 100644
--- a/railties/guides/source/caching_with_rails.textile
+++ b/railties/guides/source/caching_with_rails.textile
@@ -27,7 +27,7 @@ page to be fulfilled by the webserver, without ever having to go through the
Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
-expiration is an issue that needs to be dealt with.
+expiration is an issue that needs to be dealt with.
So, how do you enable this super-fast cache behavior? Simple, let's say you
have a controller called ProductsController and a 'list' action that lists all
@@ -95,7 +95,7 @@ result of the output from a cached copy.
Clearing the cache works in the exact same way as with Page Caching.
Let's say you only wanted authenticated users to edit or create a Product
-object, but still cache those pages:
+object, but still cache those pages:
<ruby>
class ProductsController < ActionController
@@ -138,7 +138,7 @@ created page where different parts of the page need to be cached and expired
differently Rails provides a mechanism called Fragment Caching.
Fragment Caching allows a fragment of view logic to be wrapped in a cache
-block and served out of the cache store when the next request comes in.
+block and served out of the cache store when the next request comes in.
As an example, if you wanted to show all the orders placed on your website
in real time and didn't want to cache that part of the page, but did want
@@ -149,9 +149,9 @@ could use this piece of code:
<% Order.find_recent.each do |o| %>
<%= o.buyer.name %> bought <% o.product.name %>
<% end %>
-
+
<% cache do %>
- All available products:
+ All available products:
<% Product.find(:all).each do |p| %>
<%= link_to p.name, product_url(p) %>
<% end %>
@@ -164,7 +164,7 @@ want to cache multiple fragments per action, you should provide an +action_suffi
<ruby>
<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
- All available products:
+ All available products:
</ruby>
and you can expire it using the +expire_fragment+ method, like so:
@@ -179,7 +179,7 @@ so:
<ruby>
<% cache(:key => ['all_available_products', @latest_product.created_at].join(':')) do %>
- All available products:
+ All available products:
<% end %>
</ruby>
@@ -212,23 +212,23 @@ class StoreSweeper < ActionController::Caching::Sweeper
def after_create(product)
expire_cache_for(product)
end
-
+
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
-
+
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
-
+
private
def expire_cache_for(record)
# Expire the list page now that we added a new product
expire_page(:controller => '#{record}', :action => 'list')
-
- # Expire a fragment
+
+ # Expire a fragment
expire_fragment(:controller => '#{record}', :action => 'recent', :action_suffix => 'all_products')
end
end
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
index 788629617b..b1a3dace16 100644
--- a/railties/guides/source/command_line.textile
+++ b/railties/guides/source/command_line.textile
@@ -21,7 +21,7 @@ There are a few commands that are absolutely critical to your everyday usage of
* rake
* generate
* rails
-
+
Let's create a simple Rails application to step through each of these commands in context.
h4. rails
@@ -33,7 +33,7 @@ WARNING: You know you need the rails gem installed by typing +gem install rails+
<shell>
$ rails commandsapp
- create
+ create
create app/controllers
create app/helpers
create app/models
@@ -190,7 +190,7 @@ Examples:
creates a Post model with a string title, text body, and published flag.
</shell>
-But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
+But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
@@ -345,7 +345,7 @@ $ cd gitapp
$ git init
Initialized empty Git repository in .git/
$ rails . --git --database=postgresql
- exists
+ exists
create app/controllers
create app/helpers
...
@@ -367,7 +367,7 @@ add 'log/test.log'
We had to create the *gitapp* directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
<shell>
-$ cat config/database.yml
+$ cat config/database.yml
# PostgreSQL. Versions 7.4 and 8.x are supported.
#
# Install the ruby-postgres driver:
@@ -448,7 +448,7 @@ class TutorialTestGenerator < Rails::Generator::Base
super(*runtime_args)
@tut_args = runtime_args
end
-
+
def manifest
record do |m|
m.directory "public"
@@ -469,10 +469,10 @@ We take whatever args are supplied, save them to an instance variable, and liter
Next we'll build the template:
<shell>
-$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
+$ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
I'm a template!
-I got assigned some args:
+I got assigned some args:
<%= require 'pp'; PP.pp(args, "") %>
</shell>
@@ -497,10 +497,10 @@ $ ./script/generate tutorial_test arg1 arg2 arg3
And the result:
<shell>
-$ cat public/tutorial.txt
+$ cat public/tutorial.txt
I'm a template!
-I got assigned some args:
+I got assigned some args:
[["arg1", "arg2", "arg3"],
{:collision=>:ask,
:quiet=>false,
@@ -508,4 +508,4 @@ I got assigned some args:
:command=>:create}]
</shell>
-Tada! \ No newline at end of file
+Tada!
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index f096747b52..dd89bef027 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -193,14 +193,14 @@ Here's an example of the log generated by this method:
Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
- Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
- "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
+ "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
"authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
-New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
"published"=>false, "created_at"=>nil}
Post should be valid: true
- Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
- "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
+ "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
The post was saved and now is the user is going to be redirected...
Redirected to #<Post:0x20af760>
@@ -646,8 +646,8 @@ Make sure to run a couple hundred requests to get better data samples, then pres
** BleakHouse: complete
** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
</shell>
-
-To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
+
+To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
<shell>
191691 total objects
@@ -682,7 +682,7 @@ There are some Rails plugins to help you to find errors and debug your applicati
* "Footnotes":http://github.com/drnic/rails-footnotes/tree/master: Every Rails page has footnotes that give request information and link back to your source via TextMate.
* "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
-* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
+* "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
* "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
* "Exception Notifier":http://github.com/rails/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
* "Exception Logger":http://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index 8d29816e54..4e61bdcd26 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -273,7 +273,7 @@ which produces the following output:
<html>
<form action="/people/create" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
+ <input id="person_name" name="person[name]" size="30" type="text" />
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
</form>
</html>
@@ -553,7 +553,7 @@ h3. Uploading Files
A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash.
-The following two forms both upload a file.
+The following two forms both upload a file.
<erb>
<% form_tag({:action => :upload}, :multipart => true) do %>
@@ -590,7 +590,7 @@ Unlike other forms making an asynchronous file upload form is not as simple as r
h3. Customising Form Builders
-As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example
+As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example
<erb>
<% form_for @person do |f| %>
@@ -598,7 +598,7 @@ As mentioned previously the object yielded by +form_for+ and +fields_for+ is an
<% end %>
</erb>
-can be replaced with
+can be replaced with
<erb>
<% form_for @person, :builder => LabellingFormBuilder do |f| %>
@@ -698,9 +698,9 @@ You might want to render a form with a set of edit fields for each of a person's
<erb>
<% form_for @person do |person_form| %>
<%= person_form.text_field :name %>
- <% for address in @person.addresses %>
+ <% for address in @person.addresses %>
<% person_form.fields_for address, :index => address do |address_form|%>
- <%= address_form.text_field :city %>
+ <%= address_form.text_field :city %>
<% end %>
<% end %>
<% end %>
@@ -711,8 +711,8 @@ Assuming the person had two addresses, with ids 23 and 45 this would create outp
<html>
<form action="/people/1" class="edit_person" id="edit_person_1" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
- <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
- <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
+ <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
+ <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
</form>
</html>
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index bdd2a9d429..3163fdb4bc 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -248,7 +248,7 @@ Now that you have your database configured, it's time to have Rails create an em
$ rake db:create
</shell>
-NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+.
+NOTE. Rake is a general-purpose command-runner that Rails uses for many things. You can see the list of available rake commands in your application by running +rake -T+.
h3. Hello, Rails!
@@ -313,7 +313,7 @@ NOTE. For more information about routing, refer to "Rails Routing from the Outsi
h3. Getting Up and Running Quickly With Scaffolding
-Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
+Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
h3. Creating a Resource
@@ -440,14 +440,14 @@ After the console loads, you can use it to work with your application's models:
<shell>
>> p = Post.create(:content => "A new post")
-=> #<Post id: nil, name: nil, title: nil, content: "A new post",
+=> #<Post id: nil, name: nil, title: nil, content: "A new post",
created_at: nil, updated_at: nil>
>> p.save
=> false
>> p.errors
-=> #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
-title: nil, content: "A new post", created_at: nil, updated_at: nil>,
-@errors={"name"=>["can't be blank"], "title"=>["can't be blank",
+=> #<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
+title: nil, content: "A new post", created_at: nil, updated_at: nil>,
+@errors={"name"=>["can't be blank"], "title"=>["can't be blank",
"is too short (minimum is 5 characters)"]}>
</shell>
@@ -493,7 +493,7 @@ The +respond_to+ block handles both HTML and XML calls to this action. If you br
<td><%=h post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
- <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
:method => :delete %></td>
</tr>
<% end %>
@@ -522,7 +522,7 @@ The view is only part of the story of how HTML is displayed in your web browser.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
- <meta http-equiv="content-type"
+ <meta http-equiv="content-type"
content="text/html;charset=UTF-8" />
<title>Posts: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
@@ -596,11 +596,11 @@ def create
if @post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(@post) }
- format.xml { render :xml => @post, :status => :created,
+ format.xml { render :xml => @post, :status => :created,
:location => @post }
else
format.html { render :action => "new" }
- format.xml { render :xml => @post.errors,
+ format.xml { render :xml => @post.errors,
:status => :unprocessable_entity }
end
end
@@ -701,7 +701,7 @@ def update
format.xml { head :ok }
else
format.html { render :action => "edit" }
- format.xml { render :xml => @post.errors,
+ format.xml { render :xml => @post.errors,
:status => :unprocessable_entity }
end
end
@@ -796,7 +796,7 @@ class PostsController < ApplicationController
# ...
def show
@post = Post.find(params[:id])
- # ...
+ # ...
end
def edit
@@ -819,11 +819,11 @@ Four instances of the exact same line of code doesn’t seem very DRY. Rails pro
<ruby>
class PostsController < ApplicationController
- before_filter :find_post,
+ before_filter :find_post,
:only => [:show, :edit, :update, :destroy]
# ...
def show
- # ...
+ # ...
end
def edit
@@ -852,12 +852,12 @@ h3. Adding a Second Model
Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.
-h4. Generating a Model
+h4. Generating a Model
Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal:
<shell>
-$ script/generate model Comment commenter:string body:text
+$ script/generate model Comment commenter:string body:text
post:references
</shell>
@@ -1011,7 +1011,7 @@ class CommentsController < ApplicationController
render :action => "new"
end
end
-
+
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@@ -1075,7 +1075,7 @@ The +views/comments/index.html.erb+ view:
<%= link_to 'Edit', edit_post_comment_path(@post, comment) %>
</td>
<td>
- <%= link_to 'Destroy', post_comment_path(@post, comment),
+ <%= link_to 'Destroy', post_comment_path(@post, comment),
:confirm => 'Are you sure?', :method => :delete %>
</td>
</tr>
@@ -1220,7 +1220,7 @@ class Post < ActiveRecord::Base
validates_length_of :title, :minimum => 5
has_many :comments
has_many :tags
-
+
accepts_nested_attributes_for :tags, :allow_destroy => :true ,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
@@ -1294,4 +1294,4 @@ h3. Changelog
* October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
* October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 8, 2008: initial version by James Miller (not yet approved for publication) \ No newline at end of file
+* September 8, 2008: initial version by James Miller (not yet approved for publication)
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 53a0cc2834..c5025eb86b 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -93,7 +93,7 @@ The I18n library will use *English* as a *default locale*, ie. if you don't set
NOTE: The i18n library takes *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". (For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Also, insults would be different in American and British English :) Reason for this pragmatic approach is that most of the time, you usually care about making your application available in different "languages", and working with locales is much simpler this way. However, nothing stops you from separating regional and other settings in the traditional way. In this case, you could eg. inherit from the default +en+ locale and then provide UK specific settings in a +:en-UK+ dictionary.
-The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
+The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
@@ -145,7 +145,7 @@ This requires you to pass the locale as a URL query parameter as in +http://exam
Of course, you probably don't want to manually include locale in every URL all over your application, or want the URLs look differently, eg. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.
-IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.)
+IMPORTANT: Following examples rely on having locales loaded into your application available as an array of strings like +["en", "es", "gr"]+. This is not inclued in current version of Rails 2.2 -- forthcoming Rails version 2.3 will contain easy accesor +available_locales+. (See "this commit":http://github.com/svenfuchs/i18n/commit/411f8fe7 and background at "Rails I18n Wiki":http://rails-i18n.org/wiki/pages/i18n-available_locales.)
So, for having available locales easily available in Rails 2.2, we have to include this support manually in an initializer, like this:
@@ -314,7 +314,7 @@ h3. Internationalizing your application
OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale should be used and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
-Let's _internationalize_ our application, ie. abstract every locale-specific parts, and that _localize_ it, ie. provide neccessary translations for these abstracts.
+Let's _internationalize_ our application, ie. abstract every locale-specific parts, and that _localize_ it, ie. provide neccessary translations for these abstracts.
You most probably have something like this in one of your applications:
@@ -323,7 +323,7 @@ You most probably have something like this in one of your applications:
ActionController::Routing::Routes.draw do |map|
map.root :controller => 'home', :action => 'index'
end
-
+
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
@@ -368,12 +368,12 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
en:
hello_world: Hello World
hello_flash: Hello Flash
-
+
# config/locale/pirate.yml
pirate:
hello_world: Ahoy World
hello_flash: Ahoy Flash
-</ruby>
+</ruby>
There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
@@ -551,7 +551,7 @@ The +:count+ interpolation variable has a special role in that it both is interp
<ruby>
I18n.backend.store_translations :en, :inbox => {
- :one => '1 message',
+ :one => '1 message',
:other => '{{count}} messages'
}
I18n.translate :inbox, :count => 2
@@ -561,7 +561,7 @@ I18n.translate :inbox, :count => 2
The algorithm for pluralizations in +:en+ is as simple as:
<ruby>
-entry[count == 1 ? 0 : 1]
+entry[count == 1 ? 0 : 1]
</ruby>
I.e. the translation denoted as +:one+ is regarded as singular, the other is used as plural (including the count being zero).
@@ -576,7 +576,7 @@ If no locale is passed +I18n.locale+ is used:
<ruby>
I18n.locale = :de
-I18n.t :foo
+I18n.t :foo
I18n.l Time.now
</ruby>
@@ -615,7 +615,7 @@ The equivalent YAML file would look like this:
pt:
foo:
bar: baz
-</ruby>
+</ruby>
As you see in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
@@ -657,9 +657,9 @@ en:
login: "Handle"
# will translate User attribute "login" as "Handle"
</ruby>
-
+
Then +User.human_name+ will return "Dude" and +User.human_attribute_name(:login)+ will return "Handle".
-
+
h5. Error message scopes
Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.
@@ -690,7 +690,7 @@ activerecord.errors.messages.models.user.blank
activerecord.errors.messages.blank
</ruby>
-When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.
+When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.
For example, you might have an Admin model inheriting from User:
@@ -810,9 +810,9 @@ ReservedInterpolationKey # the translation contains a reserved interpolation
UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
</ruby>
-The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught it will return the exception’s error message string containing the missing key/scope.
+The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught it will return the exception’s error message string containing the missing key/scope.
-The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
+The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
@@ -855,7 +855,7 @@ If you find your own locale (language) missing from our "example translations da
h3. Resources
* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
+* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index b1ac7d36f8..141471a50f 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -1,7 +1,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
+
<title><%= yield(:page_title) || 'Ruby on Rails guides' %></title>
<link rel="stylesheet" type="text/css" href="files/stylesheets/style.css" />
@@ -67,11 +67,11 @@
</li>
<li><a href="http://hackfest.rubyonrails.org">Contribute</a></li>
<li><a href="credits.html">Credits</a></li>
- </ul>
+ </ul>
</div>
</div>
<hr class="hide" />
-
+
<div id="feature">
<div class="wrapper">
<%= yield :header_section %>
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index dbaaed2281..d4738ec19f 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -228,7 +228,7 @@ render :file => filename, :content_type => 'application/rss'
h6. The :layout Option
-With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
+With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
@@ -296,7 +296,7 @@ You can use a symbol to defer the choice of layout until a request is processed:
<ruby>
class ProductsController < ApplicationController
layout :products_layout
-
+
def show
@product = Product.find(params[:id])
end
@@ -314,7 +314,7 @@ Now, if the current user is a special user, they'll get a special layout when vi
<ruby>
class ProductsController < ApplicationController
layout proc{ |controller| controller.
- # ...
+ # ...
end
</ruby>
@@ -725,7 +725,7 @@ The +content_for+ method is very helpful when your layout contains distinct regi
h4. Using Partials
-Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
h5. Naming Partials
@@ -826,7 +826,7 @@ If you have an instance of a model to render into a partial, you can use a short
Assuming that the +@customer+ instance variable contains an instance of the +Customer+ model, this will use +_customer.html.erb+ to render it.
-h5. Rendering Collections
+h5. Rendering Collections
Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection:
@@ -949,9 +949,9 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15
* December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates
-* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy
-* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy
-* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy
-* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy
+* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy
+* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy
+* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy
+* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) \ No newline at end of file
+* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index 9e7597ff22..58ae54f53f 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -1,6 +1,6 @@
h2. Migrations
-Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.
+Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.
Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
@@ -15,7 +15,7 @@ endprologue.
h3. Anatomy Of A Migration
-Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
+Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
<ruby>
class CreateProducts < ActiveRecord::Migration
@@ -70,7 +70,7 @@ Active Record provides methods that perform common data definition tasks in a da
* +add_column+
* +remove_column+
* +change_column+
-* +rename_column+
+* +rename_column+
* +add_index+
* +remove_index+
@@ -340,12 +340,12 @@ class ExampleMigration < ActiveRecord::Migration
end
#add a foreign key
execute "ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id)"
-
+
add_column :users, :home_page_url, :string
-
+
rename_column :users, :email, :email_address
end
-
+
def self.down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
@@ -473,7 +473,7 @@ If you just want Active Record to shut up then running +rake db:migrate VERBOSE=
h3. Using Models In Your Migrations
-When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
+When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with +rake db:migrate+, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist.
@@ -483,7 +483,7 @@ Frequently I just want to update rows in the database without writing out the SQ
class AddPartNumberToProducts < ActiveRecord::Migration
class Product < ActiveRecord::Base
end
-
+
def self.up
...
end
@@ -503,7 +503,7 @@ For performance reasons information about the columns a model has is cached. For
class AddPartNumberToProducts < ActiveRecord::Migration
class Product < ActiveRecord::Base
end
-
+
def self.up
add_column :product, :part_number, :string
Product.reset_column_information
@@ -555,7 +555,7 @@ end
In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using +create_table+, +add_index+ and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
-There is however a trade-off: +schema.rb+ cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to +:sql+.
+There is however a trade-off: +schema.rb+ cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to +:sql+.
Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the +db:structure:dump+ Rake task) into +db/#{RAILS_ENV}_structure.sql+. For example for PostgreSQL the +pg_dump+ utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.
@@ -577,4 +577,4 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/6
-* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung \ No newline at end of file
+* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index 578625783e..972b7aac50 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -88,7 +88,7 @@ class Post < ActiveRecord::Base
end
private
-
+
def recalculate_costly_stats
# CPU heavy calculations
end
@@ -97,7 +97,7 @@ end
h5. Controller Example
-Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
+Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
Here's the performance test for +HomeController#dashboard+ and +PostsController#create+:
@@ -151,7 +151,7 @@ Performance tests can be run in two modes : Benchmarking and Profiling.
h5. Benchmarking
-Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode.
+Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode.
To run performance tests in benchmarking mode:
@@ -161,7 +161,7 @@ $ rake test:benchmark
h5. Profiling
-Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode.
+Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode.
To run performance tests in profiling mode:
@@ -305,7 +305,7 @@ As +ActionController::Base.perform_caching+ is set to +true+, performance tests
h4. Installing GC-Patched Ruby
-To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation.
+To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation.
The process is fairly straight forward. If you've never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory:
@@ -490,7 +490,7 @@ For this section, we're only interested in the last line:
Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]
</shell>
-This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
+This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric.
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 9096aecc91..c4fa7a88cd 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -222,18 +222,18 @@ require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
load_schema
-
+
class Hickwall < ActiveRecord::Base
end
class Wickwall < ActiveRecord::Base
end
-
+
def test_schema_has_loaded_correctly
assert_equal [], Hickwall.all
assert_equal [], Wickwall.all
end
-
+
end
</ruby>
@@ -247,7 +247,7 @@ rake
You should see output like:
<shell>
-/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
create_table(:hickwalls, {:force=>true})
-> 0.0220s
-- create_table(:wickwalls, {:force=>true})
@@ -507,18 +507,18 @@ class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
-
+
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
- end
-
+ end
+
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
- end
+ end
end
</ruby>
@@ -642,10 +642,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase
@controller = WoodpeckersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
-
+
ActionController::Routing::Routes.draw do |map|
map.resources :woodpeckers
- end
+ end
end
def test_index
@@ -672,11 +672,11 @@ end
<ruby>
class WoodpeckersController < ActionController::Base
-
+
def index
render :text => "Squawk!"
end
-
+
end
</ruby>
@@ -718,11 +718,11 @@ end
<ruby>
module WoodpeckersHelper
-
+
def tweet(text)
"Tweet! #{text}"
end
-
+
end
</ruby>
@@ -828,7 +828,7 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
def teardown
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_correct_file_name
Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
new_file = (file_list - @original_files).first
@@ -836,15 +836,15 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
end
private
-
+
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
-
+
def file_list
Dir.glob(File.join(fake_rails_root, "*"))
end
-
+
end
</ruby>
@@ -882,7 +882,7 @@ Installed Generators
Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
</shell>
-When you run +script/generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
+When you run +script/generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
For this plugin, update the USAGE file could look like this:
@@ -998,11 +998,11 @@ class RouteGeneratorTest < Test::Unit::TestCase
def setup
FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
end
-
+
def teardown
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_route
content = <<-END
ActionController::Routing::Routes.draw do |map|
@@ -1011,7 +1011,7 @@ class RouteGeneratorTest < Test::Unit::TestCase
end
END
File.open(routes_path, 'wb') {|f| f.write(content) }
-
+
Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
assert_match /map\.yaffles/, File.read(routes_path)
end
@@ -1025,21 +1025,21 @@ class RouteGeneratorTest < Test::Unit::TestCase
end
END
File.open(routes_path, 'wb') {|f| f.write(content) }
-
+
Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
assert_no_match /map\.yaffles/, File.read(routes_path)
end
-
+
private
-
+
def fake_rails_root
File.join(File.dirname(__FILE__), "rails_root")
end
-
+
def routes_path
File.join(fake_rails_root, "config", "routes.rb")
end
-
+
end
</ruby>
@@ -1152,7 +1152,7 @@ h4. Create a custom rake task
namespace :db do
namespace :migrate do
description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate"
- description << "and update db/schema.rb by invoking db:schema:dump."
+ description << "and update db/schema.rb by invoking db:schema:dump."
description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false."
desc description
@@ -1218,9 +1218,9 @@ class MigrationGeneratorTest < Test::Unit::TestCase
ActiveRecord::Base.pluralize_table_names = true
FileUtils.rm_r(fake_rails_root)
end
-
+
def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
:destination => fake_rails_root)
new_file = (file_list - @original_files).first
assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
@@ -1229,7 +1229,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase
def test_pluralizes_properly
ActiveRecord::Base.pluralize_table_names = false
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
:destination => fake_rails_root)
new_file = (file_list - @original_files).first
assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
@@ -1240,11 +1240,11 @@ class MigrationGeneratorTest < Test::Unit::TestCase
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
-
+
def file_list
Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
end
-
+
end
</ruby>
@@ -1348,14 +1348,14 @@ It's common practice to put any developer-centric rake tasks (such as tests, rdo
<ruby>
PKG_FILES = FileList[
'[a-zA-Z]*',
- 'generators/**/*',
- 'lib/**/*',
+ 'generators/**/*',
+ 'lib/**/*',
'rails/**/*',
- 'tasks/**/*',
+ 'tasks/**/*',
'test/**/*'
]
-spec = Gem::Specification.new do |s|
+spec = Gem::Specification.new do |s|
s.name = "yaffle"
s.version = "0.0.1"
s.author = "Gleeful Yaffler"
@@ -1372,7 +1372,7 @@ end
desc 'Turn this plugin into a gem.'
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
-end
+end
</ruby>
To build and install the gem locally, run the following commands:
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index 1166ec1c3b..8e169dd1fb 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -199,7 +199,7 @@ Metal applications are an optimization. You should make sure to "understand the
h4. Execution Order
-All Metal Applications are executed by +Rails::Rack::Metal+ middleware, which is a part of the +ActionController::MiddlewareStack+ chain.
+All Metal Applications are executed by +Rails::Rack::Metal+ middleware, which is a part of the +ActionController::MiddlewareStack+ chain.
Here's the primary method responsible for running the Metal applications:
@@ -223,4 +223,4 @@ h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4
-* January 11, 2009: First version by "Pratik":credits.html#lifo \ No newline at end of file
+* January 11, 2009: First version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 7dadbf0231..c31307e77f 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -22,7 +22,7 @@ GET /patients/17
</pre>
the routing engine within Rails is the piece of code that dispatches the request to the appropriate spot in your application. In this case, the application would most likely end up running the +show+ action within the +patients+ controller, displaying the details of the patient whose ID is 17.
-
+
h4. Generating URLs from Code
Routing also works in reverse. If your application contains this code:
@@ -111,7 +111,7 @@ h4. What is REST?
The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, "Architectural Styles and the Design of Network-based Software Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
-* Transferring representations of the state of that resource between system components.
+* Transferring representations of the state of that resource between system components.
For example, to a Rails application a request such as this:
@@ -120,7 +120,7 @@ DELETE /photos/17
</pre>
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities.
-
+
h4. CRUD, Verbs, and Actions
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as
@@ -170,7 +170,7 @@ If you need to create routes for more than one RESTful resource, you can save a
map.resources :photos, :books, :videos
</ruby>
-This has exactly the same effect as
+This has exactly the same effect as
<ruby>
map.resources :photos
@@ -229,7 +229,7 @@ The +:controller+ option lets you use a controller name that is different from t
map.resources :photos, :controller => "images"
</ruby>
-will recognize incoming URLs containing +photo+ but route the requests to the Images controller:
+will recognize incoming URLs containing +photo+ but route the requests to the Images controller:
|_.HTTP verb |_.URL |_.controller |_.action |_.used for|
|GET |/photos |Images |index |display a list of all images|
@@ -302,7 +302,7 @@ The +:as+ option lets you override the normal naming for the actual generated pa
map.resources :photos, :as => "images"
</ruby>
-will recognize incoming URLs containing +image+ but route the requests to the Photos controller:
+will recognize incoming URLs containing +image+ but route the requests to the Photos controller:
|_.HTTP verb |_.URL |_.controller |_.action |_:used for|
|GET |/images |Photos |index |display a list of all photos|
@@ -411,7 +411,7 @@ Each ad is logically subservient to one magazine. Nested routes allow you to cap
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads
-end
+end
</ruby>
In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL:
@@ -435,7 +435,7 @@ The +:name_prefix+ option overrides the automatically-generated prefix in nested
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads, :name_prefix => 'periodical'
-end
+end
</ruby>
This will create routing helpers such as +periodical_ads_url+ and +periodical_edit_ad_path+. You can even use +:name_prefix+ to suppress the prefix entirely:
@@ -443,7 +443,7 @@ This will create routing helpers such as +periodical_ads_url+ and +periodical_ed
<ruby>
map.resources :magazines do |magazine|
magazine.resources :ads, :name_prefix => nil
-end
+end
</ruby>
This will create routing helpers such as +ads_url+ and +edit_ad_path+. Note that calling these will still require supplying an article id:
@@ -470,7 +470,7 @@ map.resources :photos do |photo|
photo.resources :versions
end
</ruby>
-
+
h5. Limits to Nesting
You can nest resources within other nested resources if you like. For example:
@@ -544,7 +544,7 @@ Another way to refer to the same route is with an array of objects:
</ruby>
This format is especially useful when you might not know until runtime which of several types of object will be used in a particular link.
-
+
h4. Namespaced Resources
It's possible to do some quite complex things by combining +:path_prefix+ and +:name_prefix+. For example, you can use the combination of these two options to move administrative resources to their own folder in your application:
@@ -628,7 +628,7 @@ h3. Regular Routes
In addition to RESTful routing, Rails supports regular routing - a way to map URLs to controllers and actions. With regular routing, you don't get the masses of routes automatically generated by RESTful routing. Instead, you must set up each route within your application separately.
-While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit.
+While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing _when possible_, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit.
h4. Bound Parameters
@@ -711,7 +711,7 @@ This route would respond to URLs such as +/photo/A12345+. You can more succinctl
<ruby>
map.connect 'photo/:id', :controller => 'photos', :action => 'show',
- :id => /[A-Z]\d{5}/
+ :id => /[A-Z]\d{5}/
</ruby>
h4. Route Conditions
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 28e0e12e34..a89cfaddbe 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -641,7 +641,7 @@ And now let's inject another query using the UNION statement:
This will result in the following SQL query:
<pre>
-SELECT * FROM projects WHERE (name = '') UNION
+SELECT * FROM projects WHERE (name = '') UNION
SELECT id,login AS name,password AS description,1,1,1 FROM users --')
</pre>
@@ -750,7 +750,7 @@ Especially for XSS, it is important to do _(highlight)whitelist input filtering
Imagine a blacklist deletes “script” from the user input. Now the attacker injects “&lt;scrscriptipt&gt;”, and after the filter, “&lt;script&gt;” remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:
<pre>
-strip_tags("some<<b>script>alert('hello')<</b>/script>")
+strip_tags("some<<b>script>alert('hello')<</b>/script>")
</pre>
This returned "some&lt;script&gt;alert('hello')&lt;/script&gt;", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize():
@@ -782,7 +782,7 @@ h5. Examples from the underground
The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1 Yahoo! Mail "worm":http://groovin.net/stuff/yammer.txt. It appeared on June 11, 2006 and was the first webmail interface worm:
<pre>
-<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
+<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
target=""onload="var http_request = false; var Email = '';
var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
</pre>
@@ -810,13 +810,13 @@ MySpace blocks many tags, however it allows CSS. So the worm's author put JavaSc
So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript allows has a handy eval() function which executes any string as code.
<pre>
-<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
+<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
</pre>
The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word “innerHTML”:
<pre>
-alert(eval('document.body.inne' + 'rHTML'));
+alert(eval('document.body.inne' + 'rHTML'));
</pre>
The next problem was MySpace filtering the word “javascript”, so the author used “java&lt;NEWLINE&gt;script" to get around this:
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index ad51c053f1..8129dc34c2 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -186,7 +186,7 @@ The +PostTest+ class defines a _test case_ because it inherits from +ActiveSuppo
def test_truth
</ruby>
-Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
+Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
<ruby>
assert true
@@ -194,10 +194,10 @@ assert true
This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
-* is this value = that value?
-* is this object nil?
-* does this line of code throw an exception?
-* is the user's password greater than 5 characters?
+* is this value = that value?
+* is this object nil?
+* does this line of code throw an exception?
+* is the user's password greater than 5 characters?
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
@@ -232,7 +232,7 @@ Running a test is as simple as invoking the file containing the test cases throu
<shell>
$ cd test
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb
Loaded suite unit/post_test
Started
@@ -257,7 +257,7 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
</pre>
-The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
+The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
@@ -336,7 +336,7 @@ Finished in 0.193608 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
</pre>
-Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html.
@@ -370,7 +370,7 @@ NameError: undefined local variable or method `some_undefined_variable' for #<Po
1 tests, 0 assertions, 0 failures, 1 errors
</pre>
-Notice the 'E' in the output. It denotes a test with error.
+Notice the 'E' in the output. It denotes a test with error.
NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
@@ -427,7 +427,7 @@ You'll see the usage of some of these assertions in the next chapter.
h3. Functional Tests for Your Controllers
-In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
h4. What to include in your Functional Tests
@@ -451,11 +451,11 @@ def test_should_get_index
end
</ruby>
-In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
+In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
-* The action of the controller you are requesting. This can be in the form of a string or a symbol.
+* The action of the controller you are requesting. This can be in the form of a string or a symbol.
* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
* An optional hash of session variables to pass along with the request.
* An optional hash of flash values.
@@ -604,12 +604,12 @@ end
h3. Integration Testing
-Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
+Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
-Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
+Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
<shell>
-$ script/generate integration_test user_flows
+$ script/generate integration_test user_flows
exists test/integration/
create test/integration/user_flows_test.rb
</shell>
@@ -629,7 +629,7 @@ class UserFlowsTest < ActionController::IntegrationTest
end
</ruby>
-Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
+Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
h4. Helpers Available for Integration tests
@@ -663,11 +663,11 @@ class UserFlowsTest < ActionController::IntegrationTest
https!
get "/login"
assert_response :success
-
+
post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
assert_equal '/welcome', path
assert_equal 'Welcome avs!', flash[:notice]
-
+
https!(false)
get "/posts/all"
assert_response :success
@@ -687,26 +687,26 @@ class UserFlowsTest < ActionController::IntegrationTest
fixtures :users
def test_login_and_browse_site
-
+
# User avs logs in
avs = login(:avs)
# User guest logs in
guest = login(:guest)
-
+
# Both are now available in different sessions
assert_equal 'Welcome avs!', avs.flash[:notice]
assert_equal 'Welcome guest!', guest.flash[:notice]
-
+
# User avs can browse site
avs.browses_site
# User guest can browse site aswell
guest.browses_site
-
+
# Continue with other assertions
end
-
+
private
-
+
module CustomDsl
def browses_site
get "/products/all"
@@ -714,7 +714,7 @@ class UserFlowsTest < ActionController::IntegrationTest
assert assigns(:products)
end
end
-
+
def login(user)
open_session do |sess|
sess.extend(CustomDsl)
@@ -764,7 +764,7 @@ class PostsControllerTest < ActionController::TestCase
# called after every single test
def teardown
# as we are re-initializing @post before every test
- # setting it to nil here is not essential but I hope
+ # setting it to nil here is not essential but I hope
# you understand how you can use the teardown method
@post = nil
end
@@ -781,7 +781,7 @@ class PostsControllerTest < ActionController::TestCase
assert_redirected_to posts_path
end
-
+
end
</ruby>
@@ -791,7 +791,7 @@ Above, the +setup+ method is called before each test and so +@post+ is available
* a method (like in the earlier example)
* a method name as a symbol
* a lambda
-
+
Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
<ruby>
@@ -811,7 +811,7 @@ class PostsControllerTest < ActionController::TestCase
get :show, :id => @post.id
assert_response :success
end
-
+
def test_should_update_post
put :update, :id => @post.id, :post => { }
assert_redirected_to post_path(assigns(:post))
@@ -824,13 +824,13 @@ class PostsControllerTest < ActionController::TestCase
assert_redirected_to posts_path
end
-
- private
-
+
+ private
+
def initialize_post
@post = posts(:one)
end
-
+
end
</ruby>
@@ -870,7 +870,7 @@ h5. Revenge of the Fixtures
For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory.
-When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
h5. The Basic Test case
@@ -901,7 +901,7 @@ Here's the content of the +invite+ fixture:
<pre>
Hi friend@example.com,
-You have been invited.
+You have been invited.
Cheers!
</pre>
@@ -923,7 +923,7 @@ class UserControllerTest < ActionController::TestCase
post :invite_friend, :email => 'friend@example.com'
end
invite_email = ActionMailer::Base.deliveries.first
-
+
assert_equal invite_email.subject, "You have been invited by me@example.com"
assert_equal invite_email.to[0], 'friend@example.com'
assert_match /Hi friend@example.com/, invite_email.body