提交 b047929c 编写于 作者: P Pratik Naik

Merge with docrails

上级 5a02f0bc
......@@ -1062,6 +1062,9 @@ def default_url_options(options = nil)
# When using <tt>redirect_to :back</tt>, if there is no referrer,
# RedirectBackError will be raised. You may specify some fallback
# behavior for this case by rescuing RedirectBackError.
#
# When using <tt>redirect_to</tt> an instance variable called
# @performed_redirect will be set to true.
def redirect_to(options = {}, response_status = {}) #:doc:
raise ActionControllerError.new("Cannot redirect to nil!") if options.nil?
......
......@@ -344,9 +344,9 @@ def simple_format(text, html_options={})
text << "</p>"
end
# Turns all URLs and e-mail addresses into clickable links. The +link+ parameter
# Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option
# will limit what should be linked. You can add HTML attributes to the links using
# +href_options+. Options for +link+ are <tt>:all</tt> (default),
# <tt>:href_options</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default),
# <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and
# e-mail address is yielded and the result is used as the link text.
#
......@@ -355,15 +355,15 @@ def simple_format(text, html_options={})
# # => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
# # say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
#
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :urls)
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls)
# # => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a>
# # or e-mail david@loudthinking.com"
#
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :email_addresses)
# auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :email_addresses)
# # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"
#
# post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com."
# auto_link(post_body, :all, :target => '_blank') do |text|
# auto_link(post_body, :href_options => { :target => '_blank' }) do |text|
# truncate(text, 15)
# end
# # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>.
......
require 'benchmark'
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
module Cache
# Creates a new CacheStore object according to the given options.
#
# If no arguments are passed to this method, then a new
# ActiveSupport::Cache::MemoryStore object will be returned.
#
# If you pass a Symbol as the first argument, then a corresponding cache
# store class under the ActiveSupport::Cache namespace will be created.
# For example:
#
# ActiveSupport::Cache.lookup_store(:memory_store)
# # => returns a new ActiveSupport::Cache::MemoryStore object
#
# ActiveSupport::Cache.lookup_store(:drb_store)
# # => returns a new ActiveSupport::Cache::DRbStore object
#
# Any additional arguments will be passed to the corresponding cache store
# class's constructor:
#
# ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
# # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
#
# If the first argument is not a Symbol, then it will simply be returned:
#
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
# # => returns MyOwnCacheStore.new
def self.lookup_store(*store_option)
store, *parameters = *([ store_option ].flatten)
......@@ -36,6 +62,21 @@ def self.expand_cache_key(key, namespace = nil)
expanded_cache_key
end
# An abstract cache store class. There are multiple cache store
# implementations, each having its own additional features. See the classes
# under the ActiveSupport::Cache module, e.g.
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
# popular cache store for large production websites.
#
# ActiveSupport::Cache::Store is meant for caching strings. Some cache
# store implementations, like MemoryStore, are able to cache arbitrary
# Ruby objects, but don't count on every cache store to be able to do that.
#
# cache = ActiveSupport::Cache::MemoryStore.new
#
# cache.read("city") # => nil
# cache.write("city", "Duckburgh")
# cache.read("city") # => "Duckburgh"
class Store
cattr_accessor :logger
......@@ -44,7 +85,46 @@ def silence!
self
end
# Pass <tt>:force => true</tt> to force a cache miss.
# Fetches data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned.
#
# If there is no such data in the cache (a cache miss occurred), then
# then nil will be returned. However, if a block has been passed, then
# that block will be run in the event of a cache miss. The return value
# of the block will be written to the cache under the given cache key,
# and that return value will be returned.
#
# cache.write("today", "Monday")
# cache.fetch("today") # => "Monday"
#
# cache.fetch("city") # => nil
# cache.fetch("city") do
# "Duckburgh"
# end
# cache.fetch("city") # => "Duckburgh"
#
# You may also specify additional options via the +options+ argument.
# Setting <tt>:force => true</tt> will force a cache miss:
#
# cache.write("today", "Monday")
# cache.fetch("today", :force => true) # => nil
#
# Other options will be handled by the specific cache store implementation.
# Internally, #fetch calls #read, and calls #write on a cache miss.
# +options+ will be passed to the #read and #write calls.
#
# For example, MemCacheStore's #write method supports the +:expires_in+
# option, which tells the memcached server to automatically expire the
# cache item after a certain period. We can use this option with #fetch
# too:
#
# cache = ActiveSupport::Cache::MemCacheStore.new
# cache.fetch("foo", :force => true, :expires_in => 5.seconds) do
# "bar"
# end
# cache.fetch("foo") # => "bar"
# sleep(6)
# cache.fetch("foo") # => nil
def fetch(key, options = {})
@logger_off = true
if !options[:force] && value = read(key, options)
......@@ -68,10 +148,32 @@ def fetch(key, options = {})
end
end
# Fetches data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned. Otherwise,
# nil is returned.
#
# You may also specify additional options via the +options+ argument.
# The specific cache store implementation will decide what to do with
# +options+.
def read(key, options = nil)
log("read", key, options)
end
# Writes the given value to the cache, with the given key.
#
# You may also specify additional options via the +options+ argument.
# The specific cache store implementation will decide what to do with
# +options+.
#
# For example, MemCacheStore supports the +:expires_in+ option, which
# tells the memcached server to automatically expire the cache item after
# a certain period:
#
# cache = ActiveSupport::Cache::MemCacheStore.new
# cache.write("foo", "bar", :expires_in => 5.seconds)
# cache.read("foo") # => "bar"
# sleep(6)
# cache.read("foo") # => nil
def write(key, value, options = nil)
log("write", key, options)
end
......
module ActiveSupport
module Cache
# A cache store implementation which stores everything on the filesystem.
class FileStore < Store
attr_reader :cache_path
......
......@@ -2,8 +2,19 @@
module ActiveSupport
module Cache
# A cache store implementation which stores data in Memcached:
# http://www.danga.com/memcached/
#
# This is currently the most popular cache store for production websites.
#
# Special features:
# - Clustering and load balancing. One can specify multiple memcached servers,
# and MemCacheStore will load balance between all available servers. If a
# server goes down, then MemCacheStore will ignore it until it goes back
# online.
# - Time-based expiry support. See #write and the +:expires_in+ option.
class MemCacheStore < Store
module Response
module Response # :nodoc:
STORED = "STORED\r\n"
NOT_STORED = "NOT_STORED\r\n"
EXISTS = "EXISTS\r\n"
......@@ -13,6 +24,14 @@ module Response
attr_reader :addresses
# Creates a new MemCacheStore object, with the given memcached server
# addresses. Each address is either a host name, or a host-with-port string
# in the form of "host_name:port". For example:
#
# ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229")
#
# If no addresses are specified, then MemCacheStore will connect to
# localhost port 11211 (the default memcached port).
def initialize(*addresses)
addresses = addresses.flatten
options = addresses.extract_options!
......@@ -21,7 +40,7 @@ def initialize(*addresses)
@data = MemCache.new(addresses, options)
end
def read(key, options = nil)
def read(key, options = nil) # :nodoc:
super
@data.get(key, raw?(options))
rescue MemCache::MemCacheError => e
......@@ -29,8 +48,13 @@ def read(key, options = nil)
nil
end
# Set key = value. Pass :unless_exist => true if you don't
# want to update the cache if the key is already set.
# Writes a value to the cache.
#
# Possible options:
# - +:unless_exist+ - set to true if you don't want to update the cache
# if the key is already set.
# - +:expires_in+ - the number of seconds that this value may stay in
# the cache. See ActiveSupport::Cache::Store#write for an example.
def write(key, value, options = nil)
super
method = options && options[:unless_exist] ? :add : :set
......@@ -44,7 +68,7 @@ def write(key, value, options = nil)
false
end
def delete(key, options = nil)
def delete(key, options = nil) # :nodoc:
super
response = @data.delete(key, expires_in(options))
response == Response::DELETED
......@@ -53,13 +77,13 @@ def delete(key, options = nil)
false
end
def exist?(key, options = nil)
def exist?(key, options = nil) # :nodoc:
# Doesn't call super, cause exist? in memcache is in fact a read
# But who cares? Reading is very fast anyway
!read(key, options).nil?
end
def increment(key, amount = 1)
def increment(key, amount = 1) # :nodoc:
log("incrementing", key, amount)
response = @data.incr(key, amount)
......@@ -68,7 +92,7 @@ def increment(key, amount = 1)
nil
end
def decrement(key, amount = 1)
def decrement(key, amount = 1) # :nodoc:
log("decrement", key, amount)
response = @data.decr(key, amount)
......@@ -77,7 +101,7 @@ def decrement(key, amount = 1)
nil
end
def delete_matched(matcher, options = nil)
def delete_matched(matcher, options = nil) # :nodoc:
super
raise "Not supported by Memcache"
end
......
module ActiveSupport
module Cache
# A cache store implementation which stores everything into memory in the
# same process. If you're running multiple Ruby on Rails server processes
# (which is the case if you're using mongrel_cluster or Phusion Passenger),
# then this means that your Rails server process instances won't be able
# to share cache data with each other. If your application never performs
# manual cache item expiry (e.g. when you're using generational cache keys),
# then using MemoryStore is ok. Otherwise, consider carefully whether you
# should be using this cache store.
#
# MemoryStore is not only able to store strings, but also arbitrary Ruby
# objects.
#
# MemoryStore is not thread-safe. Use SynchronizedMemoryStore instead
# if you need thread-safety.
class MemoryStore < Store
def initialize
@data = {}
......
module ActiveSupport
module Cache
# Like MemoryStore, but thread-safe.
class SynchronizedMemoryStore < MemoryStore
def initialize
super
......
......@@ -337,72 +337,72 @@ More information :
<div class="ilist"><ul>
<li>
<p>
Getting Started with Rails
<a href="http://guides.rubyonrails.org/getting_started_with_rails.html">Getting Started with Rails</a>
</p>
</li>
<li>
<p>
Rails Database Migrations
<a href="http://guides.rubyonrails.org/migrations.html">Rails Database Migrations</a>
</p>
</li>
<li>
<p>
Active Record Associations
<a href="http://guides.rubyonrails.org/association_basics.html">Active Record Associations</a>
</p>
</li>
<li>
<p>
Active Record Finders
<a href="http://guides.rubyonrails.org/finders.html">Active Record Finders</a>
</p>
</li>
<li>
<p>
Layouts and Rendering in Rails
<a href="http://guides.rubyonrails.org/layouts_and_rendering.html">Layouts and Rendering in Rails</a>
</p>
</li>
<li>
<p>
Action View Form Helpers
<a href="http://guides.rubyonrails.org/form_helpers.html">Action View Form Helpers</a>
</p>
</li>
<li>
<p>
Rails Routing from the Outside In
<a href="http://guides.rubyonrails.org/routing_outside_in.html">Rails Routing from the Outside In</a>
</p>
</li>
<li>
<p>
Basics of Action Controller
<a href="http://guides.rubyonrails.org/actioncontroller_basics.html">Basics of Action Controller</a>
</p>
</li>
<li>
<p>
Rails Caching
<a href="http://guides.rubyonrails.org/caching_with_rails.html">Rails Caching</a>
</p>
</li>
<li>
<p>
Testing Rails Applications
<a href="http://guides.rubyonrails.org/testing_rails_applications.html">Testing Rails Applications</a>
</p>
</li>
<li>
<p>
Securing Rails Applications
<a href="http://guides.rubyonrails.org/security.html">Securing Rails Applications</a>
</p>
</li>
<li>
<p>
Debugging Rails Applications
<a href="http://guides.rubyonrails.org/debugging_rails_applications.html">Debugging Rails Applications</a>
</p>
</li>
<li>
<p>
Benchmarking and Profiling Rails Applications
<a href="http://guides.rubyonrails.org/benchmarking_and_profiling.html">Benchmarking and Profiling Rails Applications</a>
</p>
</li>
<li>
<p>
The Basics of Creating Rails Plugins
<a href="http://guides.rubyonrails.org/creating_plugins.html">The Basics of Creating Rails Plugins</a>
</p>
</li>
</ul></div>
......@@ -612,7 +612,7 @@ More information:
</ul></div>
<h3 id="_new_dynamic_finders">5.4. New Dynamic Finders</h3>
<div class="para"><p>Two new sets of methods have been added to Active Record's dynamic finders family.</p></div>
<h4 id="_find_last_by_lt_attributes_gt">5.4.1. find_last_by_&lt;attributes&gt;</h4>
<h4 id="_tt_find_last_by_lt_attribute_gt_tt">5.4.1. <tt>find_last_by_&lt;attribute&gt;</tt></h4>
<div class="para"><p>The <tt>find_last_by_&lt;attribute&gt;</tt> method is equivalent to <tt>Model.last(:conditions &#8658; {:attribute &#8658; value})</tt></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
......@@ -629,8 +629,8 @@ Lead Contributor: <a href="http://www.workingwithrails.com/person/9147-emilio-ta
</p>
</li>
</ul></div>
<h4 id="_find_by_lt_attributes_gt">5.4.2. find_by_&lt;attributes&gt;!</h4>
<div class="para"><p>The new bang! version of <tt>find_by_&lt;attribute&gt;! is equivalent to +Model.first(:conditions &#8658; {:attribute &#8658; value}) || raise ActiveRecord::RecordNotFound</tt> Instead of returning <tt>nil</tt> if it can't find a matching record, this method will raise an exception if it cannot find a match.</p></div>
<h4 id="_tt_find_by_lt_attribute_gt_tt">5.4.2. <tt>find_by_&lt;attribute&gt;!</tt></h4>
<div class="para"><p>The new bang! version of <tt>find_by_&lt;attribute&gt;!</tt> is equivalent to <tt>Model.first(:conditions &#8658; {:attribute &#8658; value}) || raise ActiveRecord::RecordNotFound</tt> Instead of returning <tt>nil</tt> if it can't find a matching record, this method will raise an exception if it cannot find a match.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
......@@ -779,6 +779,16 @@ Benchmarking numbers are now reported in milliseconds rather than tiny fractions
Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
</p>
</li>
<li>
<p>
<tt>redirect_to</tt> now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
</p>
</li>
<li>
<p>
<tt>render</tt> now supports a <tt>:js</tt> option to render plain vanilla javascript with the right mime type.
</p>
</li>
</ul></div>
</div>
<h2 id="_action_view">7. Action View</h2>
......@@ -791,7 +801,7 @@ Rails now supports HTTP-only cookies (and uses them for sessions), which help mi
</li>
<li>
<p>
The included Prototype javascript library has been upgraded to version 1.6.0.2.
The included Prototype javascript library has been upgraded to version 1.6.0.3.
</p>
</li>
<li>
......@@ -893,23 +903,23 @@ http://www.gnu.org/software/src-highlite -->
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Vendor <span style="color: #990000">&lt;&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Vendor <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
has_one <span style="color: #990000">:</span>account
delegate <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span>to <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>prefix <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This will produce delegated methods <tt>vendor.account_email</tt> and <tt>vendor.account_password</tt>. You can also specify a custom prefix:</p></div>
<div class="para"><p>This will produce delegated methods <tt>vendor#account_email</tt> and <tt>vendor#account_password</tt>. You can also specify a custom prefix:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Vendor <span style="color: #990000">&lt;&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Vendor <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
has_one <span style="color: #990000">:</span>account
delegate <span style="color: #990000">:</span>email<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">,</span> <span style="color: #990000">:</span>to <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>prefix <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>owner
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>This will produce delegated methods <tt>vendor.owner_email</tt> and <tt>vendor.owner_password</tt>.</p></div>
<div class="para"><p>This will produce delegated methods <tt>vendor#owner_email</tt> and <tt>vendor#owner_password</tt>.</p></div>
<div class="para"><p>Lead Contributor: <a href="http://workingwithrails.com/person/5830-daniel-schierbeck">Daniel Schierbeck</a></p></div>
<h3 id="_other_active_support_changes">9.4. Other Active Support Changes</h3>
<div class="ilist"><ul>
......@@ -953,6 +963,11 @@ The addition of <tt>ActiveSupport::Rescuable</tt> allows any class to mix in the
The included TzInfo library has been upgraded to version 0.3.11.
</p>
</li>
<li>
<p>
<tt>ActiveSuport::StringInquirer</tt> gives you a pretty way to test for equality in strings: <tt>ActiveSupport::StringInquirer.new("abc").abc? &#8658; true</tt>
</p>
</li>
</ul></div>
</div>
<h2 id="_railties">10. Railties</h2>
......@@ -997,7 +1012,7 @@ The included TzInfo library has been upgraded to version 0.3.11.
</p>
</li>
</ul></div>
<div class="para"><p>You can unpack or install a single gem by specifying <tt>GEM=_gem_name</tt> on the command line.</p></div>
<div class="para"><p>You can unpack or install a single gem by specifying <tt>GEM=<em>gem_name</em></tt> on the command line.</p></div>
<div class="ilist"><ul>
<li>
<p>
......@@ -1014,6 +1029,11 @@ More information:
<a href="http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies">What's New in Edge Rails: Gem Dependencies</a>
</p>
</li>
<li>
<p>
<a href="http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/">Rails 2.1.2 and 2.2RC1: Update Your RubyGems</a>
</p>
</li>
</ul></div>
</li>
</ul></div>
......@@ -1046,7 +1066,7 @@ Instructions for setting up a continuous integration server to build Rails itsel
</li>
<li>
<p>
Wrapped <tt>Rails.env</tt> in <tt>StringQuestioneer</tt> so you can do <tt>Rails.env.development?</tt>
Wrapped <tt>Rails.env</tt> in <tt>StringInquirer</tt> so you can do <tt>Rails.env.development?</tt>
</p>
</li>
<li>
......
......@@ -693,7 +693,6 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
<h3 id="_after_filters_and_around_filters">6.1. After filters and around filters</h3>
<div class="para"><p>In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.</p></div>
<div class="para"><p>TODO: Find a real example for an around filter</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
......
......@@ -691,7 +691,7 @@ http://www.gnu.org/software/src-highlite -->
belongs_to <span style="color: #990000">:</span>manager<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With this setup, you can retrieve <tt>@employee.subordinates</tt> and <tt>@employee.managers</tt>.</p></div>
<div class="para"><p>With this setup, you can retrieve <tt>@employee.subordinates</tt> and <tt>@employee.manager</tt>.</p></div>
</div>
<h2 id="_tips_tricks_and_warnings">3. Tips, Tricks, and Warnings</h2>
<div class="sectionbody">
......@@ -1185,6 +1185,14 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt"><tt>:select</tt></h5>
<div class="para"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">If you set the <tt>:select</tt> option on a <tt>belongs_to</tt> association, you should also set the <tt>foreign_key</tt> option to guarantee the correct results.</td>
</tr></table>
</div>
<h5 id="_tt_validate_tt"><tt>:validate</tt></h5>
<div class="para"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved">4.1.3. When are Objects Saved?</h4>
......
......@@ -2010,6 +2010,11 @@ The <a href="http://wiki.rubyonrails.org/rails">Rails wiki</a>
<div class="ilist"><ul>
<li>
<p>
November 1, 2008: First approved version by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
</li>
<li>
<p>
October 16, 2008: Revised based on feedback from Pratik Naik by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
......
......@@ -219,14 +219,6 @@ ul#navMain {
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="getting_started_with_rails.html">Getting Started with Rails</a></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/caution.png" alt="Caution" />
</td>
<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/2">Lighthouse Ticket</a></td>
</tr></table>
</div>
<div class="para"><p>Everything you need to know to install Rails and create your first application.</p></div>
</div></div>
<h2>Models</h2>
......@@ -326,14 +318,6 @@ Enjoy.</p></div>
<div class="sidebarblock">
<div class="sidebar-content">
<div class="sidebar-title"><a href="security.html">Securing Rails Applications</a></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/caution.png" alt="Caution" />
</td>
<td class="content"><a href="http://rails.lighthouseapp.com/projects/16213/tickets/7">Lighthouse Ticket</a></td>
</tr></table>
</div>
<div class="para"><p>This manual describes common security problems in web applications and how to
avoid them with Rails.</p></div>
</div></div>
......
......@@ -1756,7 +1756,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="color: #990000">:</span>has_many <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>tags<span style="color: #990000">,</span> <span style="color: #990000">:</span>ratings<span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get <tt>admin_photos_url</tt> that expects to find an <tt>Admin::PhotosController</tt> and that matches <tt>admin/photos</tt>, and <tt>admin_photos_ratings+path</tt> that matches <tt>/admin/photos/<em>photo_id</em>/ratings</tt>, expecting to use <tt>Admin::RatingsController</tt>. Even though you're not specifying <tt>path_prefix</tt> explicitly, the routing code will calculate the appropriate <tt>path_prefix</tt> from the route nesting.</p></div>
<div class="para"><p>As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get <tt>admin_photos_url</tt> that expects to find an <tt>Admin::PhotosController</tt> and that matches <tt>admin/photos</tt>, and <tt>admin_photos_ratings_path</tt> that matches <tt>/admin/photos/<em>photo_id</em>/ratings</tt>, expecting to use <tt>Admin::RatingsController</tt>. Even though you're not specifying <tt>path_prefix</tt> explicitly, the routing code will calculate the appropriate <tt>path_prefix</tt> from the route nesting.</p></div>
<h3 id="_adding_more_restful_actions">3.11. Adding More RESTful Actions</h3>
<div class="para"><p>You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional member routes (those which apply to a single instance of the resource), additional new routes (those that apply to creating a new resource), or additional collection routes (those which apply to the collection of resources as a whole).</p></div>
<h4 id="_adding_member_routes">3.11.1. Adding Member Routes</h4>
......
......@@ -310,6 +310,9 @@ ul#navMain {
<li>
<a href="#_additional_resources">Additional resources</a>
</li>
<li>
<a href="#_changelog">Changelog</a>
</li>
</ol>
</div>
......@@ -1324,6 +1327,17 @@ Another <a href="http://www.0x000000.com/">good security blog</a> with some Chea
</p>
</li>
</ul></div>
</div>
<h2 id="_changelog">10. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/7">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
<li>
<p>
November 1, 2008: First approved version by Heiko Webers
</p>
</li>
</ul></div>
</div>
</div>
......
......@@ -27,20 +27,20 @@ Along with thread safety, a lot of work has been done to make Rails work well wi
The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the link:http://guides.rubyonrails.org/[Ruby on Rails Guides] project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:
* Getting Started with Rails
* Rails Database Migrations
* Active Record Associations
* Active Record Finders
* Layouts and Rendering in Rails
* Action View Form Helpers
* Rails Routing from the Outside In
* Basics of Action Controller
* Rails Caching
* Testing Rails Applications
* Securing Rails Applications
* Debugging Rails Applications
* Benchmarking and Profiling Rails Applications
* The Basics of Creating Rails Plugins
* link:http://guides.rubyonrails.org/getting_started_with_rails.html[Getting Started with Rails]
* link:http://guides.rubyonrails.org/migrations.html[Rails Database Migrations]
* link:http://guides.rubyonrails.org/association_basics.html[Active Record Associations]
* link:http://guides.rubyonrails.org/finders.html[Active Record Finders]
* link:http://guides.rubyonrails.org/layouts_and_rendering.html[Layouts and Rendering in Rails]
* link:http://guides.rubyonrails.org/form_helpers.html[Action View Form Helpers]
* link:http://guides.rubyonrails.org/routing_outside_in.html[Rails Routing from the Outside In]
* link:http://guides.rubyonrails.org/actioncontroller_basics.html[Basics of Action Controller]
* link:http://guides.rubyonrails.org/caching_with_rails.html[Rails Caching]
* link:http://guides.rubyonrails.org/testing_rails_applications.html[Testing Rails Applications]
* link:http://guides.rubyonrails.org/security.html[Securing Rails Applications]
* link:http://guides.rubyonrails.org/debugging_rails_applications.html[Debugging Rails Applications]
* link:http://guides.rubyonrails.org/benchmarking_and_profiling.html[Benchmarking and Profiling Rails Applications]
* link:http://guides.rubyonrails.org/creating_plugins.html[The Basics of Creating Rails Plugins]
All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
......@@ -167,7 +167,7 @@ Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false
Two new sets of methods have been added to Active Record's dynamic finders family.
==== find_last_by_<attributes>
==== +find_last_by_<attribute>+
The +find_last_by_<attribute>+ method is equivalent to +Model.last(:conditions => {:attribute => value})+
......@@ -179,9 +179,9 @@ User.find_last_by_city('London')
* Lead Contributor: link:http://www.workingwithrails.com/person/9147-emilio-tagua[Emilio Tagua]
==== find_by_<attributes>!
==== +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.
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.
[source, ruby]
-------------------------------------------------------
......@@ -257,11 +257,13 @@ Action Controller now offers good support for HTTP conditional GET requests, as
* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.user_accept_header = true+.
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
== Action View
* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
* The included Prototype javascript library has been upgraded to version 1.6.0.2.
* The included Prototype javascript library has been upgraded to version 1.6.0.3.
* +RJS#page.reload+ to reload the browser's current location via javascript
* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
......@@ -323,23 +325,23 @@ If you delegate behavior from one class to another, you can now specify a prefix
[source, ruby]
-------------------------------------------------------
class Vendor << ActiveRecord::Base
class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account, :prefix => true
end
-------------------------------------------------------
This will produce delegated methods +vendor.account_email+ and +vendor.account_password+. You can also specify a custom prefix:
This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix:
[source, ruby]
-------------------------------------------------------
class Vendor << ActiveRecord::Base
class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account, :prefix => :owner
end
-------------------------------------------------------
This will produce delegated methods +vendor.owner_email+ and +vendor.owner_password+.
This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+.
Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck[Daniel Schierbeck]
......@@ -353,6 +355,7 @@ Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck
* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+.
* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on.
* The included TzInfo library has been upgraded to version 0.3.11.
* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+
== Railties
......@@ -370,11 +373,12 @@ To avoid deployment issues and make Rails applications more self-contained, it's
* +rake gems:build+ to build any missing native extensions
* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them
You can unpack or install a single gem by specifying +GEM=_gem_name+ on the command line.
You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line.
* Lead Contributor: link:http://github.com/al2o3cr[Matt Jones]
* More information:
- link:http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies[What's New in Edge Rails: Gem Dependencies]
- link:http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/[Rails 2.1.2 and 2.2RC1: Update Your RubyGems]
=== Other Railties Changes
......@@ -383,7 +387,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name+ on the comm
* +script/console+ now supports a +--debugger+ option
* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations.
* Wrapped +Rails.env+ in +StringQuestioneer+ so you can do +Rails.env.development?+
* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+
* +script/generate+ works without deprecation warnings when RubyGems 1.3.0 is present
== Deprecated
......
......@@ -55,8 +55,6 @@ Now, the LoginsController's "new" and "create" actions will work as before witho
In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
TODO: Find a real example for an around filter
[source, ruby]
---------------------------------
# Example taken from the Rails API filter documentation:
......
Active Record Basics
====================
Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide explains in detail how This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of AcitveRecord.
Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of AcitveRecord.
After reading this guide readers should have a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make them a stronger and better developer.
......@@ -178,4 +178,4 @@ Rails has a reputation of being a zero-config framework which means that it aim
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save
\ No newline at end of file
* (8) after_save
......@@ -359,7 +359,7 @@ class Employee < ActiveRecord::Base
end
-------------------------------------------------------
With this setup, you can retrieve +@employee.subordinates+ and +@employee.managers+.
With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
== Tips, Tricks, and Warnings
......@@ -765,6 +765,8 @@ If you set the +:readonly+ option to +true+, then the associated object will be
The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
===== +:validate+
If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
......
......@@ -1225,6 +1225,7 @@ Now that you've seen your first Rails application, you should feel free to updat
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket]
* November 1, 2008: First approved version by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* October 12, 2008: More detail, rearrangement, editing by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
......
......@@ -11,8 +11,6 @@ CAUTION: Guides marked with this icon are currently being worked on. While they
.link:getting_started_with_rails.html[Getting Started with Rails]
***********************************************************
CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/2[Lighthouse Ticket]
Everything you need to know to install Rails and create your first application.
***********************************************************
......@@ -94,8 +92,6 @@ Enjoy.
.link:security.html[Securing Rails Applications]
***********************************************************
CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/7[Lighthouse Ticket]
This manual describes common security problems in web applications and how to
avoid them with Rails.
***********************************************************
......
......@@ -166,6 +166,17 @@ render :xml => @product
TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you.
==== Rendering Vanilla JavaScript
Rails can render vanilla JavaScript (as an alternative to using +update+ with n +.rjs+ file):
[source, ruby]
-------------------------------------------------------
render :js => "alert('Hello Rails');"
-------------------------------------------------------
This will send the supplied string to the browser with a MIME type of +text/javascript+.
==== Options for +render+
Calls to the +render+ method generally accept four options:
......@@ -302,22 +313,39 @@ With those declarations, the +inventory+ layout would be used only for the +inde
Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
+application.rb+:
[source, ruby]
-------------------------------------------------------
class ApplicationController < ActionController::Base
layout "main"
#...
end
-------------------------------------------------------
+posts_controller.rb+:
[source, ruby]
-------------------------------------------------------
class PostsController < ApplicationController
# ...
end
-------------------------------------------------------
+special_posts_controller.rb+:
[source, ruby]
-------------------------------------------------------
class SpecialPostsController < PostsController
layout "special"
# ...
end
-------------------------------------------------------
+old_posts_controller.rb+:
[source, ruby]
-------------------------------------------------------
class OldPostsController < SpecialPostsController
layout nil
......@@ -534,7 +562,7 @@ You can supply the +:recursive+ option to load files in subfolders of +public/ja
[source, ruby]
-------------------------------------------------------
<%= javascript_include_tag :all, :recursive %>
<%= javascript_include_tag :all, :recursive => true %>
-------------------------------------------------------
If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
......@@ -601,7 +629,7 @@ You can supply the +:recursive+ option to link files in subfolders of +public/st
[source, ruby]
-------------------------------------------------------
<%= stylesheet_link_tag :all, :recursive %>
<%= stylesheet_link_tag :all, :recursive => true %>
-------------------------------------------------------
If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+:
......@@ -766,23 +794,29 @@ This would look for a partial named +_link_area.html.erb+ and render it using th
You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
+new.html.erb+:
[source, html]
-------------------------------------------------------
new.html.erb:
<h1>New zone</h1>
<%= error_messages_for :zone %>
<%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %>
-------------------------------------------------------
edit.html.erb:
+edit.html.erb+:
[source, html]
-------------------------------------------------------
<h1>Editing zone</h1>
<%= error_messages_for :zone %>
<%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %>
-------------------------------------------------------
_form.html.erb:
+_form.html.erb:+
<% form_for(@zone) do |f| %>
[source, html]
-------------------------------------------------------
<% form_for(zone) do |f| %>
<p>
<b>Zone name</b><br />
<%= f.text_field :name %>
......@@ -795,7 +829,7 @@ _form.html.erb:
Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.
Every partial also has a local variable with the same name as the partial (minus the underscore). By default, it will look for an instance variable with the same name as the partial in the parent. You can pass an object in to this local variable via the +:object+ option:
Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the +:object+ option:
[source, html]
-------------------------------------------------------
......@@ -804,6 +838,8 @@ Every partial also has a local variable with the same name as the partial (minus
Within the +customer+ partial, the +@customer+ variable will refer to +@new_customer+ from the parent view.
WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior is deprecated in Rails 2.2 and will be removed in a future version.
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
[source, html]
......@@ -817,15 +853,18 @@ Assuming that the +@customer+ instance variable contains an instance of the +Cus
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:
+index.html.erb+:
[source, html]
-------------------------------------------------------
index.html.erb:
<h1>Products</h1>
<%= render :partial => "product", :collection => @products %>
-------------------------------------------------------
_product.html.erb:
+_product.html.erb+:
[source, html]
-------------------------------------------------------
<p>Product Name: <%= product.name %></p>
-------------------------------------------------------
......@@ -849,33 +888,42 @@ Rails will render the +_product_ruler+ partial (with no data passed in to it) be
There's also a shorthand syntax available for rendering collections. For example, if +@products+ is a collection of products, you can render the collection this way:
+index.html.erb+:
[source, html]
-------------------------------------------------------
index.html.erb:
<h1>Products</h1>
<%= render :partial => @products %>
-------------------------------------------------------
_product.html.erb:
+_product.html.erb+:
[source, html]
-------------------------------------------------------
<p>Product Name: <%= product.name %></p>
-------------------------------------------------------
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
+index.html.erb+:
[source, html]
-------------------------------------------------------
index.html.erb:
<h1>Contacts</h1>
<%= render :partial => [customer1, employee1, customer2, employee2] %>
-------------------------------------------------------
_customer.html.erb:
+_customer.html.erb+:
[source, html]
-------------------------------------------------------
<p>Name: <%= customer.name %></p>
-------------------------------------------------------
_employee.html.erb:
+_employee.html.erb+:
[source, html]
-------------------------------------------------------
<p>Name: <%= employee.name %></p>
-------------------------------------------------------
......@@ -885,6 +933,7 @@ In this case, Rails will use the customer or employee partials as appropriate fo
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket]
* November 1, 2008: Added +:js+ option for +render+ by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy]
* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
* September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
......
......@@ -600,7 +600,7 @@ map.namespace(:admin) do |admin|
end
-------------------------------------------------------
As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings+path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting.
As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get +admin_photos_url+ that expects to find an +Admin::PhotosController+ and that matches +admin/photos+, and +admin_photos_ratings_path+ that matches +/admin/photos/_photo_id_/ratings+, expecting to use +Admin::RatingsController+. Even though you're not specifying +path_prefix+ explicitly, the routing code will calculate the appropriate +path_prefix+ from the route nesting.
=== Adding More RESTful Actions
......
......@@ -976,3 +976,9 @@ The security landscape shifts and it is important to keep up to date, because mi
- http://secunia.com/[Keep up to date on the other application layers] (they have a weekly newsletter, too)
- A http://ha.ckers.org/blog/[good security blog] including the http://ha.ckers.org/xss.html[Cross-Site scripting Cheat Sheet]
- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/7[Lighthouse ticket]
* November 1, 2008: First approved version by Heiko Webers
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册