Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'master' of git://github.com/lifo/docrails

  • Loading branch information...
commit 236f1f52cdcb695ee42ec1ad384fc9bee643f435 2 parents a282301 + 94e0f1d
@fxn fxn authored
View
38 activemodel/lib/active_model/mass_assignment_security.rb
@@ -20,32 +20,32 @@ module MassAssignmentSecurity
# For example, a logged in user may need to assign additional attributes depending
# on their role:
#
- # class AccountsController < ApplicationController
- # include ActiveModel::MassAssignmentSecurity
+ # class AccountsController < ApplicationController
+ # include ActiveModel::MassAssignmentSecurity
#
- # attr_accessible :first_name, :last_name
+ # attr_accessible :first_name, :last_name
#
- # def self.admin_accessible_attributes
- # accessible_attributes + [ :plan_id ]
- # end
+ # def self.admin_accessible_attributes
+ # accessible_attributes + [ :plan_id ]
+ # end
#
- # def update
- # ...
- # @account.update_attributes(account_params)
- # ...
- # end
+ # def update
+ # ...
+ # @account.update_attributes(account_params)
+ # ...
+ # end
#
- # protected
+ # protected
#
- # def account_params
- # sanitize_for_mass_assignment(params[:account])
- # end
+ # def account_params
+ # sanitize_for_mass_assignment(params[:account])
+ # end
#
- # def mass_assignment_authorizer
- # admin ? admin_accessible_attributes : super
- # end
+ # def mass_assignment_authorizer
+ # admin ? admin_accessible_attributes : super
+ # end
#
- # end
+ # end
#
module ClassMethods
# Attributes named in this macro are protected from mass-assignment
View
10 activemodel/lib/active_model/observing.rb
@@ -13,14 +13,18 @@ module ClassMethods
#
# Activates the observers assigned. Examples:
#
+ # class ORM
+ # include ActiveModel::Observing
+ # end
+ #
# # Calls PersonObserver.instance
- # ActiveRecord::Base.observers = :person_observer
+ # ORM.observers = :person_observer
#
# # Calls Cacher.instance and GarbageCollector.instance
- # ActiveRecord::Base.observers = :cacher, :garbage_collector
+ # ORM.observers = :cacher, :garbage_collector
#
# # Same as above, just using explicit class references
- # ActiveRecord::Base.observers = Cacher, GarbageCollector
+ # ORM.observers = Cacher, GarbageCollector
#
# Note: Setting this does not instantiate the observers yet.
# +instantiate_observers+ is called during startup, and before
View
14 activerecord/lib/active_record/relation/spawn_methods.rb
@@ -63,6 +63,13 @@ def merge(r)
alias :& :merge
+ # Removes from the query the condition(s) specified in +skips+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').except(:order) # discards the order condition
+ # Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
+ #
def except(*skips)
result = self.class.new(@klass, table)
@@ -77,6 +84,13 @@ def except(*skips)
result
end
+ # Removes any condition from the query other than the one(s) specified in +onlies+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').only(:where) # discards the order condition
+ # Post.order('id asc').only(:where, :order) # uses the specified order
+ #
def only(*onlies)
result = self.class.new(@klass, table)
View
2  activerecord/lib/active_record/validations.rb
@@ -37,7 +37,7 @@ def create!(attributes = nil, &block)
end
end
- # The validation process on save can be skipped by passing false. The regular Base#save method is
+ # The validation process on save can be skipped by passing :validate => false. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
perform_validations(options) ? super : false
View
11 activerecord/lib/active_record/validations/uniqueness.rb
@@ -85,11 +85,16 @@ module ClassMethods
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
- # validates_uniqueness_of :user_name, :scope => :account_id
+ # validates_uniqueness_of :user_name
# end
#
- # It can also validate whether the value of the specified attributes are unique based on multiple
- # scope parameters. For example, making sure that a teacher can only be on the schedule once
+ # It can also validate whether the value of the specified attributes are unique based on a scope parameter:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_uniqueness_of :user_name, :scope => :account_id
+ # end
+ #
+ # Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once
# per semester for a particular class.
#
# class TeacherSchedule < ActiveRecord::Base
View
229 activesupport/lib/active_support/callbacks.rb
@@ -5,27 +5,28 @@
require 'active_support/core_ext/kernel/singleton_class'
module ActiveSupport
- # Callbacks are hooks into the life cycle of an object that allow you to trigger logic
- # before or after an alteration of the object state.
+ # \Callbacks are code hooks that are run at key points in an object's lifecycle.
+ # The typical use case is to have a base class define a set of callbacks relevant
+ # to the other functionality it supplies, so that subclasses can install callbacks
+ # that enhance or modify the base functionality without needing to override
+ # or redefine methods of the base class.
#
- # Mixing in this module allows you to define callbacks in your class.
+ # Mixing in this module allows you to define the events in the object's lifecycle
+ # that will support callbacks (via +ClassMethods.define_callbacks+), set the instance
+ # methods, procs, or callback objects to be called (via +ClassMethods.set_callback+),
+ # and run the installed callbacks at the appropriate times (via +run_callbacks+).
#
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
+ # Three kinds of callbacks are supported: before callbacks, run before a certain event;
+ # after callbacks, run after the event; and around callbacks, blocks that surround the
+ # event, triggering it when they yield. Callback code can be contained in instance
+ # methods, procs or lambdas, or callback objects that respond to certain predetermined
+ # methods. See +ClassMethods.set_callback+ for details.
#
- # define_callbacks :save
- # end
+ # ==== Example
#
- # class ConfigStorage < Storage
- # set_callback :save, :before, :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # set_callback :save, :after do |object|
- # puts "saved"
- # end
+ # class Record
+ # include ActiveSupport::Callbacks
+ # define_callbacks :save
#
# def save
# run_callbacks :save do
@@ -34,29 +35,7 @@ module ActiveSupport
# end
# end
#
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # saving...
- # - save
- # saved
- #
- # Callbacks from parent classes are inherited.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- #
- # set_callback :save, :before, :prepare
- # def prepare
- # puts "preparing save"
- # end
- # end
- #
- # class ConfigStorage < Storage
+ # class PersonRecord < Record
# set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
@@ -65,19 +44,12 @@ module ActiveSupport
# set_callback :save, :after do |object|
# puts "saved"
# end
- #
- # def save
- # run_callbacks :save do
- # puts "- save"
- # end
- # end
# end
#
- # config = ConfigStorage.new
- # config.save
+ # person = PersonRecord.new
+ # person.save
#
# Output:
- # preparing save
# saving...
# - save
# saved
@@ -89,11 +61,25 @@ module Callbacks
extend ActiveSupport::DescendantsTracker
end
+ # Runs the callbacks for the given event.
+ #
+ # Calls the before and around callbacks in the order they were set, yields
+ # the block (if given one), and then runs the after callbacks in reverse order.
+ # Optionally accepts a key, which will be used to compile an optimized callback
+ # method for each key. See +ClassMethods.define_callbacks+ for more information.
+ #
+ # If the callback chain was halted, returns +false+. Otherwise returns the result
+ # of the block, or +true+ if no block is given.
+ #
+ # run_callbacks :save do
+ # save
+ # end
+ #
def run_callbacks(kind, *args, &block)
send("_run_#{kind}_callbacks", *args, &block)
end
- class Callback
+ class Callback #:nodoc:#
@@_callback_sequence = 0
attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter
@@ -332,7 +318,7 @@ def filter.around(context)
end
# An Array with a compile method
- class CallbackChain < Array
+ class CallbackChain < Array #:nodoc:#
attr_reader :name, :config
def initialize(name, config)
@@ -377,18 +363,7 @@ def compile(key=nil, object=nil)
end
module ClassMethods
- # Make the run_callbacks :save method. The generated method takes
- # a block that it'll yield to. It'll call the before and around filters
- # in order, yield the block, and then run the after filters.
- #
- # run_callbacks :save do
- # save
- # end
- #
- # The run_callbacks :save method can optionally take a key, which
- # will be used to compile an optimized callback method for each
- # key. See #define_callbacks for more information.
- #
+ # Generate the internal runner method called by +run_callbacks+.
def __define_runner(symbol) #:nodoc:
body = send("_#{symbol}_callbacks").compile
@@ -444,18 +419,42 @@ def __update_callbacks(name, filters = [], block = nil) #:nodoc:
end
end
- # Set callbacks for a previously defined callback.
+ # Install a callback for the given event.
#
- # Syntax:
# set_callback :save, :before, :before_meth
# set_callback :save, :after, :after_meth, :if => :condition
# set_callback :save, :around, lambda { |r| stuff; yield; stuff }
#
- # If the second argument is not :before, :after or :around then an implicit :before is assumed.
- # It means the first example mentioned above can also be written as:
+ # The second arguments indicates whether the callback is to be run +:before+,
+ # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
+ # means the first example above can also be written as:
+ #
# set_callback :save, :before_meth
#
- # Use skip_callback to skip any defined one.
+ # The callback can specified as a symbol naming an instance method; as a proc,
+ # lambda, or block; as a string to be instance evaluated; or as an object that
+ # responds to a certain method determined by the <tt>:scope</tt> argument to
+ # +define_callback+.
+ #
+ # If a proc, lambda, or block is given, its body is evaluated in the context
+ # of the current object. It can also optionally accept the current object as
+ # an argument.
+ #
+ # Before and around callbacks are called in the order that they are set; after
+ # callbacks are called in the reverse order.
+ #
+ # ===== Options
+ #
+ # * <tt>:if</tt> - A symbol naming an instance method or a proc; the callback
+ # will be called only when it returns a true value.
+ # * <tt>:unless</tt> - A symbol naming an instance method or a proc; the callback
+ # will be called only when it returns a false value.
+ # * <tt>:prepend</tt> - If true, the callback will be prepended to the existing
+ # chain rather than appended.
+ # * <tt>:per_key</tt> - A hash with <tt>:if</tt> and <tt>:unless</tt> options;
+ # see "Per-key conditions" below.
+ #
+ # ===== Per-key conditions
#
# When creating or skipping callbacks, you can specify conditions that
# are always the same for a given key. For instance, in Action Pack,
@@ -467,7 +466,7 @@ def __update_callbacks(name, filters = [], block = nil) #:nodoc:
#
# set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
#
- # Per-Key conditions are evaluated only once per use of a given key.
+ # Per-key conditions are evaluated only once per use of a given key.
# In the case of the above example, you would do:
#
# run_callbacks(:process_action, action_name) { ... dispatch stuff ... }
@@ -494,7 +493,8 @@ def set_callback(name, *filter_list, &block)
end
end
- # Skip a previously defined callback.
+ # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or <tt>:unless</tt>
+ # options may be passed in order to control when the callback is skipped.
#
# class Writer < Person
# skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }
@@ -517,7 +517,7 @@ def skip_callback(name, *filter_list, &block)
end
end
- # Reset callbacks for a given type.
+ # Remove all set callbacks for the given event.
#
def reset_callbacks(symbol)
callbacks = send("_#{symbol}_callbacks")
@@ -534,68 +534,71 @@ def reset_callbacks(symbol)
__define_runner(symbol)
end
- # Defines callbacks types:
+ # Define sets of events in the object lifecycle that support callbacks.
#
# define_callbacks :validate
+ # define_callbacks :initialize, :save, :destroy
#
- # This macro accepts the following options:
+ # ===== Options
#
- # * <tt>:terminator</tt> - Indicates when a before filter is considered
- # to halted. This is a string to be eval'ed and has the result of the
- # very filter available in the <tt>result</tt> variable:
+ # * <tt>:terminator</tt> - Determines when a before filter will halt the callback
+ # chain, preventing following callbacks from being called and the event from being
+ # triggered. This is a string to be eval'ed. The result of the callback is available
+ # in the <tt>result</tt> variable.
#
- # define_callbacks :validate, :terminator => "result == false"
+ # define_callbacks :validate, :terminator => "result == false"
#
- # In the example above, if any before validate callbacks returns +false+,
- # other callbacks are not executed. Defaults to "false", meaning no value
- # halts the chain.
+ # In this example, if any before validate callbacks returns +false+,
+ # other callbacks are not executed. Defaults to "false", meaning no value
+ # halts the chain.
#
# * <tt>:rescuable</tt> - By default, after filters are not executed if
- # the given block or a before filter raises an error. Set this option to
- # true to change this behavior.
+ # the given block or a before filter raises an error. By setting this option
+ # to <tt>true</tt> exception raised by given block is stored and after
+ # executing all the after callbacks the stored exception is raised.
#
- # * <tt>:scope</tt> - Indicates which methods should be executed when a class
- # is given as callback. Defaults to <tt>[:kind]</tt>.
+ # * <tt>:scope</tt> - Indicates which methods should be executed when an object
+ # is used as a callback.
#
- # class Audit
- # def before(caller)
- # puts 'Audit: before is called'
- # end
+ # class Audit
+ # def before(caller)
+ # puts 'Audit: before is called'
+ # end
#
- # def before_save(caller)
- # puts 'Audit: before_save is called'
- # end
- # end
+ # def before_save(caller)
+ # puts 'Audit: before_save is called'
+ # end
+ # end
#
- # class Account
- # include ActiveSupport::Callbacks
+ # class Account
+ # include ActiveSupport::Callbacks
#
- # define_callbacks :save
- # set_callback :save, :before, Audit.new
+ # define_callbacks :save
+ # set_callback :save, :before, Audit.new
#
- # def save
- # run_callbacks :save do
- # puts 'save in main'
- # end
- # end
- # end
+ # def save
+ # run_callbacks :save do
+ # puts 'save in main'
+ # end
+ # end
+ # end
#
- # In the above case whenever you save an account the method <tt>Audit#before</tt> will
- # be called. On the other hand
+ # In the above case whenever you save an account the method <tt>Audit#before</tt> will
+ # be called. On the other hand
#
- # define_callbacks :save, :scope => [:kind, :name]
+ # define_callbacks :save, :scope => [:kind, :name]
#
- # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
- # <tt>"#{kind}_#{name}"</tt> on the given instance. In this case "kind" is "before" and
- # "name" is "save". In this context ":kind" and ":name" have special meanings: ":kind"
- # refers to the kind of callback (before/after/around) and ":name" refers to the
- # method on which callbacks are being defined.
+ # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
+ # <tt>#{kind}_#{name}</tt> on the given instance. In this case "kind" is "before" and
+ # "name" is "save". In this context +:kind+ and +:name+ have special meanings: +:kind+
+ # refers to the kind of callback (before/after/around) and +:name+ refers to the
+ # method on which callbacks are being defined.
#
- # A declaration like
+ # A declaration like
#
- # define_callbacks :save, :scope => [:name]
+ # define_callbacks :save, :scope => [:name]
#
- # would call <tt>Audit#save</tt>.
+ # would call <tt>Audit#save</tt>.
#
def define_callbacks(*callbacks)
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
View
9 railties/guides/rails_guides/generator.rb
@@ -38,6 +38,10 @@
# Note that if you are working on a guide generation will by default process
# only that one, so ONLY is rarely used nowadays.
#
+# LANGUAGE
+# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt>
+# folder (such as <tt>source/es</tt>). Ignore it when generating English guides.
+#
# EDGE
# Set to "1" to indicate generated guides should be marked as edge. This
# inserts a badge and changes the preamble of the home page.
@@ -63,6 +67,7 @@ class Generator
GUIDES_RE = /\.(?:textile|html\.erb)$/
def initialize(output=nil)
+ @lang = ENV['LANGUAGE']
initialize_dirs(output)
create_output_dir_if_needed
set_flags_from_environment
@@ -76,8 +81,8 @@ def generate
private
def initialize_dirs(output)
@guides_dir = File.join(File.dirname(__FILE__), '..')
- @source_dir = File.join(@guides_dir, "source")
- @output_dir = output || File.join(@guides_dir, "output")
+ @source_dir = File.join(@guides_dir, "source", @lang.to_s)
+ @output_dir = output || File.join(@guides_dir, "output", @lang.to_s)
end
def create_output_dir_if_needed
View
2  railties/guides/source/active_record_basics.textile
@@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar
<ruby>
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC')
+ users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
</ruby>
You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
View
36 railties/guides/source/active_record_querying.textile
@@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m
TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
-<br />
-
<ruby>
class Client < ActiveRecord::Base
has_one :address
@@ -440,7 +438,7 @@ And this will give you a single +Order+ object for each date where there are ord
The SQL that would be executed would be something like this:
<sql>
-SELECT * FROM orders GROUP BY date(created_at)
+SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at
</sql>
h3. Having
@@ -461,6 +459,36 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
This will return single order objects for each day, but only for the last month.
+h3. Overriding Conditions
+
+You can specify certain conditions to be excepted by using the +except+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id asc').except(:order)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 LIMIT 20
+</sql>
+
+You can also override conditions using the +only+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
+</sql>
+
h3. Readonly Objects
Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
@@ -664,7 +692,7 @@ Eager loading is the mechanism for loading the associated records of the objects
Consider the following code, which finds 10 clients and prints their postcodes:
<ruby>
-clients = Client.all(:limit => 10)
+clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
View
2  railties/guides/source/active_support_core_extensions.textile
@@ -1264,7 +1264,7 @@ Active Support adds that functionality to <tt>%</tt> in previous versions of Rub
NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.
-h4. +starts_with?+ and +ends_width?+
+h4. +starts_with?+ and +ends_with?+
Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
View
22 railties/guides/source/ajax_on_rails.textile
@@ -1,10 +1,10 @@
h2. AJAX on Rails
-This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
+This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
* Quick introduction to AJAX and related technologies
-* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
-* Testing Javascript functionality
+* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
+* Testing JavaScript functionality
endprologue.
@@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro
If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails.
-h4. Asynchronous Javascript + XML
+h4. Asynchronous JavaScript + XML
Basic terminology, new style of creating web apps
@@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi
h3. Built-in Rails Helpers
-Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
+Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so:
<ruby>
@@ -136,7 +136,7 @@ link_to_remote "Add new item",
:before => "$('progress').show()",
:complete => "$('progress').hide()",
:success => "display_item_added(request)",
- :failure => "display_error(request)",
+ :failure => "display_error(request)"
</ruby>
** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
* Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
@@ -153,7 +153,7 @@ There are three different ways of adding AJAX forms to your view using Rails Pro
* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
-Let's se them in action one by one!
+Let's see them in action one by one!
h5. +remote_form_for+
@@ -183,7 +183,7 @@ h3. JavaScript the Rails way: RJS
In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code.
-h4. Javascript without RJS
+h4. JavaScript without RJS
First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
@@ -329,9 +329,9 @@ h4. Drag and Drop
-h3. Testing Javascript
+h3. Testing JavaScript
-Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
+JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
* (Fire)Watir
* Selenium
@@ -339,4 +339,4 @@ Javascript testing reminds me the definition of the world 'classic' by Mark Twai
* Cucumber+Webrat
* Mention stuff like screw.unit/jsSpec
-Note to self: check out the RailsConf JS testing video
+Note to self: check out the RailsConf JS testing video
View
12 railties/guides/source/configuring.textile
@@ -397,6 +397,15 @@ Some parts of Rails can also be configured externally by supplying environment v
* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
+
+h3. Using Initializer Files
+
+After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
+
+TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
+
h3. Initialization events
Rails has 5 initialization events which can be hooked into (listed in order that they are ran):
@@ -551,8 +560,7 @@ TIP: If you have any ordering dependency in your initializers, you can control t
*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
-*+disable_dependency_loading+*
-
+*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to +true+ and +config.dependency_loading+ is set to +false+.
h3. Changelog
View
2  railties/guides/source/generators.textile
@@ -396,7 +396,7 @@ This command will generate the +Thud+ application, and then apply the template t
Templates don't have to be stored on the local system, the +-m+ option also supports online templates:
<shell>
- rails new thud -m https://gist.github.com/722911
+ rails new thud -m https://gist.github.com/722911.txt
</shell>
Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
View
6 railties/guides/source/i18n.textile
@@ -713,12 +713,12 @@ end
Then Active Record will look for messages in this order:
<ruby>
-activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
-activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
-errors.attributes.title.blank
+errors.attributes.name.blank
errors.messages.blank
</ruby>
View
6 railties/guides/source/routing.textile
@@ -498,7 +498,7 @@ You specify a request-based constraint the same way that you specify a segment c
match "photos", :constraints => {:subdomain => "admin"}
</ruby>
-You can also specify constrains in a block form:
+You can also specify constraints in a block form:
<ruby>
namespace :admin do
@@ -598,7 +598,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method:
root :to => 'pages#main'
</ruby>
-You should put the +root+ route at the end of the file. You also need to delete the public/index.html.erb file for the root route to take effect.
+You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect.
h3. Customizing Resourceful Routes
@@ -633,7 +633,7 @@ You can use the +:constraints+ option to specify a required format on the implic
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
</ruby>
-This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
+This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
You can specify a single constraint to apply to a number of routes by using the block form:
View
8 railties/guides/source/ruby_on_rails_guides_guidelines.textile
@@ -62,7 +62,13 @@ To force process of all the guides, pass +ALL=1+.
It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links.
-h3. HTML validation
+If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable.
+
+<plain>
+rake generate_guides LANGUAGE=es
+</plain>
+
+h3. HTML Validation
Please do validate the generated HTML with
View
12 railties/guides/source/testing.textile
@@ -229,13 +229,13 @@ $ rake db:test:load
Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists.
+NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
h5. Rake Tasks for Preparing your Application for Testing
|_.Tasks |_.Description|
|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
+|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
|+rake db:test:purge+ |Empty the test database.|
@@ -512,12 +512,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc.
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
<ruby>
- flash["gordon"] flash[:gordon]
- session["shmession"] session[:shmession]
- cookies["are_good_for_u"] cookies[:are_good_for_u]
+flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
- assigns["something"] assigns(:something)
+assigns["something"] assigns(:something)
</ruby>
h4. Instance Variables Available
View
188 railties/lib/rails/engine.rb
@@ -5,19 +5,20 @@
require 'rails/engine/railties'
module Rails
- # Rails::Engine allows you to wrap a specific Rails application and share it accross
- # different applications. Since Rails 3.0, every Rails::Application is nothing
- # more than an Engine, allowing you to share it very easily.
+ # Rails::Engine allows you to wrap a specific Rails application and share it across
+ # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing
+ # more than an engine, allowing you to share it very easily.
#
- # Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and
- # generators) and configuration available in the latter can also be used in the former.
+ # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods
+ # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the
+ # latter can also be used in the former.
#
# == Creating an Engine
#
- # In Rails versions before to 3.0, your gems automatically behaved as Engine, however
+ # In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
- # behave as Engine, you have to specify an Engine for it somewhere inside your plugin
- # lib folder (similar to how we specify a Railtie):
+ # behave as an engine, you have to specify an +Engine+ for it somewhere inside
+ # your plugin's +lib+ folder (similar to how we specify a +Railtie+):
#
# # lib/my_engine.rb
# module MyEngine
@@ -25,16 +26,17 @@ module Rails
# end
# end
#
- # Then ensure that this file is loaded at the top of your config/application.rb (or in
- # your Gemfile) and it will automatically load models, controllers and helpers
- # inside app, load routes at "config/routes.rb", load locales at "config/locales/*",
- # load tasks at "lib/tasks/*".
+ # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
+ # (or in your +Gemfile+) and it will automatically load models, controllers and helpers
+ # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
+ # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
#
# == Configuration
#
- # Besides the Railtie configuration which is shared across the application, in a
- # Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths,
- # which differently from a Railtie, are scoped to the current Engine.
+ # Besides the +Railtie+ configuration which is shared across the application, in a
+ # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
+ # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
+ # the current engine.
#
# Example:
#
@@ -49,7 +51,7 @@ module Rails
#
# == Generators
#
- # You can set up generators for engine with config.generators method:
+ # You can set up generators for engines with <tt>config.generators</tt> method:
#
# class MyEngine < Rails::Engine
# config.generators do |g|
@@ -59,7 +61,7 @@ module Rails
# end
# end
#
- # You can also set generators for application by using config.app_generators:
+ # You can also set generators for an application by using <tt>config.app_generators</tt>:
#
# class MyEngine < Rails::Engine
# # note that you can also pass block to app_generators in the same way you
@@ -69,25 +71,25 @@ module Rails
#
# == Paths
#
- # Since Rails 3.0, both your Application and Engines do not have hardcoded paths.
- # This means that you are not required to place your controllers at "app/controllers",
+ # Since Rails 3.0, both your application and engines do not have hardcoded paths.
+ # This means that you are not required to place your controllers at <tt>app/controllers</tt>,
# but in any place which you find convenient.
#
- # For example, let's suppose you want to lay your controllers at lib/controllers, all
- # you need to do is:
+ # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
+ # All you would need to do is:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] = "lib/controllers"
# end
#
- # You can also have your controllers being loaded from both "app/controllers" and
- # "lib/controllers":
+ # You can also have your controllers loaded from both <tt>app/controllers</tt> and
+ # <tt>lib/controllers</tt>:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] << "lib/controllers"
# end
#
- # The available paths in an Engine are:
+ # The available paths in an engine are:
#
# class MyEngine < Rails::Engine
# paths["app"] #=> ["app"]
@@ -103,16 +105,17 @@ module Rails
# paths["config/routes"] #=> ["config/routes.rb"]
# end
#
- # Your Application class adds a couple more paths to this set. And as in your Application,
- # all folders under "app" are automatically added to the load path. So if you have
- # "app/observers", it's added by default.
+ # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your
+ # <tt>Application</tt>,all folders under +app+ are automatically added to the load path.
+ # So if you have <tt>app/observers</tt>, it's added by default.
#
# == Endpoint
#
- # Engine can be also a rack application. It can be useful if you have a rack application that
- # you would like to wrap with Engine and provide some of the Engine's features.
+ # An engine can be also a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ #
+ # To do that, use the +endpoint+ method:
#
- # To do that, use endpoint method:
# module MyEngine
# class Engine < Rails::Engine
# endpoint MyRackApplication
@@ -121,14 +124,14 @@ module Rails
#
# Now you can mount your engine in application's routes just like that:
#
- # MyRailsApp::Application.routes.draw do
- # mount MyEngine::Engine => "/engine"
- # end
+ # MyRailsApp::Application.routes.draw do
+ # mount MyEngine::Engine => "/engine"
+ # end
#
# == Middleware stack
#
- # As Engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
- # the same as in application:
+ # As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
+ # the same as in <tt>Application</tt>:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -138,8 +141,8 @@ module Rails
#
# == Routes
#
- # If you don't specify endpoint, routes will be used as default endpoint. You can use them
- # just like you use application's routes:
+ # If you don't specify an endpoint, routes will be used as the default endpoint. You can use them
+ # just like you use an application's routes:
#
# # ENGINE/config/routes.rb
# MyEngine::Engine.routes.draw do
@@ -148,30 +151,31 @@ module Rails
#
# == Mount priority
#
- # Note that now there can be more than one router in you application and it's better to avoid
- # passing requests through many routers. Consider such situation:
+ # Note that now there can be more than one router in your application, and it's better to avoid
+ # passing requests through many routers. Consider this situation:
#
# MyRailsApp::Application.routes.draw do
# mount MyEngine::Engine => "/blog"
# match "/blog/omg" => "main#omg"
# end
#
- # MyEngine is mounted at "/blog" path and additionaly "/blog/omg" points application's controller.
- # In such situation request to "/blog/omg" will go through MyEngine and if there is no such route
- # in Engine's routes, it will be dispatched to "main#omg". It's much better to swap that:
+ # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
+ # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
+ # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
+ # It's much better to swap that:
#
# MyRailsApp::Application.routes.draw do
# match "/blog/omg" => "main#omg"
# mount MyEngine::Engine => "/blog"
# end
#
- # Now, Engine will get only requests that were not handled by application.
+ # Now, +Engine+ will get only requests that were not handled by +Application+.
#
# == Asset path
#
- # When you use engine with its own public directory, you will probably want to copy or symlink it
- # to application's public directory. To simplify generating paths for assets, you can set asset_path
- # for an Engine:
+ # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it
+ # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt>
+ # for an engine:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -179,27 +183,30 @@ module Rails
# end
# end
#
- # With such config, asset paths will be automatically modified inside Engine:
- # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
+ # With such a config, asset paths will be automatically modified inside +Engine+:
+ #
+ # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
#
# == Serving static files
#
- # By default, rails use ActionDispatch::Static to serve static files in development mode. This is ok
- # while you develop your application, but when you want to deploy it, assets from engine will not be
+ # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok
+ # while you develop your application, but when you want to deploy it, assets from an engine will not be
# served by default. You should choose one of the two following strategies:
#
# * enable serving static files by setting config.serve_static_assets to true
- # * copy engine's public files to application's public folder with rake ENGINE_NAME:install:assets, for example
- # rake my_engine:install:assets
+ # * copy engine's public files to application's public folder with <tt>rake ENGINE_NAME:install:assets</tt>, for example
+ # <tt>rake my_engine:install:assets</tt>
#
# == Engine name
#
- # There are some places where engine's name is used:
- # * routes: when you mount engine with mount(MyEngine::Engine => '/my_engine'), it's used as default :as option
- # * some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets
+ # There are some places where an Engine's name is used:
+ # * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
+ # it's used as default :as option
+ # * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>,
+ # <tt>my_engine:install:assets</tt>
#
- # Engine name is set by default based on class name. For MyEngine::Engine it will be my_engine_engine.
- # You can change it manually it manually using engine_name method:
+ # Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
+ # <tt>my_engine_engine</tt>. You can change it manually it manually using the <tt>engine_name</tt> method:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -209,12 +216,12 @@ module Rails
#
# == Isolated Engine
#
- # Normally when you create controllers, helpers and models inside engine, they are treated
- # as they were created inside the application. This means all applications helpers and named routes
- # will be available to your engine controllers.
+ # Normally when you create controllers, helpers and models inside an engine, they are treated
+ # as they were created inside the application. This means all application helpers and named routes
+ # will be available to your engine's controllers.
#
- # However, sometimes you want to isolate your engine from the application, specially if your engine
- # have its own router. To do that, you simply need to call +isolate_namespace+. This method requires
+ # However, sometimes you want to isolate your engine from the application, especially if your engine
+ # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
# you to pass a module where all your controllers, helpers and models should be nested to:
#
# module MyEngine
@@ -223,7 +230,8 @@ module Rails
# end
# end
#
- # With such Engine, everything that is inside MyEngine module, will be isolated from application.
+ # With such an engine, everything that is inside the +MyEngine+ module will be isolated from
+ # the application.
#
# Consider such controller:
#
@@ -232,24 +240,24 @@ module Rails
# end
# end
#
- # If engine is marked as isolated, FooController has access only to helpers from engine and
- # url_helpers from MyEngine::Engine.routes.
+ # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
+ # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
#
- # The next thing that changes in isolated engine is routes behaviour. Normally, when you namespace
- # your controllers, you also need to do namespace all your routes. With isolated engine,
+ # The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace
+ # your controllers, you also need to do namespace all your routes. With an isolated engine,
# the namespace is applied by default, so you can ignore it in routes:
#
# MyEngine::Engine.routes.draw do
# resources :articles
# end
- #
- # The routes above will automatically point to MyEngine::ApplicationContoller. Further more, you don't
- # need to use longer url helpers like "my_engine_articles_path". Instead, you shuold simply use
- # articles_path as you would do with your application.
- #
- # To make that behaviour consistent with other parts of framework, isolated engine has influence also on
- # ActiveModel::Naming. When you use namespaced model, like MyEngine::Article, it will normally
- # use the prefix "my_engine". In isolated engine, the prefix will be ommited in url helpers and
+ #
+ # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</tt>. Furthermore, you don't
+ # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you shuold simply use
+ # <tt>articles_path</tt> as you would do with your application.
+ #
+ # To make that behaviour consistent with other parts of the framework, an isolated engine also has influence on
+ # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
+ # use the prefix "my_engine". In an isolated engine, the prefix will be ommited in url helpers and
# form fields for convenience.
#
# polymorphic_url(MyEngine::Article.new) #=> "articles_path"
@@ -264,9 +272,9 @@ module Rails
#
# == Using Engine's routes outside Engine
#
- # Since now you can mount engine inside application's routes, you do not have direct access to engine's
- # url_helpers inside application. When you mount Engine in application's routes, a special helper is
- # created to allow you to do that. Consider such scenario:
+ # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
+ # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
+ # created to allow you to do that. Consider such a scenario:
#
# # APP/config/routes.rb
# MyApplication::Application.routes.draw do
@@ -274,7 +282,7 @@ module Rails
# match "/foo" => "foo#index"
# end
#
- # Now, you can use my_engine helper inside your application:
+ # Now, you can use the <tt>my_engine</tt> helper inside your application:
#
# class FooController < ApplicationController
# def index
@@ -282,7 +290,7 @@ module Rails
# end
# end
#
- # There is also 'main_app' helper that gives you access to application's routes inside Engine:
+ # There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
#
# module MyEngine
# class BarController
@@ -292,34 +300,34 @@ module Rails
# end
# end
#
- # Note that the :as option given to mount takes the engine_name as default, so most of the time
- # you can simply ommit it.
+ # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tT> as default, so most of the time
+ # you can simply omit it.
#
- # Finally, if you want to generate url to engine's route using polymorphic_url, you also need
+ # Finally, if you want to generate a url to an engine's route using <tt>polymorphic_url</tt>, you also need
# to pass the engine helper. Let's say that you want to create a form pointing to one of the
# engine's routes. All you need to do is pass the helper as the first element in array with
# attributes for url:
#
- # form_for([my_engine, @user])
+ # form_for([my_engine, @user])
#
- # This code will use my_engine.user_path(@user) to generate the proper route.
+ # This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
#
# == Migrations & seed data
#
- # Engines can have their own migrations. Default path for migrations is exactly the same
- # as in application: db/migrate
+ # Engines can have their own migrations. The default path for migrations is exactly the same
+ # as in application: <tt>db/migrate</tt>
#
# To use engine's migrations in application you can use rake task, which copies them to
# application's dir:
#
# rake ENGINE_NAME:install:migrations
#
- # Note that some of the migrations may be skipped if migration with the same name already exists
- # in application. In such situation you must decide whether to leave that migration or rename the
+ # Note that some of the migrations may be skipped if a migration with the same name already exists
+ # in application. In such a situation you must decide whether to leave that migration or rename the
# migration in application and rerun copying migrations.
#
# If your engine has migrations, you may also want to prepare data for the database in
- # seeds.rb file. You can load that data using load_seed method, e.g.
+ # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
#
# MyEngine::Engine.load_seed
#
View
4 railties/lib/rails/generators/rails/app/templates/README
@@ -91,7 +91,7 @@ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
- @posts = Post.find(:all)
+ @posts = Post.all
debugger
end
end
@@ -139,7 +139,7 @@ To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
-link:http://www.rubycentral.com/pickaxe/irb.html
+link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
Please sign in to comment.
Something went wrong with that request. Please try again.