diff options
125 files changed, 5916 insertions, 2294 deletions
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index 1617b88c8e..ad1eac912b 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -9,6 +9,10 @@ require 'action_mailer/test_case' # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true +# Bogus template processors +ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!" } +ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup" } + $:.unshift "#{File.dirname(__FILE__)}/fixtures/helpers" ActionMailer::Base.template_root = "#{File.dirname(__FILE__)}/fixtures" diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index c49049cc6a..e469302fe1 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -389,6 +389,8 @@ class ActionMailerTest < Test::Unit::TestCase end def test_custom_templating_extension + assert ActionView::Template.template_handler_extensions.include?("haml"), "haml extension was not registered" + # N.b., custom_templating_extension.text.plain.haml is expected to be in fixtures/test_mailer directory expected = new_mail expected.to = @recipient @@ -799,6 +801,8 @@ EOF end def test_implicitly_multipart_messages + assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered" + mail = TestMailer.create_implicitly_multipart_example(@recipient) assert_equal 3, mail.parts.length assert_equal "1.0", mail.mime_version @@ -812,6 +816,8 @@ EOF end def test_implicitly_multipart_messages_with_custom_order + assert ActionView::Template.template_handler_extensions.include?("bak"), "bak extension was not registered" + mail = TestMailer.create_implicitly_multipart_example(@recipient, nil, ["text/yaml", "text/plain"]) assert_equal 3, mail.parts.length assert_equal "text/html", mail.parts[0].content_type diff --git a/actionpack/README b/actionpack/README index 6090089bb9..e4ce4aa044 100644 --- a/actionpack/README +++ b/actionpack/README @@ -10,7 +10,7 @@ Action Pack implements these actions as public methods on Action Controllers and uses Action Views to implement the template rendering. Action Controllers are then responsible for handling all the actions relating to a certain part of an application. This grouping usually consists of actions for lists and for -CRUDs revolving around a single (or a few) model objects. So ContactController +CRUDs revolving around a single (or a few) model objects. So ContactsController would be responsible for listing contacts, creating, deleting, and updating contacts. A WeblogController could be responsible for both posts and comments. @@ -33,7 +33,7 @@ A short rundown of the major features: * Actions grouped in controller as methods instead of separate command objects and can therefore share helper methods - BlogController < ActionController::Base + CustomersController < ActionController::Base def show @customer = find_customer end @@ -42,7 +42,7 @@ A short rundown of the major features: @customer = find_customer @customer.attributes = params[:customer] @customer.save ? - redirect_to(:action => "display") : + redirect_to(:action => "show") : render(:action => "edit") end @@ -59,7 +59,7 @@ A short rundown of the major features: Title: <%= post.title %> <% end %> - All post titles: <%= @post.collect{ |p| p.title }.join ", " %> + All post titles: <%= @posts.collect{ |p| p.title }.join ", " %> <% unless @person.is_client? %> Not for clients to see... @@ -123,7 +123,7 @@ A short rundown of the major features: <%= text_field "post", "title", "size" => 30 %> <%= html_date_select(Date.today) %> <%= link_to "New post", :controller => "post", :action => "new" %> - <%= truncate(post.title, 25) %> + <%= truncate(post.title, :length => 25) %> {Learn more}[link:classes/ActionView/Helpers.html] @@ -177,21 +177,6 @@ A short rundown of the major features: {Learn more}[link:classes/ActionView/Helpers/JavaScriptHelper.html] -* Pagination for navigating lists of results - - # controller - def list - @pages, @people = - paginate :people, :order => 'last_name, first_name' - end - - # view - <%= link_to "Previous page", { :page => @pages.current.previous } if @pages.current.previous %> - <%= link_to "Next page", { :page => @pages.current.next } if @pages.current.next %> - - {Learn more}[link:classes/ActionController/Pagination.html] - - * Easy testing of both controller and rendered template through ActionController::TestCase class LoginControllerTest < ActionController::TestCase @@ -215,11 +200,11 @@ A short rundown of the major features: If Active Record is used as the model, you'll have the database debugging as well: - Processing WeblogController#create (for 127.0.0.1 at Sat Jun 19 14:04:23) - Params: {"controller"=>"weblog", "action"=>"create", + Processing PostsController#create (for 127.0.0.1 at Sat Jun 19 14:04:23) + Params: {"controller"=>"posts", "action"=>"create", "post"=>{"title"=>"this is good"} } SQL (0.000627) INSERT INTO posts (title) VALUES('this is good') - Redirected to http://test/weblog/display/5 + Redirected to http://example.com/posts/5 Completed in 0.221764 (4 reqs/sec) | DB: 0.059920 (27%) You specify a logger through a class method, such as: @@ -256,30 +241,6 @@ A short rundown of the major features: {Learn more}[link:classes/ActionController/Caching.html] -* Component requests from one controller to another - - class WeblogController < ActionController::Base - # Performs a method and then lets hello_world output its render - def delegate_action - do_other_stuff_before_hello_world - render_component :controller => "greeter", :action => "hello_world" - end - end - - class GreeterController < ActionController::Base - def hello_world - render_text "Hello World!" - end - end - - The same can be done in a view to do a partial rendering: - - Let's see a greeting: - <%= render_component :controller => "greeter", :action => "hello_world" %> - - {Learn more}[link:classes/ActionController/Components.html] - - * Powerful debugging mechanism for local requests All exceptions raised on actions performed on the request of a local user @@ -336,7 +297,7 @@ A short rundown of the major features: class WeblogController < ActionController::Base def create post = Post.create(params[:post]) - redirect_to :action => "display", :id => post.id + redirect_to :action => "show", :id => post.id end end @@ -362,7 +323,7 @@ methods: @posts = Post.find(:all) end - def display + def show @post = Post.find(params[:id]) end @@ -372,7 +333,7 @@ methods: def create @post = Post.create(params[:post]) - redirect_to :action => "display", :id => @post.id + redirect_to :action => "show", :id => @post.id end end @@ -385,47 +346,32 @@ request from the web-server (like to be Apache). And the templates look like this: - weblog/layout.erb: + weblog/layout.html.erb: <html><body> <%= yield %> </body></html> - weblog/index.erb: + weblog/index.html.erb: <% for post in @posts %> - <p><%= link_to(post.title, :action => "display", :id => post.id %></p> + <p><%= link_to(post.title, :action => "show", :id => post.id) %></p> <% end %> - weblog/display.erb: + weblog/show.html.erb: <p> - <b><%= post.title %></b><br/> - <b><%= post.content %></b> + <b><%= @post.title %></b><br/> + <b><%= @post.content %></b> </p> - weblog/new.erb: + weblog/new.html.erb: <%= form "post" %> This simple setup will list all the posts in the system on the index page, which is called by accessing /weblog/. It uses the form builder for the Active Record model to make the new screen, which in turn hands everything over to the create action (that's the default target for the form builder when given a -new model). After creating the post, it'll redirect to the display page using -an URL such as /weblog/display/5 (where 5 is the id of the post). - - -== Examples - -Action Pack ships with three examples that all demonstrate an increasingly -detailed view of the possibilities. First is blog_controller that is just a -single file for the whole MVC (but still split into separate parts). Second is -the debate_controller that uses separate template files and multiple screens. -Third is the address_book_controller that uses the layout feature to separate -template casing from content. - -Please note that you might need to change the "shebang" line to -#!/usr/local/env ruby, if your Ruby is not placed in /usr/local/bin/ruby +new model). After creating the post, it'll redirect to the show page using +an URL such as /weblog/5 (where 5 is the id of the post). -Also note that these examples are all for demonstrating using Action Pack on -its own. Not for when it's used inside of Rails. == Download @@ -460,4 +406,4 @@ And as Jim from Rake says: Feel free to submit commits or feature requests. If you send a patch, remember to update the corresponding unit tests. If fact, I prefer - new feature to be submitted in the form of new unit tests.
\ No newline at end of file + new feature to be submitted in the form of new unit tests. diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index 2981f625a1..5d5d6b8c9c 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -46,10 +46,9 @@ module ActionController autoload :Base, 'action_controller/base' autoload :Benchmarking, 'action_controller/benchmarking' autoload :Caching, 'action_controller/caching' - autoload :CgiRequest, 'action_controller/cgi_process' - autoload :CgiResponse, 'action_controller/cgi_process' autoload :Cookies, 'action_controller/cookies' autoload :Dispatcher, 'action_controller/dispatcher' + autoload :Failsafe, 'action_controller/failsafe' autoload :Filters, 'action_controller/filters' autoload :Flash, 'action_controller/flash' autoload :Helpers, 'action_controller/helpers' @@ -89,6 +88,11 @@ module ActionController module Http autoload :Headers, 'action_controller/headers' end + + # DEPRECATE: Remove CGI support + autoload :CgiRequest, 'action_controller/cgi_process' + autoload :CgiResponse, 'action_controller/cgi_process' + autoload :CGIHandler, 'action_controller/cgi_process' end class CGI diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb index c41b1a12cf..95cba0e411 100644 --- a/actionpack/lib/action_controller/caching/fragments.rb +++ b/actionpack/lib/action_controller/caching/fragments.rb @@ -83,15 +83,23 @@ module ActionController #:nodoc: end end - # Name can take one of three forms: - # * String: This would normally take the form of a path like "pages/45/notes" - # * Hash: Is treated as an implicit call to url_for, like { :controller => "pages", :action => "notes", :id => 45 } - # * Regexp: Will destroy all the matched fragments, example: - # %r{pages/\d*/notes} - # Ensure you do not specify start and finish in the regex (^$) because - # the actual filename matched looks like ./cache/filename/path.cache - # Regexp expiration is only supported on caches that can iterate over - # all keys (unlike memcached). + # Removes fragments from the cache. + # + # +key+ can take one of three forms: + # * String - This would normally take the form of a path, like + # <tt>"pages/45/notes"</tt>. + # * Hash - Treated as an implicit call to +url_for+, like + # <tt>{:controller => "pages", :action => "notes", :id => 45}</tt> + # * Regexp - Will remove any fragment that matches, so + # <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you + # don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because + # the actual filename matched looks like + # <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is + # only supported on caches that can iterate over all keys (unlike + # memcached). + # + # +options+ is passed through to the cache store's <tt>delete</tt> + # method (or <tt>delete_matched</tt>, for Regexp keys.) def expire_fragment(key, options = nil) return unless cache_configured? diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index a70ed72f03..22e4fbec43 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -33,28 +33,26 @@ module ActionController #:nodoc: # # Additionally, you can expire caches using Sweepers that act on changes in the model to determine when a cache is supposed to be # expired. - # - # == Setting the cache directory - # - # The cache directory should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. - # For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>RAILS_ROOT + "/public"</tt>). Changing - # this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your - # web server to look in the new location for cached files. - # - # == Setting the cache extension - # - # Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in - # order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>. - # If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an - # extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps. module Pages def self.included(base) #:nodoc: base.extend(ClassMethods) base.class_eval do @@page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : "" + ## + # :singleton-method: + # The cache directory should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. + # For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>RAILS_ROOT + "/public"</tt>). Changing + # this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your + # web server to look in the new location for cached files. cattr_accessor :page_cache_directory @@page_cache_extension = '.html' + ## + # :singleton-method: + # Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in + # order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>. + # If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an + # extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps. cattr_accessor :page_cache_extension end end diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb index 45b51a7488..5d6988e1b1 100644 --- a/actionpack/lib/action_controller/cgi_process.rb +++ b/actionpack/lib/action_controller/cgi_process.rb @@ -1,184 +1,72 @@ require 'action_controller/cgi_ext' module ActionController #:nodoc: - class Base - # Process a request extracted from a CGI object and return a response. Pass false as <tt>session_options</tt> to disable - # sessions (large performance increase if sessions are not needed). The <tt>session_options</tt> are the same as for CGI::Session: - # - # * <tt>:database_manager</tt> - standard options are CGI::Session::FileStore, CGI::Session::MemoryStore, and CGI::Session::PStore - # (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in - # lib/action_controller/session. - # * <tt>:session_key</tt> - the parameter name used for the session id. Defaults to '_session_id'. - # * <tt>:session_id</tt> - the session id to use. If not provided, then it is retrieved from the +session_key+ cookie, or - # automatically generated for a new session. - # * <tt>:new_session</tt> - if true, force creation of a new session. If not set, a new session is only created if none currently - # exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set, - # an ArgumentError is raised. - # * <tt>:session_expires</tt> - the time the current session expires, as a Time object. If not set, the session will continue - # indefinitely. - # * <tt>:session_domain</tt> - the hostname domain for which this session is valid. If not set, defaults to the hostname of the - # server. - # * <tt>:session_secure</tt> - if +true+, this session will only work over HTTPS. - # * <tt>:session_path</tt> - the path for which this session applies. Defaults to the directory of the CGI script. - # * <tt>:cookie_only</tt> - if +true+ (the default), session IDs will only be accepted from cookies and not from - # the query string or POST parameters. This protects against session fixation attacks. - def self.process_cgi(cgi = CGI.new, session_options = {}) - new.process_cgi(cgi, session_options) - end - - def process_cgi(cgi, session_options = {}) #:nodoc: - process(CgiRequest.new(cgi, session_options), CgiResponse.new(cgi)).out - end - end - - class CgiRequest < AbstractRequest #:nodoc: - attr_accessor :cgi, :session_options - class SessionFixationAttempt < StandardError #:nodoc: - end - - DEFAULT_SESSION_OPTIONS = { - :database_manager => CGI::Session::CookieStore, # store data in cookie - :prefix => "ruby_sess.", # prefix session file names - :session_path => "/", # available to all paths in app - :session_key => "_session_id", - :cookie_only => true, - :session_http_only=> true - } - - def initialize(cgi, session_options = {}) - @cgi = cgi - @session_options = session_options - @env = @cgi.__send__(:env_table) - super() - end - - def query_string - qs = @cgi.query_string if @cgi.respond_to?(:query_string) - if !qs.blank? - qs - else - super - end - end - - def body_stream #:nodoc: - @cgi.stdinput - end - - def cookies - @cgi.cookies.freeze - end - - def session - unless defined?(@session) - if @session_options == false - @session = Hash.new - else - stale_session_check! do - if cookie_only? && query_parameters[session_options_with_string_keys['session_key']] - raise SessionFixationAttempt - end - case value = session_options_with_string_keys['new_session'] - when true - @session = new_session - when false - begin - @session = CGI::Session.new(@cgi, session_options_with_string_keys) - # CGI::Session raises ArgumentError if 'new_session' == false - # and no session cookie or query param is present. - rescue ArgumentError - @session = Hash.new - end - when nil - @session = CGI::Session.new(@cgi, session_options_with_string_keys) - else - raise ArgumentError, "Invalid new_session option: #{value}" - end - @session['__valid_session'] - end + class CGIHandler + module ProperStream + def each + while line = gets + yield line end end - @session - end - def reset_session - @session.delete if defined?(@session) && @session.is_a?(CGI::Session) - @session = new_session - end - - def method_missing(method_id, *arguments) - @cgi.__send__(method_id, *arguments) rescue super - end - - private - # Delete an old session if it exists then create a new one. - def new_session - if @session_options == false - Hash.new + def read(*args) + if args.empty? + super || "" else - CGI::Session.new(@cgi, session_options_with_string_keys.merge("new_session" => false)).delete rescue nil - CGI::Session.new(@cgi, session_options_with_string_keys.merge("new_session" => true)) + super end end + end - def cookie_only? - session_options_with_string_keys['cookie_only'] - end + def self.dispatch_cgi(app, cgi, out = $stdout) + env = cgi.__send__(:env_table) + env.delete "HTTP_CONTENT_LENGTH" - def stale_session_check! - yield - rescue ArgumentError => argument_error - if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} - begin - # Note that the regexp does not allow $1 to end with a ':' - $1.constantize - rescue LoadError, NameError => const_error - raise ActionController::SessionRestoreError, <<-end_msg -Session contains objects whose class definition isn\'t available. -Remember to require the classes for all objects kept in the session. -(Original exception: #{const_error.message} [#{const_error.class}]) -end_msg - end + cgi.stdinput.extend ProperStream - retry - else - raise - end - end + env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - def session_options_with_string_keys - @session_options_with_string_keys ||= DEFAULT_SESSION_OPTIONS.merge(@session_options).stringify_keys - end - end + env.update({ + "rack.version" => [0,1], + "rack.input" => cgi.stdinput, + "rack.errors" => $stderr, + "rack.multithread" => false, + "rack.multiprocess" => true, + "rack.run_once" => false, + "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" + }) - class CgiResponse < AbstractResponse #:nodoc: - def initialize(cgi) - @cgi = cgi - super() - end - - def out(output = $stdout) - output.binmode if output.respond_to?(:binmode) - output.sync = false if output.respond_to?(:sync=) + env["QUERY_STRING"] ||= "" + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["REQUEST_PATH"] ||= "/" + env.delete "PATH_INFO" if env["PATH_INFO"] == "" + status, headers, body = app.call(env) begin - output.write(@cgi.header(@headers)) - - if @cgi.__send__(:env_table)['REQUEST_METHOD'] == 'HEAD' - return - elsif @body.respond_to?(:call) - # Flush the output now in case the @body Proc uses - # #syswrite. - output.flush if output.respond_to?(:flush) - @body.call(self, output) - else - output.write(@body) - end - - output.flush if output.respond_to?(:flush) - rescue Errno::EPIPE, Errno::ECONNRESET - # lost connection to parent process, ignore output + out.binmode if out.respond_to?(:binmode) + out.sync = false if out.respond_to?(:sync=) + + headers['Status'] = status.to_s + out.write(cgi.header(headers)) + + body.each { |part| + out.write part + out.flush if out.respond_to?(:flush) + } + ensure + body.close if body.respond_to?(:close) end end end + + class CgiRequest #:nodoc: + DEFAULT_SESSION_OPTIONS = { + :database_manager => CGI::Session::CookieStore, + :prefix => "ruby_sess.", + :session_path => "/", + :session_key => "_session_id", + :cookie_only => true, + :session_http_only => true + } + end end diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index 47199af2b4..203f6b1683 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -24,8 +24,7 @@ module ActionController end end - # Backward-compatible class method takes CGI-specific args. Deprecated - # in favor of Dispatcher.new(output, request, response).dispatch. + # DEPRECATE: Remove CGI support def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, output = $stdout) new(output).dispatch_cgi(cgi, session_options) end @@ -43,60 +42,19 @@ module ActionController callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier) @prepare_dispatch_callbacks.replace_or_append!(callback) end - - # If the block raises, send status code as a last-ditch response. - def failsafe_response(fallback_output, status, originating_exception = nil) - yield - rescue Exception => exception - begin - log_failsafe_exception(status, originating_exception || exception) - body = failsafe_response_body(status) - fallback_output.write "Status: #{status}\r\nContent-Type: text/html\r\n\r\n#{body}" - nil - rescue Exception => failsafe_error # Logger or IO errors - $stderr.puts "Error during failsafe response: #{failsafe_error}" - $stderr.puts "(originally #{originating_exception})" if originating_exception - end - end - - private - def failsafe_response_body(status) - error_path = "#{error_file_path}/#{status.to_s[0..2]}.html" - - if File.exist?(error_path) - File.read(error_path) - else - "<html><body><h1>#{status}</h1></body></html>" - end - end - - def log_failsafe_exception(status, exception) - message = "/!\\ FAILSAFE /!\\ #{Time.now}\n Status: #{status}\n" - message << " #{exception}\n #{exception.backtrace.join("\n ")}" if exception - failsafe_logger.fatal message - end - - def failsafe_logger - if defined?(::RAILS_DEFAULT_LOGGER) && !::RAILS_DEFAULT_LOGGER.nil? - ::RAILS_DEFAULT_LOGGER - else - Logger.new($stderr) - end - end end cattr_accessor :middleware self.middleware = MiddlewareStack.new - - cattr_accessor :error_file_path - self.error_file_path = Rails.public_path if defined?(Rails.public_path) + self.middleware.use "ActionController::Failsafe" include ActiveSupport::Callbacks define_callbacks :prepare_dispatch, :before_dispatch, :after_dispatch + # DEPRECATE: Remove arguments def initialize(output = $stdout, request = nil, response = nil) @output, @request, @response = output, request, response - @app = @@middleware.build(lambda { |env| self._call(env) }) + @app = @@middleware.build(lambda { |env| self.dup._call(env) }) end def dispatch_unlocked @@ -120,14 +78,9 @@ module ActionController end end + # DEPRECATE: Remove CGI support def dispatch_cgi(cgi, session_options) - if cgi ||= self.class.failsafe_response(@output, '400 Bad Request') { CGI.new } - @request = CgiRequest.new(cgi, session_options) - @response = CgiResponse.new(cgi) - dispatch - end - rescue Exception => exception - failsafe_rescue exception + CGIHandler.dispatch_cgi(self, cgi, @output) end def call(env) @@ -160,34 +113,24 @@ module ActionController Base.logger.flush end - def mark_as_test_request! - @test_request = true - self - end - - def test_request? - @test_request - end - def checkin_connections # Don't return connection (and peform implicit rollback) if this request is a part of integration test - return if test_request? + # TODO: This callback should have direct access to env + return if @request.key?("action_controller.test") ActiveRecord::Base.clear_active_connections! end protected def handle_request @controller = Routing::Routes.recognize(@request) - @controller.process(@request, @response).out(@output) + @controller.process(@request, @response).out end def failsafe_rescue(exception) - self.class.failsafe_response(@output, '500 Internal Server Error', exception) do - if @controller ||= (::ApplicationController rescue Base) - @controller.process_with_exception(@request, @response, exception).out(@output) - else - raise exception - end + if @controller ||= (::ApplicationController rescue Base) + @controller.process_with_exception(@request, @response, exception).out + else + raise exception end end end diff --git a/actionpack/lib/action_controller/failsafe.rb b/actionpack/lib/action_controller/failsafe.rb new file mode 100644 index 0000000000..bb6ef39470 --- /dev/null +++ b/actionpack/lib/action_controller/failsafe.rb @@ -0,0 +1,52 @@ +module ActionController + class Failsafe + cattr_accessor :error_file_path + self.error_file_path = Rails.public_path if defined?(Rails.public_path) + + def initialize(app) + @app = app + end + + def call(env) + @app.call(env) + rescue Exception => exception + # Reraise exception in test environment + if env["action_controller.test"] + raise exception + else + failsafe_response(exception) + end + end + + private + def failsafe_response(exception) + log_failsafe_exception(exception) + [500, {'Content-Type' => 'text/html'}, failsafe_response_body] + rescue Exception => failsafe_error # Logger or IO errors + $stderr.puts "Error during failsafe response: #{failsafe_error}" + end + + def failsafe_response_body + error_path = "#{self.class.error_file_path}/500.html" + if File.exist?(error_path) + File.read(error_path) + else + "<html><body><h1>500 Internal Server Error</h1></body></html>" + end + end + + def log_failsafe_exception(exception) + message = "/!\\ FAILSAFE /!\\ #{Time.now}\n Status: 500 Internal Server Error\n" + message << " #{exception}\n #{exception.backtrace.join("\n ")}" if exception + failsafe_logger.fatal(message) + end + + def failsafe_logger + if defined?(::RAILS_DEFAULT_LOGGER) && !::RAILS_DEFAULT_LOGGER.nil? + ::RAILS_DEFAULT_LOGGER + else + Logger.new($stderr) + end + end + end +end diff --git a/actionpack/lib/action_controller/integration.rb b/actionpack/lib/action_controller/integration.rb index 65e3eed678..eeabe5b845 100644 --- a/actionpack/lib/action_controller/integration.rb +++ b/actionpack/lib/action_controller/integration.rb @@ -9,13 +9,17 @@ module ActionController # multiple sessions and run them side-by-side, you can also mimic (to some # limited extent) multiple simultaneous users interacting with your system. # - # Typically, you will instantiate a new session using IntegrationTest#open_session, - # rather than instantiating Integration::Session directly. + # Typically, you will instantiate a new session using + # IntegrationTest#open_session, rather than instantiating + # Integration::Session directly. class Session include Test::Unit::Assertions include ActionController::TestCase::Assertions include ActionController::TestProcess + # Rack application to use + attr_accessor :application + # The integer HTTP status code of the last request. attr_reader :status @@ -57,7 +61,8 @@ module ActionController end # Create and initialize a new Session instance. - def initialize + def initialize(app) + @application = app reset! end @@ -76,11 +81,13 @@ module ActionController self.host = "www.example.com" self.remote_addr = "127.0.0.1" - self.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" + self.accept = "text/xml,application/xml,application/xhtml+xml," + + "text/html;q=0.9,text/plain;q=0.8,image/png," + + "*/*;q=0.5" unless defined? @named_routes_configured # install the named routes in this session instance. - klass = class<<self; self; end + klass = class << self; self; end Routing::Routes.install_helpers(klass) # the helpers are made protected by default--we make them public for @@ -94,7 +101,7 @@ module ActionController # # session.https! # session.https!(false) - def https!(flag=true) + def https!(flag = true) @https = flag end @@ -164,17 +171,21 @@ module ActionController # Performs a GET request with the given parameters. # - # - +path+: The URI (as a String) on which you want to perform a GET request. - # - +parameters+: The HTTP parameters that you want to pass. This may be +nil+, + # - +path+: The URI (as a String) on which you want to perform a GET + # request. + # - +parameters+: The HTTP parameters that you want to pass. This may + # be +nil+, # a Hash, or a String that is appropriately encoded - # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>). + # (<tt>application/x-www-form-urlencoded</tt> or + # <tt>multipart/form-data</tt>). # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will # automatically be upcased, with the prefix 'HTTP_' added if needed. # - # This method returns an AbstractResponse object, which one can use to inspect - # the details of the response. Furthermore, if this method was called from an - # ActionController::IntegrationTest object, then that object's <tt>@response</tt> - # instance variable will point to the same response object. + # This method returns an AbstractResponse object, which one can use to + # inspect the details of the response. Furthermore, if this method was + # called from an ActionController::IntegrationTest object, then that + # object's <tt>@response</tt> instance variable will point to the same + # response object. # # You can also perform POST, PUT, DELETE, and HEAD requests with +post+, # +put+, +delete+, and +head+. @@ -182,22 +193,26 @@ module ActionController process :get, path, parameters, headers end - # Performs a POST request with the given parameters. See get() for more details. + # Performs a POST request with the given parameters. See get() for more + # details. def post(path, parameters = nil, headers = nil) process :post, path, parameters, headers end - # Performs a PUT request with the given parameters. See get() for more details. + # Performs a PUT request with the given parameters. See get() for more + # details. def put(path, parameters = nil, headers = nil) process :put, path, parameters, headers end - # Performs a DELETE request with the given parameters. See get() for more details. + # Performs a DELETE request with the given parameters. See get() for + # more details. def delete(path, parameters = nil, headers = nil) process :delete, path, parameters, headers end - # Performs a HEAD request with the given parameters. See get() for more details. + # Performs a HEAD request with the given parameters. See get() for more + # details. def head(path, parameters = nil, headers = nil) process :head, path, parameters, headers end @@ -212,7 +227,8 @@ module ActionController def xml_http_request(request_method, path, parameters = nil, headers = nil) headers ||= {} headers['X-Requested-With'] = 'XMLHttpRequest' - headers['Accept'] ||= 'text/javascript, text/html, application/xml, text/xml, */*' + headers['Accept'] ||= 'text/javascript, text/html, application/xml, ' + + 'text/xml, */*' process(request_method, path, parameters, headers) end @@ -221,7 +237,9 @@ module ActionController # Returns the URL for the given options, according to the rules specified # in the application's routes. def url_for(options) - controller ? controller.url_for(options) : generic_url_rewriter.rewrite(options) + controller ? + controller.url_for(options) : + generic_url_rewriter.rewrite(options) end private @@ -247,17 +265,34 @@ module ActionController data = nil end + env["QUERY_STRING"] ||= "" + + data = data.is_a?(IO) ? data : StringIO.new(data || '') + env.update( - "REQUEST_METHOD" => method.to_s.upcase, + "REQUEST_METHOD" => method.to_s.upcase, + "SERVER_NAME" => host, + "SERVER_PORT" => (https? ? "443" : "80"), + "HTTPS" => https? ? "on" : "off", + "rack.url_scheme" => https? ? "https" : "http", + "SCRIPT_NAME" => "", + "REQUEST_URI" => path, "HTTP_HOST" => host, "REMOTE_ADDR" => remote_addr, - "SERVER_PORT" => (https? ? "443" : "80"), "CONTENT_TYPE" => "application/x-www-form-urlencoded", "CONTENT_LENGTH" => data ? data.length.to_s : nil, "HTTP_COOKIE" => encode_cookies, - "HTTPS" => https? ? "on" : "off", - "HTTP_ACCEPT" => accept + "HTTP_ACCEPT" => accept, + + "rack.version" => [0,1], + "rack.input" => data, + "rack.errors" => StringIO.new, + "rack.multithread" => true, + "rack.multiprocess" => true, + "rack.run_once" => false, + + "action_controller.test" => true ) (headers || {}).each do |key, value| @@ -272,48 +307,43 @@ module ActionController ActionController::Base.clear_last_instantiation! - env['rack.input'] = data.is_a?(IO) ? data : StringIO.new(data || '') - @status, @headers, result_body = ActionController::Dispatcher.new.mark_as_test_request!.call(env) + app = Rack::Lint.new(@application) + + status, headers, body = app.call(env) @request_count += 1 - @controller = ActionController::Base.last_instantiation - @request = @controller.request - @response = @controller.response + if @controller = ActionController::Base.last_instantiation + @request = @controller.request + @response = @controller.response - # Decorate the response with the standard behavior of the TestResponse - # so that things like assert_response can be used in integration - # tests. - @response.extend(TestResponseBehavior) + # Decorate the response with the standard behavior of the + # TestResponse so that things like assert_response can be + # used in integration tests. + @response.extend(TestResponseBehavior) + end @html_document = nil - # Inject status back in for backwords compatibility with CGI - @headers['Status'] = @status - - @status, @status_message = @status.split(/ /) - @status = @status.to_i + @status = status.to_i + @status_message = StatusCodes::STATUS_CODES[@status] - cgi_headers = Hash.new { |h,k| h[k] = [] } - @headers.each do |key, value| - cgi_headers[key.downcase] << value - end - cgi_headers['set-cookie'] = cgi_headers['set-cookie'].first - @headers = cgi_headers + @headers = Rack::Utils::HeaderHash.new(headers) - @response.headers['cookie'] ||= [] - (@headers['set-cookie'] || []).each do |cookie| + (@headers['Set-Cookie'] || []).each do |cookie| name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2] @cookies[name] = value - - # Fake CGI cookie header - # DEPRECATE: Use response.headers["Set-Cookie"] instead - @response.headers['cookie'] << CGI::Cookie::new("name" => name, "value" => value) end - return status + @body = "" + body.each { |part| @body << part } + + return @status rescue MultiPartNeededException boundary = "----------XnJLe9ZIbbGUYtzPQJ16u1" - status = process(method, path, multipart_body(parameters, boundary), (headers || {}).merge({"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"})) + status = process(method, path, + multipart_body(parameters, boundary), + (headers || {}).merge( + {"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"})) return status end @@ -335,7 +365,7 @@ module ActionController "SERVER_PORT" => https? ? "443" : "80", "HTTPS" => https? ? "on" : "off" } - ActionController::UrlRewriter.new(ActionController::RackRequest.new(env), {}) + UrlRewriter.new(RackRequest.new(env), {}) end def name_with_prefix(prefix, name) @@ -349,9 +379,13 @@ module ActionController raise MultiPartNeededException elsif Hash === parameters return nil if parameters.empty? - parameters.map { |k,v| requestify(v, name_with_prefix(prefix, k)) }.join("&") + parameters.map { |k,v| + requestify(v, name_with_prefix(prefix, k)) + }.join("&") elsif Array === parameters - parameters.map { |v| requestify(v, name_with_prefix(prefix, "")) }.join("&") + parameters.map { |v| + requestify(v, name_with_prefix(prefix, "")) + }.join("&") elsif prefix.nil? parameters else @@ -458,7 +492,8 @@ EOF # can use this method to open multiple sessions that ought to be tested # simultaneously. def open_session - session = Integration::Session.new + application = ActionController::Dispatcher.new + session = Integration::Session.new(application) # delegate the fixture accessors back to the test instance extras = Module.new { attr_accessor :delegate, :test_result } @@ -466,12 +501,16 @@ EOF self.class.fixture_table_names.each do |table_name| name = table_name.tr(".", "_") next unless respond_to?(name) - extras.__send__(:define_method, name) { |*args| delegate.send(name, *args) } + extras.__send__(:define_method, name) { |*args| + delegate.send(name, *args) + } end end # delegate add_assertion to the test case - extras.__send__(:define_method, :add_assertion) { test_result.add_assertion } + extras.__send__(:define_method, :add_assertion) { + test_result.add_assertion + } session.extend(extras) session.delegate = self session.test_result = @_result @@ -599,7 +638,8 @@ EOF # would potentially have to set their values for both Test::Unit::TestCase # ActionController::IntegrationTest, since by the time the value is set on # TestCase, IntegrationTest has already been defined and cannot inherit - # changes to those variables. So, we make those two attributes copy-on-write. + # changes to those variables. So, we make those two attributes + # copy-on-write. class << self def use_transactional_fixtures=(flag) #:nodoc: diff --git a/actionpack/lib/action_controller/rack_process.rb b/actionpack/lib/action_controller/rack_process.rb index 58d7b53e31..568f893c6c 100644 --- a/actionpack/lib/action_controller/rack_process.rb +++ b/actionpack/lib/action_controller/rack_process.rb @@ -55,14 +55,7 @@ module ActionController #:nodoc: end def cookies - return {} unless @env["HTTP_COOKIE"] - - unless @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"] - @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"] - @env["rack.request.cookie_hash"] = CGI::Cookie::parse(@env["rack.request.cookie_string"]) - end - - @env["rack.request.cookie_hash"] + Rack::Request.new(@env).cookies end def server_port @@ -164,7 +157,7 @@ end_msg @status || super end - def out(output = $stdout, &block) + def out(&block) # Nasty hack because CGI sessions are closed after the normal # prepare! statement set_cookies! diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb index 9c24c3def4..d7b0e96c93 100644 --- a/actionpack/lib/action_controller/rescue.rb +++ b/actionpack/lib/action_controller/rescue.rb @@ -1,13 +1,19 @@ module ActionController #:nodoc: - # Actions that fail to perform as expected throw exceptions. These exceptions can either be rescued for the public view - # (with a nice user-friendly explanation) or for the developers view (with tons of debugging information). The developers view - # is already implemented by the Action Controller, but the public view should be tailored to your specific application. - # - # The default behavior for public exceptions is to render a static html file with the name of the error code thrown. If no such - # file exists, an empty response is sent with the correct status code. + # Actions that fail to perform as expected throw exceptions. These + # exceptions can either be rescued for the public view (with a nice + # user-friendly explanation) or for the developers view (with tons of + # debugging information). The developers view is already implemented by + # the Action Controller, but the public view should be tailored to your + # specific application. # - # You can override what constitutes a local request by overriding the <tt>local_request?</tt> method in your own controller. - # Custom rescue behavior is achieved by overriding the <tt>rescue_action_in_public</tt> and <tt>rescue_action_locally</tt> methods. + # The default behavior for public exceptions is to render a static html + # file with the name of the error code thrown. If no such file exists, an + # empty response is sent with the correct status code. + # + # You can override what constitutes a local request by overriding the + # <tt>local_request?</tt> method in your own controller. Custom rescue + # behavior is achieved by overriding the <tt>rescue_action_in_public</tt> + # and <tt>rescue_action_locally</tt> methods. module Rescue LOCALHOST = '127.0.0.1'.freeze @@ -32,6 +38,9 @@ module ActionController #:nodoc: 'ActionView::TemplateError' => 'template_error' } + RESCUES_TEMPLATE_PATH = ActionView::PathSet::Path.new( + "#{File.dirname(__FILE__)}/templates", true) + def self.included(base) #:nodoc: base.cattr_accessor :rescue_responses base.rescue_responses = Hash.new(DEFAULT_RESCUE_RESPONSE) @@ -56,12 +65,15 @@ module ActionController #:nodoc: end protected - # Exception handler called when the performance of an action raises an exception. + # Exception handler called when the performance of an action raises + # an exception. def rescue_action(exception) - rescue_with_handler(exception) || rescue_action_without_handler(exception) + rescue_with_handler(exception) || + rescue_action_without_handler(exception) end - # Overwrite to implement custom logging of errors. By default logs as fatal. + # Overwrite to implement custom logging of errors. By default + # logs as fatal. def log_error(exception) #:doc: ActiveSupport::Deprecation.silence do if ActionView::TemplateError === exception @@ -75,16 +87,19 @@ module ActionController #:nodoc: end end - # Overwrite to implement public exception handling (for requests answering false to <tt>local_request?</tt>). By - # default will call render_optional_error_file. Override this method to provide more user friendly error messages. + # Overwrite to implement public exception handling (for requests + # answering false to <tt>local_request?</tt>). By default will call + # render_optional_error_file. Override this method to provide more + # user friendly error messages. def rescue_action_in_public(exception) #:doc: render_optional_error_file response_code_for_rescue(exception) end - - # Attempts to render a static error page based on the <tt>status_code</tt> thrown, - # or just return headers if no such file exists. For example, if a 500 error is - # being handled Rails will first attempt to render the file at <tt>public/500.html</tt>. - # If the file doesn't exist, the body of the response will be left empty. + + # Attempts to render a static error page based on the + # <tt>status_code</tt> thrown, or just return headers if no such file + # exists. For example, if a 500 error is being handled Rails will first + # attempt to render the file at <tt>public/500.html</tt>. If the file + # doesn't exist, the body of the response will be left empty. def render_optional_error_file(status_code) status = interpret_status(status_code) path = "#{Rails.public_path}/#{status[0,3]}.html" @@ -106,11 +121,13 @@ module ActionController #:nodoc: # a controller action. def rescue_action_locally(exception) @template.instance_variable_set("@exception", exception) - @template.instance_variable_set("@rescues_path", File.dirname(rescues_path("stub"))) - @template.instance_variable_set("@contents", @template.render(:file => template_path_for_local_rescue(exception))) + @template.instance_variable_set("@rescues_path", RESCUES_TEMPLATE_PATH) + @template.instance_variable_set("@contents", + @template.render(:file => template_path_for_local_rescue(exception))) response.content_type = Mime::HTML - render_for_file(rescues_path("layout"), response_code_for_rescue(exception)) + render_for_file(rescues_path("layout"), + response_code_for_rescue(exception)) end def rescue_action_without_handler(exception) @@ -138,7 +155,7 @@ module ActionController #:nodoc: end def rescues_path(template_name) - "#{File.dirname(__FILE__)}/templates/rescues/#{template_name}.erb" + RESCUES_TEMPLATE_PATH["rescues/#{template_name}.erb"] end def template_path_for_local_rescue(exception) @@ -150,8 +167,9 @@ module ActionController #:nodoc: end def clean_backtrace(exception) - defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ? - Rails.backtrace_cleaner.clean(exception.backtrace) : exception.backtrace + defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ? + Rails.backtrace_cleaner.clean(exception.backtrace) : + exception.backtrace end end end diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index b6cfe2dd68..e8988aa737 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -283,7 +283,12 @@ module ActionController # * <tt>:new</tt> - Same as <tt>:collection</tt>, but for actions that operate on the new \resource action. # * <tt>:controller</tt> - Specify the controller name for the routes. # * <tt>:singular</tt> - Specify the singular name used in the member routes. - # * <tt>:requirements</tt> - Set custom routing parameter requirements. + # * <tt>:requirements</tt> - Set custom routing parameter requirements; this is a hash of either + # regular expressions (which must match for the route to match) or extra parameters. For example: + # + # map.resource :profile, :path_prefix => ':name', :requirements => { :name => /[a-zA-Z]+/, :extra => 'value' } + # + # will only match if the first part is alphabetic, and will pass the parameter :extra to the controller. # * <tt>:conditions</tt> - Specify custom routing recognition conditions. \Resources sets the <tt>:method</tt> value for the method-specific routes. # * <tt>:as</tt> - Specify a different \resource name to use in the URL path. For example: # # products_path == '/productos' diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb index efd474097e..da9b56fdf9 100644 --- a/actionpack/lib/action_controller/routing.rb +++ b/actionpack/lib/action_controller/routing.rb @@ -83,9 +83,11 @@ module ActionController # This sets up +blog+ as the default controller if no other is specified. # This means visiting '/' would invoke the blog controller. # - # More formally, you can define defaults in a route with the <tt>:defaults</tt> key. + # More formally, you can include arbitrary parameters in the route, thus: # - # map.connect ':controller/:action/:id', :action => 'show', :defaults => { :page => 'Dashboard' } + # map.connect ':controller/:action/:id', :action => 'show', :page => 'Dashboard' + # + # This will pass the :page parameter to all incoming requests that match this route. # # Note: The default routes, as provided by the Rails generator, make all actions in every # controller accessible via GET requests. You should consider removing them or commenting diff --git a/actionpack/lib/action_controller/session/active_record_store.rb b/actionpack/lib/action_controller/session/active_record_store.rb index 1e8eb57acb..fadf2a6b32 100644 --- a/actionpack/lib/action_controller/session/active_record_store.rb +++ b/actionpack/lib/action_controller/session/active_record_store.rb @@ -56,6 +56,8 @@ class CGI class ActiveRecordStore # The default Active Record class. class Session < ActiveRecord::Base + ## + # :singleton-method: # Customizable data column name. Defaults to 'data'. cattr_accessor :data_column_name self.data_column_name = 'data' @@ -166,17 +168,25 @@ class CGI # binary session data in a +text+ column. For higher performance, # store in a +blob+ column instead and forgo the Base64 encoding. class SqlBypass + ## + # :singleton-method: # Use the ActiveRecord::Base.connection by default. cattr_accessor :connection + ## + # :singleton-method: # The table name defaults to 'sessions'. cattr_accessor :table_name @@table_name = 'sessions' + ## + # :singleton-method: # The session id field defaults to 'session_id'. cattr_accessor :session_id_column @@session_id_column = 'session_id' + ## + # :singleton-method: # The data field defaults to 'data'. cattr_accessor :data_column @@data_column = 'data' diff --git a/actionpack/lib/action_controller/templates/rescues/diagnostics.erb b/actionpack/lib/action_controller/templates/rescues/diagnostics.erb index b5483eccae..669da1b26e 100644 --- a/actionpack/lib/action_controller/templates/rescues/diagnostics.erb +++ b/actionpack/lib/action_controller/templates/rescues/diagnostics.erb @@ -6,6 +6,6 @@ </h1> <pre><%=h @exception.clean_message %></pre> -<%= render(:file => @rescues_path + "/_trace.erb") %> +<%= render :file => @rescues_path["rescues/_trace.erb"] %> -<%= render(:file => @rescues_path + "/_request_and_response.erb") %> +<%= render :file => @rescues_path["rescues/_request_and_response.erb"] %> diff --git a/actionpack/lib/action_controller/templates/rescues/template_error.erb b/actionpack/lib/action_controller/templates/rescues/template_error.erb index 76fa3df89d..2e34e03bd5 100644 --- a/actionpack/lib/action_controller/templates/rescues/template_error.erb +++ b/actionpack/lib/action_controller/templates/rescues/template_error.erb @@ -15,7 +15,7 @@ <% @real_exception = @exception @exception = @exception.original_exception || @exception %> -<%= render(:file => @rescues_path + "/_trace.erb") %> +<%= render :file => @rescues_path["rescues/_trace.erb"] %> <% @exception = @real_exception %> -<%= render(:file => @rescues_path + "/_request_and_response.erb") %> +<%= render :file => @rescues_path["rescues/_request_and_response.erb"] %> diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index da1f283deb..33517ffb7b 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -5,7 +5,7 @@ module ActionView #:nodoc: class MissingTemplate < ActionViewError #:nodoc: def initialize(paths, path, template_format = nil) full_template_path = path.include?('.') ? path : "#{path}.erb" - display_paths = paths.join(':') + display_paths = paths.compact.join(":") template_type = (path =~ /layouts/i) ? 'layout' : 'template' super("Missing #{template_type} #{full_template_path} in view path #{display_paths}") end @@ -183,13 +183,17 @@ module ActionView #:nodoc: @@exempt_from_layout.merge(regexps) end + @@debug_rjs = false + ## + # :singleton-method: # Specify whether RJS responses should be wrapped in a try/catch block # that alert()s the caught exception (and then re-raises it). - @@debug_rjs = false cattr_accessor :debug_rjs - # A warning will be displayed whenever an action results in a cache miss on your view paths. @@warn_cache_misses = false + ## + # :singleton-method: + # A warning will be displayed whenever an action results in a cache miss on your view paths. cattr_accessor :warn_cache_misses attr_internal :request @@ -275,7 +279,7 @@ module ActionView #:nodoc: if defined? @template_format @template_format elsif controller && controller.respond_to?(:request) - @template_format = controller.request.template_format + @template_format = controller.request.template_format.to_sym else @template_format = :html end @@ -327,9 +331,6 @@ module ActionView #:nodoc: elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension) && (template = self.view_paths["#{template_file_name}.#{first_render.format_and_extension}"]) template - elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"] - @template_format = :html - template else template = Template.new(template_path, view_paths) diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index 2bdd960f4c..3b301248ff 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -97,7 +97,7 @@ module ActionView # Returns an escaped version of +html+ without affecting existing escaped entities. # # ==== Examples - # escape_once("1 > 2 & 3") + # escape_once("1 < 2 & 3") # # => "1 < 2 & 3" # # escape_once("<< Accept & Checkout") diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb index ecb6103ade..9c8b8ade1e 100644 --- a/actionpack/lib/action_view/paths.rb +++ b/actionpack/lib/action_view/paths.rb @@ -41,7 +41,7 @@ module ActionView #:nodoc: class Path #:nodoc: attr_reader :path, :paths - delegate :to_s, :to_str, :hash, :inspect, :to => :path + delegate :hash, :inspect, :to => :path def initialize(path, load = false) raise ArgumentError, "path already is a Path class" if path.is_a?(Path) @@ -49,6 +49,14 @@ module ActionView #:nodoc: reload! if load end + def to_s + if defined?(RAILS_ROOT) + path.to_s.sub(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') + else + path.to_s + end + end + def ==(path) to_str == path.to_str end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 52378e049e..e32b7688d0 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -9,9 +9,9 @@ module ActionView #:nodoc: def initialize(template_path, load_paths = []) template_path = template_path.dup + @load_path, @filename = find_full_path(template_path, load_paths) @base_path, @name, @format, @extension = split(template_path) @base_path.to_s.gsub!(/\/$/, '') # Push to split method - @load_path, @filename = find_full_path(template_path, load_paths) # Extend with partial super powers extend RenderablePartial if @name =~ /^_/ diff --git a/actionpack/lib/action_view/template_handlers/erb.rb b/actionpack/lib/action_view/template_handlers/erb.rb index f8d3da15be..e3120ba267 100644 --- a/actionpack/lib/action_view/template_handlers/erb.rb +++ b/actionpack/lib/action_view/template_handlers/erb.rb @@ -3,6 +3,8 @@ module ActionView class ERB < TemplateHandler include Compilable + ## + # :singleton-method: # Specify trim mode for the ERB compiler. Defaults to '-'. # See ERb documentation for suitable values. cattr_accessor :erb_trim_mode diff --git a/actionpack/lib/action_view/template_handlers/rjs.rb b/actionpack/lib/action_view/template_handlers/rjs.rb index a700655c9a..41a1fddb47 100644 --- a/actionpack/lib/action_view/template_handlers/rjs.rb +++ b/actionpack/lib/action_view/template_handlers/rjs.rb @@ -4,6 +4,7 @@ module ActionView include Compilable def compile(template) + "@template_format = :html;" + "controller.response.content_type ||= Mime::JS;" + "update_page do |page|;#{template.source}\nend" end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 10c65acd9a..7e7f488df6 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -67,7 +67,7 @@ class PageCachingTest < ActionController::TestCase def teardown FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) - + ActionController::Routing::Routes.clear! ActionController::Base.perform_caching = false end @@ -401,7 +401,7 @@ class ActionCacheTest < ActionController::TestCase def test_xml_version_of_resource_is_treated_as_different_cache with_routing do |set| - ActionController::Routing::Routes.draw do |map| + set.draw do |map| map.connect ':controller/:action.:format' map.connect ':controller/:action' end diff --git a/actionpack/test/controller/cgi_test.rb b/actionpack/test/controller/cgi_test.rb deleted file mode 100644 index ac1c8abc59..0000000000 --- a/actionpack/test/controller/cgi_test.rb +++ /dev/null @@ -1,262 +0,0 @@ -require 'abstract_unit' - -class BaseCgiTest < Test::Unit::TestCase - def setup - @request_hash = { - "HTTP_MAX_FORWARDS" => "10", - "SERVER_NAME" => "glu.ttono.us:8007", - "FCGI_ROLE" => "RESPONDER", - "AUTH_TYPE" => "Basic", - "HTTP_X_FORWARDED_HOST" => "glu.ttono.us", - "HTTP_ACCEPT_CHARSET" => "UTF-8", - "HTTP_ACCEPT_ENCODING" => "gzip, deflate", - "HTTP_CACHE_CONTROL" => "no-cache, max-age=0", - "HTTP_PRAGMA" => "no-cache", - "HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", - "PATH_INFO" => "/homepage/", - "HTTP_ACCEPT_LANGUAGE" => "en", - "HTTP_NEGOTIATE" => "trans", - "HTTP_HOST" => "glu.ttono.us:8007", - "HTTP_REFERER" => "http://www.google.com/search?q=glu.ttono.us", - "HTTP_FROM" => "googlebot", - "SERVER_PROTOCOL" => "HTTP/1.1", - "REDIRECT_URI" => "/dispatch.fcgi", - "SCRIPT_NAME" => "/dispatch.fcgi", - "SERVER_ADDR" => "207.7.108.53", - "REMOTE_ADDR" => "207.7.108.53", - "REMOTE_HOST" => "google.com", - "REMOTE_IDENT" => "kevin", - "REMOTE_USER" => "kevin", - "SERVER_SOFTWARE" => "lighttpd/1.4.5", - "HTTP_COOKIE" => "_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes", - "HTTP_X_FORWARDED_SERVER" => "glu.ttono.us", - "REQUEST_URI" => "/admin", - "DOCUMENT_ROOT" => "/home/kevinc/sites/typo/public", - "PATH_TRANSLATED" => "/home/kevinc/sites/typo/public/homepage/", - "SERVER_PORT" => "8007", - "QUERY_STRING" => "", - "REMOTE_PORT" => "63137", - "GATEWAY_INTERFACE" => "CGI/1.1", - "HTTP_X_FORWARDED_FOR" => "65.88.180.234", - "HTTP_ACCEPT" => "*/*", - "SCRIPT_FILENAME" => "/home/kevinc/sites/typo/public/dispatch.fcgi", - "REDIRECT_STATUS" => "200", - "REQUEST_METHOD" => "GET" - } - # some Nokia phone browsers omit the space after the semicolon separator. - # some developers have grown accustomed to using comma in cookie values. - @alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"} - @cgi = CGI.new - class << @cgi; attr_accessor :env_table end - @cgi.env_table = @request_hash - @request = ActionController::CgiRequest.new(@cgi) - end - - def default_test; end - - private - - def set_content_data(data) - @request.env['REQUEST_METHOD'] = 'POST' - @request.env['CONTENT_LENGTH'] = data.length - @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' - @request.env['RAW_POST_DATA'] = data - end -end - -class CgiRequestTest < BaseCgiTest - def test_proxy_request - assert_equal 'glu.ttono.us', @request.host_with_port - end - - def test_http_host - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash['HTTP_HOST'] = "rubyonrails.org:8080" - assert_equal "rubyonrails.org:8080", @request.host_with_port - - @request_hash['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org" - assert_equal "www.secondhost.org", @request.host(true) - end - - def test_http_host_with_default_port_overrides_server_port - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash['HTTP_HOST'] = "rubyonrails.org" - assert_equal "rubyonrails.org", @request.host_with_port - end - - def test_host_with_port_defaults_to_server_name_if_no_host_headers - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash.delete "HTTP_HOST" - assert_equal "glu.ttono.us:8007", @request.host_with_port - end - - def test_host_with_port_falls_back_to_server_addr_if_necessary - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash.delete "HTTP_HOST" - @request_hash.delete "SERVER_NAME" - assert_equal "207.7.108.53:8007", @request.host_with_port - end - - def test_host_with_port_if_http_standard_port_is_specified - @request_hash['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80" - assert_equal "glu.ttono.us", @request.host_with_port - end - - def test_host_with_port_if_https_standard_port_is_specified - @request_hash['HTTP_X_FORWARDED_PROTO'] = "https" - @request_hash['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443" - assert_equal "glu.ttono.us", @request.host_with_port - end - - def test_host_if_ipv6_reference - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]" - assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host - end - - def test_host_if_ipv6_reference_with_port - @request_hash.delete "HTTP_X_FORWARDED_HOST" - @request_hash['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008" - assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host - end - - def test_cgi_environment_variables - assert_equal "Basic", @request.auth_type - assert_equal 0, @request.content_length - assert_equal nil, @request.content_type - assert_equal "CGI/1.1", @request.gateway_interface - assert_equal "*/*", @request.accept - assert_equal "UTF-8", @request.accept_charset - assert_equal "gzip, deflate", @request.accept_encoding - assert_equal "en", @request.accept_language - assert_equal "no-cache, max-age=0", @request.cache_control - assert_equal "googlebot", @request.from - assert_equal "glu.ttono.us", @request.host - assert_equal "trans", @request.negotiate - assert_equal "no-cache", @request.pragma - assert_equal "http://www.google.com/search?q=glu.ttono.us", @request.referer - assert_equal "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", @request.user_agent - assert_equal "/homepage/", @request.path_info - assert_equal "/home/kevinc/sites/typo/public/homepage/", @request.path_translated - assert_equal "", @request.query_string - assert_equal "207.7.108.53", @request.remote_addr - assert_equal "google.com", @request.remote_host - assert_equal "kevin", @request.remote_ident - assert_equal "kevin", @request.remote_user - assert_equal :get, @request.request_method - assert_equal "/dispatch.fcgi", @request.script_name - assert_equal "glu.ttono.us:8007", @request.server_name - assert_equal 8007, @request.server_port - assert_equal "HTTP/1.1", @request.server_protocol - assert_equal "lighttpd", @request.server_software - end - - def test_cookie_syntax_resilience - cookies = CGI::Cookie::parse(@request_hash["HTTP_COOKIE"]); - assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], cookies["_session_id"], cookies.inspect - assert_equal ["yes"], cookies["is_admin"], cookies.inspect - - alt_cookies = CGI::Cookie::parse(@alt_cookie_fmt_request_hash["HTTP_COOKIE"]); - assert_equal ["c84ace847,96670c052c6ceb2451fb0f2"], alt_cookies["_session_id"], alt_cookies.inspect - assert_equal ["yes"], alt_cookies["is_admin"], alt_cookies.inspect - end -end - -class CgiRequestParamsParsingTest < BaseCgiTest - def test_doesnt_break_when_content_type_has_charset - set_content_data 'flamenco=love' - - assert_equal({"flamenco"=> "love"}, @request.request_parameters) - end - - def test_doesnt_interpret_request_uri_as_query_string_when_missing - @request.env['REQUEST_URI'] = 'foo' - assert_equal({}, @request.query_parameters) - end -end - -class CgiRequestContentTypeTest < BaseCgiTest - def test_html_content_type_verification - @request.env['CONTENT_TYPE'] = Mime::HTML.to_s - assert @request.content_type.verify_request? - end - - def test_xml_content_type_verification - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - assert !@request.content_type.verify_request? - end -end - -class CgiRequestMethodTest < BaseCgiTest - def test_get - assert_equal :get, @request.request_method - end - - def test_post - @request.env['REQUEST_METHOD'] = 'POST' - assert_equal :post, @request.request_method - end - - def test_put - set_content_data '_method=put' - - assert_equal :put, @request.request_method - end - - def test_delete - set_content_data '_method=delete' - - assert_equal :delete, @request.request_method - end -end - -class CgiRequestNeedsRewoundTest < BaseCgiTest - def test_body_should_be_rewound - data = 'foo' - fake_cgi = Struct.new(:env_table, :query_string, :stdinput).new(@request_hash, '', StringIO.new(data)) - fake_cgi.env_table['CONTENT_LENGTH'] = data.length - fake_cgi.env_table['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' - - # Read the request body by parsing params. - request = ActionController::CgiRequest.new(fake_cgi) - request.request_parameters - - # Should have rewound the body. - assert_equal 0, request.body.pos - end -end - -uses_mocha 'CGI Response' do - class CgiResponseTest < BaseCgiTest - def setup - super - @cgi.expects(:header).returns("HTTP/1.0 200 OK\nContent-Type: text/html\n") - @response = ActionController::CgiResponse.new(@cgi) - @output = StringIO.new('') - end - - def test_simple_output - @response.body = "Hello, World!" - - @response.out(@output) - assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\nHello, World!", @output.string - end - - def test_head_request - @cgi.env_table['REQUEST_METHOD'] = 'HEAD' - @response.body = "Hello, World!" - - @response.out(@output) - assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\n", @output.string - end - - def test_streaming_block - @response.body = Proc.new do |response, output| - 5.times { |n| output.write(n) } - end - - @response.out(@output) - assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\n01234", @output.string - end - end -end diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb index 61bfb2b6e9..30dda87bb4 100644 --- a/actionpack/test/controller/dispatcher_test.rb +++ b/actionpack/test/controller/dispatcher_test.rb @@ -6,7 +6,6 @@ class DispatcherTest < Test::Unit::TestCase Dispatcher = ActionController::Dispatcher def setup - @output = StringIO.new ENV['REQUEST_METHOD'] = 'GET' # Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks @@ -16,7 +15,7 @@ class DispatcherTest < Test::Unit::TestCase Dispatcher.stubs(:require_dependency) - @dispatcher = Dispatcher.new(@output) + @dispatcher = Dispatcher.new end def teardown @@ -25,17 +24,17 @@ class DispatcherTest < Test::Unit::TestCase def test_clears_dependencies_after_dispatch_if_in_loading_mode ActiveSupport::Dependencies.expects(:clear).once - dispatch(@output, false) + dispatch(false) end def test_reloads_routes_before_dispatch_if_in_loading_mode ActionController::Routing::Routes.expects(:reload).once - dispatch(@output, false) + dispatch(false) end def test_clears_asset_tag_cache_before_dispatch_if_in_loading_mode ActionView::Helpers::AssetTagHelper::AssetTag::Cache.expects(:clear).once - dispatch(@output, false) + dispatch(false) end def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode @@ -51,12 +50,16 @@ class DispatcherTest < Test::Unit::TestCase end def test_failsafe_response - CGI.expects(:new).raises('some multipart parsing failure') - Dispatcher.expects(:log_failsafe_exception) - - assert_nothing_raised { dispatch } - - assert_equal "Status: 400 Bad Request\r\nContent-Type: text/html\r\n\r\n<html><body><h1>400 Bad Request</h1></body></html>", @output.string + Dispatcher.any_instance.expects(:dispatch_unlocked).raises('b00m') + ActionController::Failsafe.any_instance.expects(:log_failsafe_exception) + + assert_nothing_raised do + assert_equal [ + 500, + {"Content-Type" => "text/html"}, + "<html><body><h1>500 Internal Server Error</h1></body></html>" + ], dispatch + end end def test_prepare_callbacks @@ -77,7 +80,7 @@ class DispatcherTest < Test::Unit::TestCase # Make sure they are only run once a = b = c = nil - @dispatcher.send :dispatch + dispatch assert_nil a || b || c end @@ -92,15 +95,10 @@ class DispatcherTest < Test::Unit::TestCase end private - def dispatch(output = @output, cache_classes = true) - controller = mock - controller.stubs(:process).returns(controller) - controller.stubs(:out).with(output).returns('response') - - ActionController::Routing::Routes.stubs(:recognize).returns(controller) - + def dispatch(cache_classes = true) + Dispatcher.any_instance.stubs(:handle_request).returns([200, {}, 'response']) Dispatcher.define_dispatcher_callbacks(cache_classes) - Dispatcher.dispatch(nil, {}, output) + @dispatcher.call({}) end def assert_subclasses(howmany, klass, message = klass.subclasses.inspect) diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index b39d35930d..4735b2927b 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -2,19 +2,13 @@ require 'abstract_unit' uses_mocha 'integration' do -module IntegrationSessionStubbing - def stub_integration_session(session) - session.stubs(:process) - session.stubs(:generic_url_rewriter) - end -end - class SessionTest < Test::Unit::TestCase - include IntegrationSessionStubbing + StubApp = lambda { |env| + [200, {"Content-Type" => "text/html"}, "Hello, World!"] + } def setup - @session = ActionController::Integration::Session.new - stub_integration_session(@session) + @session = ActionController::Integration::Session.new(StubApp) end def test_https_bang_works_and_sets_truth_by_default @@ -207,13 +201,10 @@ class SessionTest < Test::Unit::TestCase end class IntegrationTestTest < Test::Unit::TestCase - include IntegrationSessionStubbing - def setup @test = ::ActionController::IntegrationTest.new(:default_test) @test.class.stubs(:fixture_table_names).returns([]) @session = @test.open_session - stub_integration_session(@session) end def test_opens_new_session @@ -231,15 +222,15 @@ end # Tests that integration tests don't call Controller test methods for processing. # Integration tests have their own setup and teardown. class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest - include IntegrationSessionStubbing - def self.fixture_table_names [] end def test_integration_methods_called reset! - stub_integration_session(@integration_session) + @integration_session.stubs(:generic_url_rewriter) + @integration_session.stubs(:process) + %w( get post head put delete ).each do |verb| assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') } end @@ -281,13 +272,9 @@ class IntegrationProcessTest < ActionController::IntegrationTest get '/get' assert_equal 200, status assert_equal "OK", status_message - assert_equal "200 OK", response.headers["Status"] - assert_equal ["200 OK"], headers["status"] assert_response 200 assert_response :success assert_response :ok - assert_equal [], response.headers["cookie"] - assert_equal [], headers["cookie"] assert_equal({}, cookies) assert_equal "OK", response.body assert_kind_of HTML::Document, html_document @@ -300,13 +287,9 @@ class IntegrationProcessTest < ActionController::IntegrationTest post '/post' assert_equal 201, status assert_equal "Created", status_message - assert_equal "201 Created", response.headers["Status"] - assert_equal ["201 Created"], headers["status"] assert_response 201 assert_response :success assert_response :created - assert_equal [], response.headers["cookie"] - assert_equal [], headers["cookie"] assert_equal({}, cookies) assert_equal "Created", response.body assert_kind_of HTML::Document, html_document @@ -321,17 +304,9 @@ class IntegrationProcessTest < ActionController::IntegrationTest get '/cookie_monster' assert_equal 410, status assert_equal "Gone", status_message - assert_equal "410 Gone", response.headers["Status"] - assert_equal ["410 Gone"], headers["status"] assert_response 410 assert_response :gone - assert_equal ["cookie_1=; path=/", "cookie_3=chocolate; path=/"], response.headers["Set-Cookie"] - assert_equal ["cookie_1=; path=/", "cookie_3=chocolate; path=/"], headers['set-cookie'] - assert_equal [ - CGI::Cookie::new("name" => "cookie_1", "value" => ""), - CGI::Cookie::new("name" => "cookie_3", "value" => "chocolate") - ], response.headers["cookie"] - assert_equal [], headers["cookie"] + assert_equal ["cookie_1=; path=/", "cookie_3=chocolate; path=/"], headers["Set-Cookie"] assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies) assert_equal "Gone", response.body end @@ -342,8 +317,6 @@ class IntegrationProcessTest < ActionController::IntegrationTest get '/redirect' assert_equal 302, status assert_equal "Found", status_message - assert_equal "302 Found", response.headers["Status"] - assert_equal ["302 Found"], headers["status"] assert_response 302 assert_response :redirect assert_response :found @@ -358,8 +331,6 @@ class IntegrationProcessTest < ActionController::IntegrationTest xhr :get, '/get' assert_equal 200, status assert_equal "OK", status_message - assert_equal "200 OK", response.headers["Status"] - assert_equal ["200 OK"], headers["status"] assert_response 200 assert_response :success assert_response :ok @@ -372,7 +343,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest get '/get_with_params?foo=bar' assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"] assert_equal '/get_with_params?foo=bar', request.request_uri - assert_equal nil, request.env["QUERY_STRING"] + assert_equal "", request.env["QUERY_STRING"] assert_equal 'foo=bar', request.query_string assert_equal 'bar', request.parameters['foo'] diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb index 7e8b0f9bf2..641ef9626e 100644 --- a/actionpack/test/controller/rack_test.rb +++ b/actionpack/test/controller/rack_test.rb @@ -153,12 +153,12 @@ class RackRequestTest < BaseRackTest def test_cookie_syntax_resilience cookies = @request.cookies - assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], cookies["_session_id"], cookies.inspect - assert_equal ["yes"], cookies["is_admin"], cookies.inspect + assert_equal "c84ace84796670c052c6ceb2451fb0f2", cookies["_session_id"], cookies.inspect + assert_equal "yes", cookies["is_admin"], cookies.inspect alt_cookies = @alt_cookie_fmt_request.cookies - assert_equal ["c84ace847,96670c052c6ceb2451fb0f2"], alt_cookies["_session_id"], alt_cookies.inspect - assert_equal ["yes"], alt_cookies["is_admin"], alt_cookies.inspect + #assert_equal "c84ace847,96670c052c6ceb2451fb0f2", alt_cookies["_session_id"], alt_cookies.inspect + assert_equal "yes", alt_cookies["is_admin"], alt_cookies.inspect end end @@ -230,14 +230,13 @@ class RackResponseTest < BaseRackTest def setup super @response = ActionController::RackResponse.new(@request) - @output = StringIO.new('') end def test_simple_output @response.body = "Hello, World!" @response.prepare! - status, headers, body = @response.out(@output) + status, headers, body = @response.out assert_equal "200 OK", status assert_equal({ "Content-Type" => "text/html; charset=utf-8", @@ -258,7 +257,7 @@ class RackResponseTest < BaseRackTest end @response.prepare! - status, headers, body = @response.out(@output) + status, headers, body = @response.out assert_equal "200 OK", status assert_equal({"Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "no-cache", "Set-Cookie" => []}, headers) @@ -274,7 +273,7 @@ class RackResponseTest < BaseRackTest @response.body = "Hello, World!" @response.prepare! - status, headers, body = @response.out(@output) + status, headers, body = @response.out assert_equal "200 OK", status assert_equal({ "Content-Type" => "text/html; charset=utf-8", @@ -294,7 +293,6 @@ class RackResponseHeadersTest < BaseRackTest def setup super @response = ActionController::RackResponse.new(@request) - @output = StringIO.new('') @response.headers['Status'] = "200 OK" end @@ -317,6 +315,6 @@ class RackResponseHeadersTest < BaseRackTest private def response_headers @response.prepare! - @response.out(@output)[1] + @response.out[1] end end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 972e425e35..c5496a9af5 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -246,13 +246,10 @@ class TestController < ActionController::Base :locals => { :local_name => name } end - def helper_method_to_render_to_string(*args) - render_to_string(*args) + def render_implicit_html_template end - helper_method :helper_method_to_render_to_string - def render_html_only_partial_within_inline - render :inline => "Hello world <%= helper_method_to_render_to_string :partial => 'test/partial_with_only_html_version' %>" + def render_explicit_html_template end def formatted_html_erb @@ -942,9 +939,22 @@ class RenderTest < ActionController::TestCase assert_equal "Goodbye, Local David", @response.body end - def test_rendering_html_only_partial_within_inline_with_js - get :render_html_only_partial_within_inline, :format => :js - assert_equal "Hello world partial with only html version", @response.body + def test_render_in_an_rjs_template_should_pick_html_templates_when_available + [:js, "js"].each do |format| + assert_nothing_raised do + get :render_implicit_html_template, :format => format + assert_equal %(document.write("Hello world\\n");), @response.body + end + end + end + + def test_explicitly_rendering_an_html_template_with_implicit_html_template_renders_should_be_possible_from_an_rjs_template + [:js, "js"].each do |format| + assert_nothing_raised do + get :render_explicit_html_template, :format => format + assert_equal %(document.write("Hello world\\n");), @response.body + end + end end def test_should_render_formatted_template diff --git a/actionpack/test/controller/request_test.rb b/actionpack/test/controller/request_test.rb index ba4a6da39b..71da50fab0 100644 --- a/actionpack/test/controller/request_test.rb +++ b/actionpack/test/controller/request_test.rb @@ -637,7 +637,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase input = { "customers[boston][first][name]" => [ "David" ], "something_else" => [ "blah" ], - "logo" => [ File.new(File.dirname(__FILE__) + "/cgi_test.rb").path ] + "logo" => [ File.new(File.dirname(__FILE__) + "/rack_test.rb").path ] } expected_output = { @@ -649,7 +649,7 @@ class UrlEncodedRequestParameterParsingTest < ActiveSupport::TestCase } }, "something_else" => "blah", - "logo" => File.new(File.dirname(__FILE__) + "/cgi_test.rb").path, + "logo" => File.new(File.dirname(__FILE__) + "/rack_test.rb").path, } assert_equal expected_output, ActionController::AbstractRequest.parse_request_parameters(input) diff --git a/actionpack/test/controller/session_fixation_test.rb b/actionpack/test/controller/session_fixation_test.rb index 164438c513..e8dc8bd295 100644 --- a/actionpack/test/controller/session_fixation_test.rb +++ b/actionpack/test/controller/session_fixation_test.rb @@ -1,20 +1,13 @@ require 'abstract_unit' - -class SessionFixationTest < Test::Unit::TestCase - class MockCGI < CGI #:nodoc: - attr_accessor :stdoutput, :env_table - - def initialize(env, data = '') - self.env_table = env - self.stdoutput = StringIO.new - super(nil, StringIO.new(data)) - end - end - +class SessionFixationTest < ActionController::IntegrationTest class TestController < ActionController::Base - session :session_key => '_myapp_session_id', :secret => CGI::Session.generate_unique_id, :except => :default_session_key - session :cookie_only => false, :only => :allow_session_fixation + session :session_key => '_myapp_session_id', + :secret => CGI::Session.generate_unique_id, + :except => :default_session_key + + session :cookie_only => false, + :only => :allow_session_fixation def default_session_key render :text => "default_session_key" @@ -36,54 +29,56 @@ class SessionFixationTest < Test::Unit::TestCase end def test_should_be_able_to_make_a_successful_request - cgi = mock_cgi_for_request_to(:custom_session_key, :id => 1) - - assert_nothing_raised do - @controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi)) + with_test_route_set do + assert_nothing_raised do + get '/custom_session_key', :id => "1" + end + assert_equal 'custom_session_key: 1', @controller.response.body + assert_not_nil @controller.session end - assert_equal 'custom_session_key: 1', @controller.response.body - assert_not_nil @controller.session end def test_should_catch_session_fixation_attempt - cgi = mock_cgi_for_request_to(:custom_session_key, :_myapp_session_id => 42) - - assert_raises ActionController::CgiRequest::SessionFixationAttempt do - @controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi)) + with_test_route_set do + assert_raises(ActionController::RackRequest::SessionFixationAttempt) do + get '/custom_session_key', :_myapp_session_id => "42" + end + assert_nil @controller.session end - assert_nil @controller.session end def test_should_not_catch_session_fixation_attempt_when_cookie_only_setting_is_disabled - cgi = mock_cgi_for_request_to(:allow_session_fixation, :_myapp_session_id => 42) - - assert_nothing_raised do - @controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi)) + with_test_route_set do + assert_nothing_raised do + get '/allow_session_fixation', :_myapp_session_id => "42" + end + assert !@controller.response.body.blank? + assert_not_nil @controller.session end - assert ! @controller.response.body.blank? - assert_not_nil @controller.session end def test_should_catch_session_fixation_attempt_with_default_session_key - ActionController::Base.session_store = :p_store # using the default session_key is not possible with cookie store - cgi = mock_cgi_for_request_to(:default_session_key, :_session_id => 42) - - assert_raises ActionController::CgiRequest::SessionFixationAttempt do - @controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi)) + # using the default session_key is not possible with cookie store + ActionController::Base.session_store = :p_store + + with_test_route_set do + assert_raises ActionController::RackRequest::SessionFixationAttempt do + get '/default_session_key', :_session_id => "42" + end + assert_nil @controller.response + assert_nil @controller.session end - assert @controller.response.body.blank? - assert_nil @controller.session - end - -private - - def mock_cgi_for_request_to(action, params = {}) - MockCGI.new({ - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "action=#{action}&#{params.to_query}", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "HTTP_HOST" => "testdomain.com" }, '') end + private + def with_test_route_set + with_routing do |set| + set.draw do |map| + map.with_options :controller => "session_fixation_test/test" do |c| + c.connect "/:action" + end + end + yield + end + end end diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb index 04e14d8eac..ac84e2dfcd 100644 --- a/actionpack/test/controller/view_paths_test.rb +++ b/actionpack/test/controller/view_paths_test.rb @@ -43,29 +43,29 @@ class ViewLoadPathsTest < ActionController::TestCase end def test_template_load_path_was_set_correctly - assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_controller_appends_view_path_correctly @controller.append_view_path 'foo' - assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s) @controller.append_view_path(%w(bar baz)) - assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s) @controller.append_view_path(FIXTURE_LOAD_PATH) - assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_controller_prepends_view_path_correctly @controller.prepend_view_path 'baz' - assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(%w(foo bar)) - assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(FIXTURE_LOAD_PATH) - assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) end def test_template_appends_view_path_correctly @@ -73,10 +73,10 @@ class ViewLoadPathsTest < ActionController::TestCase class_view_paths = TestController.view_paths @controller.append_view_path 'foo' - assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s) @controller.append_view_path(%w(bar baz)) - assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths + assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s) assert_equal class_view_paths, TestController.view_paths end @@ -85,10 +85,10 @@ class ViewLoadPathsTest < ActionController::TestCase class_view_paths = TestController.view_paths @controller.prepend_view_path 'baz' - assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) @controller.prepend_view_path(%w(foo bar)) - assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths + assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s) assert_equal class_view_paths, TestController.view_paths end @@ -130,12 +130,12 @@ class ViewLoadPathsTest < ActionController::TestCase A.view_paths = ['a/path'] - assert_equal ['a/path'], A.view_paths + assert_equal ['a/path'], A.view_paths.map(&:to_s) assert_equal A.view_paths, B.view_paths assert_equal original_load_paths, C.view_paths C.view_paths = [] assert_nothing_raised { C.view_paths << 'c/path' } - assert_equal ['c/path'], C.view_paths + assert_equal ['c/path'], C.view_paths.map(&:to_s) end end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 6d2b3e4f23..4c44ea4205 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -1,16 +1,6 @@ require 'abstract_unit' -class WebServiceTest < Test::Unit::TestCase - class MockCGI < CGI #:nodoc: - attr_accessor :stdoutput, :env_table - - def initialize(env, data = '') - self.env_table = env - self.stdoutput = StringIO.new - super(nil, StringIO.new(data)) - end - end - +class WebServiceTest < ActionController::IntegrationTest class TestController < ActionController::Base session :off @@ -22,7 +12,7 @@ class WebServiceTest < Test::Unit::TestCase end end - def dump_params_keys(hash=params) + def dump_params_keys(hash = params) hash.keys.sort.inject("") do |s, k| value = hash[k] value = Hash === value ? "(#{dump_params_keys(value)})" : "" @@ -33,7 +23,7 @@ class WebServiceTest < Test::Unit::TestCase def rescue_action(e) raise end end - + def setup @controller = TestController.new @default_param_parsers = ActionController::Base.param_parsers.dup @@ -44,185 +34,229 @@ class WebServiceTest < Test::Unit::TestCase end def test_check_parameters - process('GET') - assert_equal '', @controller.response.body + with_test_route_set do + get "/" + assert_equal '', @controller.response.body + end end def test_post_xml - process('POST', 'application/xml', '<entry attributed="true"><summary>content...</summary></entry>') - - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'content...', @controller.params["entry"]['summary'] - assert_equal 'true', @controller.params["entry"]['attributed'] + with_test_route_set do + post "/", '<entry attributed="true"><summary>content...</summary></entry>', + {'CONTENT_TYPE' => 'application/xml'} + + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'content...', @controller.params["entry"]['summary'] + assert_equal 'true', @controller.params["entry"]['attributed'] + end end def test_put_xml - process('PUT', 'application/xml', '<entry attributed="true"><summary>content...</summary></entry>') + with_test_route_set do + put "/", '<entry attributed="true"><summary>content...</summary></entry>', + {'CONTENT_TYPE' => 'application/xml'} - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'content...', @controller.params["entry"]['summary'] - assert_equal 'true', @controller.params["entry"]['attributed'] + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'content...', @controller.params["entry"]['summary'] + assert_equal 'true', @controller.params["entry"]['attributed'] + end end def test_put_xml_using_a_type_node - process('PUT', 'application/xml', '<type attributed="true"><summary>content...</summary></type>') + with_test_route_set do + put "/", '<type attributed="true"><summary>content...</summary></type>', + {'CONTENT_TYPE' => 'application/xml'} - assert_equal 'type', @controller.response.body - assert @controller.params.has_key?(:type) - assert_equal 'content...', @controller.params["type"]['summary'] - assert_equal 'true', @controller.params["type"]['attributed'] + assert_equal 'type', @controller.response.body + assert @controller.params.has_key?(:type) + assert_equal 'content...', @controller.params["type"]['summary'] + assert_equal 'true', @controller.params["type"]['attributed'] + end end def test_put_xml_using_a_type_node_and_attribute - process('PUT', 'application/xml', '<type attributed="true"><summary type="boolean">false</summary></type>') + with_test_route_set do + put "/", '<type attributed="true"><summary type="boolean">false</summary></type>', + {'CONTENT_TYPE' => 'application/xml'} - assert_equal 'type', @controller.response.body - assert @controller.params.has_key?(:type) - assert_equal false, @controller.params["type"]['summary'] - assert_equal 'true', @controller.params["type"]['attributed'] + assert_equal 'type', @controller.response.body + assert @controller.params.has_key?(:type) + assert_equal false, @controller.params["type"]['summary'] + assert_equal 'true', @controller.params["type"]['attributed'] + end end def test_post_xml_using_a_type_node - process('POST', 'application/xml', '<font attributed="true"><type>arial</type></font>') + with_test_route_set do + post "/", '<font attributed="true"><type>arial</type></font>', + {'CONTENT_TYPE' => 'application/xml'} - assert_equal 'font', @controller.response.body - assert @controller.params.has_key?(:font) - assert_equal 'arial', @controller.params['font']['type'] - assert_equal 'true', @controller.params["font"]['attributed'] + assert_equal 'font', @controller.response.body + assert @controller.params.has_key?(:font) + assert_equal 'arial', @controller.params['font']['type'] + assert_equal 'true', @controller.params["font"]['attributed'] + end end def test_post_xml_using_a_root_node_named_type - process('POST', 'application/xml', '<type type="integer">33</type>') + with_test_route_set do + post "/", '<type type="integer">33</type>', + {'CONTENT_TYPE' => 'application/xml'} - assert @controller.params.has_key?(:type) - assert_equal 33, @controller.params['type'] + assert @controller.params.has_key?(:type) + assert_equal 33, @controller.params['type'] + end end def test_post_xml_using_an_attributted_node_named_type - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } - process('POST', 'application/xml', '<request><type type="string">Arial,12</type><z>3</z></request>') + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } + post "/", '<request><type type="string">Arial,12</type><z>3</z></request>', + {'CONTENT_TYPE' => 'application/xml'} - assert_equal 'type, z', @controller.response.body - assert @controller.params.has_key?(:type) - assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect - assert_equal '3', @controller.params['z'], @controller.params.inspect + assert_equal 'type, z', @controller.response.body + assert @controller.params.has_key?(:type) + assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect + assert_equal '3', @controller.params['z'], @controller.params.inspect + end end def test_register_and_use_yaml - ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) } - process('POST', 'application/x-yaml', {"entry" => "loaded from yaml"}.to_yaml) - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'loaded from yaml', @controller.params["entry"] + with_test_route_set do + ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) } + post "/", {"entry" => "loaded from yaml"}.to_yaml, + {'CONTENT_TYPE' => 'application/x-yaml'} + + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'loaded from yaml', @controller.params["entry"] + end end - + def test_register_and_use_yaml_as_symbol - ActionController::Base.param_parsers[Mime::YAML] = :yaml - process('POST', 'application/x-yaml', {"entry" => "loaded from yaml"}.to_yaml) - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'loaded from yaml', @controller.params["entry"] + with_test_route_set do + ActionController::Base.param_parsers[Mime::YAML] = :yaml + post "/", {"entry" => "loaded from yaml"}.to_yaml, + {'CONTENT_TYPE' => 'application/x-yaml'} + + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'loaded from yaml', @controller.params["entry"] + end end def test_register_and_use_xml_simple - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } - process('POST', 'application/xml', '<request><summary>content...</summary><title>SimpleXml</title></request>' ) - assert_equal 'summary, title', @controller.response.body - assert @controller.params.has_key?(:summary) - assert @controller.params.has_key?(:title) - assert_equal 'content...', @controller.params["summary"] - assert_equal 'SimpleXml', @controller.params["title"] + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } + post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>', + {'CONTENT_TYPE' => 'application/xml'} + + assert_equal 'summary, title', @controller.response.body + assert @controller.params.has_key?(:summary) + assert @controller.params.has_key?(:title) + assert_equal 'content...', @controller.params["summary"] + assert_equal 'SimpleXml', @controller.params["title"] + end end def test_use_xml_ximple_with_empty_request - ActionController::Base.param_parsers[Mime::XML] = :xml_simple - assert_nothing_raised { process('POST', 'application/xml', "") } - assert_equal "", @controller.response.body + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = :xml_simple + assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} } + assert_equal "", @controller.response.body + end end def test_dasherized_keys_as_xml - ActionController::Base.param_parsers[Mime::XML] = :xml_simple - process('POST', 'application/xml', "<first-key>\n<sub-key>...</sub-key>\n</first-key>", true) - assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body - assert_equal "...", @controller.params[:first_key][:sub_key] + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = :xml_simple + post "/?full=1", "<first-key>\n<sub-key>...</sub-key>\n</first-key>", + {'CONTENT_TYPE' => 'application/xml'} + assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body + assert_equal "...", @controller.params[:first_key][:sub_key] + end end def test_typecast_as_xml - ActionController::Base.param_parsers[Mime::XML] = :xml_simple - process('POST', 'application/xml', <<-XML) - <data> - <a type="integer">15</a> - <b type="boolean">false</b> - <c type="boolean">true</c> - <d type="date">2005-03-17</d> - <e type="datetime">2005-03-17T21:41:07Z</e> - <f>unparsed</f> - <g type="integer">1</g> - <g>hello</g> - <g type="date">1974-07-25</g> - </data> - XML - params = @controller.params - assert_equal 15, params[:data][:a] - assert_equal false, params[:data][:b] - assert_equal true, params[:data][:c] - assert_equal Date.new(2005,3,17), params[:data][:d] - assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] - assert_equal "unparsed", params[:data][:f] - assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = :xml_simple + xml = <<-XML + <data> + <a type="integer">15</a> + <b type="boolean">false</b> + <c type="boolean">true</c> + <d type="date">2005-03-17</d> + <e type="datetime">2005-03-17T21:41:07Z</e> + <f>unparsed</f> + <g type="integer">1</g> + <g>hello</g> + <g type="date">1974-07-25</g> + </data> + XML + post "/", xml, {'CONTENT_TYPE' => 'application/xml'} + + params = @controller.params + assert_equal 15, params[:data][:a] + assert_equal false, params[:data][:b] + assert_equal true, params[:data][:c] + assert_equal Date.new(2005,3,17), params[:data][:d] + assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] + assert_equal "unparsed", params[:data][:f] + assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] + end end def test_entities_unescaped_as_xml_simple - ActionController::Base.param_parsers[Mime::XML] = :xml_simple - process('POST', 'application/xml', <<-XML) - <data><foo "bar's" & friends></data> - XML - assert_equal %(<foo "bar's" & friends>), @controller.params[:data] + with_test_route_set do + ActionController::Base.param_parsers[Mime::XML] = :xml_simple + xml = <<-XML + <data><foo "bar's" & friends></data> + XML + post "/", xml, {'CONTENT_TYPE' => 'application/xml'} + assert_equal %(<foo "bar's" & friends>), @controller.params[:data] + end end def test_typecast_as_yaml - ActionController::Base.param_parsers[Mime::YAML] = :yaml - process('POST', 'application/x-yaml', <<-YAML) - --- - data: - a: 15 - b: false - c: true - d: 2005-03-17 - e: 2005-03-17T21:41:07Z - f: unparsed - g: - - 1 - - hello - - 1974-07-25 - YAML - params = @controller.params - assert_equal 15, params[:data][:a] - assert_equal false, params[:data][:b] - assert_equal true, params[:data][:c] - assert_equal Date.new(2005,3,17), params[:data][:d] - assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] - assert_equal "unparsed", params[:data][:f] - assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] - end - - private - - def process(verb, content_type = 'application/x-www-form-urlencoded', data = '', full=false) - - cgi = MockCGI.new({ - 'REQUEST_METHOD' => verb, - 'CONTENT_TYPE' => content_type, - 'QUERY_STRING' => "action=assign_parameters&controller=webservicetest/test#{"&full=1" if full}", - "REQUEST_URI" => "/", - "HTTP_HOST" => 'testdomain.com', - "CONTENT_LENGTH" => data.size, - "SERVER_PORT" => "80", - "HTTPS" => "off"}, data) - - @controller.send(:process, ActionController::CgiRequest.new(cgi, {}), ActionController::CgiResponse.new(cgi)) - end - + with_test_route_set do + ActionController::Base.param_parsers[Mime::YAML] = :yaml + yaml = <<-YAML + --- + data: + a: 15 + b: false + c: true + d: 2005-03-17 + e: 2005-03-17T21:41:07Z + f: unparsed + g: + - 1 + - hello + - 1974-07-25 + YAML + post "/", yaml, {'CONTENT_TYPE' => 'application/x-yaml'} + params = @controller.params + assert_equal 15, params[:data][:a] + assert_equal false, params[:data][:b] + assert_equal true, params[:data][:c] + assert_equal Date.new(2005,3,17), params[:data][:d] + assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] + assert_equal "unparsed", params[:data][:f] + assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] + end + end + + private + def with_test_route_set + with_routing do |set| + set.draw do |map| + map.with_options :controller => "web_service_test/test" do |c| + c.connect "/", :action => "assign_parameters" + end + end + yield + end + end end diff --git a/actionpack/test/fixtures/test/_one.html.erb b/actionpack/test/fixtures/test/_one.html.erb new file mode 100644 index 0000000000..f796291cb4 --- /dev/null +++ b/actionpack/test/fixtures/test/_one.html.erb @@ -0,0 +1 @@ +<%= render :partial => "two" %> world diff --git a/actionpack/test/fixtures/test/_two.html.erb b/actionpack/test/fixtures/test/_two.html.erb new file mode 100644 index 0000000000..5ab2f8a432 --- /dev/null +++ b/actionpack/test/fixtures/test/_two.html.erb @@ -0,0 +1 @@ +Hello
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/render_explicit_html_template.js.rjs b/actionpack/test/fixtures/test/render_explicit_html_template.js.rjs new file mode 100644 index 0000000000..4eb12fd6af --- /dev/null +++ b/actionpack/test/fixtures/test/render_explicit_html_template.js.rjs @@ -0,0 +1 @@ +page.call "document.write", render(:partial => "one.html.erb") diff --git a/actionpack/test/fixtures/test/render_implicit_html_template.js.rjs b/actionpack/test/fixtures/test/render_implicit_html_template.js.rjs new file mode 100644 index 0000000000..3d68041756 --- /dev/null +++ b/actionpack/test/fixtures/test/render_implicit_html_template.js.rjs @@ -0,0 +1 @@ +page.call "document.write", render(:partial => "one") diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 9e827abbca..0387a11de2 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -137,12 +137,6 @@ module RenderTestCases end # TODO: The reason for this test is unclear, improve documentation - def test_render_js_partial_and_fallback_to_erb_layout - @view.template_format = :js - assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" }) - end - - # TODO: The reason for this test is unclear, improve documentation def test_render_missing_xml_partial_and_raise_missing_template @view.template_format = :xml assert_raise(ActionView::MissingTemplate) { @view.render(:partial => "test/layout_for_partial") } diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index a99bb001e4..bcf0810290 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -24,6 +24,8 @@ module ActiveModel :even => "must be even" } + ## + # :singleton-method: # Holds a hash with all the default error messages that can be replaced by your own copy or localizations. cattr_accessor :default_error_messages diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index cca70f1fb7..423a0bd0cc 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0/3.0* +* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 [Akira Matsuda] + * Add :having as a key to find and the relevant associations. [miloops] * Added default_scope to Base #1381 [Paweł Kondzior]. Example: diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb index 75ec4fbb2e..59f1d3b867 100644 --- a/activerecord/lib/active_record/associations/association_proxy.rb +++ b/activerecord/lib/active_record/associations/association_proxy.rb @@ -207,7 +207,10 @@ module ActiveRecord # Forwards any missing method call to the \target. def method_missing(method, *args) if load_target - raise NoMethodError unless @target.respond_to?(method) + unless @target.respond_to?(method) + message = "undefined method `#{method.to_s}' for \"#{@target}\":#{@target.class.to_s}" + raise NoMethodError, message + end if block_given? @target.send(method, *args) { |*block_args| yield(*block_args) } diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 8f8ed241d5..5d614442c3 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -389,6 +389,8 @@ module ActiveRecord #:nodoc: # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all # instances in the current object space. class Base + ## + # :singleton-method: # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+. cattr_accessor :logger, :instance_writer => false @@ -414,7 +416,9 @@ module ActiveRecord #:nodoc: end @@subclasses = {} - + + ## + # :singleton-method: # Contains the database configuration - as is typically stored in config/database.yml - # as a Hash. # @@ -443,6 +447,8 @@ module ActiveRecord #:nodoc: cattr_accessor :configurations, :instance_writer => false @@configurations = {} + ## + # :singleton-method: # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember @@ -450,34 +456,46 @@ module ActiveRecord #:nodoc: cattr_accessor :primary_key_prefix_type, :instance_writer => false @@primary_key_prefix_type = nil + ## + # :singleton-method: # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace # for tables in a shared database. By default, the prefix is the empty string. cattr_accessor :table_name_prefix, :instance_writer => false @@table_name_prefix = "" + ## + # :singleton-method: # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", # "people_basecamp"). By default, the suffix is the empty string. cattr_accessor :table_name_suffix, :instance_writer => false @@table_name_suffix = "" + ## + # :singleton-method: # Indicates whether table names should be the pluralized versions of the corresponding class names. # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. # See table_name for the full rules on table/class naming. This is true, by default. cattr_accessor :pluralize_table_names, :instance_writer => false @@pluralize_table_names = true + ## + # :singleton-method: # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but # may complicate matters if you use software like syslog. This is true, by default. cattr_accessor :colorize_logging, :instance_writer => false @@colorize_logging = true + ## + # :singleton-method: # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database. # This is set to :local by default. cattr_accessor :default_timezone, :instance_writer => false @@default_timezone = :local + ## + # :singleton-method: # Specifies the format to use when dumping the database schema with Rails' # Rakefile. If :sql, the schema is dumped as (potentially database- # specific) SQL statements. If :ruby, the schema is dumped as an @@ -487,6 +505,8 @@ module ActiveRecord #:nodoc: cattr_accessor :schema_format , :instance_writer => false @@schema_format = :ruby + ## + # :singleton-method: # Specify whether or not to use timestamps for migration numbers cattr_accessor :timestamped_migrations , :instance_writer => false @@timestamped_migrations = true @@ -640,16 +660,24 @@ module ActiveRecord #:nodoc: connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) } end - # Checks whether a record exists in the database that matches conditions given. These conditions - # can either be a single integer representing a primary key id to be found, or a condition to be - # matched like using ActiveRecord#find. + + # Returns true if a record exists in the table that matches the +id+ or + # conditions given, or false otherwise. The argument can take four forms: + # + # * Integer - Finds the record with this primary key. + # * String - Finds the record with a primary key corresponding to this + # string (such as <tt>'5'</tt>). + # * Array - Finds the record that matches these +find+-style conditions + # (such as <tt>['color = ?', 'red']</tt>). + # * Hash - Finds the record that matches these +find+-style conditions + # (such as <tt>{:color => 'red'}</tt>). # - # The +id_or_conditions+ parameter can be an Integer or a String if you want to search the primary key - # column of the table for a matching id, or if you're looking to match against a condition you can use - # an Array or a Hash. + # For more information about specifying conditions as a Hash or Array, + # see the Conditions section in the introduction to ActiveRecord::Base. # - # Possible gotcha: You can't pass in a condition as a string e.g. "name = 'Jamie'", this would be - # sanitized and then queried against the primary key column as "id = 'name = \'Jamie" + # Note: You can't pass in a condition as a string (like <tt>name = + # 'Jamie'</tt>), since it would be sanitized and then queried against + # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>. # # ==== Examples # Person.exists?(5) @@ -2320,15 +2348,15 @@ module ActiveRecord #:nodoc: # object. The default implementation returns this record's id as a String, # or nil if this record's unsaved. # - # For example, suppose that you have a Users model, and that you have a - # <tt>map.resources :users</tt> route. Normally, +users_path+ will - # construct an URI with the user object's 'id' in it: + # For example, suppose that you have a User model, and that you have a + # <tt>map.resources :users</tt> route. Normally, +user_path+ will + # construct a path with the user object's 'id' in it: # # user = User.find_by_name('Phusion') # user_path(user) # => "/users/1" # - # You can override +to_param+ in your model to make +users_path+ construct - # an URI using the user's name instead of the user's id: + # You can override +to_param+ in your model to make +user_path+ construct + # a path using the user's name instead of the user's id: # # class User < ActiveRecord::Base # def to_param # overridden diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb index a968fc0fd3..ccb79f547a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb @@ -7,6 +7,8 @@ module ActiveRecord end end + ## + # :singleton-method: # The connection handler cattr_accessor :connection_handler, :instance_writer => false @@connection_handler = ConnectionAdapters::ConnectionHandler.new diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 76ade2a980..3fbbb46f73 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -156,13 +156,16 @@ module ActiveRecord # * <tt>:sslcapath</tt> - Necessary to use MySQL with an SSL connection. # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection. # - # By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt> - # as boolean. If you wish to disable this emulation (which was the default - # behavior in versions 0.13.1 and earlier) you can add the following line - # to your environment.rb file: - # - # ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false class MysqlAdapter < AbstractAdapter + + ## + # :singleton-method: + # By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt> + # as boolean. If you wish to disable this emulation (which was the default + # behavior in versions 0.13.1 and earlier) you can add the following line + # to your environment.rb file: + # + # ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false cattr_accessor :emulate_booleans self.emulate_booleans = true diff --git a/activerecord/lib/active_record/dirty.rb b/activerecord/lib/active_record/dirty.rb index ae573799ae..a1760875ba 100644 --- a/activerecord/lib/active_record/dirty.rb +++ b/activerecord/lib/active_record/dirty.rb @@ -151,12 +151,12 @@ module ActiveRecord def field_changed?(attr, old, value) if column = column_for_attribute(attr) - if column.type == :integer && column.null && (old.nil? || old == 0) + if column.type == :integer && column.null && (old.nil? || old == 0) && value.blank? # For nullable integer columns, NULL gets stored in database for blank (i.e. '') values. # Hence we don't record it as a change if the value changes from nil to ''. # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll # be typecast back to 0 (''.to_i => 0) - value = nil if value.blank? + value = nil else value = column.type_cast(value) end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 1d843fff28..15350cf1e1 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -130,7 +130,9 @@ module ActiveRecord # To run migrations against the currently configured database, use # <tt>rake db:migrate</tt>. This will update the database by running all of the # pending migrations, creating the <tt>schema_migrations</tt> table - # (see "About the schema_migrations table" section below) if missing. + # (see "About the schema_migrations table" section below) if missing. It will also + # invoke the db:schema:dump task, which will update your db/schema.rb file + # to match the structure of your database. # # To roll the database back to a previous migration version, use # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 2181bdf2dd..557a554966 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -7,6 +7,8 @@ module ActiveRecord class SchemaDumper #:nodoc: private_class_method :new + ## + # :singleton-method: # A list of tables which should not be dumped to the schema. # Acceptable values are strings as well as regexp. # This setting is only used if ActiveRecord::Base.schema_format == :ruby diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 9220eae4d1..4b275ddd70 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -205,7 +205,7 @@ module ActiveRecord else #key = :"activerecord.att.#{@base.class.name.underscore.to_sym}.#{attr}" attr_name = @base.class.human_attribute_name(attr) - full_messages << attr_name + ' ' + message + full_messages << attr_name + I18n.t('activerecord.errors.format.separator', :default => ' ') + message end end end @@ -494,18 +494,20 @@ module ActiveRecord # The first_name attribute must be in the object and it cannot be blank. # # If you want to validate the presence of a boolean field (where the real values are true and false), - # you will want to use validates_inclusion_of :field_name, :in => [true, false] - # This is due to the way Object#blank? handles boolean values. false.blank? # => true + # you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>. + # + # This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "can't be blank"). - # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>). + # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, + # <tt>:update</tt>). # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should - # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). + # The method, proc or string should return or evaluate to a true or false value. # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should - # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). + # The method, proc or string should return or evaluate to a true or false value. # def validates_presence_of(*attr_names) configuration = { :on => :save } diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 39d38c4e1e..10cdbdc622 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -68,6 +68,18 @@ class DirtyTest < ActiveRecord::TestCase end end + def test_nullable_integer_zero_to_string_zero_not_marked_as_changed + pirate = Pirate.new + pirate.parrot_id = 0 + pirate.catchphrase = 'arrr' + assert pirate.save! + + assert !pirate.changed? + + pirate.parrot_id = '0' + assert !pirate.changed? + end + def test_zero_to_blank_marked_as_changed pirate = Pirate.new pirate.catchphrase = "Yarrrr, me hearties" diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index ad9ae6df1f..4192fab525 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -202,6 +202,8 @@ module ActiveResource # sets the <tt>read_timeout</tt> of the internal Net::HTTP instance to the same value. The default # <tt>read_timeout</tt> is 60 seconds on most Ruby implementations. class Base + ## + # :singleton-method: # The logger for diagnosing and tracing Active Resource calls. cattr_accessor :logger diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index d142f21d61..0e796d802c 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,9 @@ *2.3.0 [Edge]* +* Multibyte: add multibyte-safe Chars#ord rather than falling back to String#ord. #1483 [Jason Cheow] + +* I18n support for Array#to_sentence. Introduces support.array.words_connector, .two_words_connector, and .last_word_connector translation keys. #1397 [Akira Matsuda] + * Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 [Christoffer Sawicki] * Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. [Koz] diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb index 77e0b1d33f..b2c863c893 100644 --- a/activesupport/lib/active_support/buffered_logger.rb +++ b/activesupport/lib/active_support/buffered_logger.rb @@ -13,6 +13,8 @@ module ActiveSupport MAX_BUFFER_SIZE = 1000 + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb index f0d6591135..69d35dafd3 100644 --- a/activesupport/lib/active_support/core_ext/array/conversions.rb +++ b/activesupport/lib/active_support/core_ext/array/conversions.rb @@ -3,15 +3,16 @@ module ActiveSupport #:nodoc: module Array #:nodoc: module Conversions # Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options: - # * <tt>:connector</tt> - The word used to join the last element in arrays with two or more elements (default: "and") - # * <tt>:skip_last_comma</tt> - Set to true to return "a, b and c" instead of "a, b, and c". + # * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", ") + # * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ") + # * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ") def to_sentence(options = {}) - options.assert_valid_keys(:connector, :skip_last_comma, :locale) + options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) - default = I18n.translate(:'support.array.sentence_connector', :locale => options[:locale]) - default_skip_last_comma = I18n.translate(:'support.array.skip_last_comma', :locale => options[:locale]) - options.reverse_merge! :connector => default, :skip_last_comma => default_skip_last_comma - options[:connector] = "#{options[:connector]} " unless options[:connector].nil? || options[:connector].strip == '' + default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale]) + default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale]) + default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale]) + options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector case length when 0 @@ -19,9 +20,9 @@ module ActiveSupport #:nodoc: when 1 self[0].to_s when 2 - "#{self[0]} #{options[:connector]}#{self[1]}" + "#{self[0]}#{options[:two_words_connector]}#{self[1]}" else - "#{self[0...-1].join(', ')}#{options[:skip_last_comma] ? '' : ','} #{options[:connector]}#{self[-1]}" + "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" end end diff --git a/activesupport/lib/active_support/core_ext/exception.rb b/activesupport/lib/active_support/core_ext/exception.rb index 73470cbe05..cde0df4153 100644 --- a/activesupport/lib/active_support/core_ext/exception.rb +++ b/activesupport/lib/active_support/core_ext/exception.rb @@ -11,10 +11,11 @@ class Exception # :nodoc: def clean_message Pathname.clean_within message end - + TraceSubstitutions = [] - FrameworkRegexp = /generated|vendor|dispatch|ruby|script\/\w+/ - + FrameworkStart = /action_controller\/dispatcher\.rb/.freeze + FrameworkRegexp = /generated|vendor|dispatch|ruby|script\/\w+/.freeze + def clean_backtrace backtrace.collect do |line| Pathname.clean_within(TraceSubstitutions.inject(line) do |result, (regexp, sub)| @@ -22,20 +23,22 @@ class Exception # :nodoc: end) end end - + def application_backtrace + before_framework_frame = nil before_application_frame = true - + trace = clean_backtrace.reject do |line| + before_framework_frame ||= (line =~ FrameworkStart) non_app_frame = (line =~ FrameworkRegexp) before_application_frame = false unless non_app_frame - non_app_frame && ! before_application_frame + before_framework_frame || (non_app_frame && !before_application_frame) end - + # If we didn't find any application frames, return an empty app trace. before_application_frame ? [] : trace end - + def framework_backtrace clean_backtrace.grep FrameworkRegexp end diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index c622554860..24fe7294c9 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -30,6 +30,8 @@ require 'logger' # # Note: This logger is deprecated in favor of ActiveSupport::BufferedLogger class Logger + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 683af4556e..4921b99677 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -254,7 +254,7 @@ module ActiveSupport # @person = Person.find(1) # # => #<Person id: 1, name: "Donald E. Knuth"> # - # <%= link_to(@person.name, person_path %> + # <%= link_to(@person.name, person_path(@person)) %> # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> def parameterize(string, sep = '-') re_sep = Regexp.escape(sep) diff --git a/activesupport/lib/active_support/locale/en.yml b/activesupport/lib/active_support/locale/en.yml index 92132cacd5..e604c9ee8c 100644 --- a/activesupport/lib/active_support/locale/en.yml +++ b/activesupport/lib/active_support/locale/en.yml @@ -28,5 +28,6 @@ en: # Used in array.to_sentence. support: array: - sentence_connector: "and" - skip_last_comma: false + words_connector: ", " + two_words_connector: " and " + last_word_connector: ", and " diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index be9c6d3567..a00b165222 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -344,6 +344,14 @@ module ActiveSupport #:nodoc: end alias_method :[], :slice + # Converts first character in the string to Unicode value + # + # Example: + # 'こんにちは'.mb_chars.ord #=> 12371 + def ord + self.class.u_unpack(@wrapped_string)[0] + end + # Convert characters in the string to uppercase. # # Example: diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 01b243cdb5..93f4482307 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -55,21 +55,22 @@ class ArrayExtToSentenceTests < Test::Unit::TestCase assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence end - def test_to_sentence_with_connector - assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(:connector => 'and also') - assert_equal "one, two, three", ['one', 'two', 'three'].to_sentence(:connector => '') - assert_equal "one, two, three", ['one', 'two', 'three'].to_sentence(:connector => nil) - assert_equal "one, two, three", ['one', 'two', 'three'].to_sentence(:connector => ' ') - assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence(:connector => 'and ') + def test_to_sentence_with_words_connector + assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' ') + assert_equal "one & two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' & ') + assert_equal "onetwo, and three", ['one', 'two', 'three'].to_sentence(:words_connector => nil) end - def test_to_sentence_with_skip_last_comma - assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence(:skip_last_comma => false) + def test_to_sentence_with_last_word_connector + assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ', and also ') + assert_equal "one, twothree", ['one', 'two', 'three'].to_sentence(:last_word_connector => nil) + assert_equal "one, two three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' ') + assert_equal "one, two and three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' and ') end def test_two_elements assert_equal "one and two", ['one', 'two'].to_sentence - assert_equal "one two", ['one', 'two'].to_sentence(:connector => '') + assert_equal "one two", ['one', 'two'].to_sentence(:two_words_connector => ' ') end def test_one_element diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb index cfb8c76d52..7535f4ad7a 100644 --- a/activesupport/test/i18n_test.rb +++ b/activesupport/test/i18n_test.rb @@ -71,19 +71,28 @@ class I18nTest < Test::Unit::TestCase assert_equal 'pm', I18n.translate(:'time.pm') end - def test_sentence_connector - assert_equal 'and', I18n.translate(:'support.array.sentence_connector') + def test_words_connector + assert_equal ', ', I18n.translate(:'support.array.words_connector') end - def test_skip_last_comma - assert_equal false, I18n.translate(:'support.array.skip_last_comma') + def test_two_words_connector + assert_equal ' and ', I18n.translate(:'support.array.two_words_connector') + end + + def test_last_word_connector + assert_equal ', and ', I18n.translate(:'support.array.last_word_connector') end def test_to_sentence + default_two_words_connector = I18n.translate(:'support.array.two_words_connector') + default_last_word_connector = I18n.translate(:'support.array.last_word_connector') assert_equal 'a, b, and c', %w[a b c].to_sentence - I18n.backend.store_translations 'en', :support => { :array => { :skip_last_comma => true } } + I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => ' & ' } } + assert_equal 'a & b', %w[a b].to_sentence + I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => ' and ' } } assert_equal 'a, b and c', %w[a b c].to_sentence ensure - I18n.backend.store_translations 'en', :support => { :array => { :skip_last_comma => false } } + I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => default_two_words_connector } } + I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => default_last_word_connector } } end end diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index ca2af9b986..067c461837 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -397,6 +397,10 @@ class MultibyteCharsUTF8BehaviourTest < Test::Unit::TestCase assert_raise(ArgumentError) { @chars.slice(1, 1, 1) } end + def test_ord_should_return_unicode_value_for_first_character + assert_equal 12371, @chars.ord + end + def test_upcase_should_upcase_ascii_characters assert_equal '', ''.mb_chars.upcase assert_equal 'ABC', 'aBc'.mb_chars.upcase diff --git a/railties/CHANGELOG b/railties/CHANGELOG index ca49c5d1c7..9ce7b6349c 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb [Pratik] + * Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally] This has been extracted from rg - http://github.com/jeremymcanally/rg diff --git a/railties/Rakefile b/railties/Rakefile index f812b42f1d..692c96ddbb 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -282,6 +282,7 @@ task :guides do FileUtils.mkdir(html) template = File.expand_path("doc/guides/source/templates/guides.html.erb") + asciidoc_conf = 'doc/guides/asciidoc.conf' ignore = ['..', 'icons', 'images', 'templates', 'stylesheets'] ignore << 'active_record_basics.txt' @@ -311,7 +312,7 @@ task :guides do begin puts "GENERATING => #{output}" ENV['MANUALSONRAILS_TOC'] = 'no' if indexless.include?(entry) - Mizuho::Generator.new(input, :output => output, :template => template).start + Mizuho::Generator.new(input, :output => output, :template => template, :conf_file => asciidoc_conf).start rescue Mizuho::GenerationError STDERR.puts "*** ERROR" exit 2 diff --git a/railties/doc/guides/asciidoc.conf b/railties/doc/guides/asciidoc.conf new file mode 100644 index 0000000000..f8e0c0a32c --- /dev/null +++ b/railties/doc/guides/asciidoc.conf @@ -0,0 +1,26 @@ +# Asciidoc substitutes some characters by default, those are called +# "replacements" in the docs. For example => becomes a unicode arrow. +# +# We override replacements to allow copy & paste of source code. + +[replacements] + +# Ellipsis +(?<!\\)\.\.\.=... +\\\.\.\.=... + +# -> right arrow +(?<!\\)->==-> +\\->=-> + +# => right double arrow +(?<!\\)\=>==> +\\\=>==> + +# <- left arrow +(?<!\\)<-=<- +\\<-=<- + +# <= left double arrow +(?<!\\)<\==<= +\\<\==<=
\ No newline at end of file diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index 68b8188f7c..778144b688 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -789,7 +789,7 @@ You can now easily <a href="http://m.onkey.org/2008/7/20/rescue-from-dispatching </li>
<li>
<p>
-The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as <tt>/customers/1.xml</tt>) to indicate the format that you want. If you need the Accept headers, you can turn them back on with <tt>config.action_controller.user_accept_header = true</tt>.
+The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as <tt>/customers/1.xml</tt>) to indicate the format that you want. If you need the Accept headers, you can turn them back on with <tt>config.action_controller.use_accept_header = true</tt>.
</p>
</li>
<li>
@@ -974,7 +974,7 @@ The addition of <tt>ActiveSupport::Rescuable</tt> allows any class to mix in the </li>
<li>
<p>
-<tt>Array#second</tt> through <tt>Array#tenth</tt> as aliases for <tt>Array#[1]</tt> through <tt>Array#[9]</tt>
+<tt>Array#second</tt> through <tt>Array#fifth</tt> as aliases for <tt>Array#[1]</tt> through <tt>Array#[4]</tt>
</p>
</li>
<li>
@@ -994,7 +994,7 @@ The addition of <tt>ActiveSupport::Rescuable</tt> allows any class to mix in the </li>
<li>
<p>
-The included TzInfo library has been upgraded to version 0.3.11.
+The included TzInfo library has been upgraded to version 0.3.12.
</p>
</li>
<li>
@@ -1017,7 +1017,7 @@ The included TzInfo library has been upgraded to version 0.3.11. </li>
<li>
<p>
-<tt>rake gems</tt> to list all configured gems, as well as whether they (and their dependencies) are installed or frozen
+<tt>rake gems</tt> to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen)
</p>
</li>
<li>
@@ -1068,6 +1068,11 @@ More information: <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>
+<li>
+<p>
+<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128">Detailed discussion on Lighthouse</a>
+</p>
+</li>
</ul></div>
</li>
</ul></div>
diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 66563bf1a3..4af157d4f7 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -723,7 +723,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Note that while for session values, you set the key to <tt>nil</tt>, to delete a cookie value, you should use <tt>cookies.delete(:key)</tt>.</p></div>
+<div class="para"><p>Note that while for session values you set the key to <tt>nil</tt>, to delete a cookie value you should use <tt>cookies.delete(:key)</tt>.</p></div>
</div>
<h2 id="_filters">6. Filters</h2>
<div class="sectionbody">
@@ -767,7 +767,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <tt>skip_before_filter</tt> :</p></div>
+<div class="para"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <tt>skip_before_filter</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -779,7 +779,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Now, the <tt>LoginsController</tt>'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>
+<div class="para"><p>Now, the LoginsController's <tt>new</tt> and <tt>create</tt> 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="listingblock">
@@ -872,7 +872,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>Now the <tt>create</tt> action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for <strong>every</strong> action in LoginsController, which is not what we want. You can limit which actions it will be used for with the <tt>:only</tt> and <tt>:except</tt> options just like a filter:</p></div>
+<div class="para"><p>Now the <tt>create</tt> action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the <tt>new</tt> action will be rendered. But there's something rather important missing from the verification above: It will be used for <strong>every</strong> action in LoginsController, which is not what we want. You can limit which actions it will be used for with the <tt>:only</tt> and <tt>:except</tt> options just like a filter:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -934,7 +934,7 @@ host - The hostname used for this request. </li>
<li>
<p>
-domain - The hostname without the first segment (usually "www").
+domain(n=2) - The hostname's first <tt>n</tt> segments, starting from the right (the TLD)
</p>
</li>
<li>
@@ -949,7 +949,7 @@ method - The HTTP method used for the request. </li>
<li>
<p>
-get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.
</p>
</li>
<li>
@@ -964,7 +964,7 @@ port - The port number (integer) used for the request. </li>
<li>
<p>
-protocol - The protocol used for the request.
+protocol - Returns a string containing the prototol used plus "://", for example "http://"
</p>
</li>
<li>
@@ -1118,7 +1118,7 @@ http://www.gnu.org/software/src-highlite --> <td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
-<td class="content">It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.</td>
+<td class="content">It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the <tt>:x_sendfile</tt> option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the <tt>X-Sendfile</tt> header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.</td>
</tr></table>
</div>
<h3 id="_restful_downloads">11.2. RESTful Downloads</h3>
@@ -1166,7 +1166,7 @@ http://www.gnu.org/software/src-highlite --> </div>
<h2 id="_parameter_filtering">12. Parameter Filtering</h2>
<div class="sectionbody">
-<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <tt>filter_parameter_logging</tt> method can be used to filter out sensitive information from the log. It works by replacing certain values in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
+<div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the <tt>log</tt> folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <tt>filter_parameter_logging</tt> method can be used to filter out sensitive information from the log. It works by replacing certain values in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1178,7 +1178,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.</p></div>
+<div class="para"><p>The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.</p></div>
</div>
<h2 id="_rescue">13. Rescue</h2>
<div class="sectionbody">
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 0aa507a9b9..cb381e7191 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -267,6 +267,53 @@ ul#navMain { <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a> </li> <li> + <a href="#_using_the_tt_errors_tt_collection">Using the <tt>errors</tt> collection</a> + </li> + <li> + <a href="#_callbacks">Callbacks</a> + <ul> + + <li><a href="#_callbacks_registration">Callbacks registration</a></li> + + <li><a href="#_registering_callbacks_by_overriding_the_callback_methods">Registering callbacks by overriding the callback methods</a></li> + + <li><a href="#_registering_callbacks_by_using_macro_style_class_methods">Registering callbacks by using macro-style class methods</a></li> + + </ul> + </li> + <li> + <a href="#_available_callbacks">Available callbacks</a> + <ul> + + <li><a href="#_callbacks_called_both_when_creating_or_updating_a_record">Callbacks called both when creating or updating a record.</a></li> + + <li><a href="#_callbacks_called_only_when_creating_a_new_record">Callbacks called only when creating a new record.</a></li> + + <li><a href="#_callbacks_called_only_when_updating_an_existing_record">Callbacks called only when updating an existing record.</a></li> + + <li><a href="#_callbacks_called_when_removing_a_record_from_the_database">Callbacks called when removing a record from the database.</a></li> + + <li><a href="#_the_tt_after_initialize_tt_and_tt_after_find_tt_callbacks">The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks</a></li> + + </ul> + </li> + <li> + <a href="#_halting_execution">Halting Execution</a> + </li> + <li> + <a href="#_callback_classes">Callback classes</a> + </li> + <li> + <a href="#_observers">Observers</a> + <ul> + + <li><a href="#_registering_observers">Registering observers</a></li> + + <li><a href="#_where_to_put_the_observers_source_files">Where to put the observers' source files</a></li> + + </ul> + </li> + <li> <a href="#_changelog">Changelog</a> </li> </ol> @@ -358,7 +405,15 @@ http://www.gnu.org/software/src-highlite --> >> p.new_record?
=> false</tt></pre>
</div></div>
-<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt>, <tt>update_attribute</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
+<div class="para"><p>Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either <tt>save</tt> or <tt>update_attributes</tt>) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/caution.png" alt="Caution" />
+</td>
+<td class="content">There are four methods that when called will trigger validation: <tt>save</tt>, <tt>save!</tt>, <tt>update_attributes</tt> and <tt>update_attributes!</tt>. There is one method left, which is <tt>update_attribute</tt>. This method will update the value of an attribute without triggering any validation, so be careful when using <tt>update_attribute</tt>, since it can let you save your objects in an invalid state.</td>
+</tr></table>
+</div>
<h3 id="_the_meaning_of_em_valid_em">2.2. The meaning of <em>valid</em></h3>
<div class="para"><p>For verifying if an object is valid, Active Record uses the <tt>valid?</tt> method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the <tt>errors</tt> instance method. The proccess is really simple: If the <tt>errors</tt> method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the <tt>errors</tt> collection.</p></div>
</div>
@@ -719,7 +774,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</p></div>
+<div class="para"><p>If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -738,7 +793,400 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_changelog">7. Changelog</h2>
+<h2 id="_using_the_tt_errors_tt_collection">7. Using the <tt>errors</tt> collection</h2>
+<div class="sectionbody">
+<div class="para"><p>You can do more than just call <tt>valid?</tt> upon your objects based on the existance of the <tt>errors</tt> collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>add_to_base</tt> lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. <tt>add_to_base</tt> receives a string with the message.
+</p>
+</li>
+</ul></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> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> a_method_used_for_validation_purposes
+ errors<span style="color: #990000">.</span>add_to_base<span style="color: #990000">(</span><span style="color: #FF0000">"This person is invalid because ..."</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>add</tt> lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. <tt>add</tt> receives a symbol with the name of the attribute that you want to add the message to and the message itself.
+</p>
+</li>
+</ul></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> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> a_method_used_for_validation_purposes
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>name<span style="color: #990000">,</span> <span style="color: #FF0000">"can't have the characters !@#$%*()_-+="</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>invalid?</tt> is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check.
+</p>
+</li>
+</ul></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> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=></span> <span style="color: #FF0000">"John Doe"</span><span style="color: #990000">)</span>
+person<span style="color: #990000">.</span>invalid?<span style="color: #990000">(:</span>email<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># => true</span></span>
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>on</tt> is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the <tt>errors</tt> collection for the given attribute. If there are no errors related to the attribute, <tt>on</tt> will return <tt>nil</tt>. If there is just one errors message for this attribute, <tt>on</tt> will return a string with the message. When <tt>errors</tt> holds two or more error messages for the attribute, <tt>on</tt> will return an array of strings, each one with one error message.
+</p>
+</li>
+</ul></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> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name
+ validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=></span> <span style="color: #993399">3</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=></span> <span style="color: #FF0000">"John Doe"</span><span style="color: #990000">)</span>
+person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># => true</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># => nil</span></span>
+
+person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=></span> <span style="color: #FF0000">"JD"</span><span style="color: #990000">)</span>
+person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># => false</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># => "is too short (minimum is 3 characters)"</span></span>
+
+person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
+person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># => false</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># => ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>clear</tt> is used when you intentionally wants to clear all the messages in the <tt>errors</tt> collection.
+</p>
+</li>
+</ul></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> Person <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name
+ validates_length_of <span style="color: #990000">:</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>minimum <span style="color: #990000">=></span> <span style="color: #993399">3</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+person <span style="color: #990000">=</span> Person<span style="color: #990000">.</span>new
+puts person<span style="color: #990000">.</span>valid? <span style="font-style: italic"><span style="color: #9A1900"># => false</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>on<span style="color: #990000">(:</span>name<span style="color: #990000">)</span> <span style="font-style: italic"><span style="color: #9A1900"># => ["can't be blank", "is too short (minimum is 3 characters)"]</span></span>
+person<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>clear
+person<span style="color: #990000">.</span>errors <span style="font-style: italic"><span style="color: #9A1900"># => nil</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_callbacks">8. Callbacks</h2>
+<div class="sectionbody">
+<div class="para"><p>Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.</p></div>
+<h3 id="_callbacks_registration">8.1. Callbacks registration</h3>
+<div class="para"><p>In order to use the available callbacks, you need to registrate them. There are two ways of doing that.</p></div>
+<h3 id="_registering_callbacks_by_overriding_the_callback_methods">8.2. Registering callbacks by overriding the callback methods</h3>
+<div class="para"><p>You can specify the callback method direcly, by overriding it. Let's see how it works using the <tt>before_validation</tt> callback, which will surprisingly run right before any validation is done.</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> User <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+
+ protected
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> before_validation
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login <span style="color: #990000">=</span> email <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> email<span style="color: #990000">.</span>blank?
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_registering_callbacks_by_using_macro_style_class_methods">8.3. Registering callbacks by using macro-style class methods</h3>
+<div class="para"><p>The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:</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> User <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+
+ before_validation <span style="color: #990000">:</span>ensure_login_has_a_value
+
+ protected
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> ensure_login_has_a_value
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>login <span style="color: #990000">=</span> email <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> email<span style="color: #990000">.</span>blank?
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.</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> User <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>login<span style="color: #990000">,</span> <span style="color: #990000">:</span>email
+
+ before_create <span style="color: #FF0000">{</span><span style="color: #990000">|</span>user<span style="color: #990000">|</span> user<span style="color: #990000">.</span>name <span style="color: #990000">=</span> user<span style="color: #990000">.</span>login<span style="color: #990000">.</span>capitalize <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> user<span style="color: #990000">.</span>name<span style="color: #990000">.</span>blank?<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>In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered.
+</p>
+</li>
+<li>
+<p>
+Readability, since your callback declarations will live at the beggining of your models' files.
+</p>
+</li>
+</ul></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/caution.png" alt="Caution" />
+</td>
+<td class="content">Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.</td>
+</tr></table>
+</div>
+</div>
+<h2 id="_available_callbacks">9. Available callbacks</h2>
+<div class="sectionbody">
+<div class="para"><p>Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.</p></div>
+<h3 id="_callbacks_called_both_when_creating_or_updating_a_record">9.1. Callbacks called both when creating or updating a record.</h3>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>before_validation</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>after_validation</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>before_save</tt>
+</p>
+</li>
+<li>
+<p>
+<strong>INSERT OR UPDATE OPERATION</strong>
+</p>
+</li>
+<li>
+<p>
+<tt>after_save</tt>
+</p>
+</li>
+</ul></div>
+<h3 id="_callbacks_called_only_when_creating_a_new_record">9.2. Callbacks called only when creating a new record.</h3>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>before_validation_on_create</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>after_validation_on_create</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>before_create</tt>
+</p>
+</li>
+<li>
+<p>
+<strong>INSERT OPERATION</strong>
+</p>
+</li>
+<li>
+<p>
+<tt>after_create</tt>
+</p>
+</li>
+</ul></div>
+<h3 id="_callbacks_called_only_when_updating_an_existing_record">9.3. Callbacks called only when updating an existing record.</h3>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>before_validation_on_update</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>after_validation_on_update</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>before_update</tt>
+</p>
+</li>
+<li>
+<p>
+<strong>UPDATE OPERATION</strong>
+</p>
+</li>
+<li>
+<p>
+<tt>after_update</tt>
+</p>
+</li>
+</ul></div>
+<h3 id="_callbacks_called_when_removing_a_record_from_the_database">9.4. Callbacks called when removing a record from the database.</h3>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>before_destroy</tt>
+</p>
+</li>
+<li>
+<p>
+<strong>DELETE OPERATION</strong>
+</p>
+</li>
+<li>
+<p>
+<tt>after_destroy</tt>
+</p>
+</li>
+</ul></div>
+<div class="para"><p>The <tt>before_destroy</tt> and <tt>after_destroy</tt> callbacks will only be called if you delete the model using either the <tt>destroy</tt> instance method or one of the <tt>destroy</tt> or <tt>destroy_all</tt> class methods of your Active Record class. If you use <tt>delete</tt> or <tt>delete_all</tt> no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.</p></div>
+<h3 id="_the_tt_after_initialize_tt_and_tt_after_find_tt_callbacks">9.5. The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks</h3>
+<div class="para"><p>The <tt>after_initialize</tt> callback will be called whenever an Active Record object is instantiated, either by direcly using <tt>new</tt> or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record <tt>initialize</tt> method.</p></div>
+<div class="para"><p>The <tt>after_find</tt> callback will be called whenever Active Record loads a record from the database. When used together with <tt>after_initialize</tt> it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.</p></div>
+<div class="para"><p>The <tt>after_initialize</tt> and <tt>after_find</tt> callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register <tt>after_initialize</tt> or <tt>after_find</tt> using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since <tt>after_initialize</tt> and <tt>after_find</tt> will both be called for each record found in the database, significantly slowing down the queries.</p></div>
+</div>
+<h2 id="_halting_execution">10. Halting Execution</h2>
+<div class="sectionbody">
+<div class="para"><p>As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean <tt>false</tt> (not <tt>nil</tt>) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.</p></div>
+</div>
+<h2 id="_callback_classes">11. Callback classes</h2>
+<div class="sectionbody">
+<div class="para"><p>Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.</p></div>
+<div class="para"><p>Here's an example where we create a class with a after_destroy callback for a PictureFile model.</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> PictureFileCallbacks
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> after_destroy<span style="color: #990000">(</span>picture_file<span style="color: #990000">)</span>
+ File<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> File<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:</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> PictureFile <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ after_destroy PictureFileCallbacks<span style="color: #990000">.</span>new
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.</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> PictureFileCallbacks
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>after_destroy<span style="color: #990000">(</span>picture_file<span style="color: #990000">)</span>
+ File<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> File<span style="color: #990000">.</span>exists?<span style="color: #990000">(</span>picture_file<span style="color: #990000">.</span>filepath<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.</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> PictureFile <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ after_destroy PictureFileCallbacks
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>You can declare as many callbacks as you want inside your callback classes.</p></div>
+</div>
+<h2 id="_observers">12. Observers</h2>
+<div class="sectionbody">
+<div class="para"><p>Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that's not directly related to the model's purpose. In object-oriented software, it's always a good idea to design your classes with a single responsability in the whole system. For example, it wouldn't make much sense to have a <tt>User</tt> model with a method that writes data about a login attempt to a log file. Whenever you're using callbacks to write code that's not directly related to your model class purposes, it may be a good moment to create an Observer.</p></div>
+<div class="para"><p>An Active Record Observer is an object that links itself to a model and register it's methods for callbacks. Your model's implementation remain clean, while you can reuse the code in the Observer to add behaviuor to more than one model class. Ok, you may say that we can also do that using callback classes, but it would still force us to add code to our model's implementation.</p></div>
+<div class="para"><p>Observer classes are subclasses of the <tt>ActiveRecord::Observer</tt> class. When this class is subclassed, Active Record will look at the name of the new class and then strip the <em>Observer</em> part to find the name of the Active Record class to observe.</p></div>
+<div class="para"><p>Consider a <tt>Registration</tt> model, where we want to send an email everytime a new registration is created. Since sending emails is not directly related to our model's purpose, we could create an Observer to do just that:</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> RegistrationObserver <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Observer
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> after_create<span style="color: #990000">(</span>model<span style="color: #990000">)</span>
+ <span style="font-style: italic"><span style="color: #9A1900"># code to send registration confirmation emails...</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Like in callback classes, the observer's methods receive the observed model as a parameter.</p></div>
+<div class="para"><p>Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.</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> Auditor <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Observer
+ observe User<span style="color: #990000">,</span> Registration<span style="color: #990000">,</span> Invoice
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_registering_observers">12.1. Registering observers</h3>
+<div class="para"><p>If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's <strong>config/environment.rb</strong> file. In this file there is a commented out line where we can define the observers that our application should load at start-up.</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-style: italic"><span style="color: #9A1900"># Activate observers that should always be running</span></span>
+config<span style="color: #990000">.</span>active_record<span style="color: #990000">.</span>observers <span style="color: #990000">=</span> <span style="color: #990000">:</span>registration_observer<span style="color: #990000">,</span> <span style="color: #990000">:</span>auditor
+</tt></pre></div></div>
+<h3 id="_where_to_put_the_observers_source_files">12.2. Where to put the observers' source files</h3>
+<div class="para"><p>By convention, you should always save your observers' source files inside <strong>app/models</strong>.</p></div>
+</div>
+<h2 id="_changelog">13. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks</a></p></div>
</div>
diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html index 9159eaab2a..a2f89e3c43 100644 --- a/railties/doc/guides/html/association_basics.html +++ b/railties/doc/guides/html/association_basics.html @@ -687,8 +687,8 @@ 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> Employee <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
- has_many <span style="color: #990000">:</span>subordinates<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=></span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=></span> <span style="color: #FF0000">"manager_id"</span>
- belongs_to <span style="color: #990000">:</span>manager<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=></span> <span style="color: #FF0000">"User"</span>
+ has_many <span style="color: #990000">:</span>subordinates<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=></span> <span style="color: #FF0000">"Employee"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=></span> <span style="color: #FF0000">"manager_id"</span>
+ belongs_to <span style="color: #990000">:</span>manager<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=></span> <span style="color: #FF0000">"Employee"</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.manager</tt>.</p></div>
@@ -742,7 +742,9 @@ customer<span style="color: #990000">.</span>orders<span style="color: #990000"> <h3 id="_avoiding_name_collisions">3.2. Avoiding Name Collisions</h3>
<div class="para"><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <tt>ActiveRecord::Base</tt>. The association method would override the base method and break things. For instance, <tt>attributes</tt> or <tt>connection</tt> are bad names for associations.</p></div>
<h3 id="_updating_the_schema">3.3. Updating the Schema</h3>
-<div class="para"><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:</p></div>
+<div class="para"><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <tt>belongs_to</tt> associations you need to create foreign keys, and for <tt>has_and_belongs_to_many</tt> associations you need to create the appropriate join table.</p></div>
+<h4 id="_creating_foreign_keys_for_tt_belongs_to_tt_associations">3.3.1. Creating Foreign Keys for <tt>belongs_to</tt> Associations</h4>
+<div class="para"><p>When you declare a <tt>belongs_to</tt> association, you need to create foreign keys as appropriate. For example, consider this model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -761,9 +763,9 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateOrders <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
create_table <span style="color: #990000">:</span>orders <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
- t<span style="color: #990000">.</span>order_date <span style="color: #990000">:</span>datetime
- t<span style="color: #990000">.</span>order_number <span style="color: #990000">:</span>string
- t<span style="color: #990000">.</span>customer_id <span style="color: #990000">:</span>integer
+ t<span style="color: #990000">.</span>datetime <span style="color: #990000">:</span>order_date
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>order_number
+ t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>customer_id
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -773,7 +775,8 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you create an association some time after you build the underlying model, you need to remember to create an <tt>add_column</tt> migration to provide the necessary foreign key.</p></div>
-<div class="para"><p>Second, if you create a <tt>has_and_belongs_to_many</tt> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <tt>:join_table</tt> option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p></div>
+<h4 id="_creating_join_tables_for_tt_has_and_belongs_to_many_tt_associations">3.3.2. Creating Join Tables for <tt>has_and_belongs_to_many</tt> Associations</h4>
+<div class="para"><p>If you create a <tt>has_and_belongs_to_many</tt> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <tt>:join_table</tt> option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
@@ -1938,7 +1941,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_offset_tt"><tt>:offset</tt></h5>
-<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset ⇒ 11</tt>, it will skip the first 10 records.</p></div>
+<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset ⇒ 11</tt>, it will skip the first 11 records.</p></div>
<h5 id="_tt_order_tt_2"><tt>:order</tt></h5>
<div class="para"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
@@ -2409,7 +2412,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<h5 id="_tt_offset_tt_2"><tt>:offset</tt></h5>
-<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset ⇒ 11</tt>, it will skip the first 10 records.</p></div>
+<div class="para"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset ⇒ 11</tt>, it will skip the first 11 records.</p></div>
<h5 id="_tt_order_tt_3"><tt>:order</tt></h5>
<div class="para"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html index a54135b14d..6fd556d2cd 100644 --- a/railties/doc/guides/html/authors.html +++ b/railties/doc/guides/html/authors.html @@ -231,6 +231,11 @@ Heiko has rarely looked back.</p></div> <div class="para"><p>Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
and unobtrusive JavaScript. His home on the internet is his blog <a href="http://tore.darell.no/">Sneaky Abstractions</a>.</p></div>
</div></div>
+<div class="sidebarblock" id="zilkey">
+<div class="sidebar-content">
+<div class="sidebar-title">Jeff Dean</div>
+<div class="para"><p>Jeff Dean is a software engineer with <a href="http://pivotallabs.com/">Pivotal Labs</a>.</p></div>
+</div></div>
</div>
</div>
diff --git a/railties/doc/guides/html/caching_with_rails.html b/railties/doc/guides/html/caching_with_rails.html index 7aa5999e1a..32a98d1314 100644 --- a/railties/doc/guides/html/caching_with_rails.html +++ b/railties/doc/guides/html/caching_with_rails.html @@ -217,6 +217,9 @@ ul#navMain { </ul> </li> <li> + <a href="#_conditional_get_support">Conditional GET support</a> + </li> + <li> <a href="#_advanced_caching">Advanced Caching</a> </li> </ol> @@ -235,8 +238,8 @@ need to return to those hungry web clients in the shortest time possible.</p></d <div class="sectionbody">
<div class="para"><p>This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.</p></div>
-<div class="para"><p>To get started make sure config.action_controller.perform_caching is set
-to true for your environment. This flag is normally set in the
+<div class="para"><p>To get started make sure <tt>config.action_controller.perform_caching</tt> is set
+to <tt>true</tt> for your environment. This flag is normally set in the
corresponding config/environments/*.rb and caching is disabled by default
there for development and test, and enabled for production.</p></div>
<div class="listingblock">
@@ -270,19 +273,19 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>The first time anyone requests products/index, Rails will generate a file
-called index.html and the webserver will then look for that file before it
+called <tt>index.html</tt> and the webserver will then look for that file before it
passes the next request for products/index to your Rails application.</p></div>
<div class="para"><p>By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by
-changing the configuration setting ActionController::Base.page_cache_directory. Changing the
-default from /public helps avoid naming conflicts, since you may want to
-put other static html in /public, but changing this will require web
-server reconfiguration to let the web server know where to serve the
-cached files from.</p></div>
-<div class="para"><p>The Page Caching mechanism will automatically add a .html exxtension to
+usually set to <tt>RAILS_ROOT + "/public"</tt>) and this can be configured by
+changing the configuration setting <tt>config.action_controller.page_cache_directory</tt>.
+Changing the default from /public helps avoid naming conflicts, since you may
+want to put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the cached
+files from.</p></div>
+<div class="para"><p>The Page Caching mechanism will automatically add a <tt>.html</tt> exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting ActionController::Base.page_cache_extension.</p></div>
+configuration setting <tt>config.action_controller.page_cache_extension</tt>.</p></div>
<div class="para"><p>In order to expire this page when a new product is added we could extend our
example controler like this:</p></div>
<div class="listingblock">
@@ -337,8 +340,8 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>And you can also use :if (or :unless) to pass a Proc that specifies when the
-action should be cached. Also, you can use :layout ⇒ false to cache without
+<div class="para"><p>And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a Proc that specifies when the
+action should be cached. Also, you can use <tt>:layout ⇒ false</tt> to cache without
layout so that dynamic information in the layout such as logged in user info
or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.</p></div>
@@ -377,7 +380,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_suffix to the cache call:</p></div>
+want to cache multiple fragments per action, you should provide an <tt>action_suffix</tt> to the cache call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -386,18 +389,38 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="color: #FF0000"><% cache(:action =></span> <span style="color: #FF0000">'recent'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action_suffix <span style="color: #990000">=></span> <span style="color: #FF0000">'all_products'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">%></span>
All available products<span style="color: #990000">:</span>
</tt></pre></div></div>
-<div class="para"><p>and you can expire it using the expire_fragment method, like so:</p></div>
+<div class="para"><p>and you can expire it using the <tt>expire_fragment</tt> method, like so:</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>expire_fragment<span style="color: #990000">(:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'products'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'recent'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action_suffix <span style="color: #990000">=></span> 'all_products<span style="color: #990000">)</span>
+</tt></pre></div></div>
+<div class="para"><p>If you don't want the cache block to bind to the action that called it, You can
+also use globally keyed fragments by calling the cache method with a key, like
+so:</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>expire_fragment<span style="color: #990000">(:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'producst'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'recent'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action_suffix <span style="color: #990000">=></span> 'all_products<span style="color: #990000">)</span>
+<pre><tt><span style="color: #FF0000"><% cache(:key =></span> <span style="color: #990000">[</span><span style="color: #FF0000">'all_available_products'</span><span style="color: #990000">,</span> <span style="color: #009900">@latest_product</span><span style="color: #990000">.</span>created_at<span style="color: #990000">].</span>join<span style="color: #990000">(</span><span style="color: #FF0000">':'</span><span style="color: #990000">))</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">%></span>
+ All available products<span style="color: #990000">:</span>
+</tt></pre></div></div>
+<div class="para"><p>This fragment is then available to all actions in the ProductsController using
+the key and can be expired the same way:</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>expire_fragment<span style="color: #990000">(:</span>key <span style="color: #990000">=></span> <span style="color: #990000">[</span><span style="color: #FF0000">'all_available_products'</span><span style="color: #990000">,</span> <span style="color: #009900">@latest_product</span><span style="color: #990000">.</span>created_at<span style="color: #990000">].</span>join<span style="color: #990000">(</span><span style="color: #FF0000">':'</span><span style="color: #990000">))</span>
</tt></pre></div></div>
<h3 id="_sweepers">1.4. Sweepers</h3>
<div class="para"><p>Cache sweeping is a mechanism which allows you to get around having a ton of
expire_{page,action,fragment} calls in your code by moving all the work
-required to expire cached content into a ActionController::Caching::Sweeper
+required to expire cached content into a <tt>ActionController::Caching::Sweeper</tt>
class that is an Observer and looks for changes to an object via callbacks,
and when a change occurs it expires the caches associated with that object n
an around or after filter.</p></div>
@@ -547,8 +570,7 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>ActionController<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>cache_store <span style="color: #990000">=</span> <span style="color: #990000">:</span>drb_store<span style="color: #990000">,</span> <span style="color: #FF0000">"druby://localhost:9192"</span>
</tt></pre></div></div>
<div class="para"><p>4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead.
- Requires the ruby-memcache library:
- gem install ruby-memcache.</p></div>
+ Rails uses the bundled memcached-client gem by default.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -564,8 +586,70 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>ActionController<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>cache_store <span style="color: #990000">=</span> MyOwnStore<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"parameter"</span><span style="color: #990000">)</span>
</tt></pre></div></div>
+<div class="para"><p><tt>Note: config.cache_store can be used in place of
+ActionController::Base.cache_store in your Rails::Initializer.run block in
+environment.rb</tt></p></div>
+</div>
+<h2 id="_conditional_get_support">2. Conditional GET support</h2>
+<div class="sectionbody">
+<div class="para"><p>Conditional GETs are a facility of the HTTP spec that provide a way for web
+servers to tell browsers that the response to a GET request hasn’t changed
+since the last request and can be safely pulled from the browser cache.</p></div>
+<div class="para"><p>They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to
+pass back and forth both a unique content identifier and the timestamp of when
+the content was last changed. If the browser makes a request where the content
+identifier (etag) or last modified since timestamp matches the server’s version
+then the server only needs to send back an empty response with a not modified
+status.</p></div>
+<div class="para"><p>It is the server’s (i.e. our) responsibility to look for a last modified
+timestamp and the if-none-match header and determine whether or not to send
+back the full response. With conditional-get support in rails this is a pretty
+easy task:</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> ProductsController <span style="color: #990000"><</span> ApplicationController
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> show
+ <span style="color: #009900">@product</span> <span style="color: #990000">=</span> Product<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
+
+ <span style="font-style: italic"><span style="color: #9A1900"># If the request is stale according to the given timestamp and etag value</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># (i.e. it needs to be processed again) then execute this block</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> stale?<span style="color: #990000">(:</span>last_modified <span style="color: #990000">=></span> <span style="color: #009900">@product</span><span style="color: #990000">.</span>updated_at<span style="color: #990000">.</span>utc<span style="color: #990000">,</span> <span style="color: #990000">:</span>etag <span style="color: #990000">=></span> <span style="color: #009900">@product</span><span style="color: #990000">)</span>
+ respond_to <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>wants<span style="color: #990000">|</span>
+ <span style="font-style: italic"><span style="color: #9A1900"># ... normal response processing</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-style: italic"><span style="color: #9A1900"># If the request is fresh (i.e. it's not modified) then you don't need to do</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># anything. The default render checks for this using the parameters</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># used in the previous call to stale? and will automatically send a</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># :not_modified. So that's it, you're done.</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If you don’t have any special response processing and are using the default
+rendering mechanism (i.e. you’re not using respond_to or calling render
+yourself) then you’ve got an easy helper in fresh_when:</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> ProductsController <span style="color: #990000"><</span> ApplicationController
+
+ <span style="font-style: italic"><span style="color: #9A1900"># This will automatically send back a :not_modified if the request is fresh,</span></span>
+ <span style="font-style: italic"><span style="color: #9A1900"># and will render the default template (product.*) if it's stale.</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> show
+ <span style="color: #009900">@product</span> <span style="color: #990000">=</span> Product<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
+ fresh_when <span style="color: #990000">:</span>last_modified <span style="color: #990000">=></span> <span style="color: #009900">@product</span><span style="color: #990000">.</span>published_at<span style="color: #990000">.</span>utc<span style="color: #990000">,</span> <span style="color: #990000">:</span>etag <span style="color: #990000">=></span> <span style="color: #009900">@article</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
</div>
-<h2 id="_advanced_caching">2. Advanced Caching</h2>
+<h2 id="_advanced_caching">3. Advanced Caching</h2>
<div class="sectionbody">
<div class="para"><p>Along with the built-in mechanisms outlined above, a number of excellent
plugins exist to help with finer grained control over caching. These include
diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html index 2add20446e..2a28da177e 100644 --- a/railties/doc/guides/html/command_line.html +++ b/railties/doc/guides/html/command_line.html @@ -377,7 +377,7 @@ Installed Generators <td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like <tt>rails</tt> or <tt>./script/generate</tt>). For others, you can try adding <tt>—help</tt> or <tt>-h</tt> to the end, as in <tt>./script/server —help</tt>.</td>
+<td class="content">All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can try the command without any parameters (like <tt>rails</tt> or <tt>./script/generate</tt>). For others, you can try adding <tt>—help</tt> or <tt>-h</tt> to the end, as in <tt>./script/server —help</tt>.</td>
</tr></table>
</div>
<div class="listingblock">
@@ -425,7 +425,130 @@ http://www.gnu.org/software/src-highlite --> create app/helpers/greetings_helper<span style="color: #990000">.</span>rb
create app/views/greetings/hello<span style="color: #990000">.</span>html<span style="color: #990000">.</span>erb
</tt></pre></div></div>
-<div class="para"><p>Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!</p></div>
+<div class="para"><p>Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.</p></div>
+<div class="para"><p>Let's check out the controller and modify it a little (in <tt>app/controllers/greeting_controller.rb</tt>):</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> GreetingController <span style="color: #990000"><</span> ApplicationController
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> hello
+ <span style="color: #009900">@message</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"Hello, how are you today? I am exuberant!"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Then the view, to display our nice message (in <tt>app/views/greeting/hello.html.erb</tt>):</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"><h1></span></span>A Greeting for You!<span style="font-weight: bold"><span style="color: #0000FF"></h1></span></span>
+<span style="font-weight: bold"><span style="color: #0000FF"><p></span></span><%= @message %><span style="font-weight: bold"><span style="color: #0000FF"></p></span></span>
+</tt></pre></div></div>
+<div class="para"><p>Deal. Go check it out in your browser. Fire up your server. Remember? <tt>./script/server</tt> at the root of your Rails application should do it.</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="color: #990000">.</span>/script/server
+<span style="color: #990000">=></span> Booting WEBrick<span style="color: #990000">...</span>
+</tt></pre></div></div>
+<div class="para"><p>The URL will be <tt>http://localhost:3000/greetings/hello</tt>. I'll wait for you to be suitably impressed.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">With a normal, plain-old Rails application, your URLs will generally follow the pattern of <a href="http://(host)/(controller)/(action">http://(host)/(controller)/(action</a>), and a URL like <a href="http://(host)/(controller">http://(host)/(controller</a>) will hit the <strong>index</strong> action of that controller.</td>
+</tr></table>
+</div>
+<div class="para"><p>"What about data, though?", you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name?</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="color: #990000">.</span>/script/generate model
+Usage<span style="color: #990000">:</span> <span style="color: #990000">.</span>/script/generate model ModelName <span style="color: #990000">[</span>field<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">type</span></span><span style="color: #990000">,</span> field<span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">type</span></span><span style="color: #990000">]</span>
+
+<span style="color: #990000">...</span>
+
+Examples<span style="color: #990000">:</span>
+ `<span style="color: #990000">.</span>/script/generate model account`
+
+ creates an Account model<span style="color: #990000">,</span> <span style="font-weight: bold"><span style="color: #0000FF">test</span></span><span style="color: #990000">,</span> fixture<span style="color: #990000">,</span> and migration<span style="color: #990000">:</span>
+ Model<span style="color: #990000">:</span> app/models/account<span style="color: #990000">.</span>rb
+ Test<span style="color: #990000">:</span> test/unit/account_test<span style="color: #990000">.</span>rb
+ Fixtures<span style="color: #990000">:</span> test/fixtures/accounts<span style="color: #990000">.</span>yml
+ Migration<span style="color: #990000">:</span> db/migrate/XXX_add_accounts<span style="color: #990000">.</span>rb
+
+ `<span style="color: #990000">.</span>/script/generate model post title<span style="color: #990000">:</span>string body<span style="color: #990000">:</span>text published<span style="color: #990000">:</span>boolean`
+
+ creates a Post model with a string title<span style="color: #990000">,</span> text body<span style="color: #990000">,</span> and published flag<span style="color: #990000">.</span>
+</tt></pre></div></div>
+<div class="para"><p>Let's set up a simple model called "HighScore" that will keep track of our highest score on video games we play. Then we'll wire up our controller and view to modify and list our scores.</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="color: #990000">.</span>/script/generate model HighScore id<span style="color: #990000">:</span>integer game<span style="color: #990000">:</span>string score<span style="color: #990000">:</span>integer
+ exists app/models<span style="color: #990000">/</span>
+ exists test/unit<span style="color: #990000">/</span>
+ exists test/fixtures<span style="color: #990000">/</span>
+ create app/models/high_score<span style="color: #990000">.</span>rb
+ create test/unit/high_score_test<span style="color: #990000">.</span>rb
+ create test/fixtures/high_scores<span style="color: #990000">.</span>yml
+ create db/migrate
+ create db/migrate<span style="color: #990000">/</span>20081126032945_create_high_scores<span style="color: #990000">.</span>rb
+</tt></pre></div></div>
+<div class="para"><p>Taking it from the top, we have the <strong>models</strong> directory, where all of your data models live. <strong>test/unit</strong>, where all the unit tests live (gasp! — unit tests!), fixtures for those tests, a test, the <strong>migrate</strong> directory, where the database-modifying migrations live, and a migration to create the <tt>high_scores</tt> table with the right fields.</p></div>
+<div class="para"><p>The migration requires that we <strong>migrate</strong>, that is, run some Ruby code (living in that <tt>20081126032945_create_high_scores.rb</tt>) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the <tt>rake db:migrate</tt> command. We'll talk more about Rake in-depth in a little while.</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>$ rake db<span style="color: #990000">:</span>migrate
+<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">in</span></span> /home/commandsapp<span style="color: #990000">)</span>
+<span style="color: #990000">==</span> CreateHighScores<span style="color: #990000">:</span> migrating <span style="color: #990000">===============================================</span>
+-- create_table<span style="color: #990000">(:</span>high_scores<span style="color: #990000">)</span>
+ -<span style="color: #990000">></span> <span style="color: #993399">0</span><span style="color: #990000">.</span>0070s
+<span style="color: #990000">==</span> CreateHighScores<span style="color: #990000">:</span> migrated <span style="color: #990000">(</span><span style="color: #993399">0</span><span style="color: #990000">.</span>0077s<span style="color: #990000">)</span> <span style="color: #990000">======================================</span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.</td>
+</tr></table>
+</div>
+<div class="para"><p>Yo! Let's shove a small table into our greeting controller and view, listing our sweet scores.</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> GreetingController <span style="color: #990000"><</span> ApplicationController
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> hello
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> request<span style="color: #990000">.</span>post?
+ score <span style="color: #990000">=</span> HighScore<span style="color: #990000">.</span>new<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>high_score<span style="color: #990000">])</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> score<span style="color: #990000">.</span>save
+ flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"New score posted!"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="color: #009900">@scores</span> <span style="color: #990000">=</span> HighScore<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>all<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>XXX: Go with scaffolding instead, modifying greeting controller for high scores seems dumb.</p></div>
</div>
</div> diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html index 4aa3a0f545..adc827c89a 100644 --- a/railties/doc/guides/html/configuring.html +++ b/railties/doc/guides/html/configuring.html @@ -205,6 +205,9 @@ ul#navMain { <a href="#_using_a_preinitializer">Using a Preinitializer</a> </li> <li> + <a href="#_initialization_process_settings">Initialization Process Settings</a> + </li> + <li> <a href="#_configuring_rails_components">Configuring Rails Components</a> <ul> @@ -220,6 +223,8 @@ ul#navMain { <li><a href="#_configuring_active_support">Configuring Active Support</a></li> + <li><a href="#_configuring_active_model">Configuring Active Model</a></li> + </ul> </li> <li> @@ -229,6 +234,9 @@ ul#navMain { <a href="#_using_an_after_initializer">Using an After-Initializer</a> </li> <li> + <a href="#_rails_environment_settings">Rails Environment Settings</a> + </li> + <li> <a href="#_changelog">Changelog</a> </li> </ol> @@ -264,26 +272,156 @@ after-initializer</p></div> <h2 id="_using_a_preinitializer">2. Using a Preinitializer</h2>
<div class="sectionbody">
</div>
-<h2 id="_configuring_rails_components">3. Configuring Rails Components</h2>
+<h2 id="_initialization_process_settings">3. Initialization Process Settings</h2>
<div class="sectionbody">
-<h3 id="_configuring_active_record">3.1. Configuring Active Record</h3>
-<h3 id="_configuring_action_controller">3.2. Configuring Action Controller</h3>
-<h3 id="_configuring_action_view">3.3. Configuring Action View</h3>
-<h3 id="_configuring_action_mailer">3.4. Configuring Action Mailer</h3>
-<h3 id="_configuring_active_resource">3.5. Configuring Active Resource</h3>
-<h3 id="_configuring_active_support">3.6. Configuring Active Support</h3>
</div>
-<h2 id="_using_initializers">4. Using Initializers</h2>
+<h2 id="_configuring_rails_components">4. Configuring Rails Components</h2>
+<div class="sectionbody">
+<h3 id="_configuring_active_record">4.1. Configuring Active Record</h3>
+<div class="para"><p><tt>ActiveRecord::Base</tt> includej a variety of configuration options:</p></div>
+<div class="para"><p><tt>logger</tt> accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling <tt>logger</tt> on either an ActiveRecord model class or an ActiveRecord model instance. Set to nil to disable logging.</p></div>
+<div class="para"><p><tt>primary_key_prefix_type</tt> lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named <tt>id</tt> (and this configuration option doesn't need to be set.) There are two other choices:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>:table_name</tt> would make the primary key for the Customer class <tt>customerid</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>:table_name_with_underscore</tt> would make the primary key for the Customer class <tt>customer_id</tt>
+</p>
+</li>
+</ul></div>
+<div class="para"><p><tt>table_name_prefix</tt> lets you set a global string to be prepended to table names. If you set this to <tt>northwest_</tt>, then the Customer class will look for <tt>northwest_customers</tt> as its table. The default is an empty string.</p></div>
+<div class="para"><p><tt>table_name_suffix</tt> lets you set a global string to be appended to table names. If you set this to <tt>_northwest</tt>, then the Customer class will look for <tt>customers_northwest</tt> as its table. The default is an empty string.</p></div>
+<div class="para"><p><tt>pluralize_table_names</tt> specifies whether Rails will look for singular or plural table names in the database. If set to <tt>true</tt> (the default), then the Customer class will use the <tt>customers</tt> table. If set to <tt>false</tt>, then the Customers class will use the <tt>customer</tt> table.</p></div>
+<div class="para"><p><tt>colorize_logging</tt> (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord.</p></div>
+<div class="para"><p><tt>default_timezone</tt> determines whether to use <tt>Time.local</tt> (if set to <tt>:local</tt>) or <tt>Time.utc</tt> (if set to <tt>:utc</tt>) when pulling dates and times from the database. The default is <tt>:local</tt>.</p></div>
+<div class="para"><p><tt>schema_format</tt> controls the format for dumping the database schema to a file. The options are <tt>:ruby</tt> (the default) for a database-independent version that depends on migrations, or <tt>:sql</tt> for a set of (potentially database-dependent) SQL statements.</p></div>
+<div class="para"><p><tt>timestamped_migrations</tt> controls whether migrations are numbered with serial integers or with timestamps. The default is <tt>true</tt>, to use timestamps, which are preferred if there are multiple developers working on the same application.</p></div>
+<div class="para"><p><tt>lock_optimistically</tt> controls whether ActiveRecord will use optimistic locking. By default this is <tt>true</tt>.</p></div>
+<div class="para"><p>The MySQL adapter adds one additional configuration option:</p></div>
+<div class="para"><p><tt>ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans</tt> controls whether ActiveRecord will consider all <tt>tinyint(1)</tt> columns in a MySQL database to be booleans. By default this is <tt>true</tt>.</p></div>
+<div class="para"><p>The schema dumper adds one additional configuration option:</p></div>
+<div class="para"><p><tt>ActiveRecord::SchemaDumper.ignore_tables</tt> accepts an array of tables that should <em>not</em> be included in any generated schema file. This setting is ignored unless <tt>ActiveRecord::Base.schema_format == :ruby</tt>.</p></div>
+<h3 id="_configuring_action_controller">4.2. Configuring Action Controller</h3>
+<div class="para"><p>ActionController::Base includes a number of configuration settings:</p></div>
+<div class="para"><p><tt>asset_host</tt> provides a string that is prepended to all of the URL-generating helpers in <tt>AssetHelper</tt>. This is designed to allow moving all javascript, CSS, and image files to a separate asset host.</p></div>
+<div class="para"><p><tt>consider_all_requests_local</tt> is generally set to <tt>true</tt> during development and <tt>false</tt> during production; if it is set to <tt>true</tt>, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to <tt>false</tt> and implement <tt>local_request?</tt> to specify which requests should provide debugging information on errors.</p></div>
+<div class="para"><p><tt>allow_concurrency</tt> should be set to <tt>true</tt> to allow concurrent (threadsafe) action processing. Set to <tt>false</tt> by default.</p></div>
+<div class="para"><p><tt>param_parsers</tt> provides an array of handlers that can extract information from incoming HTTP requests and add it to the <tt>params</tt> hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active.</p></div>
+<div class="para"><p><tt>default_charset</tt> specifies the default character set for all renders. The default is "utf-8".</p></div>
+<div class="para"><p><tt>logger</tt> accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.</p></div>
+<div class="para"><p><tt>resource_action_separator</tt> gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/".</p></div>
+<div class="para"><p><tt>resource_path_names</tt> is a hash of default names for several RESTful actions. By default, the new action is named <tt>new</tt> and the edit action is named <tt>edit</tt>.</p></div>
+<div class="para"><p><tt>request_forgery_protection_token</tt> sets the token parameter name for RequestForgery. Calling <tt>protect_from_forgery</tt> sets it to <tt>:authenticity_token</tt> by default.</p></div>
+<div class="para"><p><tt>optimise_named_routes</tt> turns on some optimizations in generating the routing table. It is set to <tt>true</tt> by default.</p></div>
+<div class="para"><p><tt>use_accept_header</tt> sets the rules for determining the response format. If this is set to <tt>true</tt> (the default) then <tt>respond_to</tt> and <tt>Request#format</tt> will take the Accept header into account. If it is set to false then the request format will be determined solely by examining <tt>params[:format]</tt>. If there is no <tt>format</tt> parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request.</p></div>
+<div class="para"><p><tt>allow_forgery_protection</tt> enables or disables CSRF protection. By default this is <tt>false</tt> in test mode and <tt>true</tt> in all other modes.</p></div>
+<div class="para"><p><tt>relative_url_root</tt> can be used to tell Rails that you are deploying to a subdirectory. The default is <tt>ENV[<em>RAILS_RELATIVE_URL_ROOT</em>]</tt>.</p></div>
+<div class="para"><p>The caching code adds two additional settings:</p></div>
+<div class="para"><p><tt>ActionController::Caching::Pages.page_cache_directory</tt> sets the directory where Rails will create cached pages for your web server. The default is <tt>Rails.public_path</tt> (which is usually set to <tt>RAILS_ROOT </tt> "/public"+).</p></div>
+<div class="para"><p><tt>ActionController::Caching::Pages.page_cache_extension</tt> sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is <tt>.html</tt>.</p></div>
+<div class="para"><p>The dispatcher includes one setting:</p></div>
+<div class="para"><p><tt>ActionController::Dispatcher.error_file_path</tt> gives the path where Rails will look for error files such as <tt>404.html</tt>. The default is <tt>Rails.public_path</tt>.</p></div>
+<div class="para"><p>The Active Record session store can also be configured:</p></div>
+<div class="para"><p><tt>CGI::Session::ActiveRecordStore::Session.data_column_name</tt> sets the name of the column to use to store session data. By default it is <em>data</em></p></div>
+<h3 id="_configuring_action_view">4.3. Configuring Action View</h3>
+<div class="para"><p>There are only a few configuration options for Action View, starting with four on <tt>ActionView::Base</tt>:</p></div>
+<div class="para"><p><tt>debug_rjs</tt> specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is <tt>false</tt>.</p></div>
+<div class="para"><p><tt>warn_cache_misses</tt> tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is <tt>false</tt>.</p></div>
+<div class="para"><p></p></div>
+<div class="para"><p><tt>default_form_builder</tt> tells Rails which form builder to use by default. The default is <tt>ActionView::Helpers::FormBuilder</tt>.</p></div>
+<div class="para"><p>The ERB template handler supplies one additional option:</p></div>
+<div class="para"><p><tt>ActionView::TemplateHandlers::ERB.erb_trim_mode</tt> gives the trim mode to be used by ERB. It defaults to <tt><em>-</em></tt>. See the <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/">ERB documentation</a> for more information.</p></div>
+<h3 id="_configuring_action_mailer">4.4. Configuring Action Mailer</h3>
+<div class="para"><p>There are a number of settings available on <tt>ActionMailer::Base</tt>:</p></div>
+<div class="para"><p><tt>template_root</tt> gives the root folder for Action Mailer templates.</p></div>
+<div class="para"><p><tt>logger</tt> accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging.</p></div>
+<div class="para"><p><tt>smtp_settings</tt> allows detailed configuration for the <tt>:smtp</tt> delivery method. It accepts a hash of options, which can include any of these options:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
+</p>
+</li>
+<li>
+<p>
+<tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
+</p>
+</li>
+<li>
+<p>
+<tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
+</p>
+</li>
+<li>
+<p>
+<tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
+</p>
+</li>
+<li>
+<p>
+<tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
+</p>
+</li>
+<li>
+<p>
+<tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
+</p>
+</li>
+</ul></div>
+<div class="para"><p><tt>sendmail_settings</tt> allows detailed configuration for the <tt>sendmail</tt> delivery method. It accepts a hash of options, which can include any of these options:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+<tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
+</p>
+</li>
+<li>
+<p>
+<tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>.
+</p>
+</li>
+</ul></div>
+<div class="para"><p><tt>raise_delivery_errors</tt> specifies whether to raise an error if email delivery cannot be completed. It defaults to <tt>true</tt>.</p></div>
+<div class="para"><p><tt>delivery_method</tt> defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.</p></div>
+<div class="para"><p><tt>perform_deliveries</tt> specifies whether mail will actually be delivered. By default this is <tt>true</tt>; it can be convenient to set it to <tt>false</tt> for testing.</p></div>
+<div class="para"><p><tt>default_charset</tt> tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to <tt>utf-8</tt>.</p></div>
+<div class="para"><p><tt>default_content_type</tt> specifies the default content type used for the main part of the message. It defaults to "text/plain"</p></div>
+<div class="para"><p><tt>default_mime_version</tt> is the default MIME version for the message. It defaults to <tt>1.0</tt>.</p></div>
+<div class="para"><p><tt>default_implicit_parts_order</tt> - When a message is built implicitly (i.e. multiple parts are assembled from templates
+which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
+<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
+and appear last in the mime encoded message.</p></div>
+<h3 id="_configuring_active_resource">4.5. Configuring Active Resource</h3>
+<div class="para"><p>There is a single configuration setting available on <tt>ActiveResource::Base</tt>:</p></div>
+<div class="para"><p><tt>logger</tt> accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging.</p></div>
+<h3 id="_configuring_active_support">4.6. Configuring Active Support</h3>
+<div class="para"><p>There are a few configuration options available in Active Support:</p></div>
+<div class="para"><p><tt>ActiveSupport::BufferedLogger.silencer</tt> is set to <tt>false</tt> to disable the ability to silence logging in a block. The default is <tt>true</tt>.</p></div>
+<div class="para"><p><tt>ActiveSupport::Cache::Store.logger</tt> specifies the logger to use within cache store operations.</p></div>
+<div class="para"><p><tt>ActiveSupport::Logger.silencer</tt> is set to <tt>false</tt> to disable the ability to silence logging in a block. The default is <tt>true</tt>.</p></div>
+<h3 id="_configuring_active_model">4.7. Configuring Active Model</h3>
+<div class="para"><p>Active Model currently has a single configuration setting:</p></div>
+<div class="para"><p>+ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages.</p></div>
+</div>
+<h2 id="_using_initializers">5. Using Initializers</h2>
<div class="sectionbody">
<div class="literalblock">
<div class="content">
<pre><tt>organization, controlling load order</tt></pre>
</div></div>
</div>
-<h2 id="_using_an_after_initializer">5. Using an After-Initializer</h2>
+<h2 id="_using_an_after_initializer">6. Using an After-Initializer</h2>
<div class="sectionbody">
</div>
-<h2 id="_changelog">6. Changelog</h2>
+<h2 id="_rails_environment_settings">7. Rails Environment Settings</h2>
+<div class="sectionbody">
+<div class="para"><p>ENV</p></div>
+</div>
+<h2 id="_changelog">8. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28">Lighthouse ticket</a></p></div>
<div class="ilist"><ul>
@@ -291,145 +429,15 @@ after-initializer</p></div> <p>
November 5, 2008: Rough outline by <a href="../authors.html#mgunderloy">Mike Gunderloy</a>
</p>
+<div class="qlist"><ol>
+<li>
+<p><em>
+need to look for def self. ?
+</em></p>
+</li>
+</ol></div>
</li>
</ul></div>
-<div class="para"><p>actionmailer/lib/action_mailer/base.rb
-257: cattr_accessor :logger
-267: cattr_accessor :smtp_settings
-273: cattr_accessor :sendmail_settings
-276: cattr_accessor :raise_delivery_errors
-282: cattr_accessor :perform_deliveries
-285: cattr_accessor :deliveries
-288: cattr_accessor :default_charset
-291: cattr_accessor :default_content_type
-294: cattr_accessor :default_mime_version
-297: cattr_accessor :default_implicit_parts_order
-299: cattr_reader :protected_instance_variables</p></div>
-<div class="para"><p>actionmailer/Rakefile
-36: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
-<div class="para"><p>actionpack/lib/action_controller/base.rb
-263: cattr_reader :protected_instance_variables
-273: cattr_accessor :asset_host
-279: cattr_accessor :consider_all_requests_local
-285: cattr_accessor :allow_concurrency
-317: cattr_accessor :param_parsers
-321: cattr_accessor :default_charset
-325: cattr_accessor :logger
-329: cattr_accessor :resource_action_separator
-333: cattr_accessor :resources_path_names
-337: cattr_accessor :request_forgery_protection_token
-341: cattr_accessor :optimise_named_routes
-351: cattr_accessor :use_accept_header
-361: cattr_accessor :relative_url_root</p></div>
-<div class="para"><p>actionpack/lib/action_controller/caching/pages.rb
-55: cattr_accessor :page_cache_directory
-58: cattr_accessor :page_cache_extension</p></div>
-<div class="para"><p>actionpack/lib/action_controller/caching.rb
-37: cattr_reader :cache_store
-48: cattr_accessor :perform_caching</p></div>
-<div class="para"><p>actionpack/lib/action_controller/dispatcher.rb
-98: cattr_accessor :error_file_path</p></div>
-<div class="para"><p>actionpack/lib/action_controller/mime_type.rb
-24: cattr_reader :html_types, :unverifiable_types</p></div>
-<div class="para"><p>actionpack/lib/action_controller/rescue.rb
-36: base.cattr_accessor :rescue_responses
-40: base.cattr_accessor :rescue_templates</p></div>
-<div class="para"><p>actionpack/lib/action_controller/session/active_record_store.rb
-60: cattr_accessor :data_column_name
-170: cattr_accessor :connection
-173: cattr_accessor :table_name
-177: cattr_accessor :session_id_column
-181: cattr_accessor :data_column
-282: cattr_accessor :session_class</p></div>
-<div class="para"><p>actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
-44: cattr_accessor :included_tags, :instance_writer ⇒ false</p></div>
-<div class="para"><p>actionpack/lib/action_view/base.rb
-189: cattr_accessor :debug_rjs
-193: cattr_accessor :warn_cache_misses</p></div>
-<div class="para"><p>actionpack/lib/action_view/helpers/active_record_helper.rb
-7: cattr_accessor :field_error_proc</p></div>
-<div class="para"><p>actionpack/lib/action_view/helpers/form_helper.rb
-805: cattr_accessor :default_form_builder</p></div>
-<div class="para"><p>actionpack/lib/action_view/template_handlers/erb.rb
-47: cattr_accessor :erb_trim_mode</p></div>
-<div class="para"><p>actionpack/test/active_record_unit.rb
-5: cattr_accessor :able_to_connect
-6: cattr_accessor :connected</p></div>
-<div class="para"><p>actionpack/test/controller/filters_test.rb
-286: cattr_accessor :execution_log</p></div>
-<div class="para"><p>actionpack/test/template/form_options_helper_test.rb
-3:TZInfo::Timezone.cattr_reader :loaded_zones</p></div>
-<div class="para"><p>activemodel/lib/active_model/errors.rb
-28: cattr_accessor :default_error_messages</p></div>
-<div class="para"><p>activemodel/Rakefile
-19: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
-<div class="para"><p>activerecord/lib/active_record/attribute_methods.rb
-9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer ⇒ false
-11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer ⇒ false</p></div>
-<div class="para"><p>activerecord/lib/active_record/base.rb
-394: cattr_accessor :logger, :instance_writer ⇒ false
-443: cattr_accessor :configurations, :instance_writer ⇒ false
-450: cattr_accessor :primary_key_prefix_type, :instance_writer ⇒ false
-456: cattr_accessor :table_name_prefix, :instance_writer ⇒ false
-461: cattr_accessor :table_name_suffix, :instance_writer ⇒ false
-467: cattr_accessor :pluralize_table_names, :instance_writer ⇒ false
-473: cattr_accessor :colorize_logging, :instance_writer ⇒ false
-478: cattr_accessor :default_timezone, :instance_writer ⇒ false
-487: cattr_accessor :schema_format , :instance_writer ⇒ false
-491: cattr_accessor :timestamped_migrations , :instance_writer ⇒ false</p></div>
-<div class="para"><p>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
-11: cattr_accessor :connection_handler, :instance_writer ⇒ false</p></div>
-<div class="para"><p>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
-166: cattr_accessor :emulate_booleans</p></div>
-<div class="para"><p>activerecord/lib/active_record/fixtures.rb
-498: cattr_accessor :all_loaded_fixtures</p></div>
-<div class="para"><p>activerecord/lib/active_record/locking/optimistic.rb
-38: base.cattr_accessor :lock_optimistically, :instance_writer ⇒ false</p></div>
-<div class="para"><p>activerecord/lib/active_record/migration.rb
-259: cattr_accessor :verbose</p></div>
-<div class="para"><p>activerecord/lib/active_record/schema_dumper.rb
-13: cattr_accessor :ignore_tables</p></div>
-<div class="para"><p>activerecord/lib/active_record/serializers/json_serializer.rb
-4: base.cattr_accessor :include_root_in_json, :instance_writer ⇒ false</p></div>
-<div class="para"><p>activerecord/Rakefile
-142: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
-<div class="para"><p>activerecord/test/cases/lifecycle_test.rb
-61: cattr_reader :last_inherited</p></div>
-<div class="para"><p>activerecord/test/cases/mixin_test.rb
-9: cattr_accessor :forced_now_time</p></div>
-<div class="para"><p>activeresource/lib/active_resource/base.rb
-206: cattr_accessor :logger</p></div>
-<div class="para"><p>activeresource/Rakefile
-43: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>-A cattr_accessor=object</em></p></div>
-<div class="para"><p>activesupport/lib/active_support/buffered_logger.rb
-17: cattr_accessor :silencer</p></div>
-<div class="para"><p>activesupport/lib/active_support/cache.rb
-81: cattr_accessor :logger</p></div>
-<div class="para"><p>activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
-5:# cattr_accessor :hair_colors
-10: def cattr_reader(*syms)
-29: def cattr_writer(*syms)
-50: def cattr_accessor(*syms)
-51: cattr_reader(*syms)
-52: cattr_writer(*syms)</p></div>
-<div class="para"><p>activesupport/lib/active_support/core_ext/logger.rb
-34: cattr_accessor :silencer</p></div>
-<div class="para"><p>activesupport/test/core_ext/class/attribute_accessor_test.rb
-6: cattr_accessor :foo
-7: cattr_accessor :bar, :instance_writer ⇒ false</p></div>
-<div class="para"><p>activesupport/test/core_ext/module/synchronization_test.rb
-6: @target.cattr_accessor :mutex, :instance_writer ⇒ false</p></div>
-<div class="para"><p>railties/doc/guides/html/creating_plugins.html
-786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field
-860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field</p></div>
-<div class="para"><p>railties/lib/rails_generator/base.rb
-93: cattr_accessor :logger</p></div>
-<div class="para"><p>railties/Rakefile
-265: rdoc.options << <em>—line-numbers</em> << <em>—inline-source</em> << <em>—accessor</em> << <em>cattr_accessor=object</em></p></div>
-<div class="para"><p>railties/test/rails_info_controller_test.rb
-12: cattr_accessor :local_request</p></div>
-<div class="para"><p>Rakefile
-32: rdoc.options << <em>-A cattr_accessor=object</em></p></div>
</div>
</div> diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 375d216b4a..850822c8ed 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -199,14 +199,22 @@ ul#navMain { <h2>Chapters</h2> <ol> <li> - <a href="#_preparation">Preparation</a> + <a href="#_setup">Setup</a> <ul> <li><a href="#_create_the_basic_app">Create the basic app</a></li> <li><a href="#_generate_the_plugin_skeleton">Generate the plugin skeleton</a></li> - <li><a href="#_setup_the_plugin_for_testing">Setup the plugin for testing</a></li> + <li><a href="#_organize_your_files">Organize your files</a></li> + + </ul> + </li> + <li> + <a href="#_tests">Tests</a> + <ul> + + <li><a href="#_test_setup">Test Setup</a></li> <li><a href="#_run_the_plugin_tests">Run the plugin tests</a></li> @@ -216,16 +224,12 @@ ul#navMain { <a href="#_extending_core_classes">Extending core classes</a> <ul> - <li><a href="#_creating_the_test">Creating the test</a></li> - - <li><a href="#_organize_your_files">Organize your files</a></li> - <li><a href="#_working_with_init_rb">Working with init.rb</a></li> </ul> </li> <li> - <a href="#_add_an_tt_acts_as_yaffle_tt_method_to_active_record">Add an <tt>acts_as_yaffle</tt> method to Active Record</a> + <a href="#_add_an_em_acts_as_em_method_to_active_record">Add an <em>acts_as</em> method to Active Record</a> <ul> <li><a href="#_add_a_class_method">Add a class method</a></li> @@ -235,56 +239,59 @@ ul#navMain { </ul> </li> <li> - <a href="#_create_a_generator">Create a generator</a> - <ul> - - <li><a href="#_testing_generators">Testing generators</a></li> - - <li><a href="#_adding_to_the_manifest">Adding to the manifest</a></li> - - <li><a href="#_manually_test_the_generator">Manually test the generator</a></li> - - <li><a href="#_the_usage_file">The USAGE file</a></li> - - </ul> + <a href="#_models">Models</a> </li> <li> - <a href="#_add_a_custom_generator_command">Add a custom generator command</a> + <a href="#_controllers">Controllers</a> </li> <li> - <a href="#_add_a_model">Add a model</a> + <a href="#_helpers">Helpers</a> </li> <li> - <a href="#_add_a_controller">Add a controller</a> + <a href="#_routes">Routes</a> </li> <li> - <a href="#_add_a_helper">Add a helper</a> + <a href="#_generators">Generators</a> + <ul> + + <li><a href="#_testing_generators">Testing generators</a></li> + + <li><a href="#_the_usage_file">The USAGE file</a></li> + + </ul> </li> <li> - <a href="#_add_a_custom_route">Add a Custom Route</a> + <a href="#_generator_commands">Generator Commands</a> </li> <li> - <a href="#_odds_and_ends">Odds and ends</a> + <a href="#_migrations">Migrations</a> <ul> - <li><a href="#_generate_rdoc_documentation">Generate RDoc Documentation</a></li> - - <li><a href="#_write_custom_rake_tasks_in_your_plugin">Write custom Rake tasks in your plugin</a></li> - - <li><a href="#_store_plugins_in_alternate_locations">Store plugins in alternate locations</a></li> + <li><a href="#_create_a_custom_rake_task">Create a custom rake task</a></li> - <li><a href="#_create_your_own_plugin_loaders_and_plugin_locators">Create your own Plugin Loaders and Plugin Locators</a></li> + <li><a href="#_call_migrations_directly">Call migrations directly</a></li> - <li><a href="#_use_custom_plugin_generators">Use Custom Plugin Generators</a></li> + <li><a href="#_generate_migrations">Generate migrations</a></li> </ul> </li> <li> + <a href="#_rake_tasks">Rake tasks</a> + </li> + <li> + <a href="#_plugingems">PluginGems</a> + </li> + <li> + <a href="#_rdoc_documentation">RDoc Documentation</a> + </li> + <li> <a href="#_appendix">Appendix</a> <ul> <li><a href="#_references">References</a></li> + <li><a href="#_contents_of_em_lib_yaffle_rb_em">Contents of <em>lib/yaffle.rb</em></a></li> + <li><a href="#_final_plugin_directory_structure">Final plugin directory structure</a></li> </ul> @@ -388,7 +395,7 @@ A custom route method that can be used in routes.rb <div class="para"><p>For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.</p></div>
</div>
</div>
-<h2 id="_preparation">1. Preparation</h2>
+<h2 id="_setup">1. Setup</h2>
<div class="sectionbody">
<h3 id="_create_the_basic_app">1.1. Create the basic app</h3>
<div class="para"><p>The examples in this guide require that you have a working rails application. To create a simple rails app execute:</p></div>
@@ -447,10 +454,30 @@ create vendor/plugins/yaffle/generators/yaffle/templates create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE</tt></pre>
</div></div>
-<div class="para"><p>To begin just change one thing - move <em>init.rb</em> to <em>rails/init.rb</em>.</p></div>
-<h3 id="_setup_the_plugin_for_testing">1.3. Setup the plugin for testing</h3>
-<div class="para"><p>If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.</p></div>
-<div class="para"><p>To setup your plugin to allow for easy testing you'll need to add 3 files:</p></div>
+<h3 id="_organize_your_files">1.3. Organize your files</h3>
+<div class="para"><p>To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>|-- lib
+| |-- yaffle
+| `-- yaffle.rb
+`-- rails
+ |
+ `-- init.rb</tt></pre>
+</div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">'yaffle'</span>
+</tt></pre></div></div>
+<div class="para"><p>Now you can add any <em>require</em> statements to <em>lib/yaffle.rb</em> and keep <em>init.rb</em> clean.</p></div>
+</div>
+<h2 id="_tests">2. Tests</h2>
+<div class="sectionbody">
+<div class="para"><p>In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -468,6 +495,7 @@ A test helper method that sets up the database </p>
</li>
</ul></div>
+<h3 id="_test_setup">2.1. Test Setup</h3>
<div class="para"><p><strong>vendor/plugins/yaffle/test/database.yml:</strong></p></div>
<div class="listingblock">
<div class="content">
@@ -558,7 +586,7 @@ ENV<span style="color: #990000">[</span><span style="color: #FF0000">'RAILS_ROOT <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Now whenever you write a test that requires the database, you can call <em>load_schema</em>.</p></div>
-<h3 id="_run_the_plugin_tests">1.4. Run the plugin tests</h3>
+<h3 id="_run_the_plugin_tests">2.2. Run the plugin tests</h3>
<div class="para"><p>Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in <em>vendor/plugins/yaffle/test/yaffle_test.rb</em> with a sample test. Replace the contents of that file with:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_test.rb:</strong></p></div>
<div class="listingblock">
@@ -619,22 +647,9 @@ rake DB=postgresql</tt></pre> </div></div>
<div class="para"><p>Now you are ready to test-drive your plugin!</p></div>
</div>
-<h2 id="_extending_core_classes">2. Extending core classes</h2>
+<h2 id="_extending_core_classes">3. Extending core classes</h2>
<div class="sectionbody">
-<div class="para"><p>This section will explain how to add a method to String that will be available anywhere in your rails app by:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Writing tests for the desired behavior
-</p>
-</li>
-<li>
-<p>
-Creating and requiring the correct files
-</p>
-</li>
-</ul></div>
-<h3 id="_creating_the_test">2.1. Creating the test</h3>
+<div class="para"><p>This section will explain how to add a method to String that will be available anywhere in your rails app.</p></div>
<div class="para"><p>In this example you will add a method to String named <tt>to_squawk</tt>. To begin, create a new test file with a few assertions:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/core_ext_test.rb</strong></p></div>
<div class="listingblock">
@@ -665,24 +680,6 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'</tt></pre>
</div></div>
<div class="para"><p>Great - now you are ready to start development.</p></div>
-<h3 id="_organize_your_files">2.2. Organize your files</h3>
-<div class="para"><p>A common pattern in rails plugins is to set up the file structure like this:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>|-- lib
-| |-- yaffle
-| | `-- core_ext.rb
-| `-- yaffle.rb</tt></pre>
-</div></div>
-<div class="para"><p>The first thing we need to to is to require our <em>lib/yaffle.rb</em> file from <em>rails/init.rb</em>:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">'yaffle'</span>
-</tt></pre></div></div>
<div class="para"><p>Then in <em>lib/yaffle.rb</em> require <em>lib/core_ext.rb</em>:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></p></div>
<div class="listingblock">
@@ -712,11 +709,11 @@ http://www.gnu.org/software/src-highlite --> >> "Hello World".to_squawk
=> "squawk! Hello World"</tt></pre>
</div></div>
-<h3 id="_working_with_init_rb">2.3. Working with init.rb</h3>
-<div class="para"><p>When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
+<h3 id="_working_with_init_rb">3.1. Working with init.rb</h3>
+<div class="para"><p>When rails loads plugins it looks for the file named <em>init.rb</em> or <em>rails/init.rb</em>. However, when the plugin is initialized, <em>init.rb</em> is invoked via <tt>eval</tt> (not <tt>require</tt>) so it has slightly different behavior.</p></div>
<div class="para"><p>Under certain circumstances if you reopen classes or modules in <em>init.rb</em> you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from <tt>init.rb</tt>, as shown above.</p></div>
<div class="para"><p>If you must reopen a class in <tt>init.rb</tt> you can use <tt>module_eval</tt> or <tt>class_eval</tt> to avoid any issues:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -729,7 +726,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Another way is to explicitly define the top-level module space for all modules and classes, like <tt>::Hash</tt>:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/rails/init.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -742,7 +739,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_add_an_tt_acts_as_yaffle_tt_method_to_active_record">3. Add an <tt>acts_as_yaffle</tt> method to Active Record</h2>
+<h2 id="_add_an_em_acts_as_em_method_to_active_record">4. Add an <em>acts_as</em> method to Active Record</h2>
<div class="sectionbody">
<div class="para"><p>A common pattern in plugins is to add a method called <em>acts_as_something</em> to models. In this case, you want to write a method called <em>acts_as_yaffle</em> that adds a <em>squawk</em> method to your models.</p></div>
<div class="para"><p>To begin, set up your files so that you have:</p></div>
@@ -801,7 +798,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>With structure you can easily separate the methods that will be used for the class (like <tt>Hickwall.some_method</tt>) and the instance (like <tt>@hickwell.some_method</tt>).</p></div>
-<h3 id="_add_a_class_method">3.1. Add a class method</h3>
+<h3 id="_add_a_class_method">4.1. Add a class method</h3>
<div class="para"><p>This plugin will expect that you've added a method to your model named <em>last_squawk</em>. However, the plugin users might have already defined a method on their model named <em>last_squawk</em> that they use for something else. This plugin will allow the name to be changed by adding a class method called <em>yaffle_text_field</em>.</p></div>
<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></p></div>
@@ -854,7 +851,7 @@ http://www.gnu.org/software/src-highlite --> ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle
</tt></pre></div></div>
-<h3 id="_add_an_instance_method">3.2. Add an instance method</h3>
+<h3 id="_add_an_instance_method">4.2. Add an instance method</h3>
<div class="para"><p>This plugin will add a method named <em>squawk</em> to any Active Record objects that call <em>acts_as_yaffle</em>. The <em>squawk</em> method will simply set the value of one of the fields in the database.</p></div>
<div class="para"><p>To start out, write a failing test that shows the behavior you'd like:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/acts_as_yaffle_test.rb</strong></p></div>
@@ -936,267 +933,7 @@ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #99000 </tr></table>
</div>
</div>
-<h2 id="_create_a_generator">4. Create a generator</h2>
-<div class="sectionbody">
-<div class="para"><p>Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in <em>vendor/plugins/yaffle/generators/yaffle</em>.</p></div>
-<div class="para"><p>Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.</p></div>
-<div class="para"><p>To create a generator you must:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Add your instructions to the <em>manifest</em> method of the generator
-</p>
-</li>
-<li>
-<p>
-Add any necessary template files to the templates directory
-</p>
-</li>
-<li>
-<p>
-Test the generator manually by running various combinations of <tt>script/generate</tt> and <tt>script/destroy</tt>
-</p>
-</li>
-<li>
-<p>
-Update the USAGE file to add helpful documentation for your generator
-</p>
-</li>
-</ul></div>
-<h3 id="_testing_generators">4.1. Testing generators</h3>
-<div class="para"><p>Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:</p></div>
-<div class="ilist"><ul>
-<li>
-<p>
-Creates a new fake rails root directory that will serve as destination
-</p>
-</li>
-<li>
-<p>
-Runs the generator forward and backward, making whatever assertions are necessary
-</p>
-</li>
-<li>
-<p>
-Removes the fake rails root
-</p>
-</li>
-</ul></div>
-<div class="para"><p>For the generator in this section, the test could look something like this:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_generator_test.rb</strong></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: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/destroy'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> GeneratorTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
- File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'rails_root'</span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
- Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">))</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
- FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
- <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
- FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_correct_file_name
- Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
- new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
- assert_match <span style="color: #FF6600">/add_yaffle_fields_to_bird/</span><span style="color: #990000">,</span> new_file
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>You can run <em>rake</em> from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.</p></div>
-<h3 id="_adding_to_the_manifest">4.2. Adding to the manifest</h3>
-<div class="para"><p>This example will demonstrate how to use one of the built-in generator methods named <em>migration_template</em> to create a migration file. To start, update your generator file to look like this:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></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> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
- m<span style="color: #990000">.</span>migration_template <span style="color: #FF0000">'migration:migration.rb'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"db/migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>assigns <span style="color: #990000">=></span> yaffle_local_assigns<span style="color: #990000">,</span>
- <span style="color: #990000">:</span>migration_file_name <span style="color: #990000">=></span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
- <span style="color: #FF0000">}</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- private
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> custom_file_name
- custom_name <span style="color: #990000">=</span> class_name<span style="color: #990000">.</span>underscore<span style="color: #990000">.</span>downcase
- custom_name <span style="color: #990000">=</span> custom_name<span style="color: #990000">.</span>pluralize <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>pluralize_table_names
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_local_assigns
- returning<span style="color: #990000">(</span>assigns <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- assigns<span style="color: #990000">[:</span>migration_action<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add"</span>
- assigns<span style="color: #990000">[:</span>class_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
- assigns<span style="color: #990000">[:</span>table_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> custom_file_name
- assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #990000">[</span>Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"string"</span><span style="color: #990000">)]</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>The generator creates a new file in <em>db/migrate</em> with a timestamp and an <em>add_column</em> statement. It reuses the built in rails <tt>migration_template</tt> method, and reuses the built-in rails migration template.</p></div>
-<div class="para"><p>It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.</p></div>
-<h3 id="_manually_test_the_generator">4.3. Manually test the generator</h3>
-<div class="para"><p>To run the generator, type the following at the command line:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>./script/generate yaffle bird</tt></pre>
-</div></div>
-<div class="para"><p>and you will see a new file:</p></div>
-<div class="para"><p><strong>db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</strong></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> AddYaffleFieldsToBirds <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
- add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
- remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<h3 id="_the_usage_file">4.4. The USAGE file</h3>
-<div class="para"><p>Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>script/generate</tt></pre>
-</div></div>
-<div class="para"><p>You should see something like this:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Installed Generators
- Plugins (vendor/plugins): yaffle
- Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration</tt></pre>
-</div></div>
-<div class="para"><p>When you run <tt>script/generate yaffle</tt> you should see the contents of your <em>vendor/plugins/yaffle/generators/yaffle/USAGE</em> file.</p></div>
-<div class="para"><p>For this plugin, update the USAGE file looks like this:</p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Description:
- Creates a migration that adds yaffle squawk fields to the given model
-
-Example:
- ./script/generate yaffle hickwall
-
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall</tt></pre>
-</div></div>
-</div>
-<h2 id="_add_a_custom_generator_command">5. Add a custom generator command</h2>
-<div class="sectionbody">
-<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>migration_template</tt>. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.</p></div>
-<div class="para"><p>This section describes how you you can create your own commands to add and remove a line of text from <em>routes.rb</em>. This example creates a very simple method that adds or removes a text file.</p></div>
-<div class="para"><p>To start, add the following test method:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/test/generator_test.rb</strong></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">def</span></span> test_generates_definition
- Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"bird"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
- definition <span style="color: #990000">=</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">))</span>
- assert_match <span style="color: #FF6600">/Yaffle\:/</span><span style="color: #990000">,</span> definition
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-<div class="para"><p>Run <tt>rake</tt> to watch the test fail, then make the test pass add the following:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/templates/definition.txt</strong></p></div>
-<div class="listingblock">
-<div class="content">
-<pre><tt>Yaffle: A bird</tt></pre>
-</div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">"yaffle/commands"</span>
-</tt></pre></div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/lib/commands.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
-<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/commands'</span>
-
-<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Generator <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Commands <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Create
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
- file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Destroy
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
- file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> List
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
- file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
- <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Update
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_definition
- file<span style="color: #990000">(</span><span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">)</span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
-Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update
-</tt></pre></div></div>
-<div class="para"><p>Finally, call your new method in the manifest:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></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> YaffleGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
- m<span style="color: #990000">.</span>yaffle_definition
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-</tt></pre></div></div>
-</div>
-<h2 id="_add_a_model">6. Add a model</h2>
+<h2 id="_models">5. Models</h2>
<div class="sectionbody">
<div class="para"><p>This section describes how to add a model named <em>Woodpecker</em> to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:</p></div>
<div class="listingblock">
@@ -1263,19 +1000,17 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>ActiveRecord<span style="color: #990000">::</span>Schema<span style="color: #990000">.</span>define<span style="color: #990000">(:</span>version <span style="color: #990000">=></span> <span style="color: #993399">0</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
- create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
- t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
- <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<pre><tt>create_table <span style="color: #990000">:</span>woodpeckers<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.</p></div>
</div>
-<h2 id="_add_a_controller">7. Add a controller</h2>
+<h2 id="_controllers">6. Controllers</h2>
<div class="sectionbody">
<div class="para"><p>This section describes how to add a controller named <em>woodpeckers</em> to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.</p></div>
<div class="para"><p>You can test your plugin's controller as you would test any other controller:</p></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:</strong></p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1292,6 +1027,10 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #009900">@controller</span> <span style="color: #990000">=</span> WoodpeckersController<span style="color: #990000">.</span>new
<span style="color: #009900">@request</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestRequest<span style="color: #990000">.</span>new
<span style="color: #009900">@response</span> <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>TestResponse<span style="color: #990000">.</span>new
+
+ ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+ map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>woodpeckers
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_index
@@ -1330,7 +1069,7 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to <a href="http://localhost:3000/woodpeckers">http://localhost:3000/woodpeckers</a> to see your controller in action.</p></div>
</div>
-<h2 id="_add_a_helper">8. Add a helper</h2>
+<h2 id="_helpers">7. Helpers</h2>
<div class="sectionbody">
<div class="para"><p>This section describes how to add a helper named <em>WoodpeckersHelper</em> to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.</p></div>
<div class="para"><p>You can test your plugin's helper as you would test any other helper:</p></div>
@@ -1362,8 +1101,6 @@ http://www.gnu.org/software/src-highlite --> ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
-
-ActionView<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> WoodpeckersHelper
</tt></pre></div></div>
<div class="para"><p><strong>vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:</strong></p></div>
<div class="listingblock">
@@ -1381,9 +1118,10 @@ http://www.gnu.org/software/src-highlite --> </tt></pre></div></div>
<div class="para"><p>Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.</p></div>
</div>
-<h2 id="_add_a_custom_route">9. Add a Custom Route</h2>
+<h2 id="_routes">8. Routes</h2>
<div class="sectionbody">
-<div class="para"><p>Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in <a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.</p></div>
+<div class="para"><p>In a standard <em>routes.rb</em> file you use routes like <em>map.connect</em> or <em>map.resources</em>. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with <em>map.yaffles</em>.</p></div>
+<div class="para"><p>Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/test/routing_test.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1406,26 +1144,22 @@ http://www.gnu.org/software/src-highlite --> private
- <span style="font-style: italic"><span style="color: #9A1900"># yes, I know about assert_recognizes, but it has proven problematic to</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># use in these tests, since it uses RouteSet#recognize (which actually</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># tries to instantiate the controller) and because it uses an awkward</span></span>
- <span style="font-style: italic"><span style="color: #9A1900"># parameter order.</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> assert_recognition<span style="color: #990000">(</span>method<span style="color: #990000">,</span> path<span style="color: #990000">,</span> options<span style="color: #990000">)</span>
result <span style="color: #990000">=</span> ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>recognize_path<span style="color: #990000">(</span>path<span style="color: #990000">,</span> <span style="color: #990000">:</span>method <span style="color: #990000">=></span> method<span style="color: #990000">)</span>
assert_equal options<span style="color: #990000">,</span> result
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/init.rb</strong></p></div>
+<div class="para"><p>Once you see the tests fail by running <em>rake</em>, you can make them pass with:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">"routing"</span>
-ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>RouteSet<span style="color: #990000">::</span>Mapper<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>MapperExtensions
+<pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/routing"</span>
</tt></pre></div></div>
-<div class="para"><p><strong>vendor/plugins/yaffle/lib/routing.rb</strong></p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/routing.rb</strong></p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1440,6 +1174,8 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>RouteSet<span style="color: #990000">::</span>Mapper<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>MapperExtensions
</tt></pre></div></div>
<div class="para"><p><strong>config/routes.rb</strong></p></div>
<div class="listingblock">
@@ -1448,47 +1184,498 @@ by Lorenzo Bettini http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
- <span style="color: #990000">...</span>
map<span style="color: #990000">.</span>yaffles
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>You can also see if your routes work by running <tt>rake routes</tt> from your app directory.</p></div>
</div>
-<h2 id="_odds_and_ends">10. Odds and ends</h2>
+<h2 id="_generators">9. Generators</h2>
<div class="sectionbody">
-<h3 id="_generate_rdoc_documentation">10.1. Generate RDoc Documentation</h3>
-<div class="para"><p>Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.</p></div>
-<div class="para"><p>The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:</p></div>
+<div class="para"><p>Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in <em>vendor/plugins/yaffle/generators/yaffle</em>.</p></div>
+<div class="para"><p>Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.</p></div>
+<h3 id="_testing_generators">9.1. Testing generators</h3>
+<div class="para"><p>Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:</p></div>
<div class="ilist"><ul>
<li>
<p>
-Your name.
+Creates a new fake rails root directory that will serve as destination
</p>
</li>
<li>
<p>
-How to install.
+Runs the generator
</p>
</li>
<li>
<p>
-How to add the functionality to the app (several examples of common use cases).
+Asserts that the correct files were generated
</p>
</li>
<li>
<p>
-Warning, gotchas or tips that might help save users time.
+Removes the fake rails root
</p>
</li>
</ul></div>
-<div class="para"><p>Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.</p></div>
-<div class="para"><p>Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.</p></div>
-<div class="para"><p>Once your comments are good to go, navigate to your plugin directory and run:</p></div>
-<div class="literalblock">
+<div class="para"><p>This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/definition_generator_test.rb</strong></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: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> DefinitionGeneratorTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_correct_file_name
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle_definition"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_equal <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> File<span style="color: #990000">.</span>basename<span style="color: #990000">(</span>new_file<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'rails_root'</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
+ Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">))</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>You can run <em>rake</em> from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.</p></div>
+<div class="para"><p>To make it pass, create the generator:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb</strong></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> YaffleDefinitionGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
+ record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
+ m<span style="color: #990000">.</span>file <span style="color: #FF0000">"definition.txt"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"definition.txt"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_the_usage_file">9.2. The USAGE file</h3>
+<div class="para"><p>If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.</p></div>
+<div class="para"><p>Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:</p></div>
+<div class="listingblock">
<div class="content">
-<pre><tt>rake rdoc</tt></pre>
+<pre><tt>./script/generate</tt></pre>
+</div></div>
+<div class="para"><p>You should see something like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Installed Generators
+ Plugins (vendor/plugins): yaffle_definition
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration</tt></pre>
</div></div>
-<h3 id="_write_custom_rake_tasks_in_your_plugin">10.2. Write custom Rake tasks in your plugin</h3>
+<div class="para"><p>When you run <tt>script/generate yaffle_definition -h</tt> you should see the contents of your <em>vendor/plugins/yaffle/generators/yaffle_definition/USAGE</em>.</p></div>
+<div class="para"><p>For this plugin, update the USAGE file could look like this:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>Description:
+ Adds a file with the definition of a Yaffle to the app's main directory</tt></pre>
+</div></div>
+</div>
+<h2 id="_generator_commands">10. Generator Commands</h2>
+<div class="sectionbody">
+<div class="para"><p>You may have noticed above that you can used one of the built-in rails migration commands <tt>migration_template</tt>. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.</p></div>
+<div class="para"><p>This section describes how you you can create your own commands to add and remove a line of text from <em>config/routes.rb</em>.</p></div>
+<div class="para"><p>To start, add the following test method:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/route_generator_test.rb</strong></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: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/destroy'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> RouteGeneratorTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"config"</span><span style="color: #990000">))</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_route
+ content <span style="color: #990000">=</span> <span style="color: #990000"><<-</span><span style="font-weight: bold"><span style="color: #0000FF">END</span></span>
+ ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+ map<span style="color: #990000">.</span>connect <span style="color: #FF0000">':controller/:action/:id'</span>
+ map<span style="color: #990000">.</span>connect <span style="color: #FF0000">':controller/:action/:id.:format'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">END</span></span>
+ File<span style="color: #990000">.</span>open<span style="color: #990000">(</span>routes_path<span style="color: #990000">,</span> <span style="color: #FF0000">'wb'</span><span style="color: #990000">)</span> <span style="color: #FF0000">{</span><span style="color: #990000">|</span>f<span style="color: #990000">|</span> f<span style="color: #990000">.</span>write<span style="color: #990000">(</span>content<span style="color: #990000">)</span> <span style="color: #FF0000">}</span>
+
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle_route"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ assert_match <span style="color: #FF6600">/map\.yaffles/</span><span style="color: #990000">,</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>routes_path<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_destroys_route
+ content <span style="color: #990000">=</span> <span style="color: #990000"><<-</span><span style="font-weight: bold"><span style="color: #0000FF">END</span></span>
+ ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+ map<span style="color: #990000">.</span>yaffles
+ map<span style="color: #990000">.</span>connect <span style="color: #FF0000">':controller/:action/:id'</span>
+ map<span style="color: #990000">.</span>connect <span style="color: #FF0000">':controller/:action/:id.:format'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">END</span></span>
+ File<span style="color: #990000">.</span>open<span style="color: #990000">(</span>routes_path<span style="color: #990000">,</span> <span style="color: #FF0000">'wb'</span><span style="color: #990000">)</span> <span style="color: #FF0000">{</span><span style="color: #990000">|</span>f<span style="color: #990000">|</span> f<span style="color: #990000">.</span>write<span style="color: #990000">(</span>content<span style="color: #990000">)</span> <span style="color: #FF0000">}</span>
+
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle_route"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ assert_no_match <span style="color: #FF6600">/map\.yaffles/</span><span style="color: #990000">,</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>routes_path<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">"rails_root"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> routes_path
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"config"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"routes.rb"</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Run <tt>rake</tt> to watch the test fail, then make the test pass add the following:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">"yaffle/commands"</span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle/commands.rb</strong></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: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/commands'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Yaffle <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Generator <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Commands <span style="font-style: italic"><span style="color: #9A1900">#:nodoc:</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Create
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_route
+ logger<span style="color: #990000">.</span>route <span style="color: #FF0000">"map.yaffle"</span>
+ look_for <span style="color: #990000">=</span> <span style="color: #FF0000">'ActionController::Routing::Routes.draw do |map|'</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> options<span style="color: #990000">[:</span>pretend<span style="color: #990000">]</span>
+ gsub_file<span style="color: #990000">(</span><span style="color: #FF0000">'config/routes.rb'</span><span style="color: #990000">,</span> <span style="color: #FF6600">/(#{Regexp.escape(look_for)})/</span>mi<span style="color: #990000">)</span><span style="color: #FF0000">{</span><span style="color: #990000">|</span>match<span style="color: #990000">|</span> <span style="color: #FF0000">"#{match}\n map.yaffles\n"</span><span style="color: #FF0000">}</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Destroy
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_route
+ logger<span style="color: #990000">.</span>route <span style="color: #FF0000">"map.yaffle"</span>
+ gsub_file <span style="color: #FF0000">'config/routes.rb'</span><span style="color: #990000">,</span> <span style="color: #FF6600">/\n.+?map\.yaffles/</span>mi<span style="color: #990000">,</span> <span style="color: #FF0000">''</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> List
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_route
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Update
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_route
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Create
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Destroy
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>List
+Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update<span style="color: #990000">.</span>send <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span><span style="color: #990000">,</span> Yaffle<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Commands<span style="color: #990000">::</span>Update
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb</strong></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> YaffleRouteGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
+ record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
+ m<span style="color: #990000">.</span>yaffle_route
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>To see this work, type:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>./script/generate yaffle_route
+./script/destroy yaffle_route</tt></pre>
+</div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">
+<div class="title">Editor's note:</div>If you haven't set up the custom route from above, <em>script/destroy</em> will fail and you'll have to remove it manually.</td>
+</tr></table>
+</div>
+</div>
+<h2 id="_migrations">11. Migrations</h2>
+<div class="sectionbody">
+<div class="para"><p>If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.</p></div>
+<div class="para"><p>If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.</p></div>
+<div class="para"><p>Let's say you have the following migration in your plugin:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:</strong></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> CreateBirdhouses <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
+ create_table <span style="color: #990000">:</span>birdhouses<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ t<span style="color: #990000">.</span>timestamps
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
+ drop_table <span style="color: #990000">:</span>birdhouses
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Here are a few possibilities for how to allow developers to use your plugin migrations:</p></div>
+<h3 id="_create_a_custom_rake_task">11.1. Create a custom rake task</h3>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:</strong></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> CreateBirdhouses <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
+ create_table <span style="color: #990000">:</span>birdhouses<span style="color: #990000">,</span> <span style="color: #990000">:</span>force <span style="color: #990000">=></span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
+ t<span style="color: #990000">.</span>string <span style="color: #990000">:</span>name
+ t<span style="color: #990000">.</span>timestamps
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
+ drop_table <span style="color: #990000">:</span>birdhouses
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/tasks/yaffle.rake:</strong></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>namespace <span style="color: #990000">:</span>db <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ namespace <span style="color: #990000">:</span>migrate <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ desc <span style="color: #FF0000">"Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false."</span>
+ task <span style="color: #990000">:</span>yaffle <span style="color: #990000">=></span> <span style="color: #990000">:</span>environment <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ ActiveRecord<span style="color: #990000">::</span>Migration<span style="color: #990000">.</span>verbose <span style="color: #990000">=</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">"VERBOSE"</span><span style="color: #990000">]</span> <span style="color: #990000">?</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">"VERBOSE"</span><span style="color: #990000">]</span> <span style="color: #990000">==</span> <span style="color: #FF0000">"true"</span> <span style="color: #990000">:</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+ ActiveRecord<span style="color: #990000">::</span>Migrator<span style="color: #990000">.</span>migrate<span style="color: #990000">(</span><span style="color: #FF0000">"vendor/plugins/yaffle/lib/db/migrate/"</span><span style="color: #990000">,</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">"VERSION"</span><span style="color: #990000">]</span> <span style="color: #990000">?</span> ENV<span style="color: #990000">[</span><span style="color: #FF0000">"VERSION"</span><span style="color: #990000">].</span>to_i <span style="color: #990000">:</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">)</span>
+ Rake<span style="color: #990000">::</span>Task<span style="color: #990000">[</span><span style="color: #FF0000">"db:schema:dump"</span><span style="color: #990000">].</span>invoke <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>schema_format <span style="color: #990000">==</span> <span style="color: #990000">:</span>ruby
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<h3 id="_call_migrations_directly">11.2. Call migrations directly</h3>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></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>Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">)).</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>file<span style="color: #990000">|</span>
+ <span style="font-weight: bold"><span style="color: #000080">require</span></span> file
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p><strong>db/migrate/20081116181115_create_birdhouses.rb:</strong></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> CreateBirdhouses <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
+ Yaffle<span style="color: #990000">::</span>CreateBirdhouses<span style="color: #990000">.</span>up
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
+ Yaffle<span style="color: #990000">::</span>CreateBirdhouses<span style="color: #990000">.</span>down
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">
+<div class="title">Editor's note:</div>several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.</td>
+</tr></table>
+</div>
+<h3 id="_generate_migrations">11.3. Generate migrations</h3>
+<div class="para"><p>Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+call your script/generate script and pass in whatever options they need
+</p>
+</li>
+<li>
+<p>
+examine the generated migration, adding/removing columns or other options as necessary
+</p>
+</li>
+</ul></div>
+<div class="para"><p>This example will demonstrate how to use one of the built-in generator methods named <em>migration_template</em> to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb</strong></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: #000080">require</span></span> File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">)</span> <span style="color: #990000">+</span> <span style="color: #FF0000">'/test_helper.rb'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator'</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">'rails_generator/scripts/generate'</span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MigrationGeneratorTest <span style="color: #990000"><</span> Test<span style="color: #990000">::</span>Unit<span style="color: #990000">::</span>TestCase
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> setup
+ FileUtils<span style="color: #990000">.</span>mkdir_p<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="color: #009900">@original_files</span> <span style="color: #990000">=</span> file_list
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> teardown
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>pluralize_table_names <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+ FileUtils<span style="color: #990000">.</span>rm_r<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_generates_correct_file_name
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle_migration"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"some_name_nobody_is_likely_to_ever_use_in_a_real_migration"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_match <span style="color: #FF6600">/add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/</span><span style="color: #990000">,</span> new_file
+ assert_match <span style="color: #FF6600">/add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/</span><span style="color: #990000">,</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>new_file<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> test_pluralizes_properly
+ ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>pluralize_table_names <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
+ Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>Scripts<span style="color: #990000">::</span>Generate<span style="color: #990000">.</span>new<span style="color: #990000">.</span>run<span style="color: #990000">([</span><span style="color: #FF0000">"yaffle_migration"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"some_name_nobody_is_likely_to_ever_use_in_a_real_migration"</span><span style="color: #990000">],</span> <span style="color: #990000">:</span>destination <span style="color: #990000">=></span> fake_rails_root<span style="color: #990000">)</span>
+ new_file <span style="color: #990000">=</span> <span style="color: #990000">(</span>file_list <span style="color: #990000">-</span> <span style="color: #009900">@original_files</span><span style="color: #990000">).</span>first
+ assert_match <span style="color: #FF6600">/add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/</span><span style="color: #990000">,</span> new_file
+ assert_match <span style="color: #FF6600">/add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/</span><span style="color: #990000">,</span> File<span style="color: #990000">.</span>read<span style="color: #990000">(</span>new_file<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> fake_rails_root
+ File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'rails_root'</span><span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> file_list
+ Dir<span style="color: #990000">.</span>glob<span style="color: #990000">(</span>File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>fake_rails_root<span style="color: #990000">,</span> <span style="color: #FF0000">"db"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"*"</span><span style="color: #990000">))</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">
+<div class="title">Editor's note:</div>the migration generator checks to see if a migation already exists, and it's hard-coded to check the <em>db/migrate</em> directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.</td>
+</tr></table>
+</div>
+<div class="para"><p>After running the test with <em>rake</em> you can make it pass with:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb</strong></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> YaffleMigrationGenerator <span style="color: #990000"><</span> Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>NamedBase
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> manifest
+ record <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>m<span style="color: #990000">|</span>
+ m<span style="color: #990000">.</span>migration_template <span style="color: #FF0000">'migration:migration.rb'</span><span style="color: #990000">,</span> <span style="color: #FF0000">"db/migrate"</span><span style="color: #990000">,</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>assigns <span style="color: #990000">=></span> yaffle_local_assigns<span style="color: #990000">,</span>
+ <span style="color: #990000">:</span>migration_file_name <span style="color: #990000">=></span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
+ <span style="color: #FF0000">}</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ private
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> custom_file_name
+ custom_name <span style="color: #990000">=</span> class_name<span style="color: #990000">.</span>underscore<span style="color: #990000">.</span>downcase
+ custom_name <span style="color: #990000">=</span> custom_name<span style="color: #990000">.</span>pluralize <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> ActiveRecord<span style="color: #990000">::</span>Base<span style="color: #990000">.</span>pluralize_table_names
+ custom_name
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> yaffle_local_assigns
+ returning<span style="color: #990000">(</span>assigns <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
+ assigns<span style="color: #990000">[:</span>migration_action<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add"</span>
+ assigns<span style="color: #990000">[:</span>class_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"add_yaffle_fields_to_#{custom_file_name}"</span>
+ assigns<span style="color: #990000">[:</span>table_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> custom_file_name
+ assigns<span style="color: #990000">[:</span>attributes<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #990000">[</span>Rails<span style="color: #990000">::</span>Generator<span style="color: #990000">::</span>GeneratedAttribute<span style="color: #990000">.</span>new<span style="color: #990000">(</span><span style="color: #FF0000">"last_squawk"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"string"</span><span style="color: #990000">)]</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The generator creates a new file in <em>db/migrate</em> with a timestamp and an <em>add_column</em> statement. It reuses the built in rails <tt>migration_template</tt> method, and reuses the built-in rails migration template.</p></div>
+<div class="para"><p>It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.</p></div>
+<div class="para"><p>To run the generator, type the following at the command line:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>./script/generate yaffle_migration bird</tt></pre>
+</div></div>
+<div class="para"><p>and you will see a new file:</p></div>
+<div class="para"><p><strong>db/migrate/20080529225649_add_yaffle_fields_to_birds.rb</strong></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> AddYaffleFieldsToBirds <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Migration
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
+ add_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk<span style="color: #990000">,</span> <span style="color: #990000">:</span>string
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
+ remove_column <span style="color: #990000">:</span>birds<span style="color: #990000">,</span> <span style="color: #990000">:</span>last_squawk
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_rake_tasks">12. Rake tasks</h2>
+<div class="sectionbody">
<div class="para"><p>When you created the plugin with the built-in rails generator, it generated a rake file for you in <em>vendor/plugins/yaffle/tasks/yaffle.rake</em>. Any rake task you add here will be available to the app.</p></div>
<div class="para"><p>Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:</p></div>
<div class="para"><p><strong>vendor/plugins/yaffle/tasks/yaffle.rake</strong></p></div>
@@ -1510,25 +1697,93 @@ http://www.gnu.org/software/src-highlite --> <pre><tt>yaffle:squawk # Prints out the word 'Yaffle'</tt></pre>
</div></div>
<div class="para"><p>You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.</p></div>
-<h3 id="_store_plugins_in_alternate_locations">10.3. Store plugins in alternate locations</h3>
-<div class="para"><p>You can store plugins wherever you want - you just have to add those plugins to the plugins path in <em>environment.rb</em>.</p></div>
-<div class="para"><p>Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.</p></div>
-<div class="para"><p>You can even store plugins inside of other plugins for complete plugin madness!</p></div>
+<div class="para"><p>Note that tasks from <em>vendor/plugins/yaffle/Rakefile</em> are not available to the main app.</p></div>
+</div>
+<h2 id="_plugingems">13. PluginGems</h2>
+<div class="sectionbody">
+<div class="para"><p>Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.</p></div>
+<div class="para"><p>Historically rails plugins loaded the plugin's <em>init.rb</em> file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, <em>init.rb</em> was moved to <em>rails/init.rb</em>.</p></div>
+<div class="para"><p>It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in <em>Rakefile</em>. A rake task that packages the gem might look like this:</p></div>
+<div class="para"><p><strong>vendor/plugins/yaffle/Rakefile:</strong></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>config<span style="color: #990000">.</span>plugin_paths <span style="color: #990000"><<</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>RAILS_ROOT<span style="color: #990000">,</span><span style="color: #FF0000">"vendor"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">,</span><span style="color: #FF0000">"yaffle"</span><span style="color: #990000">,</span><span style="color: #FF0000">"lib"</span><span style="color: #990000">,</span><span style="color: #FF0000">"plugins"</span><span style="color: #990000">)</span>
+<pre><tt>PKG_FILES <span style="color: #990000">=</span> FileList<span style="color: #990000">[</span>
+ <span style="color: #FF0000">'[a-zA-Z]*'</span><span style="color: #990000">,</span>
+ <span style="color: #FF0000">'generators/**/*'</span><span style="color: #990000">,</span>
+ <span style="color: #FF0000">'lib/**/*'</span><span style="color: #990000">,</span>
+ <span style="color: #FF0000">'rails/**/*'</span><span style="color: #990000">,</span>
+ <span style="color: #FF0000">'tasks/**/*'</span><span style="color: #990000">,</span>
+ <span style="color: #FF0000">'test/**/*'</span>
+<span style="color: #990000">]</span>
+
+spec <span style="color: #990000">=</span> Gem<span style="color: #990000">::</span>Specification<span style="color: #990000">.</span>new <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>s<span style="color: #990000">|</span>
+ s<span style="color: #990000">.</span>name <span style="color: #990000">=</span> <span style="color: #FF0000">"yaffle"</span>
+ s<span style="color: #990000">.</span>version <span style="color: #990000">=</span> <span style="color: #FF0000">"0.0.1"</span>
+ s<span style="color: #990000">.</span>author <span style="color: #990000">=</span> <span style="color: #FF0000">"Gleeful Yaffler"</span>
+ s<span style="color: #990000">.</span>email <span style="color: #990000">=</span> <span style="color: #FF0000">"yaffle@example.com"</span>
+ s<span style="color: #990000">.</span>homepage <span style="color: #990000">=</span> <span style="color: #FF0000">"http://yafflers.example.com/"</span>
+ s<span style="color: #990000">.</span>platform <span style="color: #990000">=</span> Gem<span style="color: #990000">::</span>Platform<span style="color: #990000">::</span>RUBY
+ s<span style="color: #990000">.</span>summary <span style="color: #990000">=</span> <span style="color: #FF0000">"Sharing Yaffle Goodness"</span>
+ s<span style="color: #990000">.</span>files <span style="color: #990000">=</span> PKG_FILES<span style="color: #990000">.</span>to_a
+ s<span style="color: #990000">.</span>require_path <span style="color: #990000">=</span> <span style="color: #FF0000">"lib"</span>
+ s<span style="color: #990000">.</span>has_rdoc <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
+ s<span style="color: #990000">.</span>extra_rdoc_files <span style="color: #990000">=</span> <span style="color: #990000">[</span><span style="color: #FF0000">"README"</span><span style="color: #990000">]</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+desc <span style="color: #FF0000">'Turn this plugin into a gem.'</span>
+Rake<span style="color: #990000">::</span>GemPackageTask<span style="color: #990000">.</span>new<span style="color: #990000">(</span>spec<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>pkg<span style="color: #990000">|</span>
+ pkg<span style="color: #990000">.</span>gem_spec <span style="color: #990000">=</span> spec
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<h3 id="_create_your_own_plugin_loaders_and_plugin_locators">10.4. Create your own Plugin Loaders and Plugin Locators</h3>
-<div class="para"><p>If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.</p></div>
-<h3 id="_use_custom_plugin_generators">10.5. Use Custom Plugin Generators</h3>
-<div class="para"><p>If you are an RSpec fan, you can install the <tt>rspec_plugin_generator</tt> gem, which will generate the spec folder and database for you. See <a href="http://github.com/pat-maddox/rspec-plugin-generator/tree/master">http://github.com/pat-maddox/rspec-plugin-generator/tree/master</a>.</p></div>
+<div class="para"><p>To build and install the gem locally, run the following commands:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>cd vendor/plugins/yaffle
+rake gem
+sudo gem install pkg/yaffle-0.0.1.gem</tt></pre>
+</div></div>
+<div class="para"><p>To test this, create a new rails app, add <em>config.gem "yaffle"</em> to environment.rb and all of your plugin's functionality will be available to you.</p></div>
</div>
-<h2 id="_appendix">11. Appendix</h2>
+<h2 id="_rdoc_documentation">14. RDoc Documentation</h2>
<div class="sectionbody">
-<h3 id="_references">11.1. References</h3>
+<div class="para"><p>Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.</p></div>
+<div class="para"><p>The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Your name
+</p>
+</li>
+<li>
+<p>
+How to install
+</p>
+</li>
+<li>
+<p>
+How to add the functionality to the app (several examples of common use cases)
+</p>
+</li>
+<li>
+<p>
+Warning, gotchas or tips that might help save users time
+</p>
+</li>
+</ul></div>
+<div class="para"><p>Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add <em>#:nodoc:</em> comments to those parts of the code that are not part of the public api.</p></div>
+<div class="para"><p>Once your comments are good to go, navigate to your plugin directory and run:</p></div>
+<div class="listingblock">
+<div class="content">
+<pre><tt>rake rdoc</tt></pre>
+</div></div>
+</div>
+<h2 id="_appendix">15. Appendix</h2>
+<div class="sectionbody">
+<div class="para"><p>If you prefer to use RSpec instead of Test::Unit, you may be interested in the <a href="http://github.com/pat-maddox/rspec-plugin-generator/tree/master">RSpec Plugin Generator</a>.</p></div>
+<h3 id="_references">15.1. References</h3>
<div class="ilist"><ul>
<li>
<p>
@@ -1550,41 +1805,104 @@ http://www.gnu.org/software/src-highlite --> <a href="http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html">http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html</a>
</p>
</li>
+<li>
+<p>
+<a href="http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins">http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins</a>
+</p>
+</li>
+<li>
+<p>
+<a href="http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2">http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2</a>.
+</p>
+</li>
</ul></div>
-<h3 id="_final_plugin_directory_structure">11.2. Final plugin directory structure</h3>
+<h3 id="_contents_of_em_lib_yaffle_rb_em">15.2. Contents of <em>lib/yaffle.rb</em></h3>
+<div class="para"><p><strong>vendor/plugins/yaffle/lib/yaffle.rb:</strong></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: #000080">require</span></span> <span style="color: #FF0000">"yaffle/core_ext"</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/acts_as_yaffle"</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/commands"</span>
+<span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"yaffle/routing"</span>
+
+<span style="color: #990000">%</span>w<span style="color: #FF0000">{</span> models controllers helpers <span style="color: #FF0000">}</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>dir<span style="color: #990000">|</span>
+ path <span style="color: #990000">=</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>File<span style="color: #990000">.</span>dirname<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">__FILE__</span></span><span style="color: #990000">),</span> <span style="color: #FF0000">'app'</span><span style="color: #990000">,</span> dir<span style="color: #990000">)</span>
+ <span style="color: #009900">$LOAD_PATH</span> <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_paths <span style="color: #990000"><<</span> path
+ ActiveSupport<span style="color: #990000">::</span>Dependencies<span style="color: #990000">.</span>load_once_paths<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>path<span style="color: #990000">)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># optionally:</span></span>
+<span style="font-style: italic"><span style="color: #9A1900"># Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|</span></span>
+<span style="font-style: italic"><span style="color: #9A1900"># require file</span></span>
+<span style="font-style: italic"><span style="color: #9A1900"># end</span></span>
+
+</tt></pre></div></div>
+<h3 id="_final_plugin_directory_structure">15.3. Final plugin directory structure</h3>
<div class="para"><p>The final plugin should have a directory structure that looks something like this:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt> |-- MIT-LICENSE
- |-- README
- |-- Rakefile
- |-- generators
- | `-- yaffle
- | |-- USAGE
- | |-- templates
- | | `-- definition.txt
- | `-- yaffle_generator.rb
- |-- init.rb
- |-- install.rb
- |-- lib
- | |-- acts_as_yaffle.rb
- | |-- commands.rb
- | |-- core_ext.rb
- | |-- routing.rb
- | `-- view_helpers.rb
- |-- tasks
- | `-- yaffle_tasks.rake
- |-- test
- | |-- acts_as_yaffle_test.rb
- | |-- core_ext_test.rb
- | |-- database.yml
- | |-- debug.log
- | |-- routing_test.rb
- | |-- schema.rb
- | |-- test_helper.rb
- | `-- view_helpers_test.rb
- |-- uninstall.rb
- `-- yaffle_plugin.sqlite3.db</tt></pre>
+<pre><tt>|-- MIT-LICENSE
+|-- README
+|-- Rakefile
+|-- generators
+| |-- yaffle_definition
+| | |-- USAGE
+| | |-- templates
+| | | `-- definition.txt
+| | `-- yaffle_definition_generator.rb
+| |-- yaffle_migration
+| | |-- USAGE
+| | |-- templates
+| | `-- yaffle_migration_generator.rb
+| `-- yaffle_route
+| |-- USAGE
+| |-- templates
+| `-- yaffle_route_generator.rb
+|-- install.rb
+|-- lib
+| |-- app
+| | |-- controllers
+| | | `-- woodpeckers_controller.rb
+| | |-- helpers
+| | | `-- woodpeckers_helper.rb
+| | `-- models
+| | `-- woodpecker.rb
+| |-- db
+| | `-- migrate
+| | `-- 20081116181115_create_birdhouses.rb
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | |-- core_ext.rb
+| | `-- routing.rb
+| `-- yaffle.rb
+|-- pkg
+| `-- yaffle-0.0.1.gem
+|-- rails
+| `-- init.rb
+|-- tasks
+| `-- yaffle_tasks.rake
+|-- test
+| |-- acts_as_yaffle_test.rb
+| |-- core_ext_test.rb
+| |-- database.yml
+| |-- debug.log
+| |-- definition_generator_test.rb
+| |-- migration_generator_test.rb
+| |-- route_generator_test.rb
+| |-- routes_test.rb
+| |-- schema.rb
+| |-- test_helper.rb
+| |-- woodpecker_test.rb
+| |-- woodpeckers_controller_test.rb
+| |-- wookpeckers_helper_test.rb
+| |-- yaffle_plugin.sqlite3.db
+| `-- yaffle_test.rb
+`-- uninstall.rb</tt></pre>
</div></div>
</div>
diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index 02c1654aa5..c2c1db99e3 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -215,7 +215,7 @@ ul#navMain { <li><a href="#_array_conditions">Array Conditions</a></li> - <li><a href="#_hash_conditions">Hash Conditions</a></li> + <li><a href="#_placeholder_conditions">Placeholder Conditions</a></li> </ul> </li> @@ -344,6 +344,7 @@ Perform aggregate calculations on Active Record models </li>
</ul></div>
<div class="para"><p>If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.</p></div>
+<div class="para"><p>The SQL in your log may have some quoting, and that quoting depends on the backend (MySQL, for example, puts backticks around field and table names). Attempting to copy the raw SQL contained within this guide may not work in your database system. Please consult the database systems manual before attempting to execute any SQL.</p></div>
</div>
</div>
<h2 id="_the_sample_models">1. The Sample Models</h2>
@@ -389,14 +390,14 @@ 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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(+</span>clients<span style="color: #990000">+.+</span>id<span style="color: #990000">+</span> <span style="color: #990000">=</span> <span style="color: #993399">1</span><span style="color: #990000">)</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>clients<span style="color: #990000">.</span>id <span style="color: #990000">=</span> <span style="color: #993399">1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">Because this is a standard table created from a migration in Rail, the primary key is defaulted to <em>id</em>. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.</td>
+<td class="content">Because this is a standard table created from a migration in Rails, the primary key is defaulted to <em>id</em>. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.</td>
</tr></table>
</div>
<div class="para"><p>If you wanted to find clients with id 1 or 2, you call <tt>Client.find([1,2])</tt> or <tt>Client.find(1,2)</tt> and then this will be executed as:</p></div>
@@ -405,7 +406,7 @@ 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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(+</span>clients<span style="color: #990000">+.+</span>id<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span> <span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">,</span><span style="color: #993399">2</span><span style="color: #990000">))</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>clients<span style="color: #990000">.</span>id <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span> <span style="color: #990000">(</span><span style="color: #993399">1</span><span style="color: #990000">,</span><span style="color: #993399">2</span><span style="color: #990000">))</span>
</tt></pre></div></div>
<div class="listingblock">
<div class="content">
@@ -424,14 +425,14 @@ http://www.gnu.org/software/src-highlite --> <td class="content">If <tt>find(id)</tt> or <tt>find([id1, id2])</tt> fails to find any records, it will raise a <tt>RecordNotFound</tt> exception.</td>
</tr></table>
</div>
-<div class="para"><p>If you wanted to find the first client you would simply type <tt>Client.first</tt> and that would find the first client created in your clients table:</p></div>
+<div class="para"><p>If you wanted to find the first Client object you would simply type <tt>Client.first</tt> and that would find the first client in your clients table:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>>> Client.first
=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"></tt></pre>
</div></div>
-<div class="para"><p>If you were running script/server you might see the following output:</p></div>
+<div class="para"><p>If you were reading your log file (the default is log/development.log) you may see something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -440,13 +441,29 @@ http://www.gnu.org/software/src-highlite --> <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">1</span>
</tt></pre></div></div>
<div class="para"><p>Indicating the query that Rails has performed on your database.</p></div>
-<div class="para"><p>To find the last client you would simply type <tt>Client.find(:last)</tt> and that would find the last client created in your clients table:</p></div>
+<div class="para"><p>To find the last Client object you would simply type <tt>Client.last</tt> and that would find the last client created in your clients table:</p></div>
<div class="listingblock">
<div class="content">
-<pre><tt>>> Client.find(:last)
+<pre><tt>>> Client.last
=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"></tt></pre>
</div></div>
+<div class="para"><p>If you were reading your log file (the default is log/development.log) you may see something like this:</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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">ORDER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> id <span style="font-weight: bold"><span style="color: #0000FF">DESC</span></span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">1</span>
+</tt></pre></div></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/note.png" alt="Note" />
+</td>
+<td class="content">Please be aware that the syntax that Rails uses to find the first record in the table means that it may not be the actual first record. If you want the actual first record based on a field in your table (e.g. <tt>created_at</tt>) specify an order option in your find call. The last method call works differently: it finds the last record on your table based on the primary key column.</td>
+</tr></table>
+</div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -454,7 +471,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">ORDER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> clients<span style="color: #990000">.</span>id <span style="font-weight: bold"><span style="color: #0000FF">DESC</span></span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">1</span>
</tt></pre></div></div>
-<div class="para"><p>To find all the clients you would simply type <tt>Client.all</tt> and that would find all the clients in your clients table:</p></div>
+<div class="para"><p>To find all the Client objects you would simply type <tt>Client.all</tt> and that would find all the clients in your clients table:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>>> Client.all
@@ -463,8 +480,8 @@ http://www.gnu.org/software/src-highlite --> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]</tt></pre>
</div></div>
-<div class="para"><p>As alternatives to calling <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt>, you can use the class methods <tt>Client.first</tt>, <tt>Client.last</tt>, and <tt>Client.all</tt> instead. <tt>Client.first</tt>, <tt>Client.last</tt> and <tt>Client.all</tt> just call their longer counterparts: <tt>Client.find(:first)</tt>, <tt>Client.find(:last)</tt> and <tt>Client.find(:all)</tt> respectively.</p></div>
-<div class="para"><p>Be aware that <tt>Client.first</tt>/<tt>Client.find(:first)</tt> and <tt>Client.last</tt>/<tt>Client.find(:last)</tt> will both return a single object, where as <tt>Client.all</tt>/<tt>Client.find(:all)</tt> will return an array of Client objects, just as passing in an array of ids to find will do also.</p></div>
+<div class="para"><p>You may see in Rails code that there are calls to methods such as <tt>Client.find(:all)</tt>, <tt>Client.find(:first)</tt> and <tt>Client.find(:last)</tt>. These methods are just alternatives to <tt>Client.all</tt>, <tt>Client.first</tt> and <tt>Client.last</tt> respectively.</p></div>
+<div class="para"><p>Be aware that <tt>Client.first</tt>/<tt>Client.find(:first)</tt> and <tt>Client.last</tt>/<tt>Client.find(:last)</tt> will both return a single object, where as <tt>Client.all</tt>/<tt>Client.find(:all)</tt> will return an array of Client objects, just as passing in an array of ids to <tt>find</tt> will do also.</p></div>
</div>
<h2 id="_conditions">4. Conditions</h2>
<div class="sectionbody">
@@ -480,20 +497,23 @@ http://www.gnu.org/software/src-highlite --> </tr></table>
</div>
<h3 id="_array_conditions">4.2. Array Conditions</h3>
-<div class="para"><p>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like <tt>Client.first(:conditions ⇒ ["orders_count = ?", params[:orders]])</tt>. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like <tt>Client.first(:conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false])</tt>. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has <em>2</em> as its value for the orders_count field and <em>false</em> for its locked field.</p></div>
+<div class="para"><p>Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like <tt>Client.first(:conditions ⇒ ["orders_count = ?", params[:orders]])</tt>. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like <tt>Client.first(:conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false])</tt>. In this example, the first question mark will be replaced with the value in <tt>params[:orders]</tt> and the second will be replaced with <tt>false</tt> and this will find the first record in the table that has <em>2</em> as its value for the <tt>orders_count</tt> field and <tt>false</tt> for its locked field.</p></div>
<div class="para"><p>The reason for doing code like:</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="color: #990000">+</span>Client<span style="color: #990000">.</span>first<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #990000">[</span><span style="color: #FF0000">"orders_count = ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>orders<span style="color: #990000">]])+</span>
+<pre><tt>Client<span style="color: #990000">.</span>first<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #990000">[</span><span style="color: #FF0000">"orders_count = ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>orders<span style="color: #990000">]])</span>
</tt></pre></div></div>
<div class="para"><p>instead of:</p></div>
<div class="listingblock">
-<div class="content">
-<pre><tt>+Client.first(:conditions => "orders_count = #{params[:orders]}")+</tt></pre>
-</div></div>
+<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>Client<span style="color: #990000">.</span>first<span style="color: #990000">(:</span>conditions <span style="color: #990000">=></span> <span style="color: #FF0000">"orders_count = #{params[:orders]}"</span><span style="color: #990000">)</span>
+</tt></pre></div></div>
<div class="para"><p>is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database <strong>as-is</strong>. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.</p></div>
<div class="admonitionblock">
<table><tr>
@@ -518,7 +538,7 @@ 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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>users<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>created_at <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> users <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>created_at <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span>
<span style="color: #990000">(</span><span style="color: #FF0000">'2007-12-31'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-01'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-02'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-03'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-04'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-05'</span><span style="color: #990000">,</span>
<span style="color: #FF0000">'2008-01-06'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-07'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-08'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-09'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-10'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-11'</span><span style="color: #990000">,</span>
<span style="color: #FF0000">'2008-01-12'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-13'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-14'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-15'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-16'</span><span style="color: #990000">,</span><span style="color: #FF0000">'2008-01-17'</span><span style="color: #990000">,</span>
@@ -541,7 +561,7 @@ 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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>users<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>created_at <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> users <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>created_at <span style="font-weight: bold"><span style="color: #0000FF">IN</span></span>
<span style="color: #990000">(</span><span style="color: #FF0000">'2007-12-01 00:00:00'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'2007-12-01 00:00:01'</span> <span style="color: #990000">...</span>
<span style="color: #FF0000">'2007-12-01 23:59:59'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'2007-12-02 00:00:00'</span><span style="color: #990000">))</span>
</tt></pre></div></div>
@@ -570,7 +590,7 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at >= ? AND created_at <= ?"</span><span style="color: #990000">,</span> params<span style="color: #990000">[:</span>start_date<span style="color: #990000">],</span> params<span style="color: #990000">[:</span>end_date<span style="color: #990000">]])</span>
</tt></pre></div></div>
<div class="para"><p>Just like in Ruby.</p></div>
-<h3 id="_hash_conditions">4.3. Hash Conditions</h3>
+<h3 id="_placeholder_conditions">4.3. Placeholder Conditions</h3>
<div class="para"><p>Similar to the array style of params you can also specify keys in your conditions:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -641,7 +661,7 @@ 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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>orders<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">GROUP</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> <span style="color: #009900">date</span><span style="color: #990000">(</span>created_at<span style="color: #990000">)</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> orders <span style="font-weight: bold"><span style="color: #0000FF">GROUP</span></span> <span style="font-weight: bold"><span style="color: #0000FF">BY</span></span> <span style="color: #009900">date</span><span style="color: #990000">(</span>created_at<span style="color: #990000">)</span>
</tt></pre></div></div>
</div>
<h2 id="_read_only">9. Read Only</h2>
@@ -730,20 +750,23 @@ http://www.gnu.org/software/src-highlite --> </div>
<h2 id="_dynamic_finders">13. Dynamic finders</h2>
<div class="sectionbody">
-<div class="para"><p>For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called <tt>name</tt> on your Client model for example, you get <tt>find_by_name</tt> and <tt>find_all_by_name</tt> for free from Active Record. If you have also have a <tt>locked</tt> field on the client model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt>. If you want to find both by name and locked, you can chain these finders together by simply typing <tt>and</tt> between the fields for example <tt>Client.find_by_name_and_locked(<em>Ryan</em>, true)</tt>. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type <tt>find_by_name(params[:name])</tt> than it is to type <tt>first(:conditions ⇒ ["name = ?", params[:name]])</tt>.</p></div>
+<div class="para"><p>For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called <tt>name</tt> on your Client model for example, you get <tt>find_by_name</tt> and <tt>find_all_by_name</tt> for free from Active Record. If you have also have a <tt>locked</tt> field on the client model, you also get <tt>find_by_locked</tt> and <tt>find_all_by_locked</tt>.</p></div>
+<div class="para"><p>You can do <tt>find_last_by_*</tt> methods too which will find the last record matching your parameter.</p></div>
+<div class="para"><p>You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records, like <tt>Client.find_by_name!(<em>Ryan</em>)</tt></p></div>
+<div class="para"><p>If you want to find both by name and locked, you can chain these finders together by simply typing <tt>and</tt> between the fields for example <tt>Client.find_by_name_and_locked(<em>Ryan</em>, true)</tt>.</p></div>
<div class="para"><p>There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like <tt>find_or_create_by_name(params[:name])</tt>. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for <tt>Client.find_or_create_by_name(<em>Ryan</em>)</tt>:</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">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(+</span>clients<span style="color: #990000">+.+</span>name<span style="color: #990000">+</span> <span style="color: #990000">=</span> <span style="color: #FF0000">'Ryan'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">1</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> <span style="color: #990000">*</span> <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>clients<span style="color: #990000">.</span>name <span style="color: #990000">=</span> <span style="color: #FF0000">'Ryan'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">LIMIT</span></span> <span style="color: #993399">1</span>
BEGIN
-<span style="font-weight: bold"><span style="color: #0000FF">INSERT</span></span> <span style="font-weight: bold"><span style="color: #0000FF">INTO</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="color: #990000">(+</span>name<span style="color: #990000">+,</span> <span style="color: #990000">+</span>updated_at<span style="color: #990000">+,</span> <span style="color: #990000">+</span>created_at<span style="color: #990000">+,</span> <span style="color: #990000">+</span>orders_count<span style="color: #990000">+,</span> <span style="color: #990000">+</span>locked<span style="color: #990000">+)</span>
+<span style="font-weight: bold"><span style="color: #0000FF">INSERT</span></span> <span style="font-weight: bold"><span style="color: #0000FF">INTO</span></span> clients <span style="color: #990000">(</span>name<span style="color: #990000">,</span> updated_at<span style="color: #990000">,</span> created_at<span style="color: #990000">,</span> orders_count<span style="color: #990000">,</span> locked<span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">VALUES</span></span><span style="color: #990000">(</span><span style="color: #FF0000">'Ryan'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'2008-09-28 15:39:12'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'2008-09-28 15:39:12'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'0'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'0'</span><span style="color: #990000">)</span>
COMMIT
</tt></pre></div></div>
-<div class="para"><p><tt>find_or_create</tt>'s sibling, <tt>find_or_initialize</tt>, will find an object and if it does not exist will call <tt>new</tt> with the parameters you passed in. For example:</p></div>
+<div class="para"><p><tt>find_or_create</tt>'s sibling, <tt>find_or_initialize</tt>, will find an object and if it does not exist will act similar to calling <tt>new</tt> with the parameters you passed in. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -951,7 +974,7 @@ 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">SELECT</span></span> count<span style="color: #990000">(*)</span> <span style="font-weight: bold"><span style="color: #0000FF">AS</span></span> count_all <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>first_name <span style="color: #990000">=</span> <span style="color: #993399">1</span><span style="color: #990000">)</span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> count<span style="color: #990000">(*)</span> <span style="font-weight: bold"><span style="color: #0000FF">AS</span></span> count_all <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span> <span style="color: #990000">(</span>first_name <span style="color: #990000">=</span> <span style="color: #993399">1</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>You can also use <tt>include</tt> or <tt>joins</tt> for this to do something a little more complex:</p></div>
<div class="listingblock">
@@ -967,8 +990,8 @@ 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">SELECT</span></span> count<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">DISTINCT</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+.</span>id<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">AS</span></span> count_all <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> <span style="color: #990000">+</span>clients<span style="color: #990000">+</span>
- <span style="font-weight: bold"><span style="color: #0000FF">LEFT</span></span> <span style="font-weight: bold"><span style="color: #0000FF">OUTER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">JOIN</span></span> <span style="color: #990000">+</span>orders<span style="color: #990000">+</span> <span style="font-weight: bold"><span style="color: #0000FF">ON</span></span> orders<span style="color: #990000">.</span>client_id <span style="color: #990000">=</span> client<span style="color: #990000">.</span>id <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span>
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">SELECT</span></span> count<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">DISTINCT</span></span> clients<span style="color: #990000">.</span>id<span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">AS</span></span> count_all <span style="font-weight: bold"><span style="color: #0000FF">FROM</span></span> clients
+ <span style="font-weight: bold"><span style="color: #0000FF">LEFT</span></span> <span style="font-weight: bold"><span style="color: #0000FF">OUTER</span></span> <span style="font-weight: bold"><span style="color: #0000FF">JOIN</span></span> orders <span style="font-weight: bold"><span style="color: #0000FF">ON</span></span> orders<span style="color: #990000">.</span>client_id <span style="color: #990000">=</span> client<span style="color: #990000">.</span>id <span style="font-weight: bold"><span style="color: #0000FF">WHERE</span></span>
<span style="color: #990000">(</span>clients<span style="color: #990000">.</span>first_name <span style="color: #990000">=</span> <span style="color: #FF0000">'name'</span> <span style="font-weight: bold"><span style="color: #0000FF">AND</span></span> orders<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">status</span></span> <span style="color: #990000">=</span> <span style="color: #FF0000">'received'</span><span style="color: #990000">)</span>
</tt></pre></div></div>
<div class="para"><p>This code specifies <tt>clients.first_name</tt> just in case one of the join tables has a field also called <tt>first_name</tt> and it uses <tt>orders.status</tt> because that's the name of our join table.</p></div>
@@ -1028,6 +1051,21 @@ http://www.gnu.org/software/src-highlite --> <div class="ilist"><ul>
<li>
<p>
+November 23 2008: Added documentation for <tt>find_by_last</tt> and <tt>find_by_bang!</tt>
+</p>
+</li>
+<li>
+<p>
+November 21 2008: Fixed all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13">this comment</a> and <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14">this comment</a>
+</p>
+</li>
+<li>
+<p>
+November 18 2008: Fixed all points specified in <a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11">this comment</a>
+</p>
+</li>
+<li>
+<p>
November 8, 2008: Editing pass by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
</p>
</li>
diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 5111d0c645..4fc92f8ad7 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -566,6 +566,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre><tt>$ rails blog -d postgresql
</tt></pre></div></div>
+<div class="para"><p>After you create the blog application, switch to its folder to continue work directly in that application:</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>$ cd blog
+</tt></pre></div></div>
<div class="para"><p>In any case, Rails will create a folder in your working directory called <tt>blog</tt>. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the <tt>app/</tt> folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default:</p></div>
<div class="tableblock">
<table rules="all"
@@ -764,6 +772,15 @@ http://www.gnu.org/software/src-highlite --> password<span style="color: #990000">:</span>
</tt></pre></div></div>
<div class="para"><p>Change the username and password in the <tt>development</tt> section as appropriate.</p></div>
+<h4 id="_creating_the_database">3.3.4. Creating the Database</h4>
+<div class="para"><p>Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:</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>$ rake db<span style="color: #990000">:</span>create
+</tt></pre></div></div>
</div>
<h2 id="_hello_rails">4. Hello, Rails!</h2>
<div class="sectionbody">
@@ -1031,7 +1048,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
<div class="para"><p>If you were to translate that into words, it says something like: when this migration is run, create a table named <tt>posts</tt> with two string columns (<tt>name</tt> and <tt>title</tt>) and a text column (<tt>content</tt>), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the <a href="../migrations.html">Rails Database Migrations</a> guide.</p></div>
-<div class="para"><p>At this point, you need to do two things: create the database and run the migration. You can use rake commands at the terminal for both of those tasks:</p></div>
+<div class="para"><p>At this point, you can use a rake command to run the migration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -1045,7 +1062,7 @@ $ rake db<span style="color: #990000">:</span>migrate <td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
-<td class="content">Because you're working in the development environment by default, both of these commands will apply to the database defined in the <tt>development</tt> section of your <tt>config/database.yml</tt> file.</td>
+<td class="content">Because you're working in the development environment by default, this command will apply to the database defined in the <tt>development</tt> section of your <tt>config/database.yml</tt> file.</td>
</tr></table>
</div>
<h3 id="_adding_a_link">6.2. Adding a Link</h3>
@@ -1456,7 +1473,7 @@ http://www.gnu.org/software/src-highlite --> <div class="sectionbody">
<div class="para"><p>At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use <em>partials</em> to clean up duplication in views and <em>filters</em> to help with duplication in controllers.</p></div>
<h3 id="_using_partials_to_eliminate_view_duplication">7.1. Using Partials to Eliminate View Duplication</h3>
-<div class="para"><p>As you saw earlier, the scaffold-generated views for the <tt>new</tt> and <tt>edit</tt> actions are largely identical. You can pull the shared code out into a <tt>partial</tt> template. This requires editing the new and edit views, and adding a new template:</p></div>
+<div class="para"><p>As you saw earlier, the scaffold-generated views for the <tt>new</tt> and <tt>edit</tt> actions are largely identical. You can pull the shared code out into a <tt>partial</tt> template. This requires editing the new and edit views, and adding a new template. The new <tt>_form.html.erb</tt> template should be saved in the same <tt>app/views/posts</tt> folder as the files from which it is being extracted:</p></div>
<div class="para"><p><tt>new.html.erb</tt>:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
@@ -1791,7 +1808,7 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> show
<span style="color: #009900">@post</span> <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>post_id<span style="color: #990000">])</span>
- <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> Comment<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
+ <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>comments<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
@@ -1803,7 +1820,7 @@ http://www.gnu.org/software/src-highlite --> <span style="color: #009900">@post</span> <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>post_id<span style="color: #990000">])</span>
<span style="color: #009900">@comment</span> <span style="color: #990000">=</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>comments<span style="color: #990000">.</span>build<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>comment<span style="color: #990000">])</span>
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@comment</span><span style="color: #990000">.</span>save
- redirect_to post_comment_path<span style="color: #990000">(</span><span style="color: #009900">@post</span><span style="color: #990000">,</span> <span style="color: #009900">@comment</span><span style="color: #990000">)</span>
+ redirect_to post_comment_url<span style="color: #990000">(</span><span style="color: #009900">@post</span><span style="color: #990000">,</span> <span style="color: #009900">@comment</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
render <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"new"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -1811,14 +1828,14 @@ http://www.gnu.org/software/src-highlite --> <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> edit
<span style="color: #009900">@post</span> <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>post_id<span style="color: #990000">])</span>
- <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> Comment<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
+ <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> <span style="color: #009900">@post</span><span style="color: #990000">.</span>comments<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> update
<span style="color: #009900">@post</span> <span style="color: #990000">=</span> Post<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>post_id<span style="color: #990000">])</span>
<span style="color: #009900">@comment</span> <span style="color: #990000">=</span> Comment<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
<span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@comment</span><span style="color: #990000">.</span>update_attributes<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>comment<span style="color: #990000">])</span>
- redirect_to post_comment_path<span style="color: #990000">(</span><span style="color: #009900">@post</span><span style="color: #990000">,</span> <span style="color: #009900">@comment</span><span style="color: #990000">)</span>
+ redirect_to post_comment_url<span style="color: #990000">(</span><span style="color: #009900">@post</span><span style="color: #990000">,</span> <span style="color: #009900">@comment</span><span style="color: #990000">)</span>
<span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
render <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"edit"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -1990,7 +2007,7 @@ http://www.gnu.org/software/src-highlite --> <div class="ilist"><ul>
<li>
<p>
-The <a href="http://manuals.rubyonrails.org/">Ruby On Rails guides</a>
+The <a href="http://guides.rubyonrails.org/">Ruby On Rails guides</a>
</p>
</li>
<li>
diff --git a/railties/doc/guides/html/i18n.html b/railties/doc/guides/html/i18n.html new file mode 100644 index 0000000000..3ceba0f687 --- /dev/null +++ b/railties/doc/guides/html/i18n.html @@ -0,0 +1,1086 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>The Rails Internationalization API</title> + <!--[if lt IE 8]> + <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script> + <![endif]--> + <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" /> + <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" /> + <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" /> + <style type="text/css"> + div#container { + max-width: 900px; + padding-bottom: 3em; +} + +div#content { + margin-left: 200px; +} + +div#container.notoc { + max-width: 600px; +} + +.notoc div#content { + margin-left: 0; +} + +pre { + line-height: 1.4em; +} + +#content p tt { + background: #eeeeee; + border: solid 1px #cccccc; + padding: 3px; +} + +dt { + font-weight: bold; +} + +#content dt tt { + font-size: 10pt; +} + +dd { + margin-left: 3em; +} + +#content dt tt, #content pre tt { + background: none; + padding: 0; + border: 0; +} + +#content .olist ol { + margin-left: 2em; +} + +#header { + position: relative; + max-width: 840px; + margin-left: auto; + margin-right: auto; +} + +#header.notoc { + max-width: 580px; +} + +#logo { + position: absolute; + left: 10px; + top: 10px; + width: 110px; + height: 140px; +} + +div#header h1#site_title { + background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat; + position: absolute; + width: 392px; + height: 55px; + left: 145px; + top: 20px; + margin: 0; + padding: 0; +} + +#site_title span { + display: none; +} + +#site_title_tagline { + display: none; +} + +ul#navMain { + position: absolute; + margin: 0; + padding: 0; + top: 97px; + left: 145px; +} + +.left-floaty, .right-floaty { + padding: 15px; +} + +.admonitionblock, +.tableblock { + margin-left: 1em; + margin-right: 1em; + margin-top: 0.25em; + margin-bottom: 1em; +} + +.admonitionblock .icon { + padding-right: 8px; +} + +.admonitionblock .content { + border: solid 1px #ffda78; + background: #fffebd; + padding: 10px; + padding-top: 8px; + padding-bottom: 8px; +} + +.admonitionblock .title { + font-size: 140%; + margin-bottom: 0.5em; +} + +.tableblock table { + border: solid 1px #aaaaff; + background: #f0f0ff; +} + +.tableblock th { + background: #e0e0e0; +} + +.tableblock th, +.tableblock td { + padding: 3px; + padding-left: 5px; + padding-right: 5px; +} + +.sidebarblock { + margin-top: 0.25em; + margin: 1em; + border: solid 1px #ccccbb; + padding: 8px; + background: #ffffe0; +} + +.sidebarblock .sidebar-title { + font-size: 140%; + font-weight: 600; + margin-bottom: 0.3em; +} + +.sidebarblock .sidebar-content > .para:last-child > p { + margin-bottom: 0; +} + +.sidebarblock .sidebar-title a { + text-decoration: none; +} + +.sidebarblock .sidebar-title a:hover { + text-decoration: underline; +} + + </style> +</head> +<body> + <div id="header" > + <div id="logo"> + <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a> + </div> + + <h1 id="site_title"><span>Ruby on Rails</span></h1> + <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2> + + <ul id="navMain"> + <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li> + <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li> + </ul> + </div> + + <div id="container"> + + <div id="sidebar"> + <h2>Chapters</h2> + <ol> + <li> + <a href="#_how_i18n_in_ruby_on_rails_works">How I18n in Ruby on Rails works</a> + <ul> + + <li><a href="#_the_overall_architecture_of_the_library">The overall architecture of the library</a></li> + + <li><a href="#_the_public_i18n_api">The public I18n API</a></li> + + </ul> + </li> + <li> + <a href="#_walkthrough_setup_a_simple_i18n_ed_rails_application">Walkthrough: setup a simple I18n'ed Rails application</a> + <ul> + + <li><a href="#_configure_the_i18n_module">Configure the I18n module</a></li> + + <li><a href="#_set_the_locale_in_each_request">Set the locale in each request</a></li> + + <li><a href="#_internationalize_your_application">Internationalize your application</a></li> + + </ul> + </li> + <li> + <a href="#_overview_of_the_i18n_api_features">Overview of the I18n API features</a> + <ul> + + <li><a href="#_looking_up_translations">Looking up translations</a></li> + + <li><a href="#_interpolation">Interpolation</a></li> + + <li><a href="#_pluralization">Pluralization</a></li> + + <li><a href="#_setting_and_passing_a_locale">Setting and passing a locale</a></li> + + </ul> + </li> + <li> + <a href="#_how_to_store_your_custom_translations">How to store your custom translations</a> + <ul> + + <li><a href="#_translations_for_activerecord_models">Translations for ActiveRecord models</a></li> + + <li><a href="#_other_translations_and_localizations">Other translations and localizations</a></li> + + </ul> + </li> + <li> + <a href="#_customize_your_i18n_setup">Customize your I18n setup</a> + <ul> + + <li><a href="#_using_different_backends">Using different backends</a></li> + + <li><a href="#_using_different_exception_handlers">Using different exception handlers</a></li> + + </ul> + </li> + <li> + <a href="#_resources">Resources</a> + </li> + <li> + <a href="#_footnotes">Footnotes</a> + </li> + <li> + <a href="#_credits">Credits</a> + </li> + <li> + <a href="#_notes">NOTES</a> + </li> + </ol> + </div> + + <div id="content"> + <h1>The Rails Internationalization API</h1> + <div id="preamble">
+<div class="sectionbody">
+<div class="para"><p>The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.</p></div>
+</div>
+</div>
+<h2 id="_how_i18n_in_ruby_on_rails_works">1. How I18n in Ruby on Rails works</h2>
+<div class="sectionbody">
+<div class="para"><p>Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+providing support for English and similar languages out of the box
+</p>
+</li>
+<li>
+<p>
+making it easy to customize and extend everything for other languages
+</p>
+</li>
+</ul></div>
+<h3 id="_the_overall_architecture_of_the_library">1.1. The overall architecture of the library</h3>
+<div class="para"><p>To solve this the Ruby I18n gem is split into two parts:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
+</p>
+</li>
+<li>
+<p>
+A shipped backend (which is intentionally named the Simple backend) that implements these methods.
+</p>
+</li>
+</ul></div>
+<div class="para"><p>As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one.</p></div>
+<h3 id="_the_public_i18n_api">1.2. The public I18n API</h3>
+<div class="para"><p>We will go into more detail about the public methods later but here's a quick overview. The most important methods are:</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>translate <span style="font-style: italic"><span style="color: #9A1900"># lookup translations</span></span>
+localize <span style="font-style: italic"><span style="color: #9A1900"># localize Date and Time objects to local formats</span></span>
+</tt></pre></div></div>
+<div class="para"><p>There are also attribute readers and writers for the following attributes:</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>load_path <span style="font-style: italic"><span style="color: #9A1900"># announce your custom translation files</span></span>
+locale <span style="font-style: italic"><span style="color: #9A1900"># get and set the current locale</span></span>
+default_locale <span style="font-style: italic"><span style="color: #9A1900"># get and set the default locale</span></span>
+exception_handler <span style="font-style: italic"><span style="color: #9A1900"># use a different exception_handler</span></span>
+backend <span style="font-style: italic"><span style="color: #9A1900"># use a different backend</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_walkthrough_setup_a_simple_i18n_ed_rails_application">2. Walkthrough: setup a simple I18n'ed Rails application</h2>
+<div class="sectionbody">
+<div class="para"><p>There are just a few, simple steps to get up and running with a I18n support for your application.</p></div>
+<h3 id="_configure_the_i18n_module">2.1. Configure the I18n module</h3>
+<div class="para"><p>First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.</p></div>
+<div class="para"><p>You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:</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-style: italic"><span style="color: #9A1900"># in config/initializer/locale.rb</span></span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># tell the I18n library where to find your translations</span></span>
+I18n<span style="color: #990000">.</span>load_path <span style="color: #990000">+=</span> Dir<span style="color: #990000">[</span> File<span style="color: #990000">.</span>join<span style="color: #990000">(</span>RAILS_ROOT<span style="color: #990000">,</span> <span style="color: #FF0000">'lib'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'locale'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'*.{rb,yml}'</span><span style="color: #990000">)</span> <span style="color: #990000">]</span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># you can omit this if you're happy with English as a default locale</span></span>
+I18n<span style="color: #990000">.</span>default_locale <span style="color: #990000">=</span> <span style="color: #990000">:</span><span style="color: #FF0000">"pt"</span>
+</tt></pre></div></div>
+<div class="para"><p>I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.</p></div>
+<h3 id="_set_the_locale_in_each_request">2.2. Set the locale in each request</h3>
+<div class="para"><p>By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English).</p></div>
+<div class="para"><p>If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:</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>before_filter <span style="color: #990000">:</span>set_locale
+<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> set_locale
+ <span style="font-style: italic"><span style="color: #9A1900"># if this is nil then I18n.default_locale will be used</span></span>
+ I18n<span style="color: #990000">.</span>locale <span style="color: #990000">=</span> params<span style="color: #990000">[:</span>locale<span style="color: #990000">]</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).</p></div>
+<div class="para"><p>Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.</p></div>
+<h3 id="_internationalize_your_application">2.3. Internationalize your application</h3>
+<div class="para"><p>The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.</p></div>
+<div class="para"><p>So, let's internationalize something. You most probably have something like this in one of your applications:</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-style: italic"><span style="color: #9A1900"># config/routes.rb</span></span>
+ActionController<span style="color: #990000">::</span>Routing<span style="color: #990000">::</span>Routes<span style="color: #990000">.</span>draw <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>map<span style="color: #990000">|</span>
+ map<span style="color: #990000">.</span>root <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'home'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'index'</span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># app/controllers/home_controller.rb</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> HomeController <span style="color: #990000"><</span> ApplicationController
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
+ flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"Hello flash!"</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># app/views/home/index.html.erb</span></span>
+<span style="color: #FF0000"><h1></span>Hello world!<span style="color: #FF0000"></h1></span>
+<span style="color: #FF0000"><p><%= flash[:notice] %></p></span>
+</tt></pre></div></div>
+<div class="para"><p>TODO screenshot</p></div>
+<div class="para"><p>Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:</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-style: italic"><span style="color: #9A1900"># app/controllers/home_controller.rb</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> HomeController <span style="color: #990000"><</span> ApplicationController
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
+ flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> t<span style="color: #990000">(:</span>hello_flash<span style="color: #990000">)</span>
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+<span style="font-style: italic"><span style="color: #9A1900"># app/views/home/index.html.erb</span></span>
+<span style="color: #FF0000"><h1><%=t :hello_world %></h1></span>
+<span style="color: #FF0000"><p><%= flash[:notice] %></p></span>
+</tt></pre></div></div>
+<div class="para"><p>TODO insert note about #t helper compared to I18n.t</p></div>
+<div class="para"><p>TODO insert note/reference about structuring translation keys</p></div>
+<div class="para"><p>When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.</p></div>
+<div class="para"><p>TODO screenshot</p></div>
+<div class="para"><p>So let's add the missing translations (i.e. do the "localization" part):</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-style: italic"><span style="color: #9A1900"># lib/locale/en.yml</span></span>
+en<span style="color: #990000">-</span>US<span style="color: #990000">:</span>
+ hello_world<span style="color: #990000">:</span> Hello World
+ hello_flash<span style="color: #990000">:</span> Hello Flash
+
+<span style="font-style: italic"><span style="color: #9A1900"># lib/locale/pirate.yml</span></span>
+pirate<span style="color: #990000">:</span>
+ hello_world<span style="color: #990000">:</span> Ahoy World
+ hello_flash<span style="color: #990000">:</span> Ahoy Flash
+</tt></pre></div></div>
+<div class="para"><p>There you go. Your application now shows:</p></div>
+<div class="para"><p>TODO screenshot</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>I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'store.title'</span>
+I18n<span style="color: #990000">.</span>l Time<span style="color: #990000">.</span>now
+</tt></pre></div></div>
+</div>
+<h2 id="_overview_of_the_i18n_api_features">3. Overview of the I18n API features</h2>
+<div class="sectionbody">
+<div class="para"><p>The following purposes are covered:</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+lookup translations
+</p>
+</li>
+<li>
+<p>
+interpolate data into translations
+</p>
+</li>
+<li>
+<p>
+pluralize translations
+</p>
+</li>
+<li>
+<p>
+localize dates, numbers, currency etc.
+</p>
+</li>
+</ul></div>
+<h3 id="_looking_up_translations">3.1. Looking up translations</h3>
+<h4 id="_basic_lookup_scopes_and_nested_keys">3.1.1. Basic lookup, scopes and nested keys</h4>
+<div class="para"><p>Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>message
+I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'message'</span>
+</tt></pre></div></div>
+<div class="para"><p>translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>invalid<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">[:</span>active_record<span style="color: #990000">,</span> <span style="color: #990000">:</span>error_messages<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<div class="para"><p>This looks up the :invalid message in the ActiveRecord error messages.</p></div>
+<div class="para"><p>Additionally, both the key and scopes can be specified as dot separated keys as in:</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>I18n<span style="color: #990000">.</span>translate <span style="color: #990000">:</span><span style="color: #FF0000">"active_record.error_messages.invalid"</span>
+</tt></pre></div></div>
+<div class="para"><p>Thus the following calls are equivalent:</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>I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'active_record.error_messages.invalid'</span>
+I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'error_messages.invalid'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">:</span>active_record
+I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>invalid<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #FF0000">'active_record.error_messages'</span>
+I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>invalid<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">[:</span>active_record<span style="color: #990000">,</span> <span style="color: #990000">:</span>error_messages<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<h4 id="_defaults">3.1.2. Defaults</h4>
+<div class="para"><p>When a default option is given its value will be returned if the translation is missing:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>missing<span style="color: #990000">,</span> <span style="color: #990000">:</span>default <span style="color: #990000">=></span> <span style="color: #FF0000">'Not here'</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => 'Not here'</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.</p></div>
+<div class="para"><p>E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>missing<span style="color: #990000">,</span> <span style="color: #990000">:</span>default <span style="color: #990000">=></span> <span style="color: #990000">[:</span>also_missing<span style="color: #990000">,</span> <span style="color: #FF0000">'Not here'</span><span style="color: #990000">]</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => 'Not here'</span></span>
+</tt></pre></div></div>
+<h4 id="_bulk_and_namespace_lookup">3.1.3. Bulk and namespace lookup</h4>
+<div class="para"><p>To lookup multiple translations at once an array of keys can be passed:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">[:</span>odd<span style="color: #990000">,</span> <span style="color: #990000">:</span>even<span style="color: #990000">],</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #FF0000">'active_record.error_messages'</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => ["must be odd", "must be even"]</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all ActiveRecord error messages as a Hash with:</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>I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'active_record.error_messages'</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => { :inclusion => "is not included in the list", :exclusion => ... }</span></span>
+</tt></pre></div></div>
+<h3 id="_interpolation">3.2. Interpolation</h3>
+<div class="para"><p>TODO explain what this is good for</p></div>
+<div class="para"><p>All options besides :default and :scope that are passed to #translate will be interpolated to the translation:</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>I18n<span style="color: #990000">.</span>backend<span style="color: #990000">.</span>store_translations <span style="color: #FF0000">'en'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>thanks <span style="color: #990000">=></span> <span style="color: #FF0000">'Thanks {{name}}!'</span>
+I18n<span style="color: #990000">.</span>translate <span style="color: #990000">:</span>thanks<span style="color: #990000">,</span> <span style="color: #990000">:</span>name <span style="color: #990000">=></span> <span style="color: #FF0000">'Jeremy'</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => 'Thanks Jeremy!'</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.</p></div>
+<h3 id="_pluralization">3.3. Pluralization</h3>
+<div class="para"><p>TODO explain what this is good for</p></div>
+<div class="para"><p>The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:</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>I18n<span style="color: #990000">.</span>backend<span style="color: #990000">.</span>store_translations <span style="color: #FF0000">'en-US'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>inbox <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="font-style: italic"><span style="color: #9A1900"># TODO change this</span></span>
+ <span style="color: #990000">:</span>one <span style="color: #990000">=></span> <span style="color: #FF0000">'1 message'</span><span style="color: #990000">,</span>
+ <span style="color: #990000">:</span>other <span style="color: #990000">=></span> <span style="color: #FF0000">'{{count}} messages'</span>
+<span style="color: #FF0000">}</span>
+I18n<span style="color: #990000">.</span>translate <span style="color: #990000">:</span>inbox<span style="color: #990000">,</span> <span style="color: #990000">:</span>count <span style="color: #990000">=></span> <span style="color: #993399">2</span>
+<span style="font-style: italic"><span style="color: #9A1900"># => '2 messages'</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The algorithm for pluralizations in en-US is as simple as:</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>entry<span style="color: #990000">[</span>count <span style="color: #990000">==</span> <span style="color: #993399">1</span> <span style="color: #990000">?</span> <span style="color: #993399">0</span> <span style="color: #990000">:</span> <span style="color: #993399">1</span><span style="color: #990000">]</span>
+</tt></pre></div></div>
+<div class="para"><p>I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).</p></div>
+<div class="para"><p>If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.</p></div>
+<h3 id="_setting_and_passing_a_locale">3.4. Setting and passing a locale</h3>
+<div class="para"><p>The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.</p></div>
+<div class="para"><p>If no locale is passed I18n.locale is used:</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>I18n<span style="color: #990000">.</span>locale <span style="color: #990000">=</span> <span style="color: #990000">:</span><span style="color: #FF0000">'de'</span>
+I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>foo
+I18n<span style="color: #990000">.</span>l Time<span style="color: #990000">.</span>now
+</tt></pre></div></div>
+<div class="para"><p>Explicitely passing a locale:</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>I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>foo<span style="color: #990000">,</span> <span style="color: #990000">:</span>locale <span style="color: #990000">=></span> <span style="color: #990000">:</span><span style="color: #FF0000">'de'</span>
+I18n<span style="color: #990000">.</span>l Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>locale <span style="color: #990000">=></span> <span style="color: #990000">:</span><span style="color: #FF0000">'de'</span>
+</tt></pre></div></div>
+<div class="para"><p>I18n.locale defaults to I18n.default_locale which defaults to :<em>en</em>. The default locale can be set like this:</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>I18n<span style="color: #990000">.</span>default_locale <span style="color: #990000">=</span> <span style="color: #990000">:</span><span style="color: #FF0000">'de'</span>
+</tt></pre></div></div>
+</div>
+<h2 id="_how_to_store_your_custom_translations">4. How to store your custom translations</h2>
+<div class="sectionbody">
+<div class="para"><p>The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)</p></div>
+<div class="para"><p>For example a Ruby Hash providing translations can look like this:</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="color: #FF0000">{</span>
+ <span style="color: #990000">:</span><span style="color: #FF0000">'pt-BR'</span> <span style="color: #990000">=></span> <span style="color: #FF0000">{</span>
+ <span style="color: #990000">:</span>foo <span style="color: #990000">=></span> <span style="color: #FF0000">{</span>
+ <span style="color: #990000">:</span>bar <span style="color: #990000">=></span> <span style="color: #FF0000">"baz"</span>
+ <span style="color: #FF0000">}</span>
+ <span style="color: #FF0000">}</span>
+<span style="color: #FF0000">}</span>
+</tt></pre></div></div>
+<div class="para"><p>The equivalent YAML file would look like this:</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="color: #FF0000">"pt-BR"</span><span style="color: #990000">:</span>
+ foo<span style="color: #990000">:</span>
+ bar<span style="color: #990000">:</span> baz
+</tt></pre></div></div>
+<div class="para"><p>As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".</p></div>
+<div class="para"><p>Here is a "real" example from the ActiveSupport en-US translations YAML file:</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="color: #FF0000">"en"</span><span style="color: #990000">:</span>
+ date<span style="color: #990000">:</span>
+ formats<span style="color: #990000">:</span>
+ default<span style="color: #990000">:</span> <span style="color: #FF0000">"%Y-%m-%d"</span>
+ short<span style="color: #990000">:</span> <span style="color: #FF0000">"%b %d"</span>
+ long<span style="color: #990000">:</span> <span style="color: #FF0000">"%B %d, %Y"</span>
+</tt></pre></div></div>
+<div class="para"><p>So, all of the following equivalent lookups will return the :short date format "%B %d":</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>I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'date.formats.short'</span>
+I18n<span style="color: #990000">.</span>t <span style="color: #FF0000">'formats.short'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">:</span>date
+I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>short<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #FF0000">'date.formats'</span>
+I18n<span style="color: #990000">.</span>t <span style="color: #990000">:</span>short<span style="color: #990000">,</span> <span style="color: #990000">:</span>scope <span style="color: #990000">=></span> <span style="color: #990000">[:</span>date<span style="color: #990000">,</span> <span style="color: #990000">:</span>formats<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<h3 id="_translations_for_activerecord_models">4.1. Translations for ActiveRecord models</h3>
+<div class="para"><p>You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.</p></div>
+<div class="para"><p>For example when you add the following translations:</p></div>
+<div class="para"><p>en:
+ activerecord:
+ models:
+ user: Dude
+ attributes:
+ user:
+ login: "Handle"
+ # will translate User attribute "login" as "Handle"</p></div>
+<div class="para"><p>Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".</p></div>
+<h4 id="_error_message_scopes">4.1.1. Error message scopes</h4>
+<div class="para"><p>ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.</p></div>
+<div class="para"><p>This gives you quite powerful means to flexibly adjust your messages to your application's needs.</p></div>
+<div class="para"><p>Consider a User model with a validates_presence_of validation for the name attribute like this:</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> User <span style="color: #990000"><</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validates_presence_of <span style="color: #990000">:</span>name
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:</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>activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>messages<span style="color: #990000">.</span>models<span style="color: #990000">.</span>user<span style="color: #990000">.</span>attributes<span style="color: #990000">.</span>name<span style="color: #990000">.</span>blank
+</tt></pre></div></div>
+<div class="para"><p>If it's not there it will try:</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>activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>messages<span style="color: #990000">.</span>models<span style="color: #990000">.</span>user<span style="color: #990000">.</span>blank
+</tt></pre></div></div>
+<div class="para"><p>If this is also not there it will use the default message from:</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>activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>messages<span style="color: #990000">.</span>blank
+</tt></pre></div></div>
+<div class="para"><p>When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.</p></div>
+<div class="para"><p>For example, you might have an Admin model inheriting from User:</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> Admin <span style="color: #990000"><</span> User
+ validates_presence_of <span style="color: #990000">:</span>name
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>Then ActiveRecord will look for messages in this order:</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>activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>models<span style="color: #990000">.</span>admin<span style="color: #990000">.</span>attributes<span style="color: #990000">.</span>title<span style="color: #990000">.</span>blank
+activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>models<span style="color: #990000">.</span>admin<span style="color: #990000">.</span>blank
+activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>models<span style="color: #990000">.</span>user<span style="color: #990000">.</span>attributes<span style="color: #990000">.</span>title<span style="color: #990000">.</span>blank
+activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>models<span style="color: #990000">.</span>user<span style="color: #990000">.</span>blank
+activerecord<span style="color: #990000">.</span>errors<span style="color: #990000">.</span>messages<span style="color: #990000">.</span>blank
+</tt></pre></div></div>
+<div class="para"><p>This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes.</p></div>
+<h4 id="_error_message_interpolation">4.1.2. Error message interpolation</h4>
+<div class="para"><p>The translated model name and translated attribute name are always available for interpolation.</p></div>
+<div class="para"><p></p></div>
+<div class="para"><p>Count and/or value are available where applicable. Count can be used for pluralization if present:</p></div>
+<div class="tableblock">
+<table rules="all"
+frame="hsides"
+cellspacing="0" cellpadding="4">
+<col width="320" />
+<col width="194" />
+<col width="182" />
+<col width="194" />
+<tbody valign="top">
+ <tr>
+ <td align="left">
+ validation
+ </td>
+ <td align="left">
+ with option
+ </td>
+ <td align="left">
+ message
+ </td>
+ <td align="left">
+ interpolation
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_confirmation_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :confirmation
+ </td>
+ <td align="left">
+ -
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_acceptance_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :accepted
+ </td>
+ <td align="left">
+ -
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_presence_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :blank
+ </td>
+ <td align="left">
+ -
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_length_of
+ </td>
+ <td align="left">
+ :within, :in
+ </td>
+ <td align="left">
+ :too_short
+ </td>
+ <td align="left">
+ count
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_length_of
+ </td>
+ <td align="left">
+ :within, :in
+ </td>
+ <td align="left">
+ :too_long
+ </td>
+ <td align="left">
+ count
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_length_of
+ </td>
+ <td align="left">
+ :is
+ </td>
+ <td align="left">
+ :wrong_length
+ </td>
+ <td align="left">
+ count
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_length_of
+ </td>
+ <td align="left">
+ :minimum
+ </td>
+ <td align="left">
+ :too_short
+ </td>
+ <td align="left">
+ count
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_length_of
+ </td>
+ <td align="left">
+ :maximum
+ </td>
+ <td align="left">
+ :too_long
+ </td>
+ <td align="left">
+ count
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_uniqueness_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :taken
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_format_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :invalid
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_inclusion_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :inclusion
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_exclusion_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :exclusion
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_associated
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :invalid
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_numericality_of
+ </td>
+ <td align="left">
+ -
+ </td>
+ <td align="left">
+ :not_a_number
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_numericality_of
+ </td>
+ <td align="left">
+ :odd
+ </td>
+ <td align="left">
+ :odd
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+ <tr>
+ <td align="left">
+ validates_numericality_of
+ </td>
+ <td align="left">
+ :even
+ </td>
+ <td align="left">
+ :even
+ </td>
+ <td align="left">
+ value
+ </td>
+ </tr>
+</tbody>
+</table>
+</div>
+<h4 id="_translations_for_the_activerecord_error_messages_for_helper">4.1.3. Translations for the ActiveRecord error_messages_for helper</h4>
+<div class="para"><p>If you are using the ActiveRecord error_messages_for helper you will want to add translations for it.</p></div>
+<div class="para"><p>Rails ships with the following translations:</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="color: #FF0000">"en"</span><span style="color: #990000">:</span>
+ activerecord<span style="color: #990000">:</span>
+ errors<span style="color: #990000">:</span>
+ template<span style="color: #990000">:</span>
+ header<span style="color: #990000">:</span>
+ one<span style="color: #990000">:</span> <span style="color: #FF0000">"1 error prohibited this {{model}} from being saved"</span>
+ other<span style="color: #990000">:</span> <span style="color: #FF0000">"{{count}} errors prohibited this {{model}} from being saved"</span>
+ body<span style="color: #990000">:</span> <span style="color: #FF0000">"There were problems with the following fields:"</span>
+</tt></pre></div></div>
+<h3 id="_other_translations_and_localizations">4.2. Other translations and localizations</h3>
+<div class="para"><p>Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers.</p></div>
+<div class="para"><p>TODO list helpers and available keys</p></div>
+</div>
+<h2 id="_customize_your_i18n_setup">5. Customize your I18n setup</h2>
+<div class="sectionbody">
+<h3 id="_using_different_backends">5.1. Using different backends</h3>
+<div class="para"><p>For several reasons the shipped Simple backend only does the "simplest thing that ever could work" <em>for Ruby on Rails</em> (1) … which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.</p></div>
+<div class="para"><p>That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:</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>I18n<span style="color: #990000">.</span>backend <span style="color: #990000">=</span> Globalize<span style="color: #990000">::</span>Backend<span style="color: #990000">::</span>Static<span style="color: #990000">.</span>new
+</tt></pre></div></div>
+<div class="para"><p>TODO expand this …? list some backends and their features?</p></div>
+<h3 id="_using_different_exception_handlers">5.2. Using different exception handlers</h3>
+<div class="para"><p>TODO</p></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
+</p>
+</li>
+<li>
+<p>
+Explain the default behaviour.
+</p>
+</li>
+<li>
+<p>
+Explain the :raise option
+</p>
+</li>
+<li>
+<p>
+Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
+</p>
+</li>
+<li>
+<p>
+Example 2: for tests you might want a handler that just raises all exceptions all the time
+</p>
+</li>
+<li>
+<p>
+Example 3: a handler
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_resources">6. Resources</h2>
+<div class="sectionbody">
+<div class="ilist"><ul>
+<li>
+<p>
+<a href="http://rails-i18n.org">http://rails-i18n.org</a>
+</p>
+</li>
+</ul></div>
+</div>
+<h2 id="_footnotes">7. Footnotes</h2>
+<div class="sectionbody">
+<div class="para"><p>(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.</p></div>
+<div class="para"><p>(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.</p></div>
+</div>
+<h2 id="_credits">8. Credits</h2>
+<div class="sectionbody">
+</div>
+<h2 id="_notes">9. NOTES</h2>
+<div class="sectionbody">
+<div class="para"><p>How to contribute?</p></div>
+</div>
+ + </div> + </div> +</body> +</html> diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index 991b10c7e8..45e131012e 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -338,6 +338,19 @@ of your code.</p></div> <div class="sidebar-title"><a href="creating_plugins.html">The Basics of Creating Rails Plugins</a></div>
<div class="para"><p>This guide covers how to build a plugin to extend the functionality of Rails.</p></div>
</div></div>
+<div class="sidebarblock">
+<div class="sidebar-content">
+<div class="sidebar-title"><a href="i18n.html">The Rails Internationalization API</a></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/caution.png" alt="Caution" />
+</td>
+<td class="content">still a basic draft</td>
+</tr></table>
+</div>
+<div class="para"><p>This guide introduces you to the basic concepts and features of the Rails I18n API and shows you how to localize your application.</p></div>
+</div></div>
<div class="para"><p>Authors who have contributed to complete guides are listed <a href="authors.html">here</a>.</p></div>
<div class="para"><p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 License</a></p></div>
</div>
diff --git a/railties/doc/guides/html/migrations.html b/railties/doc/guides/html/migrations.html index 8b580d8086..9f7fa28daf 100644 --- a/railties/doc/guides/html/migrations.html +++ b/railties/doc/guides/html/migrations.html @@ -279,7 +279,7 @@ ul#navMain { <h1>Migrations</h1> <div id="preamble">
<div class="sectionbody">
-<div class="para"><p>Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run <tt>rake db:migrate</tt>. Active Record will work out which migrations should be run.</p></div>
+<div class="para"><p>Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run <tt>rake db:migrate</tt>. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.</p></div>
<div class="para"><p>Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.</p></div>
<div class="para"><p>You'll learn all about migrations including:</p></div>
<div class="ilist"><ul>
@@ -699,6 +699,7 @@ displayed saying that it can't be done.</p></div> <h2 id="_running_migrations">4. Running Migrations</h2>
<div class="sectionbody">
<div class="para"><p>Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be <tt>db:migrate</tt>. In its most basic form it just runs the <tt>up</tt> method for all the migrations that have not yet been run. If there are no such migrations it exits.</p></div>
+<div class="para"><p>Note that running the <tt>db:migrate</tt> also invokes the <tt>db:schema:dump</tt> task, which will update your db/schema.rb file to match the structure of your database.</p></div>
<div class="para"><p>If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run</p></div>
<div class="listingblock">
diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index 947d0836ce..bf45a8d046 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -1454,7 +1454,7 @@ http://www.gnu.org/software/src-highlite --> <td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
-<td class="content">If your application has many RESTful routes, using <tt>:only</tt> and <tt>:accept</tt> to generate only the routes that you actually need can cut down on memory use and speed up the routing process.</td>
+<td class="content">If your application has many RESTful routes, using <tt>:only</tt> and <tt>:except</tt> to generate only the routes that you actually need can cut down on memory use and speed up the routing process.</td>
</tr></table>
</div>
<h3 id="_nested_resources">3.8. Nested Resources</h3>
@@ -1905,7 +1905,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>map<span style="color: #990000">.</span>connect <span style="color: #FF0000">'photo/:id'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'photos'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'show'</span>
+<pre><tt>map<span style="color: #990000">.</span>connect <span style="color: #FF0000">'photos/:id'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'photos'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'show'</span>
</tt></pre></div></div>
<div class="para"><p>With this route, an incoming URL of <tt>/photos/12</tt> would be dispatched to the <tt>show</tt> action within the <tt>Photos</tt> controller.</p></div>
<div class="para"><p>You an also define other defaults in a route by supplying a hash for the <tt>:defaults</tt> option. This even applies to parameters that are not explicitly defined elsewhere in the route. For example:</p></div>
@@ -1914,7 +1914,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>map<span style="color: #990000">.</span>connect <span style="color: #FF0000">'photo/:id'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'photos'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'show'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>defaults <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>format <span style="color: #990000">=></span> <span style="color: #FF0000">'jpg'</span> <span style="color: #FF0000">}</span>
+<pre><tt>map<span style="color: #990000">.</span>connect <span style="color: #FF0000">'photos/:id'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">'photos'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">'show'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>defaults <span style="color: #990000">=></span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>format <span style="color: #990000">=></span> <span style="color: #FF0000">'jpg'</span> <span style="color: #FF0000">}</span>
</tt></pre></div></div>
<div class="para"><p>With this route, an incoming URL of <tt>photos/12</tt> would be dispatched to the <tt>show</tt> action within the <tt>Photos</tt> controller, and <tt>params[:format]</tt> will be set to <tt>jpg</tt>.</p></div>
<h3 id="_named_routes_2">4.6. Named Routes</h3>
@@ -2056,7 +2056,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>map<span style="color: #990000">.</span>index <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">"pages"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"main"</span>
+<pre><tt>map<span style="color: #990000">.</span>index <span style="color: #FF0000">'index'</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=></span> <span style="color: #FF0000">"pages"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=></span> <span style="color: #FF0000">"main"</span>
map<span style="color: #990000">.</span>root <span style="color: #990000">:</span>index
</tt></pre></div></div>
<div class="para"><p>Because of the top-down processing of the file, the named route must be specified <em>before</em> the call to <tt>map.root</tt>.</p></div>
diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt index 1e5c21f913..6aa9fa19ce 100644 --- a/railties/doc/guides/source/2_2_release_notes.txt +++ b/railties/doc/guides/source/2_2_release_notes.txt @@ -265,7 +265,7 @@ map.resources :products, :except => :destroy === Other Action Controller Changes * You can now easily link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[show a custom error page] for exceptions raised while routing a request. -* 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+. +* 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.use_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). @@ -365,11 +365,11 @@ Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck * Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes. * The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax. * +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons. -* +Array#second+ through +Array#tenth+ as aliases for +Array#[1]+ through +Array#[9]+ +* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+ * +Enumerable#many?+ to encapsulate +collection.size > 1+ * +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. +* The included TzInfo library has been upgraded to version 0.3.12. * +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+ == Railties @@ -381,7 +381,7 @@ In Railties (the core code of Rails itself) the biggest changes are in the +conf To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands: * +config.gem _gem_name_+ in your +config/environment.rb+ file -* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed or frozen +* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen) * +rake gems:install+ to install missing gems to the computer * +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+ * +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+ @@ -394,6 +394,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the com * 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] + - link:http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128[Detailed discussion on Lighthouse] === Other Railties Changes diff --git a/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/railties/doc/guides/source/actioncontroller_basics/cookies.txt index 88b99de3ee..9c30d29db4 100644 --- a/railties/doc/guides/source/actioncontroller_basics/cookies.txt +++ b/railties/doc/guides/source/actioncontroller_basics/cookies.txt @@ -31,4 +31,4 @@ class CommentsController < ApplicationController end ----------------------------------------- -Note that while for session values, you set the key to `nil`, to delete a cookie value, you should use `cookies.delete(:key)`. +Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`. diff --git a/railties/doc/guides/source/actioncontroller_basics/filters.txt b/railties/doc/guides/source/actioncontroller_basics/filters.txt index df67977efd..09a4bdf4f6 100644 --- a/railties/doc/guides/source/actioncontroller_basics/filters.txt +++ b/railties/doc/guides/source/actioncontroller_basics/filters.txt @@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base end --------------------------------- -In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter` : +In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter`: [source, ruby] --------------------------------- @@ -49,7 +49,7 @@ class LoginsController < Application end --------------------------------- -Now, the +LoginsController+'s "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` 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. +Now, the LoginsController's `new` and `create` actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` 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. === After Filters and Around Filters === diff --git a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt index e29f631038..0013492b73 100644 --- a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +++ b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt @@ -1,6 +1,6 @@ == Parameter Filtering == -Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": +Rails keeps a log file for each environment (development, test and production) in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": [source, ruby] ------------------------- @@ -11,4 +11,4 @@ class ApplicationController < ActionController::Base end ------------------------- -The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true. +The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true. diff --git a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt index 07a8ec2574..846c24052d 100644 --- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt +++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt @@ -7,13 +7,13 @@ In every controller there are two accessor methods pointing to the request and t The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are: * host - The hostname used for this request. - * domain - The hostname without the first segment (usually "www"). + * domain(n=2) - The hostname's first `n` segments, starting from the right (the TLD) * format - The content type requested by the client. * method - The HTTP method used for the request. - * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head. + * get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD. * headers - Returns a hash containing the headers associated with the request. * port - The port number (integer) used for the request. - * protocol - The protocol used for the request. + * protocol - Returns a string containing the prototol used plus "://", for example "http://" * query_string - The query string part of the URL - everything after "?". * remote_ip - The IP address of the client. * url - The entire URL used for the request. diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt index dc8ebe6d55..2a930835ee 100644 --- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt +++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt @@ -52,7 +52,7 @@ This will read and stream the file 4Kb at the time, avoiding loading the entire WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see. -TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. +TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the `:x_sendfile` option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the `X-Sendfile` header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files. === RESTful Downloads === diff --git a/railties/doc/guides/source/actioncontroller_basics/verification.txt b/railties/doc/guides/source/actioncontroller_basics/verification.txt index 5d8ee6117e..a4522a0102 100644 --- a/railties/doc/guides/source/actioncontroller_basics/verification.txt +++ b/railties/doc/guides/source/actioncontroller_basics/verification.txt @@ -25,7 +25,7 @@ class LoginsController < ApplicationController end --------------------------------------- -Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter: +Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the `new` action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter: [source, ruby] --------------------------------------- diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index fd6eb86b0b..0c82f24e66 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -7,7 +7,7 @@ After reading this guide and trying out the presented concepts, we hope that you * Correctly use all the built-in Active Record validation helpers * Create your own custom validation methods -* Work with the error messages generated by the validation proccess +* Work with the error messages generated by the validation process * Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved. * Create special classes that encapsulate common behaviour for your callbacks * Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations. @@ -47,7 +47,9 @@ We can see how it works by looking at the following script/console output: => false ------------------------------------------------------------------ -Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. +Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. + +CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state. === The meaning of 'valid' @@ -301,7 +303,7 @@ There are some common options that all the validation helpers can use. Here they === The +:allow_nil+ option -You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+. +You may use the +:allow_nil+ option everytime you want to trigger a validation only if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+. [source, ruby] ------------------------------------------------------------------ @@ -382,7 +384,7 @@ class Invoice < ActiveRecord::Base end ------------------------------------------------------------------ -If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names. +If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names. [source, ruby] ------------------------------------------------------------------ @@ -399,6 +401,284 @@ class Invoice < ActiveRecord::Base end ------------------------------------------------------------------ +== Using the +errors+ collection + +You can do more than just call +valid?+ upon your objects based on the existance of the +errors+ collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state. + +* +add_to_base+ lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. +add_to_base+ receives a string with the message. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add_to_base("This person is invalid because ...") + end +end +------------------------------------------------------------------ + +* +add+ lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. +add+ receives a symbol with the name of the attribute that you want to add the message to and the message itself. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add(:name, "can't have the characters !@#$%*()_-+=") + end +end +------------------------------------------------------------------ + +* +invalid?+ is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name, :email +end + +person = Person.new(:name => "John Doe") +person.invalid?(:email) # => true +------------------------------------------------------------------ + +* +on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new(:name => "John Doe") +person.valid? # => true +person.errors.on(:name) # => nil + +person = Person.new(:name => "JD") +person.valid? # => false +person.errors.on(:name) # => "is too short (minimum is 3 characters)" + +person = Person.new +person.valid? # => false +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +------------------------------------------------------------------ + +* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new +puts person.valid? # => false +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +person.errors.clear +person.errors # => nil +------------------------------------------------------------------ + +== Callbacks + +Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database. + +=== Callbacks registration + +In order to use the available callbacks, you need to registrate them. There are two ways of doing that. + +=== Registering callbacks by overriding the callback methods + +You can specify the callback method directly, by overriding it. Let's see how it works using the +before_validation+ callback, which will surprisingly run right before any validation is done. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + protected + def before_validation + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +=== Registering callbacks by using macro-style class methods + +The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that: + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_validation :ensure_login_has_a_value + + protected + def ensure_login_has_a_value + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_create {|user| user.name = user.login.capitalize if user.name.blank?} +end +------------------------------------------------------------------ + +In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are: + +* You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +* Readability, since your callback declarations will live at the beggining of your models' files. + +CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details. + +== Available callbacks + +Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations. + +=== Callbacks called both when creating or updating a record. + +* +before_validation+ +* +after_validation+ +* +before_save+ +* *INSERT OR UPDATE OPERATION* +* +after_save+ + +=== Callbacks called only when creating a new record. + +* +before_validation_on_create+ +* +after_validation_on_create+ +* +before_create+ +* *INSERT OPERATION* +* +after_create+ + +=== Callbacks called only when updating an existing record. + +* +before_validation_on_update+ +* +after_validation_on_update+ +* +before_update+ +* *UPDATE OPERATION* +* +after_update+ + +=== Callbacks called when removing a record from the database. + +* +before_destroy+ +* *DELETE OPERATION* +* +after_destroy+ + +The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database. + +=== The +after_initialize+ and +after_find+ callbacks + +The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by direcly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method. + +The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it. + +The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries. + +== Halting Execution + +As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. + +== Callback classes + +Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them. + +Here's an example where we create a class with a after_destroy callback for a PictureFile model. + +[source, ruby] +------------------------------------------------------------------ +class PictureFileCallbacks + def after_destroy(picture_file) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) + end +end +------------------------------------------------------------------ + +When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way: + +[source, ruby] +------------------------------------------------------------------ +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks.new +end +------------------------------------------------------------------ + +Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method. + +[source, ruby] +------------------------------------------------------------------ +class PictureFileCallbacks + def self.after_destroy(picture_file) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) + end +end +------------------------------------------------------------------ + +If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object. + +[source, ruby] +------------------------------------------------------------------ +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks +end +------------------------------------------------------------------ + +You can declare as many callbacks as you want inside your callback classes. + +== Observers + +Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that's not directly related to the model's purpose. In object-oriented software, it's always a good idea to design your classes with a single responsability in the whole system. For example, it wouldn't make much sense to have a +User+ model with a method that writes data about a login attempt to a log file. Whenever you're using callbacks to write code that's not directly related to your model class purposes, it may be a good moment to create an Observer. + +An Active Record Observer is an object that links itself to a model and register it's methods for callbacks. Your model's implementation remain clean, while you can reuse the code in the Observer to add behaviuor to more than one model class. Ok, you may say that we can also do that using callback classes, but it would still force us to add code to our model's implementation. + +Observer classes are subclasses of the +ActiveRecord::Observer+ class. When this class is subclassed, Active Record will look at the name of the new class and then strip the 'Observer' part to find the name of the Active Record class to observe. + +Consider a +Registration+ model, where we want to send an email everytime a new registration is created. Since sending emails is not directly related to our model's purpose, we could create an Observer to do just that: + +[source, ruby] +------------------------------------------------------------------ +class RegistrationObserver < ActiveRecord::Observer + def after_create(model) + # code to send registration confirmation emails... + end +end +------------------------------------------------------------------ + +Like in callback classes, the observer's methods receive the observed model as a parameter. + +Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe. + +[source, ruby] +------------------------------------------------------------------ +class Auditor < ActiveRecord::Observer + observe User, Registration, Invoice +end +------------------------------------------------------------------ + +=== Registering observers + +If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up. + +[source, ruby] +------------------------------------------------------------------ +# Activate observers that should always be running +config.active_record.observers = :registration_observer, :auditor +------------------------------------------------------------------ + +=== Where to put the observers' source files + +By convention, you should always save your observers' source files inside *app/models*. + == Changelog http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt index 5ba616642b..95d7397558 100644 --- a/railties/doc/guides/source/association_basics.txt +++ b/railties/doc/guides/source/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" - belongs_to :manager, :class_name => "User" + has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" end ------------------------------------------------------- @@ -396,7 +396,11 @@ You are not free to use just any name for your associations. Because creating an === Updating the Schema -Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate: +Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table. + +==== Creating Foreign Keys for +belongs_to+ Associations + +When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model: [source, ruby] ------------------------------------------------------- @@ -412,9 +416,9 @@ This declaration needs to be backed up by the proper foreign key declaration on class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| - t.order_date :datetime - t.order_number :string - t.customer_id :integer + t.datetime :order_date + t.string :order_number + t.integer :customer_id end end @@ -426,7 +430,9 @@ end If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key. -Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. +==== Creating Join Tables for +has_and_belongs_to_many+ Associations + +If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers". @@ -1330,7 +1336,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ @@ -1698,7 +1704,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ diff --git a/railties/doc/guides/source/authors.txt b/railties/doc/guides/source/authors.txt index 94dfc4db08..987238eb4c 100644 --- a/railties/doc/guides/source/authors.txt +++ b/railties/doc/guides/source/authors.txt @@ -37,3 +37,9 @@ Heiko has rarely looked back. Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog http://tore.darell.no/[Sneaky Abstractions]. *********************************************************** + +.Jeff Dean +[[zilkey]] +*********************************************************** +Jeff Dean is a software engineer with http://pivotallabs.com/[Pivotal Labs]. +*********************************************************** diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index e680b79d55..16dac19e08 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -10,8 +10,8 @@ need to return to those hungry web clients in the shortest time possible. This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins. -To get started make sure config.action_controller.perform_caching is set -to true for your environment. This flag is normally set in the +To get started make sure `config.action_controller.perform_caching` is set +to `true` for your environment. This flag is normally set in the corresponding config/environments/*.rb and caching is disabled by default there for development and test, and enabled for production. @@ -45,21 +45,21 @@ end ----------------------------------------------------- The first time anyone requests products/index, Rails will generate a file -called index.html and the webserver will then look for that file before it +called `index.html` and the webserver will then look for that file before it passes the next request for products/index to your Rails application. By default, the page cache directory is set to Rails.public_path (which is -usually set to RAILS_ROOT + "/public") and this can be configured by -changing the configuration setting ActionController::Base.page_cache_directory. Changing the -default from /public helps avoid naming conflicts, since you may want to -put other static html in /public, but changing this will require web -server reconfiguration to let the web server know where to serve the -cached files from. - -The Page Caching mechanism will automatically add a .html exxtension to +usually set to `RAILS_ROOT + "/public"`) and this can be configured by +changing the configuration setting `config.action_controller.page_cache_directory`. +Changing the default from /public helps avoid naming conflicts, since you may +want to put other static html in /public, but changing this will require web +server reconfiguration to let the web server know where to serve the cached +files from. + +The Page Caching mechanism will automatically add a `.html` exxtension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the -configuration setting ActionController::Base.page_cache_extension. +configuration setting `config.action_controller.page_cache_extension`. In order to expire this page when a new product is added we could extend our example controler like this: @@ -119,8 +119,8 @@ class ProductsController < ActionController end ----------------------------------------------------- -And you can also use :if (or :unless) to pass a Proc that specifies when the -action should be cached. Also, you can use :layout => false to cache without +And you can also use `:if` (or `:unless`) to pass a Proc that specifies when the +action should be cached. Also, you can use `:layout => false` to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2. @@ -164,7 +164,7 @@ could use this piece of code: The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you -want to cache multiple fragments per action, you should provide an action_suffix to the cache call: +want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call: [source, ruby] ----------------------------------------------------- @@ -172,11 +172,29 @@ want to cache multiple fragments per action, you should provide an action_suffix All available products: ----------------------------------------------------- -and you can expire it using the expire_fragment method, like so: +and you can expire it using the `expire_fragment` method, like so: [source, ruby] ----------------------------------------------------- -expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products) +expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products) +----------------------------------------------------- + +If you don't want the cache block to bind to the action that called it, You can +also use globally keyed fragments by calling the cache method with a key, like +so: + +[source, ruby] +----------------------------------------------------- +<% cache(:key => ['all_available_products', @latest_product.created_at].join(':')) do %> + All available products: +----------------------------------------------------- + +This fragment is then available to all actions in the ProductsController using +the key and can be expired the same way: + +[source, ruby] +----------------------------------------------------- +expire_fragment(:key => ['all_available_products', @latest_product.created_at].join(':')) ----------------------------------------------------- [More: more examples? description of fragment keys and expiration, etc? pagination?] @@ -185,7 +203,7 @@ expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix = Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code by moving all the work -required to expire cached content into a ActionController::Caching::Sweeper +required to expire cached content into a `ActionController::Caching::Sweeper` class that is an Observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object n an around or after filter. @@ -340,8 +358,7 @@ ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" ----------------------------------------------------- 4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead. - Requires the ruby-memcache library: - gem install ruby-memcache. + Rails uses the bundled memcached-client gem by default. [source, ruby] ----------------------------------------------------- @@ -355,6 +372,68 @@ ActionController::Base.cache_store = :mem_cache_store, "localhost" ActionController::Base.cache_store = MyOwnStore.new("parameter") ----------------------------------------------------- ++Note: config.cache_store can be used in place of +ActionController::Base.cache_store in your Rails::Initializer.run block in +environment.rb+ + +== Conditional GET support + +Conditional GETs are a facility of the HTTP spec that provide a way for web +servers to tell browsers that the response to a GET request hasn’t changed +since the last request and can be safely pulled from the browser cache. + +They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to +pass back and forth both a unique content identifier and the timestamp of when +the content was last changed. If the browser makes a request where the content +identifier (etag) or last modified since timestamp matches the server’s version +then the server only needs to send back an empty response with a not modified +status. + +It is the server’s (i.e. our) responsibility to look for a last modified +timestamp and the if-none-match header and determine whether or not to send +back the full response. With conditional-get support in rails this is a pretty +easy task: + +[source, ruby] +----------------------------------------------------- +class ProductsController < ApplicationController + + def show + @product = Product.find(params[:id]) + + # If the request is stale according to the given timestamp and etag value + # (i.e. it needs to be processed again) then execute this block + if stale?(:last_modified => @product.updated_at.utc, :etag => @product) + respond_to do |wants| + # ... normal response processing + end + end + + # If the request is fresh (i.e. it's not modified) then you don't need to do + # anything. The default render checks for this using the parameters + # used in the previous call to stale? and will automatically send a + # :not_modified. So that's it, you're done. +end +----------------------------------------------------- + +If you don’t have any special response processing and are using the default +rendering mechanism (i.e. you’re not using respond_to or calling render +yourself) then you’ve got an easy helper in fresh_when: + +[source, ruby] +----------------------------------------------------- +class ProductsController < ApplicationController + + # This will automatically send back a :not_modified if the request is fresh, + # and will render the default template (product.*) if it's stale. + + def show + @product = Product.find(params[:id]) + fresh_when :last_modified => @product.published_at.utc, :etag => @article + end +end +----------------------------------------------------- + == Advanced Caching Along with the built-in mechanisms outlined above, a number of excellent diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt index 5f7c6ceff5..1ad2e75c51 100644 --- a/railties/doc/guides/source/command_line.txt +++ b/railties/doc/guides/source/command_line.txt @@ -99,7 +99,7 @@ Using generators will save you a large amount of time by writing *boilerplate co Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: -NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`. +NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`. [source,shell] ------------------------------------------------------ @@ -143,5 +143,111 @@ $ ./script/generate controller Greeting hello create app/views/greetings/hello.html.erb ------------------------------------------------------ -Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command! +Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. +Let's check out the controller and modify it a little (in `app/controllers/greeting_controller.rb`): + +[source,ruby] +------------------------------------------------------ +class GreetingController < ApplicationController + def hello + @message = "Hello, how are you today? I am exuberant!" + end + +end +------------------------------------------------------ + +Then the view, to display our nice message (in `app/views/greeting/hello.html.erb`): + +[source,html] +------------------------------------------------------ +<h1>A Greeting for You!</h1> +<p><%= @message %></p> +------------------------------------------------------ + +Deal. Go check it out in your browser. Fire up your server. Remember? `./script/server` at the root of your Rails application should do it. + +[source,shell] +------------------------------------------------------ +$ ./script/server +=> Booting WEBrick... +------------------------------------------------------ + +The URL will be `http://localhost:3000/greetings/hello`. I'll wait for you to be suitably impressed. + +NOTE: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the *index* action of that controller. + +"What about data, though?", you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name? + +[source,shell] +------------------------------------------------------ +$ ./script/generate model +Usage: ./script/generate model ModelName [field:type, field:type] + +... + +Examples: + `./script/generate model account` + + creates an Account model, test, fixture, and migration: + Model: app/models/account.rb + Test: test/unit/account_test.rb + Fixtures: test/fixtures/accounts.yml + Migration: db/migrate/XXX_add_accounts.rb + + `./script/generate model post title:string body:text published:boolean` + + creates a Post model with a string title, text body, and published flag. +------------------------------------------------------ + +Let's set up a simple model called "HighScore" that will keep track of our highest score on video games we play. Then we'll wire up our controller and view to modify and list our scores. + +[source,shell] +------------------------------------------------------ +$ ./script/generate model HighScore id:integer game:string score:integer + exists app/models/ + exists test/unit/ + exists test/fixtures/ + create app/models/high_score.rb + create test/unit/high_score_test.rb + create test/fixtures/high_scores.yml + create db/migrate + create db/migrate/20081126032945_create_high_scores.rb +------------------------------------------------------ + +Taking it from the top, we have the *models* directory, where all of your data models live. *test/unit*, where all the unit tests live (gasp! -- unit tests!), fixtures for those tests, a test, the *migrate* directory, where the database-modifying migrations live, and a migration to create the `high_scores` table with the right fields. + +The migration requires that we *migrate*, that is, run some Ruby code (living in that `20081126032945_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. + +[source,shell] +------------------------------------------------------ +$ rake db:migrate +(in /home/commandsapp) +== CreateHighScores: migrating =============================================== +-- create_table(:high_scores) + -> 0.0070s +== CreateHighScores: migrated (0.0077s) ====================================== +------------------------------------------------------ + +NOTE: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment. + +Yo! Let's shove a small table into our greeting controller and view, listing our sweet scores. + +[source,ruby] +------------------------------------------------------ +class GreetingController < ApplicationController + def hello + if request.post? + score = HighScore.new(params[:high_score]) + if score.save + flash[:notice] = "New score posted!" + end + end + + @scores = HighScore.find(:all) + end + +end +------------------------------------------------------ + +XXX: Go with scaffolding instead, modifying greeting controller for high scores seems dumb. diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt index 07b630c59d..945e48cd45 100644 --- a/railties/doc/guides/source/configuring.txt +++ b/railties/doc/guides/source/configuring.txt @@ -16,210 +16,179 @@ after-initializer == Using a Preinitializer +== Initialization Process Settings + == Configuring Rails Components === Configuring Active Record ++ActiveRecord::Base+ includej a variety of configuration options: + ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an ActiveRecord model class or an ActiveRecord model instance. Set to nil to disable logging. + ++primary_key_prefix_type+ lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named +id+ (and this configuration option doesn't need to be set.) There are two other choices: + +* +:table_name+ would make the primary key for the Customer class +customerid+ +* +:table_name_with_underscore+ would make the primary key for the Customer class +customer_id+ + ++table_name_prefix+ lets you set a global string to be prepended to table names. If you set this to +northwest_+, then the Customer class will look for +northwest_customers+ as its table. The default is an empty string. + ++table_name_suffix+ lets you set a global string to be appended to table names. If you set this to +_northwest+, then the Customer class will look for +customers_northwest+ as its table. The default is an empty string. + ++pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table. + ++colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord. + ++default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+. + ++schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements. + ++timestamped_migrations+ controls whether migrations are numbered with serial integers or with timestamps. The default is +true+, to use timestamps, which are preferred if there are multiple developers working on the same application. + ++lock_optimistically+ controls whether ActiveRecord will use optimistic locking. By default this is +true+. + +The MySQL adapter adds one additional configuration option: + ++ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether ActiveRecord will consider all +tinyint(1)+ columns in a MySQL database to be booleans. By default this is +true+. + +The schema dumper adds one additional configuration option: + ++ActiveRecord::SchemaDumper.ignore_tables+ accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless +ActiveRecord::Base.schema_format == :ruby+. + === Configuring Action Controller -=== Configuring Action View +ActionController::Base includes a number of configuration settings: -=== Configuring Action Mailer ++asset_host+ provides a string that is prepended to all of the URL-generating helpers in +AssetHelper+. This is designed to allow moving all javascript, CSS, and image files to a separate asset host. -=== Configuring Active Resource ++consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ to specify which requests should provide debugging information on errors. -=== Configuring Active Support ++allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +false+ by default. -== Using Initializers - organization, controlling load order ++param_parsers+ provides an array of handlers that can extract information from incoming HTTP requests and add it to the +params+ hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active. -== Using an After-Initializer ++default_charset+ specifies the default character set for all renders. The default is "utf-8". -== Changelog == ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. -http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] ++resource_action_separator+ gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/". -* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] ++resource_path_names+ is a hash of default names for several RESTful actions. By default, the new action is named +new+ and the edit action is named +edit+. + ++request_forgery_protection_token+ sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ sets it to +:authenticity_token+ by default. ++optimise_named_routes+ turns on some optimizations in generating the routing table. It is set to +true+ by default. -actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables - -actionmailer/Rakefile -36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root - -actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension - -actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching - -actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path - -actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types ++use_accept_header+ sets the rules for determining the response format. If this is set to +true+ (the default) then +respond_to+ and +Request#format+ will take the Accept header into account. If it is set to false then the request format will be determined solely by examining +params[:format]+. If there is no +format+ parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request. -actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates ++allow_forgery_protection+ enables or disables CSRF protection. By default this is +false+ in test mode and +true+ in all other modes. -actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class - -actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer => false - -actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses - -actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc - -actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder - -actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode ++relative_url_root+ can be used to tell Rails that you are deploying to a subdirectory. The default is +ENV['RAILS_RELATIVE_URL_ROOT']+. -actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected +The caching code adds two additional settings: -actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log ++ActionController::Caching::Pages.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +RAILS_ROOT + "/public"+). -actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones ++ActionController::Caching::Pages.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+. -activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages +The dispatcher includes one setting: -activemodel/Rakefile -19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' ++ActionController::Dispatcher.error_file_path+ gives the path where Rails will look for error files such as +404.html+. The default is +Rails.public_path+. -activerecord/lib/active_record/attribute_methods.rb -9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false -11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false +The Active Record session store can also be configured: -activerecord/lib/active_record/base.rb -394: cattr_accessor :logger, :instance_writer => false -443: cattr_accessor :configurations, :instance_writer => false -450: cattr_accessor :primary_key_prefix_type, :instance_writer => false -456: cattr_accessor :table_name_prefix, :instance_writer => false -461: cattr_accessor :table_name_suffix, :instance_writer => false -467: cattr_accessor :pluralize_table_names, :instance_writer => false -473: cattr_accessor :colorize_logging, :instance_writer => false -478: cattr_accessor :default_timezone, :instance_writer => false -487: cattr_accessor :schema_format , :instance_writer => false -491: cattr_accessor :timestamped_migrations , :instance_writer => false ++CGI::Session::ActiveRecordStore::Session.data_column_name+ sets the name of the column to use to store session data. By default it is 'data' -activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb -11: cattr_accessor :connection_handler, :instance_writer => false +=== Configuring Action View + +There are only a few configuration options for Action View, starting with four on +ActionView::Base+: + ++debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+. + ++warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+. + ++field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is +Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }+ + ++default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. + +The ERB template handler supplies one additional option: + ++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the link:http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/[ERB documentation] for more information. + +=== Configuring Action Mailer + +There are a number of settings available on +ActionMailer::Base+: + ++template_root+ gives the root folder for Action Mailer templates. + ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging. + ++smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: -activerecord/lib/active_record/connection_adapters/mysql_adapter.rb -166: cattr_accessor :emulate_booleans +* <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +* <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it. +* <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here. +* <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting. +* <tt>:password</tt> - If your mail server requires authentication, set the password in this setting. +* <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>. -activerecord/lib/active_record/fixtures.rb -498: cattr_accessor :all_loaded_fixtures ++sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: -activerecord/lib/active_record/locking/optimistic.rb -38: base.cattr_accessor :lock_optimistically, :instance_writer => false +* <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>. +* <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>. -activerecord/lib/active_record/migration.rb -259: cattr_accessor :verbose ++raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+. -activerecord/lib/active_record/schema_dumper.rb -13: cattr_accessor :ignore_tables ++delivery_method+ defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>. -activerecord/lib/active_record/serializers/json_serializer.rb -4: base.cattr_accessor :include_root_in_json, :instance_writer => false ++perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. -activerecord/Rakefile -142: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' ++default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. -activerecord/test/cases/lifecycle_test.rb -61: cattr_reader :last_inherited ++default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" -activerecord/test/cases/mixin_test.rb -9: cattr_accessor :forced_now_time ++default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. -activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger ++default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates +which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message. -activeresource/Rakefile -43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' +=== Configuring Active Resource + +There is a single configuration setting available on +ActiveResource::Base+: + ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging. + +=== Configuring Active Support + +There are a few configuration options available in Active Support: + ++ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer ++ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. -activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger ++ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms) +=== Configuring Active Model -activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer +Active Model currently has a single configuration setting: -activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer => false ++ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages. -activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer => false +== Using Initializers + organization, controlling load order -railties/doc/guides/html/creating_plugins.html -786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field -860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field +== Using an After-Initializer -railties/lib/rails_generator/base.rb -93: cattr_accessor :logger +== Rails Environment Settings -railties/Rakefile -265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object' +ENV -railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request +== Changelog == -Rakefile -32: rdoc.options << '-A cattr_accessor=object' +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] + +* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] +need to look for def self. ??? diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index de116af7db..674f086e17 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,4 +1,4 @@ -== Add an `acts_as_yaffle` method to Active Record == +== Add an 'acts_as' method to Active Record == A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index a78890ccd5..340c03dd4e 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -1,46 +1,104 @@ == Appendix == +If you prefer to use RSpec instead of Test::Unit, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. + === References === * http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i * http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii * http://github.com/technoweenie/attachment_fu/tree/master * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html + * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins + * http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. + +=== Contents of 'lib/yaffle.rb' === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +require "yaffle/core_ext" +require "yaffle/acts_as_yaffle" +require "yaffle/commands" +require "yaffle/routing" + +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +# optionally: +# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| +# require file +# end + +---------------------------------------------- + === Final plugin directory structure === The final plugin should have a directory structure that looks something like this: ------------------------------------------------ - |-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db +|-- MIT-LICENSE +|-- README +|-- Rakefile +|-- generators +| |-- yaffle_definition +| | |-- USAGE +| | |-- templates +| | | `-- definition.txt +| | `-- yaffle_definition_generator.rb +| |-- yaffle_migration +| | |-- USAGE +| | |-- templates +| | `-- yaffle_migration_generator.rb +| `-- yaffle_route +| |-- USAGE +| |-- templates +| `-- yaffle_route_generator.rb +|-- install.rb +|-- lib +| |-- app +| | |-- controllers +| | | `-- woodpeckers_controller.rb +| | |-- helpers +| | | `-- woodpeckers_helper.rb +| | `-- models +| | `-- woodpecker.rb +| |-- db +| | `-- migrate +| | `-- 20081116181115_create_birdhouses.rb +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | |-- core_ext.rb +| | `-- routing.rb +| `-- yaffle.rb +|-- pkg +| `-- yaffle-0.0.1.gem +|-- rails +| `-- init.rb +|-- tasks +| `-- yaffle_tasks.rake +|-- test +| |-- acts_as_yaffle_test.rb +| |-- core_ext_test.rb +| |-- database.yml +| |-- debug.log +| |-- definition_generator_test.rb +| |-- migration_generator_test.rb +| |-- route_generator_test.rb +| |-- routes_test.rb +| |-- schema.rb +| |-- test_helper.rb +| |-- woodpecker_test.rb +| |-- woodpeckers_controller_test.rb +| |-- wookpeckers_helper_test.rb +| |-- yaffle_plugin.sqlite3.db +| `-- yaffle_test.rb +`-- uninstall.rb ------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index ee408adb1d..7afdef032d 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -1,10 +1,10 @@ -== Add a controller == +== Controllers == This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. You can test your plugin's controller as you would test any other controller: -*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:* +*vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* [source, ruby] ---------------------------------------------- @@ -19,6 +19,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase @controller = WoodpeckersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new + + ActionController::Routing::Routes.draw do |map| + map.resources :woodpeckers + end end def test_index diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index ca8efc3df1..cbedb9eaf2 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -1,11 +1,6 @@ == Extending core classes == -This section will explain how to add a method to String that will be available anywhere in your rails app by: - - * Writing tests for the desired behavior - * Creating and requiring the correct files - -=== Creating the test === +This section will explain how to add a method to String that will be available anywhere in your rails app. In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: @@ -40,26 +35,6 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String Great - now you are ready to start development. -=== Organize your files === - -A common pattern in rails plugins is to set up the file structure like this: - --------------------------------------------------------- -|-- lib -| |-- yaffle -| | `-- core_ext.rb -| `-- yaffle.rb --------------------------------------------------------- - -The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb': - -*vendor/plugins/yaffle/rails/init.rb* - -[source, ruby] --------------------------------------------------------- -require 'yaffle' --------------------------------------------------------- - Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': *vendor/plugins/yaffle/lib/yaffle.rb* @@ -92,13 +67,13 @@ $ ./script/console === Working with init.rb === -When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. +When rails loads plugins it looks for the file named 'init.rb' or 'rails/init.rb'. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above. If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- @@ -111,7 +86,7 @@ end Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/gems.txt b/railties/doc/guides/source/creating_plugins/gems.txt new file mode 100644 index 0000000000..67d55adb3a --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/gems.txt @@ -0,0 +1,50 @@ +== PluginGems == + +Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. + +Historically rails plugins loaded the plugin's 'init.rb' file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, 'init.rb' was moved to 'rails/init.rb'. + +It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in 'Rakefile'. A rake task that packages the gem might look like this: + +*vendor/plugins/yaffle/Rakefile:* + +[source, ruby] +---------------------------------------------- +PKG_FILES = FileList[ + '[a-zA-Z]*', + 'generators/**/*', + 'lib/**/*', + 'rails/**/*', + 'tasks/**/*', + 'test/**/*' +] + +spec = Gem::Specification.new do |s| + s.name = "yaffle" + s.version = "0.0.1" + s.author = "Gleeful Yaffler" + s.email = "yaffle@example.com" + s.homepage = "http://yafflers.example.com/" + s.platform = Gem::Platform::RUBY + s.summary = "Sharing Yaffle Goodness" + s.files = PKG_FILES.to_a + s.require_path = "lib" + s.has_rdoc = false + s.extra_rdoc_files = ["README"] +end + +desc 'Turn this plugin into a gem.' +Rake::GemPackageTask.new(spec) do |pkg| + pkg.gem_spec = spec +end +---------------------------------------------- + +To build and install the gem locally, run the following commands: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake gem +sudo gem install pkg/yaffle-0.0.1.gem +---------------------------------------------- + +To test this, create a new rails app, add 'config.gem "yaffle"' to environment.rb and all of your plugin's functionality will be available to you.
\ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt new file mode 100644 index 0000000000..f60ea3d8f1 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -0,0 +1,144 @@ +== Generator Commands == + +You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. + +To start, add the following test method: + +*vendor/plugins/yaffle/test/route_generator_test.rb* + +[source, ruby] +----------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class RouteGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_match /map\.yaffles/, File.read(routes_path) + end + + def test_destroys_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.yaffles + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_no_match /map\.yaffles/, File.read(routes_path) + end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + +end +----------------------------------------------------------- + +Run `rake` to watch the test fail, then make the test pass add the following: + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +----------------------------------------------------------- +require "yaffle/commands" +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/yaffle/commands.rb* + +[source, ruby] +----------------------------------------------------------- +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_route + logger.route "map.yaffle" + look_for = 'ActionController::Routing::Routes.draw do |map|' + unless options[:pretend] + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} + end + end + end + + module Destroy + def yaffle_route + logger.route "map.yaffle" + gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' + end + end + + module List + def yaffle_route + end + end + + module Update + def yaffle_route + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +----------------------------------------------------------- + +*vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb* + +[source, ruby] +----------------------------------------------------------- +class YaffleRouteGenerator < Rails::Generator::Base + def manifest + record do |m| + m.yaffle_route + end + end +end +----------------------------------------------------------- + +To see this work, type: + +----------------------------------------------------------- +./script/generate yaffle_route +./script/destroy yaffle_route +----------------------------------------------------------- + +.Editor's note: +NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually.
\ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt new file mode 100644 index 0000000000..f856bec7a2 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -0,0 +1,98 @@ +== Generators == + +Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. + +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. + +=== Testing generators === + +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator + * Asserts that the correct files were generated + * Removes the fake rails root + +This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: + +*vendor/plugins/yaffle/test/definition_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class DefinitionGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_equal "definition.txt", File.basename(new_file) + end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + +end +------------------------------------------------------------------ + +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +To make it pass, create the generator: + +*vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +class YaffleDefinitionGenerator < Rails::Generator::Base + def manifest + record do |m| + m.file "definition.txt", "definition.txt" + end + end +end +------------------------------------------------------------------ + +=== The USAGE file === + +If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +------------------------------------------------------------------ +./script/generate +------------------------------------------------------------------ + +You should see something like this: + +------------------------------------------------------------------ +Installed Generators + Plugins (vendor/plugins): yaffle_definition + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +------------------------------------------------------------------ + +When you run `script/generate yaffle_definition -h` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. + +For this plugin, update the USAGE file could look like this: + +------------------------------------------------------------------ +Description: + Adds a file with the definition of a Yaffle to the app's main directory +------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt index 51b4cebb01..fa4227be41 100644 --- a/railties/doc/guides/source/creating_plugins/helpers.txt +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -1,4 +1,4 @@ -== Add a helper == +== Helpers == This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. @@ -30,8 +30,6 @@ This is just a simple test to make sure the helper is being loaded correctly. A ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) end - -ActionView::Base.send :include, WoodpeckersHelper ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 19484e2830..0607bc7487 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,24 +29,32 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::test_setup.txt[] +include::setup.txt[] + +include::tests.txt[] include::core_ext.txt[] include::acts_as_yaffle.txt[] -include::migration_generator.txt[] - -include::generator_method.txt[] - include::models.txt[] include::controllers.txt[] include::helpers.txt[] -include::custom_route.txt[] +include::routes.txt[] + +include::generators.txt[] + +include::generator_commands.txt[] + +include::migrations.txt[] + +include::tasks.txt[] + +include::gems.txt[] -include::odds_and_ends.txt[] +include::rdoc.txt[] include::appendix.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt deleted file mode 100644 index f4fc32481c..0000000000 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ /dev/null @@ -1,156 +0,0 @@ -== Create a generator == - -Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. - -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. - -To create a generator you must: - - * Add your instructions to the 'manifest' method of the generator - * Add any necessary template files to the templates directory - * Test the generator manually by running various combinations of `script/generate` and `script/destroy` - * Update the USAGE file to add helpful documentation for your generator - -=== Testing generators === - -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: - - * Creates a new fake rails root directory that will serve as destination - * Runs the generator forward and backward, making whatever assertions are necessary - * Removes the fake rails root - -For the generator in this section, the test could look something like this: - -*vendor/plugins/yaffle/test/yaffle_generator_test.rb* - -[source, ruby] ------------------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' - -class GeneratorTest < Test::Unit::TestCase - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_bird/, new_file - end - -end ------------------------------------------------------------------- - -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. - -=== Adding to the manifest === - -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this: - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------------- -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - end - - def yaffle_local_assigns - returning(assigns = {}) do - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - end - end -end ------------------------------------------------------------------- - -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. - -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - -=== Manually test the generator === - -To run the generator, type the following at the command line: - ------------------------------------------------------------------- -./script/generate yaffle bird ------------------------------------------------------------------- - -and you will see a new file: - -*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* - -[source, ruby] ------------------------------------------------------------------- -class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end ------------------------------------------------------------------- - - -=== The USAGE file === - -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: - ------------------------------------------------------------------- -script/generate ------------------------------------------------------------------- - -You should see something like this: - ------------------------------------------------------------------- -Installed Generators - Plugins (vendor/plugins): yaffle - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration ------------------------------------------------------------------- - -When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file. - -For this plugin, update the USAGE file looks like this: - ------------------------------------------------------------------- -Description: - Creates a migration that adds yaffle squawk fields to the given model - -Example: - ./script/generate yaffle hickwall - - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall ------------------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt new file mode 100644 index 0000000000..e7d2e09069 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -0,0 +1,213 @@ +== Migrations == + +If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. + +If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. + +Let's say you have the following migration in your plugin: + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + +Here are a few possibilities for how to allow developers to use your plugin migrations: + +=== Create a custom rake task === + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + + +*vendor/plugins/yaffle/tasks/yaffle.rake:* + +[source, ruby] +---------------------------------------------- +namespace :db do + namespace :migrate do + desc "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false." + task :yaffle => :environment do + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true + ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + end + end +end +---------------------------------------------- + +=== Call migrations directly === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| + require file +end +---------------------------------------------- + +*db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + Yaffle::CreateBirdhouses.up + end + + def self.down + Yaffle::CreateBirdhouses.down + end +end +---------------------------------------------- + +.Editor's note: +NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. + +=== Generate migrations === + +Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: + + * call your script/generate script and pass in whatever options they need + * examine the generated migration, adding/removing columns or other options as necessary + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: + +*vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class MigrationGeneratorTest < Test::Unit::TestCase + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + ActiveRecord::Base.pluralize_table_names = true + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) + end + + def test_pluralizes_properly + ActiveRecord::Base.pluralize_table_names = false + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) + end + + private + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + +end +------------------------------------------------------------------ + +.Editor's note: +NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. + +After running the test with 'rake' you can make it pass with: + +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +class YaffleMigrationGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, + :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" + } + end + end + + private + def custom_file_name + custom_name = class_name.underscore.downcase + custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + custom_name + end + + def yaffle_local_assigns + returning(assigns = {}) do + assigns[:migration_action] = "add" + assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" + assigns[:table_name] = custom_file_name + assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] + end + end +end +------------------------------------------------------------------ + +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. + +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. + +To run the generator, type the following at the command line: + +------------------------------------------------------------------ +./script/generate yaffle_migration bird +------------------------------------------------------------------ + +and you will see a new file: + +*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* + +[source, ruby] +------------------------------------------------------------------ +class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + end + + def self.down + remove_column :birds, :last_squawk + end +end +------------------------------------------------------------------ + diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt index 458edec80a..505ab44a71 100644 --- a/railties/doc/guides/source/creating_plugins/models.txt +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -1,4 +1,4 @@ -== Add a model == +== Models == This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: @@ -66,11 +66,9 @@ Finally, add the following to your plugin's 'schema.rb': [source, ruby] ---------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :woodpeckers, :force => true do |t| - t.string :name - end +create_table :woodpeckers, :force => true do |t| + t.string :name end ---------------------------------------------- -Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.
\ No newline at end of file +Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt deleted file mode 100644 index e328c04a79..0000000000 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Odds and ends == - -=== Generate RDoc Documentation === - -Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. - -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - - * Your name. - * How to install. - * How to add the functionality to the app (several examples of common use cases). - * Warning, gotchas or tips that might help save users time. - -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. - -Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. - -Once your comments are good to go, navigate to your plugin directory and run: - - rake rdoc - -=== Write custom Rake tasks in your plugin === - -When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. - -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: - -*vendor/plugins/yaffle/tasks/yaffle.rake* - -[source, ruby] ---------------------------------------------------------- -namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end -end ---------------------------------------------------------- - -When you run `rake -T` from your plugin you will see: - ---------------------------------------------------------- -yaffle:squawk # Prints out the word 'Yaffle' ---------------------------------------------------------- - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -=== Store plugins in alternate locations === - -You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'. - -Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. - -You can even store plugins inside of other plugins for complete plugin madness! - -[source, ruby] ---------------------------------------------------------- -config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") ---------------------------------------------------------- - -=== Create your own Plugin Loaders and Plugin Locators === - -If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. - - -=== Use Custom Plugin Generators === - -If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master. - diff --git a/railties/doc/guides/source/creating_plugins/rdoc.txt b/railties/doc/guides/source/creating_plugins/rdoc.txt new file mode 100644 index 0000000000..0f6f843c42 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/rdoc.txt @@ -0,0 +1,18 @@ +== RDoc Documentation == + +Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. + +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: + + * Your name + * How to install + * How to add the functionality to the app (several examples of common use cases) + * Warning, gotchas or tips that might help save users time + +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. + +Once your comments are good to go, navigate to your plugin directory and run: + +--------------------------------------------------------- +rake rdoc +--------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/routes.txt index 1fce902a4e..dc1bf09fd1 100644 --- a/railties/doc/guides/source/creating_plugins/custom_route.txt +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -1,6 +1,8 @@ -== Add a Custom Route == +== Routes == -Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. +In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. + +Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this: *vendor/plugins/yaffle/test/routing_test.rb* @@ -22,10 +24,6 @@ class RoutingTest < Test::Unit::TestCase private - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. def assert_recognition(method, path, options) result = ActionController::Routing::Routes.recognize_path(path, :method => method) assert_equal options, result @@ -33,15 +31,16 @@ class RoutingTest < Test::Unit::TestCase end -------------------------------------------------------- -*vendor/plugins/yaffle/init.rb* +Once you see the tests fail by running 'rake', you can make them pass with: + +*vendor/plugins/yaffle/lib/yaffle.rb* [source, ruby] -------------------------------------------------------- -require "routing" -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +require "yaffle/routing" -------------------------------------------------------- -*vendor/plugins/yaffle/lib/routing.rb* +*vendor/plugins/yaffle/lib/yaffle/routing.rb* [source, ruby] -------------------------------------------------------- @@ -54,6 +53,8 @@ module Yaffle #:nodoc: end end end + +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -------------------------------------------------------- *config/routes.rb* @@ -61,7 +62,6 @@ end [source, ruby] -------------------------------------------------------- ActionController::Routing::Routes.draw do |map| - ... map.yaffles end -------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt new file mode 100644 index 0000000000..cd4b6ecb04 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/setup.txt @@ -0,0 +1,84 @@ +== Setup == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +You should see the following output: + +---------------------------------------------- +create vendor/plugins/yaffle/lib +create vendor/plugins/yaffle/tasks +create vendor/plugins/yaffle/test +create vendor/plugins/yaffle/README +create vendor/plugins/yaffle/MIT-LICENSE +create vendor/plugins/yaffle/Rakefile +create vendor/plugins/yaffle/init.rb +create vendor/plugins/yaffle/install.rb +create vendor/plugins/yaffle/uninstall.rb +create vendor/plugins/yaffle/lib/yaffle.rb +create vendor/plugins/yaffle/tasks/yaffle_tasks.rake +create vendor/plugins/yaffle/test/core_ext_test.rb +create vendor/plugins/yaffle/generators +create vendor/plugins/yaffle/generators/yaffle +create vendor/plugins/yaffle/generators/yaffle/templates +create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb +create vendor/plugins/yaffle/generators/yaffle/USAGE +---------------------------------------------- + +=== Organize your files === + +To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: + +-------------------------------------------------------- +|-- lib +| |-- yaffle +| `-- yaffle.rb +`-- rails + | + `-- init.rb +-------------------------------------------------------- + +*vendor/plugins/yaffle/rails/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean.
\ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt new file mode 100644 index 0000000000..d848c2cfa1 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tasks.txt @@ -0,0 +1,27 @@ +== Rake tasks == + +When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + +*vendor/plugins/yaffle/tasks/yaffle.rake* + +[source, ruby] +--------------------------------------------------------- +namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end +end +--------------------------------------------------------- + +When you run `rake -T` from your plugin you will see: + +--------------------------------------------------------- +yaffle:squawk # Prints out the word 'Yaffle' +--------------------------------------------------------- + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Note that tasks from 'vendor/plugins/yaffle/Rakefile' are not available to the main app.
\ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt new file mode 100644 index 0000000000..47611542cb --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tests.txt @@ -0,0 +1,165 @@ +== Tests == + +In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: + + * A 'database.yml' file with all of your connection strings + * A 'schema.rb' file with your table definitions + * A test helper method that sets up the database + +=== Test Setup === + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: root + :password: password + :database: yaffle_plugin_test +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + + db_adapter = ENV['DB'] + + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end + + ActiveRecord::Base.establish_connection(config[db_adapter]) + load(File.dirname(__FILE__) + "/schema.rb") + require File.dirname(__FILE__) + '/../rails/init.rb' +end +---------------------------------------------- + +Now whenever you write a test that requires the database, you can call 'load_schema'. + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + load_schema + + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index e5d94cffb0..4c70c2b20b 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -13,6 +13,8 @@ This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases. +The SQL in your log may have some quoting, and that quoting depends on the backend (MySQL, for example, puts backticks around field and table names). Attempting to copy the raw SQL contained within this guide may not work in your database system. Please consult the database systems manual before attempting to execute any SQL. + == The Sample Models This guide demonstrates finding using the following models: @@ -52,16 +54,16 @@ Active Record will perform queries on the database for you and is compatible wit [source, sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1) +SELECT * FROM clients WHERE (clients.id = 1) ------------------------------------------------------- -NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column. +NOTE: Because this is a standard table created from a migration in Rails, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column. If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as: [source, sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2)) +SELECT * FROM clients WHERE (clients.id IN (1,2)) ------------------------------------------------------- ------------------------------------------------------- @@ -76,7 +78,7 @@ Note that if you pass in a list of numbers that the result will be returned as a NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception. -If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table: +If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table: ------------------------------------------------------- >> Client.first @@ -84,7 +86,7 @@ If you wanted to find the first client you would simply type +Client.first+ and created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"> ------------------------------------------------------- -If you were running script/server you might see the following output: +If you were reading your log file (the default is log/development.log) you may see something like this: [source,sql] ------------------------------------------------------- @@ -93,20 +95,29 @@ SELECT * FROM clients LIMIT 1 Indicating the query that Rails has performed on your database. -To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table: +To find the last Client object you would simply type +Client.last+ and that would find the last client created in your clients table: ------------------------------------------------------- ->> Client.find(:last) +>> Client.last => #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"> ------------------------------------------------------- +If you were reading your log file (the default is log/development.log) you may see something like this: + +[source,sql] +------------------------------------------------------- +SELECT * FROM clients ORDER BY id DESC LIMIT 1 +------------------------------------------------------- + +NOTE: Please be aware that the syntax that Rails uses to find the first record in the table means that it may not be the actual first record. If you want the actual first record based on a field in your table (e.g. +created_at+) specify an order option in your find call. The last method call works differently: it finds the last record on your table based on the primary key column. + [source,sql] ------------------------------------------------------- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 ------------------------------------------------------- -To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table: +To find all the Client objects you would simply type +Client.all+ and that would find all the clients in your clients table: ------------------------------------------------------- >> Client.all @@ -114,11 +125,11 @@ To find all the clients you would simply type +Client.all+ and that would find a created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">] -------------------------------------------------------- +------------------------------------------------------- -As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively. +You may see in Rails code that there are calls to methods such as +Client.find(:all)+, +Client.find(:first)+ and +Client.find(:last)+. These methods are just alternatives to +Client.all+, +Client.first+ and +Client.last+ respectively. -Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also. +Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to +find+ will do also. == Conditions @@ -132,19 +143,20 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t === Array Conditions === -Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field. +Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with +false+ and this will find the first record in the table that has '2' as its value for the +orders_count+ field and +false+ for its locked field. The reason for doing code like: [source, ruby] ------------------------------------------------------- -+Client.first(:conditions => ["orders_count = ?", params[:orders]])+ +Client.first(:conditions => ["orders_count = ?", params[:orders]]) ------------------------------------------------------- instead of: +[source, ruby] ------------------------------------------------------- -+Client.first(:conditions => "orders_count = #{params[:orders]}")+ +Client.first(:conditions => "orders_count = #{params[:orders]}") ------------------------------------------------------- is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string. @@ -163,7 +175,7 @@ This would generate the proper query which is great for small ranges but not so [source, sql] ------------------------------------------------------- -SELECT * FROM +users+ WHERE (created_at IN +SELECT * FROM users WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11', '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17', @@ -183,7 +195,7 @@ Client.all(:conditions => ["created_at IN (?)", [source, sql] ------------------------------------------------------- -SELECT * FROM +users+ WHERE (created_at IN +SELECT * FROM users WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00')) ------------------------------------------------------- @@ -214,7 +226,7 @@ Client.all(:conditions => Just like in Ruby. -=== Hash Conditions === +=== Placeholder Conditions === Similar to the array style of params you can also specify keys in your conditions: @@ -234,6 +246,8 @@ If you're getting a set of records and want to force an order, you can use +Clie To select certain fields, you can use the select option like this: +Client.first(:select => "viewable_by, locked")+. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute +SELECT viewable_by, locked FROM clients LIMIT 0,1+ on your database. +You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this: +Client.all(:select => "DISTINCT(name)")+. + == Limit & Offset If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example: @@ -277,7 +291,7 @@ The SQL that would be executed would be something like this: [source, sql] ------------------------------------------------------- -SELECT * FROM +orders+ GROUP BY date(created_at) +SELECT * FROM orders GROUP BY date(created_at) ------------------------------------------------------- == Read Only @@ -357,20 +371,27 @@ Client.first(:include => "orders", :conditions => == Dynamic finders -For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+. +For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. + +You can do +find_last_by_*+ methods too which will find the last record matching your parameter. + +You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!('Ryan')+ + +If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. + There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+: [source,sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1 +SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1 BEGIN -INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+) +INSERT INTO clients (name, updated_at, created_at, orders_count, locked) VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0') COMMIT ------------------------------------------------------- -+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example: ++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the parameters you passed in. For example: [source, ruby] ------------------------------------------------------- @@ -379,6 +400,7 @@ client = Client.find_or_initialize_by_name('Ryan') will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it. + == Finding By SQL If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query: @@ -571,7 +593,7 @@ Which will execute: [source, sql] ------------------------------------------------------- -SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1) +SELECT count(*) AS count_all FROM clients WHERE (first_name = 1) ------------------------------------------------------- You can also use +include+ or +joins+ for this to do something a little more complex: @@ -585,8 +607,8 @@ Which will execute: [source, sql] ------------------------------------------------------- -SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+ - LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE +SELECT count(DISTINCT clients.id) AS count_all FROM clients + LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE (clients.first_name = 'name' AND orders.status = 'received') ------------------------------------------------------- @@ -655,6 +677,10 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] +* December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders[this ticket] +* November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+ +* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment] +* November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. * October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg * October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index bae8f9a4fd..b66d2f6f9e 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -154,6 +154,13 @@ And if you're using PostgreSQL for data storage, run this command: $ rails blog -d postgresql ------------------------------------------------------- +After you create the blog application, switch to its folder to continue work directly in that application: + +[source, shell] +------------------------------------------------------- +$ cd blog +------------------------------------------------------- + In any case, Rails will create a folder in your working directory called +blog+. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the +app/+ folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default: [grid="all"] @@ -239,6 +246,15 @@ development: Change the username and password in the +development+ section as appropriate. +==== Creating the Database + +Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command: + +[source, shell] +------------------------------------------------------- +$ rake db:create +------------------------------------------------------- + == Hello, Rails! One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal: @@ -370,7 +386,7 @@ end If you were to translate that into words, it says something like: when this migration is run, create a table named +posts+ with two string columns (+name+ and +title+) and a text column (+content+), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the link:../migrations.html[Rails Database Migrations] guide. -At this point, you need to do two things: create the database and run the migration. You can use rake commands at the terminal for both of those tasks: +At this point, you can use a rake command to run the migration: [source, shell] ------------------------------------------------------- @@ -378,7 +394,7 @@ $ rake db:create $ rake db:migrate ------------------------------------------------------- -NOTE: Because you're working in the development environment by default, both of these commands will apply to the database defined in the +development+ section of your +config/database.yml+ file. +NOTE: Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. === Adding a Link @@ -748,7 +764,7 @@ At this point, it’s worth looking at some of the tools that Rails provides to === Using Partials to Eliminate View Duplication -As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a +partial+ template. This requires editing the new and edit views, and adding a new template: +As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a +partial+ template. This requires editing the new and edit views, and adding a new template. The new +_form.html.erb+ template should be saved in the same +app/views/posts+ folder as the files from which it is being extracted: +new.html.erb+: @@ -1021,7 +1037,7 @@ class CommentsController < ApplicationController def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1033,7 +1049,7 @@ class CommentsController < ApplicationController @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1041,14 +1057,14 @@ class CommentsController < ApplicationController def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end @@ -1219,7 +1235,7 @@ Note that each post has its own individual comments collection, accessible as +@ Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources: -* The link:http://manuals.rubyonrails.org/[Ruby On Rails guides] +* The link:http://guides.rubyonrails.org/[Ruby On Rails guides] * The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list] * The #rubyonrails channel on irc.freenode.net * The link:http://wiki.rubyonrails.org/rails[Rails wiki] diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt new file mode 100644 index 0000000000..76f081e0bc --- /dev/null +++ b/railties/doc/guides/source/i18n.txt @@ -0,0 +1,542 @@ +The Rails Internationalization API +================================== + +The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application. + +== How I18n in Ruby on Rails works + +Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on: + +* providing support for English and similar languages out of the box +* making it easy to customize and extend everything for other languages + +=== The overall architecture of the library + +To solve this the Ruby I18n gem is split into two parts: + +* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works. +* A shipped backend (which is intentionally named the Simple backend) that implements these methods. + +As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one. + +=== The public I18n API + +We will go into more detail about the public methods later but here's a quick overview. The most important methods are: + +[source, ruby] +------------------------------------------------------- +translate # lookup translations +localize # localize Date and Time objects to local formats +------------------------------------------------------- + +There are also attribute readers and writers for the following attributes: + +[source, ruby] +------------------------------------------------------- +load_path # announce your custom translation files +locale # get and set the current locale +default_locale # get and set the default locale +exception_handler # use a different exception_handler +backend # use a different backend +------------------------------------------------------- + +== Walkthrough: setup a simple I18n'ed Rails application + +There are just a few, simple steps to get up and running with a I18n support for your application. + +=== Configure the I18n module + +First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English. + +You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer: + +[source, ruby] +------------------------------------------------------- +# in config/initializer/locale.rb + +# tell the I18n library where to find your translations +I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ] + +# you can omit this if you're happy with English as a default locale +I18n.default_locale = :"pt" +------------------------------------------------------- + +I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced. + +=== Set the locale in each request + +By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English). + +If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this: + +[source, ruby] +------------------------------------------------------- +before_filter :set_locale +def set_locale + # if this is nil then I18n.default_locale will be used + I18n.locale = params[:locale] +end +------------------------------------------------------- + +This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section). + +Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff. + +=== Internationalize your application + +The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits. + +So, let's internationalize something. You most probably have something like this in one of your applications: + +[source, ruby] +------------------------------------------------------- +# config/routes.rb +ActionController::Routing::Routes.draw do |map| + map.root :controller => 'home', :action => 'index' +end + +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = "Hello flash!" + end +end + +# app/views/home/index.html.erb +<h1>Hello world!</h1> +<p><%= flash[:notice] %></p> +------------------------------------------------------- + +TODO screenshot + +Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation: + +[source, ruby] +------------------------------------------------------- +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = t(:hello_flash) + end +end + +# app/views/home/index.html.erb +<h1><%=t :hello_world %></h1> +<p><%= flash[:notice] %></p> +------------------------------------------------------- + +TODO insert note about #t helper compared to I18n.t + +TODO insert note/reference about structuring translation keys + +When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing. + +TODO screenshot + +So let's add the missing translations (i.e. do the "localization" part): + +[source, ruby] +------------------------------------------------------- +# lib/locale/en.yml +en-US: + hello_world: Hello World + hello_flash: Hello Flash + +# lib/locale/pirate.yml +pirate: + hello_world: Ahoy World + hello_flash: Ahoy Flash +------------------------------------------------------- + +There you go. Your application now shows: + +TODO screenshot + +[source, ruby] +------------------------------------------------------- +I18n.t 'store.title' +I18n.l Time.now +------------------------------------------------------- + + +== Overview of the I18n API features + +The following purposes are covered: + +* lookup translations +* interpolate data into translations +* pluralize translations +* localize dates, numbers, currency etc. + +=== Looking up translations + +==== Basic lookup, scopes and nested keys + +Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent: + +[source, ruby] +------------------------------------------------------- +I18n.t :message +I18n.t 'message' +------------------------------------------------------- + +translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key: + +[source, ruby] +------------------------------------------------------- +I18n.t :invalid, :scope => [:active_record, :error_messages] +------------------------------------------------------- + +This looks up the :invalid message in the ActiveRecord error messages. + +Additionally, both the key and scopes can be specified as dot separated keys as in: + +[source, ruby] +------------------------------------------------------- +I18n.translate :"active_record.error_messages.invalid" +------------------------------------------------------- + +Thus the following calls are equivalent: + +[source, ruby] +------------------------------------------------------- +I18n.t 'active_record.error_messages.invalid' +I18n.t 'error_messages.invalid', :scope => :active_record +I18n.t :invalid, :scope => 'active_record.error_messages' +I18n.t :invalid, :scope => [:active_record, :error_messages] +------------------------------------------------------- + +==== Defaults + +When a default option is given its value will be returned if the translation is missing: + +[source, ruby] +------------------------------------------------------- +I18n.t :missing, :default => 'Not here' +# => 'Not here' +------------------------------------------------------- + +If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned. + +E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned: + +[source, ruby] +------------------------------------------------------- +I18n.t :missing, :default => [:also_missing, 'Not here'] +# => 'Not here' +------------------------------------------------------- + +==== Bulk and namespace lookup + +To lookup multiple translations at once an array of keys can be passed: + +[source, ruby] +------------------------------------------------------- +I18n.t [:odd, :even], :scope => 'active_record.error_messages' +# => ["must be odd", "must be even"] +------------------------------------------------------- + +Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all ActiveRecord error messages as a Hash with: + +[source, ruby] +------------------------------------------------------- +I18n.t 'active_record.error_messages' +# => { :inclusion => "is not included in the list", :exclusion => ... } +------------------------------------------------------- + +=== Interpolation + +TODO explain what this is good for + +All options besides :default and :scope that are passed to #translate will be interpolated to the translation: + +[source, ruby] +------------------------------------------------------- +I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!' +I18n.translate :thanks, :name => 'Jeremy' +# => 'Thanks Jeremy!' +------------------------------------------------------- + +If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised. + +=== Pluralization + +TODO explain what this is good for + +The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: + +[source, ruby] +------------------------------------------------------- +I18n.backend.store_translations 'en-US', :inbox => { # TODO change this + :one => '1 message', + :other => '{{count}} messages' +} +I18n.translate :inbox, :count => 2 +# => '2 messages' +------------------------------------------------------- + +The algorithm for pluralizations in en-US is as simple as: + +[source, ruby] +------------------------------------------------------- +entry[count == 1 ? 0 : 1] +------------------------------------------------------- + +I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero). + +If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised. + +=== Setting and passing a locale + +The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize. + +If no locale is passed I18n.locale is used: + +[source, ruby] +------------------------------------------------------- +I18n.locale = :'de' +I18n.t :foo +I18n.l Time.now +------------------------------------------------------- + +Explicitely passing a locale: + +[source, ruby] +------------------------------------------------------- +I18n.t :foo, :locale => :'de' +I18n.l Time.now, :locale => :'de' +------------------------------------------------------- + +I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this: + +[source, ruby] +------------------------------------------------------- +I18n.default_locale = :'de' +------------------------------------------------------- + +== How to store your custom translations + +The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2) + +For example a Ruby Hash providing translations can look like this: + +[source, ruby] +------------------------------------------------------- +{ + :'pt-BR' => { + :foo => { + :bar => "baz" + } + } +} +------------------------------------------------------- + +The equivalent YAML file would look like this: + +[source, ruby] +------------------------------------------------------- +"pt-BR": + foo: + bar: baz +------------------------------------------------------- + +As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz". + +Here is a "real" example from the ActiveSupport en-US translations YAML file: + +[source, ruby] +------------------------------------------------------- +"en": + date: + formats: + default: "%Y-%m-%d" + short: "%b %d" + long: "%B %d, %Y" +------------------------------------------------------- + +So, all of the following equivalent lookups will return the :short date format "%B %d": + +[source, ruby] +------------------------------------------------------- +I18n.t 'date.formats.short' +I18n.t 'formats.short', :scope => :date +I18n.t :short, :scope => 'date.formats' +I18n.t :short, :scope => [:date, :formats] +------------------------------------------------------- + +=== Translations for ActiveRecord models + +You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names. + +For example when you add the following translations: + +en: + activerecord: + models: + user: Dude + attributes: + user: + login: "Handle" + # will translate User attribute "login" as "Handle" + +Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle". + +==== Error message scopes + +ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account. + +This gives you quite powerful means to flexibly adjust your messages to your application's needs. + +Consider a User model with a validates_presence_of validation for the name attribute like this: + +[source, ruby] +------------------------------------------------------- +class User < ActiveRecord::Base + validates_presence_of :name +end +------------------------------------------------------- + +The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.models.user.attributes.name.blank +------------------------------------------------------- + +If it's not there it will try: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.models.user.blank +------------------------------------------------------- + +If this is also not there it will use the default message from: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.blank +------------------------------------------------------- + +When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up. + +For example, you might have an Admin model inheriting from User: + +[source, ruby] +------------------------------------------------------- +class Admin < User + validates_presence_of :name +end +------------------------------------------------------- + +Then ActiveRecord will look for messages in this order: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.models.admin.attributes.title.blank +activerecord.errors.models.admin.blank +activerecord.errors.models.user.attributes.title.blank +activerecord.errors.models.user.blank +activerecord.errors.messages.blank +------------------------------------------------------- + +This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes. + +==== Error message interpolation + +The translated model name and translated attribute name are always available for interpolation. + +So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}". + +Count and/or value are available where applicable. Count can be used for pluralization if present: + +[grid="all"] +`---------------------------`----------------`---------------`---------------- +validation with option message interpolation +validates_confirmation_of - :confirmation - +validates_acceptance_of - :accepted - +validates_presence_of - :blank - +validates_length_of :within, :in :too_short count +validates_length_of :within, :in :too_long count +validates_length_of :is :wrong_length count +validates_length_of :minimum :too_short count +validates_length_of :maximum :too_long count +validates_uniqueness_of - :taken value +validates_format_of - :invalid value +validates_inclusion_of - :inclusion value +validates_exclusion_of - :exclusion value +validates_associated - :invalid value +validates_numericality_of - :not_a_number value +validates_numericality_of :odd :odd value +validates_numericality_of :even :even value +------------------------------------------------------------------------------ + + +==== Translations for the ActiveRecord error_messages_for helper + +If you are using the ActiveRecord error_messages_for helper you will want to add translations for it. + +Rails ships with the following translations: + +[source, ruby] +------------------------------------------------------- +"en": + activerecord: + errors: + template: + header: + one: "1 error prohibited this {{model}} from being saved" + other: "{{count}} errors prohibited this {{model}} from being saved" + body: "There were problems with the following fields:" +------------------------------------------------------- + + +=== Other translations and localizations + +Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. + +TODO list helpers and available keys + +== Customize your I18n setup + +=== Using different backends + +For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format. + +That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend: + +[source, ruby] +------------------------------------------------------- +I18n.backend = Globalize::Backend::Static.new +------------------------------------------------------- + +TODO expand this ...? list some backends and their features? + +=== Using different exception handlers + +TODO + +* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend. +* Explain the default behaviour. +* Explain the :raise option + +* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing" +* Example 2: for tests you might want a handler that just raises all exceptions all the time +* Example 3: a handler + + +== Resources + +* http://rails-i18n.org + +== Footnotes + +(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. + +(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. + +== Credits + +== NOTES + +How to contribute? + diff --git a/railties/doc/guides/source/index.txt b/railties/doc/guides/source/index.txt index 8828e1d313..a5648fb757 100644 --- a/railties/doc/guides/source/index.txt +++ b/railties/doc/guides/source/index.txt @@ -113,6 +113,16 @@ This guide covers ways to analyze and optimize your running Rails code. This guide covers how to build a plugin to extend the functionality of Rails. *********************************************************** +.link:i18n.html[The Rails Internationalization API] +*********************************************************** +CAUTION: still a basic draft + +This guide introduces you to the basic concepts and features of the Rails I18n API and shows you how to localize your application. +*********************************************************** + + + + Authors who have contributed to complete guides are listed link:authors.html[here]. This work is licensed under a link:http://creativecommons.org/licenses/by-nc-sa/3.0/[Creative Commons Attribution-Noncommercial-Share Alike 3.0 License] diff --git a/railties/doc/guides/source/migrations/index.txt b/railties/doc/guides/source/migrations/index.txt index be183e8597..1670b73178 100644 --- a/railties/doc/guides/source/migrations/index.txt +++ b/railties/doc/guides/source/migrations/index.txt @@ -1,7 +1,7 @@ Migrations ========== -Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run `rake db:migrate`. Active Record will work out which migrations should be run. +Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run `rake db:migrate`. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database. Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production. diff --git a/railties/doc/guides/source/migrations/rakeing_around.txt b/railties/doc/guides/source/migrations/rakeing_around.txt index 6d8c43d7a3..b01451d54d 100644 --- a/railties/doc/guides/source/migrations/rakeing_around.txt +++ b/railties/doc/guides/source/migrations/rakeing_around.txt @@ -2,6 +2,8 @@ Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be `db:migrate`. In its most basic form it just runs the `up` method for all the migrations that have not yet been run. If there are no such migrations it exits. +Note that running the `db:migrate` also invokes the `db:schema:dump` task, which will update your db/schema.rb file to match the structure of your database. + If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run diff --git a/railties/doc/guides/source/routing_outside_in.txt b/railties/doc/guides/source/routing_outside_in.txt index 0f6cd358e2..3f6c80de5c 100644 --- a/railties/doc/guides/source/routing_outside_in.txt +++ b/railties/doc/guides/source/routing_outside_in.txt @@ -424,7 +424,7 @@ In this case, all of the normal routes except the route for +destroy+ (a +DELETE In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options. -TIP: If your application has many RESTful routes, using +:only+ and +:accept+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process. +TIP: If your application has many RESTful routes, using +:only+ and +:except+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process. === Nested Resources @@ -738,7 +738,7 @@ You do not need to explicitly use the +:controller+ and +:action+ symbols within [source, ruby] ------------------------------------------------------- -map.connect 'photo/:id', :controller => 'photos', :action => 'show' +map.connect 'photos/:id', :controller => 'photos', :action => 'show' ------------------------------------------------------- With this route, an incoming URL of +/photos/12+ would be dispatched to the +show+ action within the +Photos+ controller. @@ -747,7 +747,7 @@ You an also define other defaults in a route by supplying a hash for the +:defau [source, ruby] ------------------------------------------------------- -map.connect 'photo/:id', :controller => 'photos', :action => 'show', :defaults => { :format => 'jpg' } +map.connect 'photos/:id', :controller => 'photos', :action => 'show', :defaults => { :format => 'jpg' } ------------------------------------------------------- With this route, an incoming URL of +photos/12+ would be dispatched to the +show+ action within the +Photos+ controller, and +params[:format]+ will be set to +jpg+. @@ -886,7 +886,7 @@ For better readability, you can specify an already-created route in your call to [source, ruby] ------------------------------------------------------- -map.index :controller => "pages", :action => "main" +map.index 'index', :controller => "pages", :action => "main" map.root :index ------------------------------------------------------- diff --git a/railties/doc/guides/source/stylesheets/base.css b/railties/doc/guides/source/stylesheets/base.css index 76ee6e2ca9..1cf0a3de98 100644 --- a/railties/doc/guides/source/stylesheets/base.css +++ b/railties/doc/guides/source/stylesheets/base.css @@ -97,6 +97,10 @@ ul li { background-position: 0 0.55em; } +ul li p { + margin-bottom: 0.5em; +} + /* ---------------------------------------------------------------------------- Structure ---------------------------------------------------------------------------- */ diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt index 6cced2fdd1..b492fdb300 100644 --- a/railties/doc/guides/source/testing_rails_applications.txt +++ b/railties/doc/guides/source/testing_rails_applications.txt @@ -229,7 +229,7 @@ NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists. ==== Rake Tasks for Preparing you Application for Testing == [grid="all"] ---------------------------------`---------------------------------------------------- +------------------------------------------------------------------------------------ Tasks Description ------------------------------------------------------------------------------------ +rake db:test:clone+ Recreate the test database from the current environment's database schema @@ -239,7 +239,7 @@ Tasks Description +rake db:test:purge+ Empty the test database. ------------------------------------------------------------------------------------ -TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+ +TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+ === Running Tests === @@ -768,7 +768,7 @@ end You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project. [grid="all"] ---------------------------------`---------------------------------------------------- +------------------------------------------------------------------------------------ Tasks Description ------------------------------------------------------------------------------------ +rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default. diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 4bb1e480b7..06a3332c42 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -569,7 +569,7 @@ Run `rake gems:install` to install the missing gems. def load_application_initializers if gems_dependencies_loaded Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer| - load initializer.sub(/^#{Regexp.escape(configuration.root_path)}\//, '') + load(initializer) end end end @@ -927,7 +927,6 @@ Run `rake gems:install` to install the missing gems. app/controllers app/helpers app/services - config lib vendor ).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) } diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index d8626aaf14..f344c6477d 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -3,7 +3,9 @@ module Rails ERB_METHOD_SIG = /:in `_run_erb_.*/ VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails ) - SERVER_DIRS = %w( lib/mongrel bin/mongrel lib/rack ) + SERVER_DIRS = %w( lib/mongrel bin/mongrel + lib/passenger bin/passenger-spawn-server + lib/rack ) RAILS_NOISE = %w( script/server ) RUBY_NOISE = %w( rubygems/custom_require benchmark.rb ) @@ -30,4 +32,4 @@ module Rails Rails.backtrace_cleaner.clean(backtrace) end end -end
\ No newline at end of file +end diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 4a191578cf..795a0d7653 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -40,7 +40,7 @@ class AppGenerator < Rails::Generator::Base def after_generate if options[:template] - Rails::TemplateRunner.new(@destination_root, options[:template]) + Rails::TemplateRunner.new(options[:template], @destination_root) end end diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb index 0083e0d5a5..c6113648e6 100644 --- a/railties/lib/rails_generator/generators/applications/app/template_runner.rb +++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb @@ -7,10 +7,10 @@ require 'fileutils' module Rails class TemplateRunner - attr_reader :behavior, :description, :root + attr_reader :root - def initialize(root, template) # :nodoc: - @root = Dir.pwd + "/" + root + def initialize(template, root = '') # :nodoc: + @root = File.join(Dir.pwd, root) puts "applying template: #{template}" @@ -57,16 +57,22 @@ module Rails end # Install a plugin. You must provide either a Subversion url or Git url. + # For a Git-hosted plugin, you can specify if it should be added as a submodule instead of cloned. # # ==== Examples # # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git' + # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git', :submodule => true # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk' # def plugin(name, options) puts "installing plugin #{name}" - if options[:git] || options[:svn] + if options[:git] && options[:submodule] + in_root do + Git.run("submodule add #{options[:git]} vendor/plugins/#{name}") + end + elsif options[:git] || options[:svn] in_root do `script/plugin install #{options[:svn] || options[:git]}` end @@ -103,13 +109,13 @@ module Rails # git :add => "onefile.rb", :rm => "badfile.cxx" # def git(command = {}) - puts "running git #{command}" - in_root do if command.is_a?(Symbol) + puts "running git #{command}" Git.run(command.to_s) else command.each do |command, options| + puts "running git #{command} #{options}" Git.run("#{command} #{options}") end end @@ -233,11 +239,11 @@ module Rails # # generate(:authenticated, "user session") # - def generate(what, args = nil) + def generate(what, *args) puts "generating #{what}" - args = args.join(" ") if args.class == Array + argument = args.map(&:to_s).flatten.join(" ") - in_root { `#{root}/script/generate #{what} #{args}` } + in_root { `#{root}/script/generate #{what} #{argument}` } end # Executes a command @@ -258,11 +264,14 @@ module Rails # ==== Example # # rake("db:migrate") - # rake("db:migrate", "production") + # rake("db:migrate", :env => "production") + # rake("gems:install", :sudo => true) # - def rake(command, env = 'development') + def rake(command, options = {}) puts "running rake task #{command}" - in_root { `rake #{command} RAILS_ENV=#{env}` } + env = options[:env] || 'development' + sudo = options[:sudo] ? 'sudo ' : '' + in_root { `#{sudo}rake #{command} RAILS_ENV=#{env}` } end # Just run the capify command in root diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index a90c1d4a77..3a576063fa 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -110,7 +110,7 @@ namespace :db do end - desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false." + desc "Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false." task :migrate => :environment do ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index d639214ffe..191c9361ff 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -80,6 +80,12 @@ namespace :rails do desc "Update both configs, scripts and public/javascripts from Rails" task :update => [ "update:scripts", "update:javascripts", "update:configs", "update:application_controller" ] + desc "Applies the template supplied by LOCATION=/path/to/template" + task :template do + require 'rails_generator/generators/applications/app/template_runner' + Rails::TemplateRunner.new(ENV["LOCATION"]) + end + namespace :update do desc "Add new scripts to the application script/ directory" task :scripts do |