diff options
Diffstat (limited to 'railties')
41 files changed, 801 insertions, 305 deletions
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 555d466ca4..9b9be5eea4 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,5 +1,9 @@ ## Rails 3.2.0 (unreleased) ## +* Guides are available as a single .mobi for the Kindle and free Kindle readers apps. *Michael Pearson & Xavier Noria* + +* Allow scaffold/model/migration generators to accept a "index" and "uniq" modifiers, as in: "tracking_id:integer:uniq" in order to generate (unique) indexes. Some types also accept custom options, for instance, you can specify the precision and scale for decimals as "price:decimal{7,2}". *Dmitrii Samoilov* + * Added `config.exceptions_app` to set the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`. *José Valim* * Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting `config.reload_classes_only_on_change` to false. *José Valim* diff --git a/railties/guides/assets/images/rails_guides_kindle_cover.jpg b/railties/guides/assets/images/rails_guides_kindle_cover.jpg Binary files differnew file mode 100644 index 0000000000..9eb16720a9 --- /dev/null +++ b/railties/guides/assets/images/rails_guides_kindle_cover.jpg diff --git a/railties/guides/assets/stylesheets/kindle.css b/railties/guides/assets/stylesheets/kindle.css new file mode 100644 index 0000000000..b26cd1786a --- /dev/null +++ b/railties/guides/assets/stylesheets/kindle.css @@ -0,0 +1,11 @@ +p { text-indent: 0; } + +p, H1, H2, H3, H4, H5, H6, H7, H8, table { margin-top: 1em;} + +.pagebreak { page-break-before: always; } +#toc H3 { + text-indent: 1em; +} +#toc .document { + text-indent: 2em; +}
\ No newline at end of file diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css index cf6e9e5cc8..4a775f632c 100644 --- a/railties/guides/assets/stylesheets/main.css +++ b/railties/guides/assets/stylesheets/main.css @@ -341,6 +341,14 @@ h6 { margin-top: 0.25em; } +#mainCol dd.kindle, #subCol dd.kindle { + background: #d5e9f6 url(../images/tab_info.gif) no-repeat left top; + border: none; + padding: 1.25em 1em 1.25em 48px; + margin-left: 0; + margin-top: 0.25em; +} + #mainCol div.warning, #subCol dd.warning { background: #f9d9d8 url(../images/tab_red.gif) no-repeat left top; border: none; diff --git a/railties/guides/code/getting_started/config/environments/development.rb b/railties/guides/code/getting_started/config/environments/development.rb index d60a10568b..aefd25c6b6 100644 --- a/railties/guides/code/getting_started/config/environments/development.rb +++ b/railties/guides/code/getting_started/config/environments/development.rb @@ -6,9 +6,6 @@ Blog::Application.configure do # since you don't have to restart the web server when you make code changes. config.cache_classes = false - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true - # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false diff --git a/railties/guides/code/getting_started/config/environments/test.rb b/railties/guides/code/getting_started/config/environments/test.rb index 08697cbbc9..1d45541d5c 100644 --- a/railties/guides/code/getting_started/config/environments/test.rb +++ b/railties/guides/code/getting_started/config/environments/test.rb @@ -11,9 +11,6 @@ Blog::Application.configure do config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" - # Log error messages when you accidentally call methods on nil - config.whiny_nils = true - # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index 6f6d3bda80..49ad8f7769 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -47,6 +47,11 @@ # Set to "1" to indicate generated guides should be marked as edge. This # inserts a badge and changes the preamble of the home page. # +# KINDLE +# Set to "1" to generate the .mobi with all the guides. The kindlegen +# executable must be in your PATH. You can get it for free from +# http://www.amazon.com/kindlepublishing +# # --------------------------------------------------------------------------- require 'set' @@ -65,37 +70,81 @@ module RailsGuides class Generator attr_reader :guides_dir, :source_dir, :output_dir, :edge, :warnings, :all - GUIDES_RE = /\.(?:textile|html\.erb)$/ + GUIDES_RE = /\.(?:textile|erb)$/ def initialize(output=nil) - @lang = ENV['GUIDES_LANGUAGE'] + set_flags_from_environment + + if kindle? + check_for_kindlegen + register_kindle_mime_types + end + initialize_dirs(output) create_output_dir_if_needed - set_flags_from_environment + end + + def set_flags_from_environment + @edge = ENV['EDGE'] == '1' + @warnings = ENV['WARNINGS'] == '1' + @all = ENV['ALL'] == '1' + @kindle = ENV['KINDLE'] == '1' + @version = ENV['RAILS_VERSION'] || `git rev-parse --short HEAD`.chomp + @lang = ENV['GUIDES_LANGUAGE'] + end + + def register_kindle_mime_types + Mime::Type.register_alias("application/xml", :opf, %w(opf)) + Mime::Type.register_alias("application/xml", :ncx, %w(ncx)) end def generate generate_guides copy_assets + generate_mobi if kindle? end private + + def kindle? + @kindle + end + + def check_for_kindlegen + if `which kindlegen`.blank? + raise "Can't create a kindle version without `kindlegen`." + end + end + + def generate_mobi + opf = "#{output_dir}/rails_guides.opf" + out = "#{output_dir}/kindlegen.out" + + system "kindlegen #{opf} -o #{mobi} > #{out} 2>&1" + puts "Guides compiled as Kindle book to #{mobi}" + puts "(kindlegen log at #{out})." + end + + def mobi + "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : '') + end + def initialize_dirs(output) @guides_dir = File.join(File.dirname(__FILE__), '..') - @source_dir = File.join(@guides_dir, "source", @lang.to_s) - @output_dir = output || File.join(@guides_dir, "output", @lang.to_s) + @source_dir = "#@guides_dir/source/#@lang" + @output_dir = if output + output + elsif kindle? + "#@guides_dir/output/kindle/#@lang" + else + "#@guides_dir/output/#@lang" + end.sub(%r</$>, '') end def create_output_dir_if_needed FileUtils.mkdir_p(output_dir) end - def set_flags_from_environment - @edge = ENV['EDGE'] == '1' - @warnings = ENV['WARNINGS'] == '1' - @all = ENV['ALL'] == '1' - end - def generate_guides guides_to_generate.each do |guide| output_file = output_file_for(guide) @@ -105,6 +154,13 @@ module RailsGuides def guides_to_generate guides = Dir.entries(source_dir).grep(GUIDES_RE) + + if kindle? + Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry| + guides << "kindle/#{entry}" + end + end + ENV.key?('ONLY') ? select_only(guides) : guides end @@ -120,36 +176,47 @@ module RailsGuides end def output_file_for(guide) - guide.sub(GUIDES_RE, '.html') + if guide =~/\.textile$/ + guide.sub(/\.textile$/, '.html') + else + guide.sub(/\.erb$/, '') + end + end + + def output_path_for(output_file) + File.join(output_dir, File.basename(output_file)) end def generate?(source_file, output_file) fin = File.join(source_dir, source_file) - fout = File.join(output_dir, output_file) + fout = output_path_for(output_file) all || !File.exists?(fout) || File.mtime(fout) < File.mtime(fin) end def generate_guide(guide, output_file) - puts "Generating #{output_file}" - File.open(File.join(output_dir, output_file), 'w') do |f| - view = ActionView::Base.new(source_dir, :edge => edge) + output_path = output_path_for(output_file) + puts "Generating #{guide} as #{output_file}" + layout = kindle? ? 'kindle/layout' : 'layout' + + File.open(output_path, 'w') do |f| + view = ActionView::Base.new(source_dir, :edge => @edge, :version => @version, :mobi => "kindle/#{mobi}") view.extend(Helpers) - if guide =~ /\.html\.erb$/ + if guide =~ /\.(\w+)\.erb$/ # Generate the special pages like the home. # Passing a template handler in the template name is deprecated. So pass the file name without the extension. - result = view.render(:layout => 'layout', :file => $`) + result = view.render(:layout => layout, :formats => [$1], :file => $`) else body = File.read(File.join(source_dir, guide)) body = set_header_section(body, view) body = set_index(body, view) - result = view.render(:layout => 'layout', :text => textile(body)) + result = view.render(:layout => layout, :text => textile(body)) warn_about_broken_links(result) if @warnings end - f.write result + f.write(result) end end @@ -216,7 +283,7 @@ module RailsGuides anchors = Set.new html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor| if anchors.member?(anchor) - puts "*** DUPLICATE ID: #{anchor}, please put and explicit ID, e.g. h4(#explicit-id), or consider rewording" + puts "*** DUPLICATE ID: #{anchor}, please use an explicit ID, e.g. h4(#explicit-id), or consider rewording" else anchors << anchor end diff --git a/railties/guides/rails_guides/helpers.rb b/railties/guides/rails_guides/helpers.rb index 463df8a7a8..45ad9b9588 100644 --- a/railties/guides/rails_guides/helpers.rb +++ b/railties/guides/rails_guides/helpers.rb @@ -11,6 +11,14 @@ module RailsGuides result << content_tag(:dd, capture(&block)) result end + + def documents_by_section + @documents_by_section ||= YAML.load_file(File.expand_path('../../source/documents.yaml', __FILE__)) + end + + def documents_flat + documents_by_section.map {|section| section['documents']}.flatten + end def author(name, nick, image = 'credits_pic_blank.gif', &block) image = "images/#{image}" diff --git a/railties/guides/source/3_2_release_notes.textile b/railties/guides/source/3_2_release_notes.textile index 370881260e..c1afee004e 100644 --- a/railties/guides/source/3_2_release_notes.textile +++ b/railties/guides/source/3_2_release_notes.textile @@ -7,7 +7,7 @@ Highlights in Rails 3.2: * Automatic Query Explains * Tagged Logging -This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/3-2-stable in the main Rails repository on GitHub. +These release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/3-2-stable in the main Rails repository on GitHub. endprologue. @@ -19,7 +19,7 @@ h4. Rails 3.2 requires at least Ruby 1.8.7 Rails 3.2 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.2 is also compatible with Ruby 1.9.2. -TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 or 1.9.3 for smooth sailing. +TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on 1.9.2 or 1.9.3 for smooth sailing. h3. Creating a Rails 3.2 application @@ -33,7 +33,7 @@ h4. Vendoring Gems Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems. -More information: - "bundler homepage":http://gembundler.com +More information: - "Bundler homepage":http://gembundler.com h4. Living on the Edge @@ -71,6 +71,8 @@ h3. Railties * New applications get a flag <tt>config.active_record.auto_explain_threshold_in_seconds</tt> in the environments configuration files. With a value of <tt>0.5</tt> in <tt>development.rb</tt> and commented out in <tt>production.rb</tt>. No mention in <tt>test.rb</tt>. +* Added <tt>config.exceptions_app</tt> to set the exceptions application invoked by the +ShowException+ middleware when an exception happens. Defaults to <tt>ActionDispatch::PublicExceptions.new(Rails.public_path)</tt>. + * Added a <tt>DebugExceptions</tt> middleware which contains features extracted from <tt>ShowExceptions</tt> middleware. * Display mounted engines' routes in <tt>rake routes</tt>. @@ -91,6 +93,14 @@ config.railties_order = [Blog::Engine, :main_app, :all] * Attributes on scaffold and model generators default to string. This allows the following: <tt>rails g scaffold Post title body:text author</tt> +* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example, + +<ruby> +rails g scaffold Post title:string:index author:uniq price:decimal{7,2} +</ruby> + +will create indexes for +title+ and +author+ with the latter being an unique index. Some types such as decimal accept custom options. In the example, +price+ will be a decimal column with precision and scale set to 7 and 2 respectively. + * Remove old plugin generator +rails generate plugin+ in favor of +rails plugin new+ command. * Remove old <tt>config.paths.app.controller</tt> API in favor of <tt>config.paths["app/controller"]</tt>. @@ -101,6 +111,8 @@ h4. Action Controller * Make <tt>ActiveSupport::Benchmarkable</tt> a default module for <tt>ActionController::Base,</tt> so the <tt>#benchmark</tt> method is once again available in the controller context like it used to be. +* Added +:gzip+ option to +caches_page+. The default option can be configured globally using <tt>page_cache_compression</tt>. + * Rails will now use your default layout (such as "layouts/application") when you specify a layout with <tt>:only</tt> and <tt>:except</tt> condition, and those conditions fail. <ruby> @@ -168,6 +180,8 @@ h4. Action Dispatch * Added <tt>ActionDispatch::RequestId</tt> middleware that'll make a unique X-Request-Id header available to the response and enables the <tt>ActionDispatch::Request#uuid</tt> method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog. +* The <tt>ShowExceptions</tt> middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in +env["action_dispatch.exception"]+ and with the <tt>PATH_INFO</tt> rewritten to the status code. + * Allow rescue responses to be configured through a railtie as in <tt>config.action_dispatch.rescue_responses</tt>. h4. Action View diff --git a/railties/guides/source/_license.html.erb b/railties/guides/source/_license.html.erb new file mode 100644 index 0000000000..00b4466f50 --- /dev/null +++ b/railties/guides/source/_license.html.erb @@ -0,0 +1,2 @@ +<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p> +<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> diff --git a/railties/guides/source/_welcome.html.erb b/railties/guides/source/_welcome.html.erb new file mode 100644 index 0000000000..bcbb49a0ec --- /dev/null +++ b/railties/guides/source/_welcome.html.erb @@ -0,0 +1,19 @@ +<h2>Ruby on Rails Guides (<%= @version %>)</h2> + +<% if @edge %> +<p> + These are <b>Edge Guides</b>, based on the current <a href="https://github.com/rails/rails/tree/<%= @version %>">master</a> branch. +</p> +<p> + If you are looking for the ones for the stable version, please check + <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead. +</p> +<% else %> +<p> + These are the new guides for Rails 3.1 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>. + These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together. +</p> +<% end %> +<p> + The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>. +</p> diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 2ae336fa15..1c82a2941f 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -772,30 +772,6 @@ Absolute qualified constant names like +::Math::PI+ raise +NameError+. NOTE: Defined in +active_support/core_ext/module/qualified_const.rb+. -h4. Synchronization - -The +synchronize+ macro declares a method to be synchronized: - -<ruby> -class Counter - @@mutex = Mutex.new - attr_reader :value - - def initialize - @value = 0 - end - - def incr - @value += 1 # non-atomic - end - synchronize :incr, :with => '@@mutex' -end -</ruby> - -The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block. - -NOTE: Defined in +active_support/core_ext/module/synchronization.rb+. - h4. Reachable A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant. @@ -846,7 +822,7 @@ M.name # => "M" N = Module.new N.name # => "N" -Module.new.name # => "" in 1.8, nil in 1.9 +Module.new.name # => nil </ruby> You can check whether a module has a name with the predicate +anonymous?+: @@ -959,18 +935,6 @@ In the previous example the macro generates +avatar_size+ rather than +size+. NOTE: Defined in +active_support/core_ext/module/delegation.rb+ -h4. Method Names - -The builtin methods +instance_methods+ and +methods+ return method names as strings or symbols depending on the Ruby version. Active Support defines +instance_method_names+ and +method_names+ to be equivalent to them, respectively, but always getting strings back. - -For example, +ActionView::Helpers::FormBuilder+ knows this array difference is going to work no matter the Ruby version: - -<ruby> -self.field_helpers = (FormHelper.instance_method_names - ['form_for']) -</ruby> - -NOTE: Defined in +active_support/core_ext/module/method_names.rb+ - h4. Redefining Methods There are cases where you need to define a method with +define_method+, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either. diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index ec9bfd4d40..6419d32c13 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -64,6 +64,28 @@ end If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers. +By default, page caching automatically gzips files (for example, to +products.html.gz+ if user requests +/products+) to reduce the size of data transmitted (web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, compression ratio is maximum). + +Nginx is able to serve compressed content directly from disk by enabling +gzip_static+: + +<plain> +location / { + gzip_static on; # to serve pre-gzipped version +} +</plain> + +You can disable gzipping by setting +:gzip+ option to false (for example, if action returns image): + +<ruby> +caches_page :image, :gzip => false +</ruby> + +Or, you can set custom gzip compression level (level names are taken from +Zlib+ constants): + +<ruby> +caches_page :image, :gzip => :best_speed +</ruby> + NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. A workaround for this limitation is to include the parameters in the page's path, e.g. +/productions/page/1+. INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job. diff --git a/railties/guides/source/documents.yaml b/railties/guides/source/documents.yaml new file mode 100644 index 0000000000..dccfefb4fb --- /dev/null +++ b/railties/guides/source/documents.yaml @@ -0,0 +1,153 @@ +- + name: Start Here + documents: + - + name: Getting Started with Rails + url: getting_started.html + description: Everything you need to know to install Rails and create your first application. +- + name: Models + documents: + - + name: Rails Database Migrations + url: migrations.html + description: This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner. + - + name: Active Record Validations and Callbacks + url: active_record_validations_callbacks.html + description: This guide covers how you can use Active Record validations and callbacks. + - + name: Active Record Associations + url: association_basics.html + description: This guide covers all the associations provided by Active Record. + - + name: Active Record Query Interface + url: active_record_querying.html + description: This guide covers the database query interface provided by Active Record. +- + name: Views + documents: + - + name: Layouts and Rendering in Rails + url: layouts_and_rendering.html + description: This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials. + - + name: Action View Form Helpers + url: form_helpers.html + description: Guide to using built-in Form helpers. +- + name: Controllers + documents: + - + name: Action Controller Overview + url: action_controller_overview.html + description: This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics. + - + name: Rails Routing from the Outside In + url: routing.html + description: This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here. +- + name: Digging Deeper + documents: + - + name: Active Support Core Extensions + url: active_support_core_extensions.html + description: This guide documents the Ruby core extensions defined in Active Support. + - + name: Rails Internationalization API + url: i18n.html + description: This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on. + - + name: Action Mailer Basics + url: action_mailer_basics.html + work_in_progress: true + description: This guide describes how to use Action Mailer to send and receive emails. + - + name: Testing Rails Applications + url: testing.html + work_in_progress: true + description: This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from 'What is a test?' to the testing APIs. Enjoy. + - + name: Securing Rails Applications + url: security.html + description: This guide describes common security problems in web applications and how to avoid them with Rails. + - + name: Debugging Rails Applications + url: debugging_rails_applications.html + description: This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code. + - + name: Performance Testing Rails Applications + url: performance_testing.html + description: This guide covers the various ways of performance testing a Ruby on Rails application. + - + name: Configuring Rails Applications + url: configuring.html + description: This guide covers the basic configuration settings for a Rails application. + - + name: Rails Command Line Tools and Rake tasks + url: command_line.html + description: This guide covers the command line tools and rake tasks provided by Rails. + - + name: Caching with Rails + work_in_progress: true + url: caching_with_rails.html + description: Various caching techniques provided by Rails. + - + name: Asset Pipeline + url: asset_pipeline.html + description: This guide documents the asset pipeline. + - + name: The Rails Initialization Process + work_in_progress: true + url: initialization.html + description: This guide explains the internals of the Rails initialization process as of Rails 3.1 +- + name: Extending Rails + documents: + - + name: The Basics of Creating Rails Plugins + work_in_progress: true + url: plugins.html + description: This guide covers how to build a plugin to extend the functionality of Rails. + - + name: Rails on Rack + url: rails_on_rack.html + description: This guide covers Rails integration with Rack and interfacing with other Rack components. + - + name: Creating and Customizing Rails Generators + url: generators.html + description: This guide covers the process of adding a brand new generator to your extension or providing an alternative to an element of a built-in Rails generator (such as providing alternative test stubs for the scaffold generator). +- + name: Contributing to Ruby on Rails + documents: + - + name: Contributing to Ruby on Rails + url: contributing_to_ruby_on_rails.html + description: Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. + - + name: API Documentation Guidelines + url: api_documentation_guidelines.html + description: This guide documents the Ruby on Rails API documentation guidelines. + - + name: Ruby on Rails Guides Guidelines + url: ruby_on_rails_guides_guidelines.html + description: This guide documents the Ruby on Rails guides guidelines. +- + name: Release Notes + documents: + - + name: Ruby on Rails 3.1 Release Notes + url: 3_1_release_notes.html + description: Release notes for Rails 3.1. + - + name: Ruby on Rails 3.0 Release Notes + url: 3_0_release_notes.html + description: Release notes for Rails 3.0. + - + name: Ruby on Rails 2.3 Release Notes + url: 2_3_release_notes.html + description: Release notes for Rails 2.3. + - + name: Ruby on Rails 2.2 Release Notes + url: 2_2_release_notes.html + description: Release notes for Rails 2.2. diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index 7a863ccbc7..d93dcf40bf 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -48,7 +48,7 @@ end NOTE: +create_file+ is a method provided by +Thor::Actions+. Documentation for +create_file+ and other Thor methods can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html -Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API. +Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API. To invoke our new generator, we just need to do: diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb index c9a8c4fa5c..5439459b42 100644 --- a/railties/guides/source/index.html.erb +++ b/railties/guides/source/index.html.erb @@ -3,189 +3,28 @@ Ruby on Rails Guides <% end %> <% content_for :header_section do %> -<h2>Ruby on Rails Guides (<%= ENV['RAILS_VERSION'] || 'edge' %>)</h2> - -<% if @edge %> -<p> - These are <b>Edge Guides</b>, based on the current - <a href="https://github.com/rails/rails/tree/master">master branch</a>. -</p> -<p> - If you are looking for the ones for the stable version please check - <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead. -</p> -<% else %> -<p> - These are the new guides for Rails 3. The guides for Rails 2.3 are still available - at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>. -</p> -<% end %> -<p> - These guides are designed to make you immediately productive with Rails, - and to help you understand how all of the pieces fit together. -</p> - +<%= render 'welcome' %> <% end %> <% content_for :index_section do %> <div id="subCol"> <dl> + <dd class="kindle">Rails Guides are also available for the <%= link_to 'Kindle', 'https://kindle.amazon.com' %> +and <%= link_to 'Free Kindle Reading Apps', 'http://www.amazon.com/gp/kindle/kcp' %> for the iPad, +iPhone, Mac, Android, etc. Download them from <%= link_to 'here', @mobi %>. + </dd> <dd class="work-in-progress">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections to the author.</dd> </dl> </div> <% end %> -<h3>Start Here</h3> - -<dl> -<%= guide('Getting Started with Rails', 'getting_started.html') do %> - <p>Everything you need to know to install Rails and create your first application.</p> -<% end %> -</dl> - -<h3>Models</h3> - -<dl> -<%= guide("Rails Database Migrations", 'migrations.html') do %> - <p>This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner.</p> -<% end %> - -<%= guide("Active Record Validations and Callbacks", 'active_record_validations_callbacks.html') do %> - <p>This guide covers how you can use Active Record validations and callbacks.</p> -<% end %> - -<%= guide("Active Record Associations", 'association_basics.html') do %> - <p>This guide covers all the associations provided by Active Record.</p> -<% end %> - -<%= guide("Active Record Query Interface", 'active_record_querying.html') do %> - <p>This guide covers the database query interface provided by Active Record.</p> -<% end %> -</dl> - -<h3>Views</h3> - -<dl> -<%= guide("Layouts and Rendering in Rails", 'layouts_and_rendering.html') do %> - <p>This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials.</p> -<% end %> - -<%= guide("Action View Form Helpers", 'form_helpers.html', :work_in_progress => true) do %> - <p>Guide to using built-in Form helpers.</p> -<% end %> -</dl> - -<h3>Controllers</h3> - -<dl> -<%= guide("Action Controller Overview", 'action_controller_overview.html') do %> - <p>This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.</p> -<% end %> - -<%= guide("Rails Routing from the Outside In", 'routing.html') do %> - <p>This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here.</p> -<% end %> -</dl> - -<h3>Digging Deeper</h3> - -<dl> - -<%= guide("Active Support Core Extensions", 'active_support_core_extensions.html') do %> - <p>This guide documents the Ruby core extensions defined in Active Support.</p> -<% end %> - -<%= guide("Rails Internationalization API", 'i18n.html') do %> - <p>This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on.</p> -<% end %> - -<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :work_in_progress => true) do %> - <p>This guide describes how to use Action Mailer to send and receive emails.</p> -<% end %> - -<%= guide("Testing Rails Applications", 'testing.html', :work_in_progress => true) do %> - <p>This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from "What is a test?" to the testing APIs. Enjoy.</p> -<% end %> - -<%= guide("Securing Rails Applications", 'security.html') do %> - <p>This guide describes common security problems in web applications and how to avoid them with Rails.</p> -<% end %> - -<%= guide("Debugging Rails Applications", 'debugging_rails_applications.html') do %> - <p>This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code.</p> -<% end %> - -<%= guide("Performance Testing Rails Applications", 'performance_testing.html') do %> - <p>This guide covers the various ways of performance testing a Ruby on Rails application.</p> -<% end %> - -<%= guide("Configuring Rails Applications", 'configuring.html') do %> - <p>This guide covers the basic configuration settings for a Rails application.</p> -<% end %> - -<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html') do %> - <p>This guide covers the command line tools and rake tasks provided by Rails.</p> -<% end %> - -<%= guide("Caching with Rails", 'caching_with_rails.html', :work_in_progress => true) do %> - <p>Various caching techniques provided by Rails.</p> -<% end %> - -<%= guide('Asset Pipeline', 'asset_pipeline.html') do %> - <p>This guide documents the asset pipeline.</p> -<% end %> -</dl> - -<h3>Extending Rails</h3> - -<dl> - <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :work_in_progress => true) do %> - <p>This guide covers how to build a plugin to extend the functionality of Rails.</p> - <% end %> - - <%= guide("Rails on Rack", 'rails_on_rack.html') do %> - <p>This guide covers Rails integration with Rack and interfacing with other Rack components.</p> - <% end %> - - <%= guide("Creating and Customizing Rails Generators", 'generators.html') do %> - <p>This guide covers the process of adding a brand new generator to your extension - or providing an alternative to an element of a built-in Rails generator (such as - providing alternative test stubs for the scaffold generator).</p> - <% end %> -</dl> - -<h3>Contributing to Ruby on Rails</h3> - -<dl> - <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %> - <p>Rails is not "somebody else's framework." This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p> - <% end %> - - <%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %> - <p>This guide documents the Ruby on Rails API documentation guidelines.</p> - <% end %> - - <%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %> - <p>This guide documents the Ruby on Rails guides guidelines.</p> - <% end %> -</dl> - -<h3>Release Notes</h3> - -<dl> -<%= guide("Ruby on Rails 3.1 Release Notes", '3_1_release_notes.html') do %> - <p>Release notes for Rails 3.1.</p> -<% end %> - -<%= guide("Ruby on Rails 3.0 Release Notes", '3_0_release_notes.html') do %> - <p>Release notes for Rails 3.0.</p> -<% end %> - -<%= guide("Ruby on Rails 2.3 Release Notes", '2_3_release_notes.html') do %> - <p>Release notes for Rails 2.3.</p> -<% end %> - -<%= guide("Ruby on Rails 2.2 Release Notes", '2_2_release_notes.html') do %> - <p>Release notes for Rails 2.2.</p> +<% documents_by_section.each do |section| %> + <h3><%= section['name'] %></h3> + <dl> + <% section['documents'].each do |document| %> + <%= guide(document['name'], document['url'], :work_in_progress => document['work_in_progress']) do %> + <p><%= document['description'] %></p> + <% end %> + <% end %> + </dl> <% end %> -</dl> diff --git a/railties/guides/source/kindle/KINDLE.md b/railties/guides/source/kindle/KINDLE.md new file mode 100644 index 0000000000..a7d9a4e4cf --- /dev/null +++ b/railties/guides/source/kindle/KINDLE.md @@ -0,0 +1,26 @@ +# Rails Guides on the Kindle + + +## Synopsis + + 1. Obtain `kindlegen` from the link below and put the binary in your path + 2. Run `KINDLE=1 rake generate_guides` to generate the guides and compile the `.mobi` file + 3. Copy `output/kindle/rails_guides.mobi` to your Kindle + +## Resources + + * [StackOverflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format) + * Example Periodical [.ncx](https://gist.github.com/808c971ed087b839d462) and [.opf](https://gist.github.com/d6349aa8488eca2ee6d0) + * [Kindle Publishing guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf) + * [KindleGen & Kindle Previewer](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621) + +## TODO + +### Post release + + * Integrate generated Kindle document in to published HTML guides + * Tweak heading styles (most docs use h3/h4/h5, which end up being smaller than the text under it) + * Tweak table styles (smaller text? Many of the tables are unusable on a Kindle in portrait mode) + * Have the HTML/XML TOC 'drill down' into the TOCs of the individual guides + * `.epub` generation. + diff --git a/railties/guides/source/kindle/copyright.html.erb b/railties/guides/source/kindle/copyright.html.erb new file mode 100644 index 0000000000..bd51d87383 --- /dev/null +++ b/railties/guides/source/kindle/copyright.html.erb @@ -0,0 +1 @@ +<%= render 'license' %>
\ No newline at end of file diff --git a/railties/guides/source/kindle/layout.html.erb b/railties/guides/source/kindle/layout.html.erb new file mode 100644 index 0000000000..f0a286210b --- /dev/null +++ b/railties/guides/source/kindle/layout.html.erb @@ -0,0 +1,27 @@ +<!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" xml:lang="en" lang="en"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + +<title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title> + +<link rel="stylesheet" type="text/css" href="stylesheets/kindle.css" /> + +</head> +<body class="guide"> + + <% if content_for? :header_section %> + <%= yield :header_section %> + <div class="pagebreak"> + <% end %> + + <% if content_for? :index_section %> + <%= yield :index_section %> + <div class="pagebreak"> + <% end %> + + <%= yield.html_safe %> +</body> +</html> diff --git a/railties/guides/source/kindle/rails_guides.opf.erb b/railties/guides/source/kindle/rails_guides.opf.erb new file mode 100644 index 0000000000..4e07664fd0 --- /dev/null +++ b/railties/guides/source/kindle/rails_guides.opf.erb @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="utf-8"?> + +<package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="RailsGuides"> +<metadata> + <meta name="cover" content="cover" /> + <dc-metadata xmlns:dc="http://purl.org/dc/elements/1.1/"> + + <dc:title>Ruby on Rails Guides (<%= @version %>)</dc:title> + + <dc:language>en-us</dc:language> + <dc:creator>Ruby on Rails</dc:creator> + <dc:publisher>Ruby on Rails</dc:publisher> + <dc:subject>Reference</dc:subject> + <dc:date><%= Time.now.strftime('%Y-%m-%d') %></dc:date> + + <dc:description>These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.</dc:description> + </dc-metadata> + <x-metadata> + <output content-type="application/x-mobipocket-subscription-magazine" encoding="utf-8"/> + </x-metadata> +</metadata> + +<manifest> + <!-- HTML content files [mandatory] --> + <% documents_flat.each do |document| %> + <item id="<%= document['url'] %>" media-type="text/html" href="<%= document['url'] %>" /> + <% end %> + + <% %w{toc.html credits.html welcome.html copyright.html}.each do |url| %> + <item id="<%= url %>" media-type="text/html" href="<%= url %>" /> + <% end %> + + <item id="toc" media-type="application/x-dtbncx+xml" href="toc.ncx" /> + + <item id="cover" media-type="image/jpeg" href="images/rails_guides_kindle_cover.jpg"/> +</manifest> + +<spine toc="toc"> + <itemref idref="toc.html" /> + <itemref idref="welcome.html" /> + <itemref idref="credits.html" /> + <itemref idref="copyright.html" /> + <% documents_flat.each do |document| %> + <itemref idref="<%= document['url'] %>" /> + <% end %> +</spine> + +<guide> + <reference type="toc" title="Table of Contents" href="toc.html"></reference> +</guide> + +</package> diff --git a/railties/guides/source/kindle/toc.html.erb b/railties/guides/source/kindle/toc.html.erb new file mode 100644 index 0000000000..e013797dee --- /dev/null +++ b/railties/guides/source/kindle/toc.html.erb @@ -0,0 +1,24 @@ +<% content_for :page_title do %> +Ruby on Rails Guides +<% end %> + +<h1>Table of Contents</h1> +<div id="toc"> + <ul><li><a href="welcome.html">Welcome</a></li></ul> +<% documents_by_section.each_with_index do |section, i| %> + <h3><%= "#{i + 1}." %> <%= section['name'] %></h3> + <ul> + <% section['documents'].each do |document| %> + <li> + <a href="<%= document['url'] %>"><%= document['name'] %></a> + <% if document['work_in_progress']%>(WIP)<% end %> + </li> + <% end %> + </ul> +<% end %> +<hr /> +<ul> + <li><a href="credits.html">Credits</a></li> + <li><a href="copyright.html">Copyright & License</a></li> +<ul> +</div> diff --git a/railties/guides/source/kindle/toc.ncx.erb b/railties/guides/source/kindle/toc.ncx.erb new file mode 100644 index 0000000000..2c6d8e3bdf --- /dev/null +++ b/railties/guides/source/kindle/toc.ncx.erb @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" + "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd"> + +<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US"> +<head> + <meta name="dtb:uid" content="RailsGuides"/> + <meta name="dtb:depth" content="2"/> + <meta name="dtb:totalPageCount" content="0"/> + <meta name="dtb:maxPageNumber" content="0"/> +</head> +<docTitle><text>Ruby on Rails Guides</text></docTitle> +<docAuthor><text>docrails</text></docAuthor> +<navMap> + <navPoint playOrder="0" class="periodical" id="periodical"> + <navLabel> + <text>Table of Contents</text> + </navLabel> + <content src="toc.html"/> + + <navPoint class="section" id="welcome" playOrder="1"> + <navLabel> + <text>Introduction</text> + </navLabel> + <content src="welcome.html"/> + + <navPoint class="article" id="welcome" playOrder="2"> + <navLabel> + <text>Welcome</text> + </navLabel> + <content src="welcome.html"/> + </navPoint> + <navPoint class="article" id="credits" playOrder="3"> + <navLabel><text>Credits</text></navLabel> + <content src="credits.html"> + </navPoint> + <navPoint class="article" id="copyright" playOrder="4"> + <navLabel><text>Copyright & License</text></navLabel> + <content src="copyright.html"> + </navPoint> + </navPoint> + + <% play_order = 4 %> + <% documents_by_section.each_with_index do |section, section_no| %> + <navPoint class="section" id="chapter_<%= section_no + 1 %>" playOrder="<% play_order +=1 %>"> + <navLabel> + <text><%= section['name'] %></text> + </navLabel> + <content src="<%=section['documents'].first['url'] %>"/> + + <% section['documents'].each_with_index do |document, document_no| %> + <navPoint class="article" id="_<%=section_no+1%>.<%=document_no+1%>" playOrder="<%=play_order +=1 %>"> + <navLabel> + <text><%= document['name'] %></text> + </navLabel> + <content src="<%=document['url'] %>"/> + </navPoint> + <% end %> + </navPoint> + <% end %> + + </navPoint> +</navMap> +</ncx> diff --git a/railties/guides/source/kindle/welcome.html.erb b/railties/guides/source/kindle/welcome.html.erb new file mode 100644 index 0000000000..e30704c4e6 --- /dev/null +++ b/railties/guides/source/kindle/welcome.html.erb @@ -0,0 +1,5 @@ +<%= render 'welcome' %> + +<h3>Kindle Edition</h3> + +The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome, please see the "Feedback" section at the end of each guide for instructions. diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb index 4c979888b7..e69936b43a 100644 --- a/railties/guides/source/layout.html.erb +++ b/railties/guides/source/layout.html.erb @@ -143,8 +143,7 @@ <hr class="hide" /> <div id="footer"> <div class="wrapper"> - <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p> - <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> + <%= render 'license' %> </div> </div> diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 19e8426e60..493102a58f 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -154,15 +154,8 @@ module Rails self end - # Rails.application.env_config stores some of the Rails initial environment parameters. - # Currently stores: - # - # * action_dispatch.parameter_filter" => config.filter_parameters, - # * action_dispatch.secret_token" => config.secret_token, - # * action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions - # - # These parameters will be used by middlewares and engines to configure themselves. - # + # Stores some of the Rails initial environment parameters which + # will be used by middlewares and engines to configure themselves. def env_config @env_config ||= super.merge({ "action_dispatch.parameter_filter" => config.filter_parameters, diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index d14cf737d9..79b12ad4eb 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -65,17 +65,9 @@ module Rails def encoding=(value) @encoding = value - if "ruby".encoding_aware? - silence_warnings do - Encoding.default_external = value - Encoding.default_internal = value - end - else - $KCODE = value - if $KCODE == "NONE" - raise "The value you specified for config.encoding is " \ - "invalid. The possible values are UTF8, SJIS, or EUC" - end + silence_warnings do + Encoding.default_external = value + Encoding.default_internal = value end end diff --git a/railties/lib/rails/application/route_inspector.rb b/railties/lib/rails/application/route_inspector.rb index 26652a8e5e..3e08b78221 100644 --- a/railties/lib/rails/application/route_inspector.rb +++ b/railties/lib/rails/application/route_inspector.rb @@ -23,7 +23,7 @@ module Rails routes = routes.collect do |route| route_reqs = route.requirements - rack_app = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/ + rack_app = discover_rack_app(route.app) controller = route_reqs[:controller] || ':controller' action = route_reqs[:action] || ':action' @@ -70,6 +70,15 @@ module Rails "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}" end end + + def discover_rack_app(app) + class_name = app.class.name.to_s + if class_name == "ActionDispatch::Routing::Mapper::Constraints" + discover_rack_app(app.app) + elsif class_name !~ /^ActionDispatch::Routing/ + app + end + end end end end diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index 7733a8f116..3acac2a6f0 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -31,7 +31,7 @@ module Rails require 'ruby-debug' puts "=> Debugger enabled" rescue Exception - puts "You need to install ruby-debug to run the console in debugging mode. With gems, use 'gem install ruby-debug'" + puts "You need to install ruby-debug19 to run the console in debugging mode. With gems, use 'gem install ruby-debug19'" exit end end diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 816d82cac3..61479b9068 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -1,14 +1,48 @@ require 'active_support/time' require 'active_support/core_ext/object/inclusion' +require 'active_support/core_ext/object/blank' module Rails module Generators class GeneratedAttribute attr_accessor :name, :type + attr_reader :attr_options - def initialize(name, type) - type = :string if type.blank? - @name, @type = name, type.to_sym + class << self + def parse(column_definition) + name, type, has_index = column_definition.split(':') + + # if user provided "name:index" instead of "name:string:index" + # type should be set blank so GeneratedAttribute's constructor + # could set it to :string + has_index, type = type, nil if %w(index uniq).include?(type) + + type, attr_options = *parse_type_and_options(type) + new(name, type, has_index, attr_options) + end + + private + + # parse possible attribute options like :limit for string/text/binary/integer or :precision/:scale for decimals + # when declaring options curly brackets should be used + def parse_type_and_options(type) + case type + when /(string|text|binary|integer)\{(\d+)\}/ + return $1, :limit => $2.to_i + when /decimal\{(\d+),(\d+)\}/ + return :decimal, :precision => $1.to_i, :scale => $2.to_i + else + return type, {} + end + end + end + + def initialize(name, type=nil, index_type=false, attr_options={}) + @name = name + @type = (type.presence || :string).to_sym + @has_index = %w(index uniq).include?(index_type) + @has_uniq_index = %w(uniq).include?(index_type) + @attr_options = attr_options end def field_type @@ -45,9 +79,29 @@ module Rails name.to_s.humanize end + def index_name + reference? ? "#{name}_id" : name + end + def reference? self.type.in?([:references, :belongs_to]) end + + def has_index? + @has_index + end + + def has_uniq_index? + @has_uniq_index + end + + def inject_options + "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } } + end + + def inject_index_options + has_uniq_index? ? ", unique: true" : "" + end end end end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index e96fc63ee9..9cef55e0a6 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -150,9 +150,8 @@ module Rails # Convert attributes array into GeneratedAttribute objects. def parse_attributes! #:nodoc: - self.attributes = (attributes || []).map do |key_value| - name, type = key_value.split(':') - Rails::Generators::GeneratedAttribute.new(name, type) + self.attributes = (attributes || []).map do |attr| + Rails::Generators::GeneratedAttribute.parse(attr) end end diff --git a/railties/lib/rails/generators/rails/migration/migration_generator.rb b/railties/lib/rails/generators/rails/migration/migration_generator.rb index 39fa5b63b1..f87dce1502 100644 --- a/railties/lib/rails/generators/rails/migration/migration_generator.rb +++ b/railties/lib/rails/generators/rails/migration/migration_generator.rb @@ -1,7 +1,7 @@ module Rails module Generators class MigrationGenerator < NamedBase #metagenerator - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" hook_for :orm, :required => true end end diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb index 629d5eed3f..9bb29b784e 100644 --- a/railties/lib/rails/generators/rails/model/model_generator.rb +++ b/railties/lib/rails/generators/rails/model/model_generator.rb @@ -1,7 +1,7 @@ module Rails module Generators class ModelGenerator < NamedBase #metagenerator - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" hook_for :orm, :required => true end end diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE index be1d113ed8..4a3eb2c7c7 100644 --- a/railties/lib/rails/generators/rails/scaffold/USAGE +++ b/railties/lib/rails/generators/rails/scaffold/USAGE @@ -7,23 +7,29 @@ Description: under_scored, as the first argument, and an optional list of attribute pairs. - Attribute pairs are field:type arguments specifying the - model's attributes. Timestamps are added by default, so you don't have to - specify them by hand as 'created_at:datetime updated_at:datetime'. + Attributes are field arguments specifying the model's attributes. You can + optionally pass the type and an index to each field. For instance: + "title body:text tracking_id:integer:uniq" will generate a title field of + string type, a body with text type and a tracking_id as an integer with an + unique index. "index" could also be given instead of "uniq" if one desires + a non unique index. + + Timestamps are added by default, so you don't have to specify them by hand + as 'created_at:datetime updated_at:datetime'. You don't have to think up every attribute up front, but it helps to sketch out a few so you can start working with the resource immediately. - For example, 'scaffold post title:string body:text published:boolean' - gives you a model with those three attributes, a controller that handles + For example, 'scaffold post title body:text published:boolean' gives + you a model with those three attributes, a controller that handles the create/show/update/destroy, forms to create and edit your posts, and - an index that lists them all, as well as a resources :posts - declaration in config/routes.rb. + an index that lists them all, as well as a resources :posts declaration + in config/routes.rb. If you want to remove all the generated files, run 'rails destroy scaffold ModelName'. Examples: `rails generate scaffold post` - `rails generate scaffold post title:string body:text published:boolean` - `rails generate scaffold purchase order_id:integer amount:decimal` + `rails generate scaffold post title body:text published:boolean` + `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq` diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 7319fb79f6..d81c4c3e1d 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -218,8 +218,8 @@ module Rails # # create_generated_attribute(:string, 'name') # - def create_generated_attribute(attribute_type, name = 'test') - Rails::Generators::GeneratedAttribute.new(name, attribute_type.to_s) + def create_generated_attribute(attribute_type, name = 'test', index = nil) + Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':')) end protected diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 758b56d17d..0d64a136f8 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -282,6 +282,11 @@ module ApplicationTests assert_equal res, last_response.body # value should be unchanged end + test "sets ActionDispatch.test_app" do + make_basic_app + assert_equal Rails.application, ActionDispatch.test_app + end + test "sets all Active Record models to whitelist all attributes by default" do add_to_config <<-RUBY config.active_record.whitelist_attributes = true diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index cf6c4d8fc2..a0417360a1 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -137,7 +137,7 @@ module ApplicationTests end test "assignment config.encoding to default_charset" do - charset = "ruby".respond_to?(:force_encoding) ? 'Shift_JIS' : 'UTF8' + charset = 'Shift_JIS' add_to_config "config.encoding = '#{charset}'" require "#{app_path}/config/environment" assert_equal charset, ActionDispatch::Response.default_charset diff --git a/railties/test/application/route_inspect_test.rb b/railties/test/application/route_inspect_test.rb index 2ad5ee6c4c..6503251b9f 100644 --- a/railties/test/application/route_inspect_test.rb +++ b/railties/test/application/route_inspect_test.rb @@ -127,5 +127,22 @@ module ApplicationTests output = @inspector.format @set.routes assert_equal [" /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output end + + def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints + constraint = Class.new do + def to_s + "( my custom constraint )" + end + end + + @set.draw do + scope :constraint => constraint.new do + mount RackApp => '/foo' + end + end + + output = @inspector.format @set.routes + assert_equal [" /foo #{RackApp.name} {:constraint=>( my custom constraint )}"], output + end end end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index a06facc04b..aa55a3cf1e 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -27,23 +27,6 @@ module ApplicationTests run_test_file 'unit/foo_test.rb' end - # Run just in Ruby < 1.9 - if defined?(Test::Unit::Util::BacktraceFilter) - test "adds backtrace cleaner" do - app_file 'test/unit/backtrace_test.rb', <<-RUBY - require 'test_helper' - - class FooTest < ActiveSupport::TestCase - def test_truth - assert Test::Unit::Util::BacktraceFilter.ancestors.include?(Rails::BacktraceFilterForTestUnit) - end - end - RUBY - - run_test_file 'unit/backtrace_test.rb' - end - end - test "integration test" do controller 'posts', <<-RUBY class PostsController < ActionController::Base diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index a85829085c..6e3fc84781 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -69,7 +69,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_default_value_for_type - att = Rails::Generators::GeneratedAttribute.new("type", "string") + att = Rails::Generators::GeneratedAttribute.parse("type:string") assert_equal("", att.default) end @@ -122,4 +122,9 @@ class GeneratedAttributeTest < Rails::Generators::TestCase assert_equal :string, create_generated_attribute(nil, 'title').type assert_equal :string, create_generated_attribute("", 'title').type end + + def test_handles_index_names_for_references + assert_equal "post", create_generated_attribute('string', 'post').index_name + assert_equal "post_id", create_generated_attribute('references', 'post').index_name + end end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 337257df7d..68fbd58061 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -58,6 +58,68 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_add_migration_with_attributes_and_indices + migration = "add_title_with_index_and_body_to_posts" + run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :posts, :title, :string/, up) + assert_match(/add_column :posts, :body, :text/, up) + assert_match(/add_column :posts, :user_id, :integer/, up) + end + assert_match(/add_index :posts, :title/, content) + assert_match(/add_index :posts, :user_id, unique: true/, content) + end + end + + def test_add_migration_with_attributes_and_wrong_index_declaration + migration = "add_title_and_content_to_books" + run_generator [migration, "title:string:inex", "content:text", "user_id:integer:unik"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :books, :title, :string/, up) + assert_match(/add_column :books, :content, :text/, up) + assert_match(/add_column :books, :user_id, :integer/, up) + end + assert_no_match(/add_index :books, :title/, content) + assert_no_match(/add_index :books, :user_id/, content) + end + end + + def test_add_migration_with_attributes_without_type_and_index + migration = "add_title_with_index_and_body_to_posts" + run_generator [migration, "title:index", "body:text", "user_uuid:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :posts, :title, :string/, up) + assert_match(/add_column :posts, :body, :text/, up) + assert_match(/add_column :posts, :user_uuid, :string/, up) + end + assert_match(/add_index :posts, :title/, content) + assert_match(/add_index :posts, :user_uuid, unique: true/, content) + end + end + + def test_add_migration_with_attributes_index_declaration_and_attribute_options + migration = "add_title_and_content_to_books" + run_generator [migration, "title:string{40}:index", "content:string{255}", "price:decimal{5,2}:index", "discount:decimal{3,2}:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :books, :title, :string, limit: 40/, up) + assert_match(/add_column :books, :content, :string, limit: 255/, up) + assert_match(/add_column :books, :price, :decimal, precision: 5, scale: 2/, up) + assert_match(/add_column :books, :discount, :decimal, precision: 3, scale: 2/, up) + end + assert_match(/add_index :books, :title/, content) + assert_match(/add_index :books, :price/, content) + assert_match(/add_index :books, :discount, unique: true/, content) + end + end + def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove migration = "create_books" run_generator [migration, "title:string", "content:text"] diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index 1b0cb425c6..156fa86eee 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -113,6 +113,74 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end + def test_migration_with_attributes_and_with_index + run_generator ["product", "name:string:index", "supplier_id:integer:index", "user_id:integer:uniq", "order_id:uniq"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + assert_match(/t\.integer :user_id/, up) + assert_match(/t\.string :order_id/, up) + + assert_match(/add_index :products, :name/, up) + assert_match(/add_index :products, :supplier_id/, up) + assert_match(/add_index :products, :user_id, unique: true/, up) + assert_match(/add_index :products, :order_id, unique: true/, up) + end + end + end + + def test_migration_with_attributes_and_with_wrong_index_declaration + run_generator ["product", "name:string", "supplier_id:integer:inex", "user_id:integer:unqu"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + assert_match(/t\.integer :user_id/, up) + + assert_no_match(/add_index :products, :name/, up) + assert_no_match(/add_index :products, :supplier_id/, up) + assert_no_match(/add_index :products, :user_id/, up) + end + end + end + + def test_migration_with_missing_attribute_type_and_with_index + run_generator ["product", "name:index", "supplier_id:integer:index", "year:integer"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + + assert_match(/add_index :products, :name/, up) + assert_match(/add_index :products, :supplier_id/, up) + assert_no_match(/add_index :products, :year/, up) + end + end + end + + def test_add_migration_with_attributes_index_declaration_and_attribute_options + run_generator ["product", "title:string{40}:index", "content:string{255}", "price:decimal{5,2}:index", "discount:decimal{5,2}:uniq"] + + assert_migration "db/migrate/create_products.rb" do |content| + assert_method :change, content do |up| + assert_match(/create_table :products/, up) + assert_match(/t.string :title, limit: 40/, up) + assert_match(/t.string :content, limit: 255/, up) + assert_match(/t.decimal :price, precision: 5, scale: 2/, up) + end + assert_match(/add_index :products, :title/, content) + assert_match(/add_index :products, :price/, content) + assert_match(/add_index :products, :discount, unique: true/, content) + end + end + def test_migration_without_timestamps ActiveRecord::Base.timestamped_migrations = false run_generator ["account"] |