From 4b71fc22ca205db8f083c2eab1cc3969f7addb69 Mon Sep 17 00:00:00 2001 From: Josiah Ivey Date: Tue, 1 Jun 2010 23:14:58 -0500 Subject: Guides: Give code container a proper bottom margin --- railties/guides/assets/stylesheets/main.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css index bab0b7a9d9..0e643f48dd 100644 --- a/railties/guides/assets/stylesheets/main.css +++ b/railties/guides/assets/stylesheets/main.css @@ -367,7 +367,8 @@ tt { div.code_container { background: #EEE url(../images/tab_grey.gif) no-repeat left top; - padding: 0.25em 1em 0.5em 48px; + padding: 0.25em 1em 0.5em 48px; + margin: 0px 0px 1.5em; } code { -- cgit v1.2.3 From 3633cb854165f9e338ecddca516bfb3dabadfa33 Mon Sep 17 00:00:00 2001 From: Josiah Ivey Date: Tue, 1 Jun 2010 23:23:46 -0500 Subject: Revert "Guides: Give code container a proper bottom margin" This reverts commit 4b71fc22ca205db8f083c2eab1cc3969f7addb69. --- railties/guides/assets/stylesheets/main.css | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css index 0e643f48dd..bab0b7a9d9 100644 --- a/railties/guides/assets/stylesheets/main.css +++ b/railties/guides/assets/stylesheets/main.css @@ -367,8 +367,7 @@ tt { div.code_container { background: #EEE url(../images/tab_grey.gif) no-repeat left top; - padding: 0.25em 1em 0.5em 48px; - margin: 0px 0px 1.5em; + padding: 0.25em 1em 0.5em 48px; } code { -- cgit v1.2.3 From 785caba8666cb15df0bfb0187b857b0131ccdd5e Mon Sep 17 00:00:00 2001 From: eparreno Date: Wed, 2 Jun 2010 21:14:33 +0200 Subject: Routing: fix error in nested resources with name_prefix example [#146 state:resolved] --- railties/guides/source/routing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 2bc1736137..79c5f4fabe 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -717,7 +717,7 @@ resources :magazines do end -This will create routing helpers such as +periodical_ads_url+ and +periodical_edit_ad_path+. +This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+. h3. Inspecting and Testing Routes -- cgit v1.2.3 From 344a695383a211600d1dba16a5999bb68df92162 Mon Sep 17 00:00:00 2001 From: eparreno Date: Wed, 2 Jun 2010 21:43:37 +0200 Subject: AR validations: update sections 2.4 and 17.1 --- .../guides/source/activerecord_validations_callbacks.textile | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile index d83ea57864..1f9bc1279a 100644 --- a/railties/guides/source/activerecord_validations_callbacks.textile +++ b/railties/guides/source/activerecord_validations_callbacks.textile @@ -115,17 +115,17 @@ end >> p = Person.new => # >> p.errors -=> # +=> {} >> p.valid? => false >> p.errors -=> #["can't be blank"]}> +=> {:name=>["can't be blank"]} >> p = Person.create => # >> p.errors -=> #["can't be blank"]}> +=> {:name=>["can't be blank"]} >> p.save => false @@ -1112,6 +1112,10 @@ h4. Creating Observers For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality. + +rails generate observer User + + class UserObserver < ActiveRecord::Observer def after_create(model) -- cgit v1.2.3 From 517f709b51d1d2766d1a783d9f02fa7a6a41abc4 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 4 Jun 2010 00:53:45 +0100 Subject: Properly cache association_collection#scopes calls having arguments --- .../active_record/associations/association_collection.rb | 3 ++- activerecord/test/cases/named_scope_test.rb | 13 +++++++++++++ activerecord/test/models/comment.rb | 1 + 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 0dfd966466..d9903243ce 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -411,7 +411,8 @@ module ActiveRecord end elsif @reflection.klass.scopes[method] @_named_scopes_cache ||= {} - @_named_scopes_cache[method] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) } + @_named_scopes_cache[method] ||= {} + @_named_scopes_cache[method][args] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) } else with_scope(construct_scope) do if block_given? diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 2007f5492f..91d8d2828b 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -428,6 +428,19 @@ class NamedScopeTest < ActiveRecord::TestCase assert_no_queries { post.comments.containing_the_letter_e.all } end + def test_named_scopes_with_arguments_are_cached_on_associations + post = posts(:welcome) + + one = post.comments.limit_by(1).all + assert_equal 1, one.size + + two = post.comments.limit_by(2).all + assert_equal 2, two.size + + assert_no_queries { post.comments.limit_by(1).all } + assert_no_queries { post.comments.limit_by(2).all } + end + def test_named_scopes_are_reset_on_association_reload post = posts(:welcome) diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index a8a99f6dce..9f6e2d3b71 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -1,4 +1,5 @@ class Comment < ActiveRecord::Base + scope :limit_by, lambda {|l| limit(l) } scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'" scope :for_first_post, :conditions => { :post_id => 1 } scope :for_first_author, -- cgit v1.2.3 From 4774680405adcbf0d3f64abbc236c7653d137fa3 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Thu, 3 Jun 2010 23:47:44 +1000 Subject: Changing command line API from 'rails blog' to 'rails new blog'. Also removed the limitation of not being able to call your new server any of the rails commands (generate, server, dbconsole, console etc) as there is no longer any ambiguity here. http://rails.lighthouseapp.com/projects/8994/tickets/4665 Signed-off-by: David Heinemeier Hansson --- railties/lib/rails/commands.rb | 6 ++++++ railties/lib/rails/commands/application.rb | 7 ++++++- railties/lib/rails/generators/rails/app/USAGE | 4 ++-- railties/lib/rails/generators/rails/app/app_generator.rb | 3 +-- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index de93a87615..aad1170b56 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -38,6 +38,10 @@ when 'dbconsole' when 'application', 'runner' require "rails/commands/#{command}" +when 'new' + puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" + puts "Type 'rails' for help." + when '--version', '-v' ARGV.unshift '--version' require 'rails/commands/application' @@ -53,6 +57,8 @@ The most common rails commands are: server Start the Rails server (short-cut alias: "s") dbconsole Start a console for the database specified in config/database.yml (short-cut alias: "db") + new Create a new Rails application. "rails new my_app" creates a + new application called MyApp in "./my_app" In addition to those, there are: application Generate the Rails application code diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb index 8a8143e00e..a3a5aed399 100644 --- a/railties/lib/rails/commands/application.rb +++ b/railties/lib/rails/commands/application.rb @@ -4,7 +4,12 @@ if %w(--version -v).include? ARGV.first exit(0) end -ARGV << "--help" if ARGV.empty? +if ARGV.first != "new" || ARGV.empty? + ARGV[0] = "--help" +else + ARGV.shift +end + require 'rubygems' if ARGV.include?("--dev") require 'rails/generators' diff --git a/railties/lib/rails/generators/rails/app/USAGE b/railties/lib/rails/generators/rails/app/USAGE index 36d6061a59..9e7a78d132 100644 --- a/railties/lib/rails/generators/rails/app/USAGE +++ b/railties/lib/rails/generators/rails/app/USAGE @@ -1,9 +1,9 @@ Description: - The 'rails' command creates a new Rails application with a default + The 'rails new' command creates a new Rails application with a default directory structure and configuration at the path you specify. Example: - rails ~/Code/Ruby/weblog + rails new ~/Code/Ruby/weblog This generates a skeletal Rails installation in ~/Code/Ruby/weblog. See the README in the newly created application to get going. diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index cd4a3dce4e..fc971907df 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -149,8 +149,7 @@ module Rails # can change in Ruby 1.8.7 when we FileUtils.cd. RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__)) - RESERVED_NAMES = %w[generate g console c server s dbconsole db - application destroy benchmarker profiler + RESERVED_NAMES = %w[application destroy benchmarker profiler plugin runner test] class AppGenerator < Base -- cgit v1.2.3 From bf83c5709f212b25575249bc7e1b6d7f7a0ad085 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Fri, 4 Jun 2010 00:03:42 +1000 Subject: Updating guides to new rails initialization process Signed-off-by: David Heinemeier Hansson --- railties/guides/source/3_0_release_notes.textile | 6 +++--- railties/guides/source/generators.textile | 2 +- railties/guides/source/getting_started.textile | 2 +- railties/guides/source/rails_application_templates.textile | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index b7f4fbf35c..2a8d7fbcdb 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -81,7 +81,7 @@ The new installing rails sequence (for the beta) is: $ gem install rails --prerelease -$ rails myapp +$ rails new myapp $ cd myapp @@ -98,13 +98,13 @@ h4. Living on the Edge If you want to bundle straight from the Git repository, you can pass the +--edge+ flag: -$ rails myapp --edge +$ rails new myapp --edge If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag: -$ ruby /path/to/rails/bin/rails myapp --dev +$ ruby /path/to/rails/bin/rails new myapp --dev h3. Rails Architectural Changes diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile index b77a2837c3..704a8793b2 100644 --- a/railties/guides/source/generators.textile +++ b/railties/guides/source/generators.textile @@ -20,7 +20,7 @@ h3. First contact When you create an application using the +rails+ command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking +rails generate+: -$ rails myapp +$ rails new myapp $ cd myapp $ rails generate diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 46e709d0f5..89551a223d 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -160,7 +160,7 @@ The best way to use this guide is to follow each step as it happens, no code or To begin, open a terminal, navigate to a folder where you have rights to create files, and type: -$ rails blog +$ rails new blog This will create a Rails application called Blog in a directory called blog. diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile index baaa3d6d66..1af6f56957 100644 --- a/railties/guides/source/rails_application_templates.textile +++ b/railties/guides/source/rails_application_templates.textile @@ -14,13 +14,13 @@ h3. Usage To apply a template, you need to provide the Rails generator with the location of the template you wish to apply, using -m option : -$ rails blog -m ~/template.rb +$ rails new blog -m ~/template.rb It's also possible to apply a template using a URL : -$ rails blog -m http://gist.github.com/31208.txt +$ rails new blog -m http://gist.github.com/31208.txt Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application : -- cgit v1.2.3 From 6401ab587021b78c3dc5e4a5ac831823a9258481 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Fri, 4 Jun 2010 16:36:38 +1000 Subject: Missed fixing the banner on the Usage output for Thor Signed-off-by: David Heinemeier Hansson --- railties/lib/rails/generators/rails/app/app_generator.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index fc971907df..7d50e7da67 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -309,7 +309,7 @@ module Rails protected def self.banner - "rails #{self.arguments.map(&:usage).join(' ')} [options]" + "rails new #{self.arguments.map(&:usage).join(' ')} [options]" end def builder -- cgit v1.2.3 From 67a43554f153a3ddb97039b5fac305c0619dd372 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 5 Jun 2010 01:13:37 +0200 Subject: removes Array#random_element and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune --- .../associations/eager_load_nested_include_test.rb | 14 +++++----- activerecord/test/cases/named_scope_test.rb | 2 +- activesupport/CHANGELOG | 2 +- .../active_support/core_ext/array/random_access.rb | 22 +++++++++++++--- activesupport/test/core_ext/array_ext_test.rb | 30 +++++++++++++++++----- railties/guides/source/3_0_release_notes.textile | 1 + .../source/active_support_core_extensions.textile | 16 +++++++++--- .../application/initializers/frameworks_test.rb | 4 +-- 8 files changed, 66 insertions(+), 25 deletions(-) diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 2beb3f8365..c7671a8c22 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -17,7 +17,7 @@ module Remembered module ClassMethods def remembered; @@remembered ||= []; end - def random_element; @@remembered.random_element; end + def sample; @@remembered.sample; end end end @@ -79,14 +79,14 @@ class EagerLoadPolyAssocsTest < ActiveRecord::TestCase [Circle, Square, Triangle, NonPolyOne, NonPolyTwo].map(&:create!) end 1.upto(NUM_SIMPLE_OBJS) do - PaintColor.create!(:non_poly_one_id => NonPolyOne.random_element.id) - PaintTexture.create!(:non_poly_two_id => NonPolyTwo.random_element.id) + PaintColor.create!(:non_poly_one_id => NonPolyOne.sample.id) + PaintTexture.create!(:non_poly_two_id => NonPolyTwo.sample.id) end 1.upto(NUM_SHAPE_EXPRESSIONS) do - shape_type = [Circle, Square, Triangle].random_element - paint_type = [PaintColor, PaintTexture].random_element - ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.random_element.id, - :paint_type => paint_type.to_s, :paint_id => paint_type.random_element.id) + shape_type = [Circle, Square, Triangle].sample + paint_type = [PaintColor, PaintTexture].sample + ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.sample.id, + :paint_type => paint_type.to_s, :paint_id => paint_type.sample.id) end end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 91d8d2828b..33ffb041c1 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -301,7 +301,7 @@ class NamedScopeTest < ActiveRecord::TestCase end def test_rand_should_select_a_random_object_from_proxy - assert_kind_of Topic, Topic.approved.random_element + assert_kind_of Topic, Topic.approved.sample end def test_should_use_where_in_query_for_named_scope diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index d853788e00..0e24cc138a 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -4,7 +4,7 @@ * Ruby 1.9: support UTF-8 case folding. #4595 [Norman Clarke] -* Renames Array#rand -> Array#random_element. [Santiago Pastorino, Rizwan Reza] +* Removes Array#rand and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune. [fxn] * Ruby 1.9: Renames last_(month|year) to prev_(month|year) in Date and Time. [fxn] diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb index 67c322daea..7a4836cecd 100644 --- a/activesupport/lib/active_support/core_ext/array/random_access.rb +++ b/activesupport/lib/active_support/core_ext/array/random_access.rb @@ -1,6 +1,20 @@ class Array - # Returns a random element from the array. - def random_element - self[Kernel.rand(length)] - end + # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/ + def sample(n=nil) + return self[Kernel.rand(size)] if n.nil? + n = n.to_int + rescue Exception => e + raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})" + else + raise TypeError, "Coercion error: obj.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? Integer + raise ArgumentError, "negative array size" if n < 0 + n = size if n > size + result = Array.new(self) + n.times do |i| + r = i + Kernel.rand(size - i) + result[i], result[r] = result[r], result[i] + end + result[n..size] = [] + result + end unless method_defined? :sample end \ No newline at end of file diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index 1f7cdb8ec1..54376deee5 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -359,14 +359,30 @@ class ArrayUniqByTests < Test::Unit::TestCase end class ArrayExtRandomTests < ActiveSupport::TestCase - def test_random_element_from_array - assert_nil [].random_element - - Kernel.expects(:rand).with(1).returns(0) - assert_equal 'x', ['x'].random_element + def test_sample_from_array + assert_nil [].sample + assert_equal [], [].sample(5) + assert_equal 42, [42].sample + assert_equal [42], [42].sample(5) + + a = [:foo, :bar, 42] + s = a.sample(2) + assert_equal 2, s.size + assert_equal 1, (a-s).size + assert_equal [], a-(0..20).sum{a.sample(2)} + + o = Object.new + def o.to_int; 1; end + assert_equal [0], [0].sample(o) + + o = Object.new + assert_raises(TypeError) { [0].sample(o) } + + o = Object.new + def o.to_int; ''; end + assert_raises(TypeError) { [0].sample(o) } - Kernel.expects(:rand).with(3).returns(1) - assert_equal 2, [1, 2, 3].random_element + assert_raises(ArgumentError) { [0].sample(-7) } end end diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index 2a8d7fbcdb..75c03be87c 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -512,6 +512,7 @@ These are the main changes in Active Support: * Active Support no longer provides vendored versions of "TZInfo":http://tzinfo.rubyforge.org/, "Memcache Client":http://deveiate.org/projects/RMemCache/ and "Builder":http://builder.rubyforge.org/, these are all included as dependencies and installed via the bundle install command. * Safe buffers are implemented in ActiveSupport::SafeBuffer. * Added Array.uniq_by and Array.uniq_by!. +* Removed Array#rand and backported Array#sample from Ruby 1.9. * Fixed bug on +TimeZone.seconds_to_utc_offset+ returning wrong value. * Added ActiveSupport::Notifications middleware. * ActiveSupport.use_standard_json_time_format now defaults to true. diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index de82e871a6..6c3a005daf 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1927,13 +1927,23 @@ Similarly, +from+ returns the tail from the element at the passed index on: The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is builtin). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available. -You can pick a random element with +random_element+: +NOTE: Defined in +active_support/core_ext/array/access.rb+. + +h4. Random Access + +Active Support backports +sample+ from Ruby 1.9: + +You can pick a random element with +sample+: -shape_type = [Circle, Square, Triangle].random_element +shape_type = [Circle, Square, Triangle].sample +# => Square, for example + +shape_types = [Circle, Square, Triangle].sample(2) +# => [Triangle, Circle], for example -NOTE: Defined in +active_support/core_ext/array/access.rb+. +NOTE: Defined in +active_support/core_ext/array/random_access.rb+. h4. Options Extraction diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index fadcc4c025..35ea2729d3 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -47,7 +47,7 @@ module ApplicationTests test "if there's no config.active_support.bare, all of ActiveSupport is required" do use_frameworks [] require "#{app_path}/config/environment" - assert_nothing_raised { [1,2,3].random_element } + assert_nothing_raised { [1,2,3].sample } end test "config.active_support.bare does not require all of ActiveSupport" do @@ -57,7 +57,7 @@ module ApplicationTests Dir.chdir("#{app_path}/app") do require "#{app_path}/config/environment" - assert_raises(NoMethodError) { [1,2,3].random_element } + assert_raises(NoMethodError) { [1,2,3].sample } end end -- cgit v1.2.3 From 8e8cb1769f3a78c53e5b79d0ce6a08589045cfca Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 5 Jun 2010 01:19:23 +0200 Subject: AS guide: removes your spurious line --- railties/guides/source/active_support_core_extensions.textile | 2 -- 1 file changed, 2 deletions(-) diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 6c3a005daf..30b2099be4 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1933,8 +1933,6 @@ h4. Random Access Active Support backports +sample+ from Ruby 1.9: -You can pick a random element with +sample+: - shape_type = [Circle, Square, Triangle].sample # => Square, for example -- cgit v1.2.3 From 1535b02a9f8e0eaa3cd3182a45d2bd7855c3809c Mon Sep 17 00:00:00 2001 From: Matt Di Pasquale Date: Wed, 24 Mar 2010 02:17:09 -0400 Subject: Improve Rails README [#4740 state:resolved] Signed-off-by: Rizwan Reza --- railties/README | 198 +++++++------ .../rails/generators/rails/app/templates/README | 308 +++++++++++++-------- 2 files changed, 302 insertions(+), 204 deletions(-) diff --git a/railties/README b/railties/README index e4de4a5cb2..4d155189cd 100644 --- a/railties/README +++ b/railties/README @@ -3,12 +3,13 @@ Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. -This pattern splits the view (also called the presentation) into "dumb" templates -that are primarily responsible for inserting pre-built data in between HTML tags. -The model contains the "smart" domain objects (such as Account, Product, Person, -Post) that holds all the business logic and knows how to persist themselves to -a database. The controller handles the incoming requests (such as Save New Account, -Update Product, Show Post) by manipulating the model and directing data to the view. +This pattern splits the view (also called the presentation) into "dumb" +templates that are primarily responsible for inserting pre-built data in between +HTML tags. The model contains the "smart" domain objects (such as Account, +Product, Person, Post) that holds all the business logic and knows how to +persist themselves to a database. The controller handles the incoming requests +(such as Save New Account, Update Product, Show Post) by manipulating the model +and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from @@ -21,35 +22,45 @@ layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of -Rails. You can read more about Action Pack in +Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started -1. At the command prompt, start a new Rails application using the rails command - and your application name. Ex: rails myapp -2. Change directory into myapp and start the web server: rails server (run with --help for options) -3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" -4. Follow the guidelines to start developing your application +1. At the command prompt, create a new Rails application: + rails myapp (where myapp is the application name) + +2. Change directory to myapp and start the web server: + cd myapp; rails server (run with --help for options) + +3. Go to http://localhost:3000/ and get: + "Welcome aboard: You're riding the Rails!" + +4. Follow the guidelines to start developing your application. == Web Servers -By default, Rails will try to use Mongrel if it's installed when started with rails server, otherwise -Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails with a variety of -other web servers. +By default, Rails will try to use Mongrel if it's installed when started with +rails server, otherwise Rails will use WEBrick, the web server that +ships with Ruby. -Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is -suitable for development and deployment of Rails applications. If you have Ruby Gems installed, -getting up and running with mongrel is as easy as: gem install mongrel. +Mongrel is a Ruby-based web server with a C component (which requires +compilation) that is suitable for development and deployment of Rails +applications. If you have Ruby Gems installed, getting up and running with +mongrel is as easy as: sudo gem install mongrel. More info at: http://mongrel.rubyforge.org -Other ruby web servers exist which can run your rails application, however rails server does -not search for them or start them. These include {Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and Apache with {mod_rails}[http://www.modrails.com/]. +You can alternatively run Rails applications with other Ruby web servers, e.g., +{Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and +Apache with {mod_rails}[http://www.modrails.com/]. However, rails server +doesn't search for or start them. -For production use, often a web/proxy server such as {Apache}[http://apache.org], {Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/], {Lighttpd}[http://www.lighttpd.net/] or {IIS}[http://www.iis.net/] is -deployed as the front-end server, with the chosen ruby web server running in the back-end +For production use, often a web/proxy server, e.g., {Apache}[http://apache.org], +{Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/], +{Lighttpd}[http://www.lighttpd.net/], or {IIS}[http://www.iis.net/], is deployed +as the front end server with the chosen Ruby web server running in the back end and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI). @@ -85,24 +96,25 @@ set the RewriteBase in this htaccess file. RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ dispatch.cgi [QSA,L] -Incase Rails experiences terminal errors instead of displaying those messages you -can supply a file here which will be rendered instead. +In case Rails experiences terminal errors, you may supply a file here to be +rendered instead. ErrorDocument 500 /500.html - ErrorDocument 500 "

Application error

Rails application failed to start properly" + ErrorDocument 500 "

Application Error

Rails failed to start properly." + == Debugging Rails -Sometimes your application goes wrong. Fortunately there are a lot of tools that +Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. -First area to check is the application log files. Have "tail -f" commands running -on the server.log and development.log. Rails will automatically display debugging -and runtime information to these files. Debugging info will also be shown in the -browser on requests from 127.0.0.1. +First area to check is the application log files. Have "tail -f" commands +running on the server.log and development.log. Rails will automatically display +debugging and runtime information to these files. Debugging info will also be +shown in the browser on requests from 127.0.0.1. -You can also log your own messages directly into the log file from your code using -the Ruby logger class from inside your controllers. Example: +You can also log your own messages directly into the log file from your code +using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @@ -114,26 +126,26 @@ the Ruby logger class from inside your controllers. Example: The result will be a message in your log file along the lines of: - Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1 + Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: -* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ -* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) +* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) +* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) -These two online (and free) books will bring you up to speed on the Ruby language -and also on programming in general. +These two online (and free) books will bring you up to speed on the Ruby +language and also on programming in general. == Debugger -Debugger support is available through the debugger command when you start your Mongrel or -Webrick server with --debugger. This means that you can break out of execution at any point -in the code, investigate and change the model, AND then resume execution! -You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' -Example: +Debugger support is available through the debugger command when you start your +Mongrel or WEBrick server with --debugger. This means that you can break out of +execution at any point in the code, investigate and change the model, and then, +resume execution! You need to install ruby-debug to run the server in debugging +mode. With gems, use sudo gem install ruby-debug. Example: class WeblogController < ActionController::Base def index @@ -146,12 +158,14 @@ So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect - => "[#nil, \"body\"=>nil, \"id\"=>\"1\"}>, - #\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + => "[#nil, "body"=>nil, "id"=>"1"}>, + #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" -...and even better is that you can examine how your runtime objects actually work: +...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #nil, "body"=>nil, "id"=>"1"}> @@ -163,28 +177,37 @@ Finally, when you're ready to resume execution, you enter "cont" == Console -The console is a ruby shell, which allows you to interact with your application's domain -model. Here you'll have all parts of the application configured, just like it is when the -application is running. You can inspect domain models, change values, and save to the -database. Starting the script without arguments will launch it in the development environment. +The console is a Ruby shell, which allows you to interact with your +application's domain model. Here you'll have all parts of the application +configured, just like it is when the application is running. You can inspect +domain models, change values, and save to the database. Starting the script +without arguments will launch it in the development environment. -To start the console, just run rails console from the application directory. +To start the console, run rails console from the application +directory. Options: -* Passing the -s, --sandbox argument will rollback any modifications made to the database. -* Passing an environment name as an argument will load the corresponding environment. - Example: rails console production. +* Passing the -s, --sandbox argument will rollback any modifications + made to the database. +* Passing an environment name as an argument will load the corresponding + environment. Example: rails console production. + +To reload your controllers and models after launching the console run +reload! + +More information about irb can be found at: +link:http://www.rubycentral.com/pickaxe/irb.html -More information about irb can be found at link:http://www.rubycentral.com/pickaxe/irb.html == dbconsole -You can go to the command line of your database directly through rails dbconsole. -You would be connected to the database with the credentials defined in database.yml. -Starting the script without arguments will connect you to the development database. Passing an -argument will connect you to a different database, like rails dbconsole production. -Currently works for mysql, postgresql and sqlite. +You can go to the command line of your database directly through rails +dbconsole. You would be connected to the database with the credentials +defined in database.yml. Starting the script without arguments will connect you +to the development database. Passing an argument will connect you to a different +database, like rails dbconsole production. Currently works for mysql, +postgresql and sqlite. == Description of Contents @@ -230,8 +253,8 @@ app app/controllers Holds controllers that should be named like weblogs_controller.rb for - automated URL mapping. All controllers should descend from ApplicationController - which itself descends from ActionController::Base. + automated URL mapping. All controllers should descend from + ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. @@ -239,48 +262,53 @@ app/models app/views Holds the template files for the view that should be named like - weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby - syntax. + weblogs/index.html.erb for the WeblogsController#index action. All views use + eRuby syntax. app/views/layouts - Holds the template files for layouts to be used with views. This models the common - header/footer method of wrapping views. In your views, define a layout using the - layout :default and create a file named default.html.erb. Inside default.html.erb, - call <% yield %> to render the view using this layout. + Holds the template files for layouts to be used with views. This models the + common header/footer method of wrapping views. In your views, define a layout + using the layout :default and create a file named default.html.erb. + Inside default.html.erb, call <% yield %> to render the view using this + layout. app/helpers - Holds view helpers that should be named like weblogs_helper.rb. These are generated - for you automatically when using rails generate for controllers. Helpers can be used to - wrap functionality for your views into methods. + Holds view helpers that should be named like weblogs_helper.rb. These are + generated for you automatically when using rails generate for controllers. + Helpers can be used to wrap functionality for your views into methods. config - Configuration files for the Rails environment, the routing map, the database, and other dependencies. + Configuration files for the Rails environment, the routing map, the database, + and other dependencies. db - Contains the database schema in schema.rb. db/migrate contains all - the sequence of Migrations for your schema. + Contains the database schema in schema.rb. db/migrate contains all the + sequence of Migrations for your schema. doc - This directory is where your application documentation will be stored when generated - using rake doc:app + This directory is where your application documentation will be stored when + generated using rake doc:app lib - Application specific libraries. Basically, any kind of custom code that doesn't - belong under controllers, models, or helpers. This directory is in the load path. + Application specific libraries. Basically, any kind of custom code that + doesn't belong under controllers, models, or helpers. This directory is in + the load path. public - The directory available for the web server. Contains subdirectories for images, stylesheets, - and javascripts. Also contains the dispatchers and the default HTML files. This should be - set as the DOCUMENT_ROOT of your web server. + The directory available for the web server. Contains subdirectories for + images, stylesheets, and javascripts. Also contains the dispatchers and the + default HTML files. This should be set as the DOCUMENT_ROOT of your web + server. script Helper scripts for automation and generation. test - Unit and functional tests along with fixtures. When using the rails generate scripts, template - test files will be generated for you and placed in this directory. + Unit and functional tests along with fixtures. When using the rails generate + command, template test files will be generated for you and placed in this + directory. vendor - External libraries that the application depends on. Also includes the plugins subdirectory. - If the app has frozen rails, those gems also go here, under vendor/rails/. - This directory is in the load path. + External libraries that the application depends on. Also includes the plugins + subdirectory. If the app has frozen rails, those gems also go here, under + vendor/rails/. This directory is in the load path. diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README index 65d1459d0e..4d155189cd 100644 --- a/railties/lib/rails/generators/rails/app/templates/README +++ b/railties/lib/rails/generators/rails/app/templates/README @@ -1,14 +1,15 @@ == Welcome to Rails -Rails is a web-application framework that includes everything needed to create -database-backed web applications according to the Model-View-Control pattern. +Rails is a web-application framework that includes everything needed to create +database-backed web applications according to the Model-View-Control pattern. -This pattern splits the view (also called the presentation) into "dumb" templates -that are primarily responsible for inserting pre-built data in between HTML tags. -The model contains the "smart" domain objects (such as Account, Product, Person, -Post) that holds all the business logic and knows how to persist themselves to -a database. The controller handles the incoming requests (such as Save New Account, -Update Product, Show Post) by manipulating the model and directing data to the view. +This pattern splits the view (also called the presentation) into "dumb" +templates that are primarily responsible for inserting pre-built data in between +HTML tags. The model contains the "smart" domain objects (such as Account, +Product, Person, Post) that holds all the business logic and knows how to +persist themselves to a database. The controller handles the incoming requests +(such as Save New Account, Update Product, Show Post) by manipulating the model +and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from @@ -21,90 +22,99 @@ layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of -Rails. You can read more about Action Pack in +Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started -1. At the command prompt, start a new Rails application using the rails command - and your application name. Ex: rails myapp -2. Change directory into myapp and start the web server: rails server (run with --help for options) -3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!" -4. Follow the guidelines to start developing your application +1. At the command prompt, create a new Rails application: + rails myapp (where myapp is the application name) + +2. Change directory to myapp and start the web server: + cd myapp; rails server (run with --help for options) + +3. Go to http://localhost:3000/ and get: + "Welcome aboard: You're riding the Rails!" + +4. Follow the guidelines to start developing your application. == Web Servers -By default, Rails will try to use Mongrel if it's installed when started with rails server, otherwise -Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails -with a variety of other web servers. +By default, Rails will try to use Mongrel if it's installed when started with +rails server, otherwise Rails will use WEBrick, the web server that +ships with Ruby. -Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is -suitable for development and deployment of Rails applications. If you have Ruby Gems installed, -getting up and running with mongrel is as easy as: gem install mongrel. +Mongrel is a Ruby-based web server with a C component (which requires +compilation) that is suitable for development and deployment of Rails +applications. If you have Ruby Gems installed, getting up and running with +mongrel is as easy as: sudo gem install mongrel. More info at: http://mongrel.rubyforge.org -You can also use other Ruby web servers like Thin and Ebb or regular web servers like Apache, LiteSpeed, -Lighttpd, or IIS. The Ruby web servers are run through Rack and the others can be setup to use -FCGI or proxy to a pack of Mongrels/Thin/Ebb servers. +You can alternatively run Rails applications with other Ruby web servers, e.g., +{Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and +Apache with {mod_rails}[http://www.modrails.com/]. However, rails server +doesn't search for or start them. + +For production use, often a web/proxy server, e.g., {Apache}[http://apache.org], +{Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/], +{Lighttpd}[http://www.lighttpd.net/], or {IIS}[http://www.iis.net/], is deployed +as the front end server with the chosen Ruby web server running in the back end +and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI). + == Apache .htaccess example for FCGI/CGI -# General Apache options -AddHandler fastcgi-script .fcgi -AddHandler cgi-script .cgi -Options +FollowSymLinks +ExecCGI - -# If you don't want Rails to look in certain directories, -# use the following rewrite rules so that Apache won't rewrite certain requests -# -# Example: -# RewriteCond %{REQUEST_URI} ^/notrails.* -# RewriteRule .* - [L] - -# Redirect all requests not available on the filesystem to Rails -# By default the cgi dispatcher is used which is very slow -# -# For better performance replace the dispatcher with the fastcgi one -# -# Example: -# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] -RewriteEngine On - -# If your Rails application is accessed via an Alias directive, -# then you MUST also set the RewriteBase in this htaccess file. -# -# Example: -# Alias /myrailsapp /path/to/myrailsapp/public -# RewriteBase /myrailsapp - -RewriteRule ^$ index.html [QSA] -RewriteRule ^([^.]+)$ $1.html [QSA] -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^(.*)$ dispatch.cgi [QSA,L] - -# In case Rails experiences terminal errors -# Instead of displaying this message you can supply a file here which will be rendered instead -# -# Example: -# ErrorDocument 500 /500.html - -ErrorDocument 500 "

Application error

Rails application failed to start properly" +General Apache options + + AddHandler fastcgi-script .fcgi + AddHandler cgi-script .cgi + Options +FollowSymLinks +ExecCGI + +If you don't want Rails to look in certain directories, use the following +rewrite rules so that Apache won't rewrite certain requests. + + RewriteCond %{REQUEST_URI} ^/notrails.* + RewriteRule .* - [L] + +Redirect all requests not available on the filesystem to Rails. By default the +cgi dispatcher is used which is very slow, for better performance replace the +dispatcher with the fastcgi one. + + RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] + RewriteEngine On + +If your Rails application is accessed via an Alias directive, then you MUST also +set the RewriteBase in this htaccess file. + + Alias /myrailsapp /path/to/myrailsapp/public + RewriteBase /myrailsapp + + RewriteRule ^$ index.html [QSA] + RewriteRule ^([^.]+)$ $1.html [QSA] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ dispatch.cgi [QSA,L] + +In case Rails experiences terminal errors, you may supply a file here to be +rendered instead. + + ErrorDocument 500 /500.html + ErrorDocument 500 "

Application Error

Rails failed to start properly." == Debugging Rails -Sometimes your application goes wrong. Fortunately there are a lot of tools that +Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. -First area to check is the application log files. Have "tail -f" commands running -on the server.log and development.log. Rails will automatically display debugging -and runtime information to these files. Debugging info will also be shown in the -browser on requests from 127.0.0.1. +First area to check is the application log files. Have "tail -f" commands +running on the server.log and development.log. Rails will automatically display +debugging and runtime information to these files. Debugging info will also be +shown in the browser on requests from 127.0.0.1. -You can also log your own messages directly into the log file from your code using -the Ruby logger class from inside your controllers. Example: +You can also log your own messages directly into the log file from your code +using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @@ -122,20 +132,20 @@ More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: -* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/ -* Learn to Program: http://pine.fm/LearnToProgram/ (a beginner's guide) +* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) +* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) -These two online (and free) books will bring you up to speed on the Ruby language -and also on programming in general. +These two online (and free) books will bring you up to speed on the Ruby +language and also on programming in general. == Debugger -Debugger support is available through the debugger command when you start your Mongrel or -Webrick server with --debugger. This means that you can break out of execution at any point -in the code, investigate and change the model, AND then resume execution! -You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug' -Example: +Debugger support is available through the debugger command when you start your +Mongrel or WEBrick server with --debugger. This means that you can break out of +execution at any point in the code, investigate and change the model, and then, +resume execution! You need to install ruby-debug to run the server in debugging +mode. With gems, use sudo gem install ruby-debug. Example: class WeblogController < ActionController::Base def index @@ -148,12 +158,14 @@ So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect - => "[#nil, \"body\"=>nil, \"id\"=>\"1\"}>, - #\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + => "[#nil, "body"=>nil, "id"=>"1"}>, + #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" -...and even better is that you can examine how your runtime objects actually work: +...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #nil, "body"=>nil, "id"=>"1"}> @@ -165,31 +177,84 @@ Finally, when you're ready to resume execution, you enter "cont" == Console -You can interact with the domain model by starting the console through rails console. -Here you'll have all parts of the application configured, just like it is when the -application is running. You can inspect domain models, change values, and save to the -database. Starting the script without arguments will launch it in the development environment. -Passing an argument will specify a different environment, like rails console production. +The console is a Ruby shell, which allows you to interact with your +application's domain model. Here you'll have all parts of the application +configured, just like it is when the application is running. You can inspect +domain models, change values, and save to the database. Starting the script +without arguments will launch it in the development environment. + +To start the console, run rails console from the application +directory. + +Options: + +* Passing the -s, --sandbox argument will rollback any modifications + made to the database. +* Passing an environment name as an argument will load the corresponding + environment. Example: rails console production. + +To reload your controllers and models after launching the console run +reload! + +More information about irb can be found at: +link:http://www.rubycentral.com/pickaxe/irb.html -To reload your controllers and models after launching the console run reload! == dbconsole -You can go to the command line of your database directly through rails dbconsole. -You would be connected to the database with the credentials defined in database.yml. -Starting the script without arguments will connect you to the development database. Passing an -argument will connect you to a different database, like rails dbconsole production. -Currently works for mysql, postgresql and sqlite. +You can go to the command line of your database directly through rails +dbconsole. You would be connected to the database with the credentials +defined in database.yml. Starting the script without arguments will connect you +to the development database. Passing an argument will connect you to a different +database, like rails dbconsole production. Currently works for mysql, +postgresql and sqlite. == Description of Contents +The default directory structure of a generated Ruby on Rails applicartion: + + |-- app + | |-- controllers + | |-- helpers + | |-- models + | `-- views + | `-- layouts + |-- config + | |-- environments + | |-- initializers + | `-- locales + |-- db + |-- doc + |-- lib + | `-- tasks + |-- log + |-- public + | |-- images + | |-- javascripts + | `-- stylesheets + |-- script + | `-- performance + |-- test + | |-- fixtures + | |-- functional + | |-- integration + | |-- performance + | `-- unit + |-- tmp + | |-- cache + | |-- pids + | |-- sessions + | `-- sockets + `-- vendor + `-- plugins + app Holds all the code that's specific to this particular application. app/controllers Holds controllers that should be named like weblogs_controller.rb for - automated URL mapping. All controllers should descend from ApplicationController - which itself descends from ActionController::Base. + automated URL mapping. All controllers should descend from + ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. @@ -197,48 +262,53 @@ app/models app/views Holds the template files for the view that should be named like - weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby - syntax. + weblogs/index.html.erb for the WeblogsController#index action. All views use + eRuby syntax. app/views/layouts - Holds the template files for layouts to be used with views. This models the common - header/footer method of wrapping views. In your views, define a layout using the - layout :default and create a file named default.html.erb. Inside default.html.erb, - call <% yield %> to render the view using this layout. + Holds the template files for layouts to be used with views. This models the + common header/footer method of wrapping views. In your views, define a layout + using the layout :default and create a file named default.html.erb. + Inside default.html.erb, call <% yield %> to render the view using this + layout. app/helpers - Holds view helpers that should be named like weblogs_helper.rb. These are generated - for you automatically when using rails generate for controllers. Helpers can be used to - wrap functionality for your views into methods. + Holds view helpers that should be named like weblogs_helper.rb. These are + generated for you automatically when using rails generate for controllers. + Helpers can be used to wrap functionality for your views into methods. config - Configuration files for the Rails environment, the routing map, the database, and other dependencies. + Configuration files for the Rails environment, the routing map, the database, + and other dependencies. db - Contains the database schema in schema.rb. db/migrate contains all - the sequence of Migrations for your schema. + Contains the database schema in schema.rb. db/migrate contains all the + sequence of Migrations for your schema. doc - This directory is where your application documentation will be stored when generated - using rake doc:app + This directory is where your application documentation will be stored when + generated using rake doc:app lib - Application specific libraries. Basically, any kind of custom code that doesn't - belong under controllers, models, or helpers. This directory is in the load path. + Application specific libraries. Basically, any kind of custom code that + doesn't belong under controllers, models, or helpers. This directory is in + the load path. public - The directory available for the web server. Contains subdirectories for images, stylesheets, - and javascripts. Also contains the dispatchers and the default HTML files. This should be - set as the DOCUMENT_ROOT of your web server. + The directory available for the web server. Contains subdirectories for + images, stylesheets, and javascripts. Also contains the dispatchers and the + default HTML files. This should be set as the DOCUMENT_ROOT of your web + server. script Helper scripts for automation and generation. test - Unit and functional tests along with fixtures. When using the rails generate command, template - test files will be generated for you and placed in this directory. + Unit and functional tests along with fixtures. When using the rails generate + command, template test files will be generated for you and placed in this + directory. vendor - External libraries that the application depends on. Also includes the plugins subdirectory. - If the app has frozen rails, those gems also go here, under vendor/rails/. - This directory is in the load path. + External libraries that the application depends on. Also includes the plugins + subdirectory. If the app has frozen rails, those gems also go here, under + vendor/rails/. This directory is in the load path. -- cgit v1.2.3 From 55a5c7068cc75a14f3289385eb1637412f98dd48 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sat, 5 Jun 2010 04:26:01 +0430 Subject: Readme file changes: * Took out stuff that's not relevant (or useful) anymore. * Some formatting. * Added helpful links to get started with Rails. * Took out Apache htaccess tutorial since we aren't teaching Apache here. --- railties/README | 79 +++++++--------------- .../rails/generators/rails/app/templates/README | 79 +++++++--------------- 2 files changed, 46 insertions(+), 112 deletions(-) diff --git a/railties/README b/railties/README index 4d155189cd..b8c84dd07d 100644 --- a/railties/README +++ b/railties/README @@ -34,10 +34,14 @@ link:files/vendor/rails/actionpack/README.html. 2. Change directory to myapp and start the web server: cd myapp; rails server (run with --help for options) -3. Go to http://localhost:3000/ and get: +3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding the Rails!" -4. Follow the guidelines to start developing your application. +4. Follow the guidelines to start developing your application. You can find +the following resources handy: + +* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html +* Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Web Servers @@ -47,10 +51,11 @@ By default, Rails will try to use Mongrel if it's installed when started with ships with Ruby. Mongrel is a Ruby-based web server with a C component (which requires -compilation) that is suitable for development and deployment of Rails -applications. If you have Ruby Gems installed, getting up and running with -mongrel is as easy as: sudo gem install mongrel. -More info at: http://mongrel.rubyforge.org +compilation) that is suitable for development. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: + sudo gem install mongrel. + +You can find more info at: http://mongrel.rubyforge.org You can alternatively run Rails applications with other Ruby web servers, e.g., {Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and @@ -64,45 +69,6 @@ as the front end server with the chosen Ruby web server running in the back end and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI). -== Apache .htaccess example for FCGI/CGI - -General Apache options - - AddHandler fastcgi-script .fcgi - AddHandler cgi-script .cgi - Options +FollowSymLinks +ExecCGI - -If you don't want Rails to look in certain directories, use the following -rewrite rules so that Apache won't rewrite certain requests. - - RewriteCond %{REQUEST_URI} ^/notrails.* - RewriteRule .* - [L] - -Redirect all requests not available on the filesystem to Rails. By default the -cgi dispatcher is used which is very slow, for better performance replace the -dispatcher with the fastcgi one. - - RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] - RewriteEngine On - -If your Rails application is accessed via an Alias directive, then you MUST also -set the RewriteBase in this htaccess file. - - Alias /myrailsapp /path/to/myrailsapp/public - RewriteBase /myrailsapp - - RewriteRule ^$ index.html [QSA] - RewriteRule ^([^.]+)$ $1.html [QSA] - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^(.*)$ dispatch.cgi [QSA,L] - -In case Rails experiences terminal errors, you may supply a file here to be -rendered instead. - - ErrorDocument 500 /500.html - ErrorDocument 500 "

Application Error

Rails failed to start properly." - - == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that @@ -130,13 +96,14 @@ The result will be a message in your log file along the lines of: More information on how to use the logger is at http://www.ruby-doc.org/core/ -Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: +Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are +several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) -These two online (and free) books will bring you up to speed on the Ruby -language and also on programming in general. +These two books will bring you up to speed on the Ruby language and also on +programming in general. == Debugger @@ -172,7 +139,7 @@ with a IRB prompt in the server window. Here you can do things like: >> f. Display all 152 possibilities? (y or n) -Finally, when you're ready to resume execution, you enter "cont" +Finally, when you're ready to resume execution, you can enter "cont". == Console @@ -206,12 +173,12 @@ You can go to the command line of your database directly through rails dbconsole. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different -database, like rails dbconsole production. Currently works for mysql, -postgresql and sqlite. +database, like rails dbconsole production. Currently works for MySQL, +PostgreSQL and SQLite 3. == Description of Contents -The default directory structure of a generated Ruby on Rails applicartion: +The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers @@ -257,13 +224,13 @@ app/controllers ApplicationController which itself descends from ActionController::Base. app/models - Holds models that should be named like post.rb. - Most models will descend from ActiveRecord::Base. + Holds models that should be named like post.rb. Models descend from + ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use - eRuby syntax. + eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the @@ -274,7 +241,7 @@ app/views/layouts app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are - generated for you automatically when using rails generate for controllers. + generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README index 4d155189cd..b8c84dd07d 100644 --- a/railties/lib/rails/generators/rails/app/templates/README +++ b/railties/lib/rails/generators/rails/app/templates/README @@ -34,10 +34,14 @@ link:files/vendor/rails/actionpack/README.html. 2. Change directory to myapp and start the web server: cd myapp; rails server (run with --help for options) -3. Go to http://localhost:3000/ and get: +3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding the Rails!" -4. Follow the guidelines to start developing your application. +4. Follow the guidelines to start developing your application. You can find +the following resources handy: + +* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html +* Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Web Servers @@ -47,10 +51,11 @@ By default, Rails will try to use Mongrel if it's installed when started with ships with Ruby. Mongrel is a Ruby-based web server with a C component (which requires -compilation) that is suitable for development and deployment of Rails -applications. If you have Ruby Gems installed, getting up and running with -mongrel is as easy as: sudo gem install mongrel. -More info at: http://mongrel.rubyforge.org +compilation) that is suitable for development. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: + sudo gem install mongrel. + +You can find more info at: http://mongrel.rubyforge.org You can alternatively run Rails applications with other Ruby web servers, e.g., {Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and @@ -64,45 +69,6 @@ as the front end server with the chosen Ruby web server running in the back end and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI). -== Apache .htaccess example for FCGI/CGI - -General Apache options - - AddHandler fastcgi-script .fcgi - AddHandler cgi-script .cgi - Options +FollowSymLinks +ExecCGI - -If you don't want Rails to look in certain directories, use the following -rewrite rules so that Apache won't rewrite certain requests. - - RewriteCond %{REQUEST_URI} ^/notrails.* - RewriteRule .* - [L] - -Redirect all requests not available on the filesystem to Rails. By default the -cgi dispatcher is used which is very slow, for better performance replace the -dispatcher with the fastcgi one. - - RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] - RewriteEngine On - -If your Rails application is accessed via an Alias directive, then you MUST also -set the RewriteBase in this htaccess file. - - Alias /myrailsapp /path/to/myrailsapp/public - RewriteBase /myrailsapp - - RewriteRule ^$ index.html [QSA] - RewriteRule ^([^.]+)$ $1.html [QSA] - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^(.*)$ dispatch.cgi [QSA,L] - -In case Rails experiences terminal errors, you may supply a file here to be -rendered instead. - - ErrorDocument 500 /500.html - ErrorDocument 500 "

Application Error

Rails failed to start properly." - - == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that @@ -130,13 +96,14 @@ The result will be a message in your log file along the lines of: More information on how to use the logger is at http://www.ruby-doc.org/core/ -Also, Ruby documentation can be found at http://www.ruby-lang.org/ including: +Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are +several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) -These two online (and free) books will bring you up to speed on the Ruby -language and also on programming in general. +These two books will bring you up to speed on the Ruby language and also on +programming in general. == Debugger @@ -172,7 +139,7 @@ with a IRB prompt in the server window. Here you can do things like: >> f. Display all 152 possibilities? (y or n) -Finally, when you're ready to resume execution, you enter "cont" +Finally, when you're ready to resume execution, you can enter "cont". == Console @@ -206,12 +173,12 @@ You can go to the command line of your database directly through rails dbconsole. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different -database, like rails dbconsole production. Currently works for mysql, -postgresql and sqlite. +database, like rails dbconsole production. Currently works for MySQL, +PostgreSQL and SQLite 3. == Description of Contents -The default directory structure of a generated Ruby on Rails applicartion: +The default directory structure of a generated Ruby on Rails application: |-- app | |-- controllers @@ -257,13 +224,13 @@ app/controllers ApplicationController which itself descends from ActionController::Base. app/models - Holds models that should be named like post.rb. - Most models will descend from ActiveRecord::Base. + Holds models that should be named like post.rb. Models descend from + ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use - eRuby syntax. + eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the @@ -274,7 +241,7 @@ app/views/layouts app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are - generated for you automatically when using rails generate for controllers. + generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config -- cgit v1.2.3 From bd9805871b576984e13c3d99558eda27d22c06c5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 29 May 2010 19:26:02 -0700 Subject: Include backtrace in failsafe log. Rescue possible exceptions in failsafe response. --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- .../middleware/templates/rescues/_request_and_response.erb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 2dd2ec9fe9..f9e81a02d3 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -72,7 +72,7 @@ module ActionDispatch rescue_action_in_public(exception) end rescue Exception => failsafe_error - $stderr.puts "Error during failsafe response: #{failsafe_error}" + $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" FAILSAFE_RESPONSE end diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb index 09ff052fd0..e963b04524 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb @@ -13,7 +13,7 @@ request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n") def debug_hash(hash) - hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect}" }.join("\n") + hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") end %> -- cgit v1.2.3 From ab1407cc5bbfe67f9e59335fe0a4e8ac82d513c6 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:47:25 -0700 Subject: Improve performance of commonly used request methods --- actionpack/lib/action_dispatch/http/request.rb | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 8560a6fc9c..98f4f5ae18 100755 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -52,9 +52,11 @@ module ActionDispatch # the application should use), this \method returns the overridden # value, not the original. def request_method - method = env["REQUEST_METHOD"] - HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") - method + @request_method ||= begin + method = env["REQUEST_METHOD"] + HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") + method + end end # Returns a symbol form of the #request_method @@ -66,9 +68,11 @@ module ActionDispatch # even if it was overridden by middleware. See #request_method for # more information. def method - method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'] - HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") - method + @method ||= begin + method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'] + HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") + method + end end # Returns a symbol form of the #method @@ -113,6 +117,10 @@ module ActionDispatch Http::Headers.new(@env) end + def fullpath + @fullpath ||= super + end + def forgery_whitelisted? get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request? end @@ -134,6 +142,10 @@ module ActionDispatch end alias :xhr? :xml_http_request? + def ip + @ip ||= super + end + # Which IP addresses are "trusted proxies" that can be stripped from # the right-hand-side of X-Forwarded-For TRUSTED_PROXIES = /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i @@ -145,7 +157,7 @@ module ActionDispatch # delimited list in the case of multiple chained proxies; the last # address which is not trusted is the originating IP. def remote_ip - (@env["action_dispatch.remote_ip"] || ip).to_s + @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s end # Returns the lowercase name of the HTTP server software. -- cgit v1.2.3 From a87b62729715fb286ea613e6e3ec59135a82529d Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:47:37 -0700 Subject: Use faster form of running callbacks --- .../lib/active_record/connection_adapters/abstract/connection_pool.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index bf8c546d2e..dfc76fcae7 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -211,7 +211,7 @@ module ActiveRecord # calling +checkout+ on this pool. def checkin(conn) @connection_mutex.synchronize do - conn.run_callbacks :checkin do + conn._run_checkin_callbacks do @checked_out.delete conn @queue.signal end -- cgit v1.2.3 From 220603ee70d1655cf97a1e9f09fbc5d019c99856 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:48:03 -0700 Subject: Eliminate the need to check for superclass changes to the callback stack each time through the callbacks --- activesupport/lib/active_support/callbacks.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 933667c909..ba15043bde 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -390,9 +390,12 @@ module ActiveSupport undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks") class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 def _run_#{symbol}_callbacks(key = nil, &blk) - if self.class.send("_update_#{symbol}_superclass_callbacks") - self.class.__define_runner(#{symbol.inspect}) - return _run_#{symbol}_callbacks(key, &blk) + @_initialized_#{symbol}_callbacks ||= begin + if self.class.send("_update_#{symbol}_superclass_callbacks") + self.class.__define_runner(#{symbol.inspect}) + return _run_#{symbol}_callbacks(key, &blk) + end + true end if key -- cgit v1.2.3 From 5fa3a2d12395ce1d7188c3b7dcb5d616e77eb5dd Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:48:29 -0700 Subject: Improve performance of the log subscriber by remembering the list of all loggers instead of trying to extract them each time --- railties/lib/rails/log_subscriber.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/log_subscriber.rb b/railties/lib/rails/log_subscriber.rb index 145c7e0ace..9a74fee745 100644 --- a/railties/lib/rails/log_subscriber.rb +++ b/railties/lib/rails/log_subscriber.rb @@ -52,6 +52,7 @@ module Rails def self.add(namespace, log_subscriber, notifier = ActiveSupport::Notifications) log_subscribers << log_subscriber + @flushable_loggers = nil log_subscriber.public_methods(false).each do |event| notifier.subscribe("#{event}.#{namespace}") do |*args| @@ -70,11 +71,17 @@ module Rails @log_subscribers ||= [] end + def self.flushable_loggers + @flushable_loggers ||= begin + loggers = log_subscribers.map(&:logger) + loggers.uniq! + loggers.select { |l| l.respond_to?(:flush) } + end + end + # Flush all log_subscribers' logger. def self.flush_all! - loggers = log_subscribers.map(&:logger) - loggers.uniq! - loggers.each { |l| l.flush if l.respond_to?(:flush) } + flushable_loggers.each(&:flush) end # By default, we use the Rails.logger for logging. -- cgit v1.2.3 From 8b05c5207dd5757d55d0c384740db289e6bd5415 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:48:57 -0700 Subject: Improve performance of MessageVerifier while keeping it constant time --- activesupport/lib/active_support/message_verifier.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index 6c46b68eaf..1031662293 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -47,11 +47,11 @@ module ActiveSupport def secure_compare(a, b) return false unless a.bytesize == b.bytesize - l = a.unpack "C#{a.bytesize}" + l = a.unpack "C*" - res = 0 - b.each_byte { |byte| res |= byte ^ l.shift } - res == 0 + res = true + b.each_byte { |byte| res = (byte == l.shift) && res } + res end def generate_digest(data) -- cgit v1.2.3 From 67a2d648d88f8520612fd7b01fcc7223290aac75 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 09:49:25 -0700 Subject: Improve performance of the Logger middleware by using simpler versions of methods --- railties/lib/rails/rack/logger.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index dd8b342f59..73e9af3b41 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,4 +1,5 @@ require 'rails/log_subscriber' +require 'active_support/core_ext/time/conversions' module Rails module Rack @@ -19,10 +20,10 @@ module Rails def before_dispatch(env) request = ActionDispatch::Request.new(env) - path = request.fullpath.inspect rescue "unknown" + path = request.fullpath - info "\n\nStarted #{request.method.to_s.upcase} #{path} " << - "for #{request.remote_ip} at #{Time.now.to_s(:db)}" + info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \ + "for #{request.ip} at #{Time.now.to_default_s}" end def after_dispatch(env) -- cgit v1.2.3 From a260e02fd3e967d2d6b602aa3bd15f952d4e45cc Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 10:03:28 -0700 Subject: Whoops. _run_*_callbacks is private --- .../lib/active_record/connection_adapters/abstract/connection_pool.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index dfc76fcae7..454d3e60e3 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -211,7 +211,7 @@ module ActiveRecord # calling +checkout+ on this pool. def checkin(conn) @connection_mutex.synchronize do - conn._run_checkin_callbacks do + conn.send(:_run_checkin_callbacks) do @checked_out.delete conn @queue.signal end -- cgit v1.2.3 From cb1b2a719ac2ba31dc8d66195c0be32798255be0 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 10:03:53 -0700 Subject: Stop the flash middleware from forcibly loading sessions even if the user doesn't use sessions at all --- actionpack/lib/action_dispatch/middleware/flash.rb | 4 ++-- .../lib/action_dispatch/middleware/session/abstract_store.rb | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index adde183cdb..043966a585 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -170,13 +170,13 @@ module ActionDispatch end def call(env) - if (session = env['rack.session']) && (flash = session['flash']) + if (session = env['rack.session']) && session.key?('flash') flash.sweep end @app.call(env) ensure - if (session = env['rack.session']) && (flash = session['flash']) && flash.empty? + if (session = env['rack.session']) && session.key?('flash') && session['flash'].empty? session.delete('flash') end end diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 15493cd2eb..3e8d64b0c6 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -51,11 +51,11 @@ module ActionDispatch super end - private - def loaded? - @loaded - end + def loaded? + @loaded + end + private def load! stale_session_check! do id, session = @by.send(:load_session, @env) -- cgit v1.2.3 From ff4c218095687ef9925baaca78d644579831d3c1 Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 10:27:21 -0700 Subject: Memoizing methods on request means we need to clear them out on recycle! --- actionpack/lib/action_controller/test_case.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 34499fa784..37906b79f6 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -155,6 +155,8 @@ module ActionController @formats = nil @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } + @method = @request_method = nil + @fullpath = @ip = @remote_ip = nil @env['action_dispatch.request.query_parameters'] = {} end end @@ -167,9 +169,7 @@ module ActionController @block = nil @length = 0 @body = [] - @charset = nil - @content_type = nil - + @charset = @content_type = nil @request = @template = nil end end -- cgit v1.2.3 From b8af484476d1dda685f058a0f185608cd18a862e Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 11:49:55 -0700 Subject: No need to unescape params twice if we came from Rack::Mount --- actionpack/lib/action_dispatch/routing/route_set.rb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 0d071dd7fe..5c4c96d9fc 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -29,13 +29,6 @@ module ActionDispatch def prepare_params!(params) merge_default_action!(params) split_glob_param!(params) if @glob_param - - params.each do |key, value| - if value.is_a?(String) - value = value.dup.force_encoding(Encoding::BINARY) if value.respond_to?(:force_encoding) - params[key] = URI.unescape(value) - end - end end def controller(params, raise_error=true) @@ -466,6 +459,13 @@ module ActionDispatch req = Rack::Request.new(env) @set.recognize(req) do |route, matches, params| + params.each do |key, value| + if value.is_a?(String) + value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware? + params[key] = URI.unescape(value) + end + end + dispatcher = route.app if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false) dispatcher.prepare_params!(params) -- cgit v1.2.3 From 16ee4b4d1b125bd3edb5c191d58c7afdf6d3232e Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 11:50:34 -0700 Subject: Small optimization of 1.9 unescape. We should make sure that inbound ASCII always means UTF-8. It seems so based on a quick survey of common browsers, but let's be sure --- activesupport/lib/active_support/core_ext/uri.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/uri.rb b/activesupport/lib/active_support/core_ext/uri.rb index 28eabd2111..b7fe0a6209 100644 --- a/activesupport/lib/active_support/core_ext/uri.rb +++ b/activesupport/lib/active_support/core_ext/uri.rb @@ -6,11 +6,15 @@ if RUBY_VERSION >= '1.9' str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese. parser = URI::Parser.new + unless str == parser.unescape(parser.escape(str)) URI::Parser.class_eval do remove_method :unescape - def unescape(str, escaped = @regexp[:ESCAPED]) - enc = (str.encoding == Encoding::US_ASCII) ? Encoding::UTF_8 : str.encoding + def unescape(str, escaped = /%[a-fA-F\d]{2}/) + # TODO: Are we actually sure that ASCII == UTF-8? + # YK: My initial experiments say yes, but let's be sure please + enc = str.encoding + enc = Encoding::UTF_8 if enc == Encoding::US_ASCII str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc) end end -- cgit v1.2.3 From a6b39428431abeaa0251bbf4b6582e578f81783f Mon Sep 17 00:00:00 2001 From: wycats Date: Fri, 4 Jun 2010 17:28:04 -0700 Subject: Optimize LookupContext --- .../lib/action_dispatch/routing/route_set.rb | 13 ++++++-- actionpack/lib/action_view/base.rb | 1 + actionpack/lib/action_view/lookup_context.rb | 35 +++++++++++++++------- actionpack/lib/action_view/template/handlers.rb | 2 +- activesupport/lib/active_support/dependencies.rb | 23 ++++++++++++++ activesupport/test/dependencies_test.rb | 15 ++++++++++ 6 files changed, 75 insertions(+), 14 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 5c4c96d9fc..750912b251 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -12,6 +12,7 @@ module ActionDispatch def initialize(options={}) @defaults = options[:defaults] @glob_param = options.delete(:glob) + @controllers = {} end def call(env) @@ -32,9 +33,15 @@ module ActionDispatch end def controller(params, raise_error=true) - if params && params.has_key?(:controller) - controller = "#{params[:controller].camelize}Controller" - ActiveSupport::Inflector.constantize(controller) + if params && params.key?(:controller) + controller_param = params[:controller] + unless controller = @controllers[controller_param] + controller_name = "#{controller_param.camelize}Controller" + controller = @controllers[controller_param] = + ActiveSupport::Dependencies.ref(controller_name) + end + + controller.get end rescue NameError => e raise ActionController::RoutingError, e.message, e.backtrace if raise_error diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index f4af763afe..16d7d25279 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -201,6 +201,7 @@ module ActionView #:nodoc: end def self.process_view_paths(value) + return value.dup if value.is_a?(PathSet) ActionView::PathSet.new(Array.wrap(value)) end diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 7021342b4a..801b08b19d 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -13,8 +13,12 @@ module ActionView mattr_accessor :registered_details self.registered_details = [] + mattr_accessor :registered_detail_setters + self.registered_detail_setters = [] + def self.register_detail(name, options = {}, &block) self.registered_details << name + self.registered_detail_setters << [name, "#{name}="] Accessors.send :define_method, :"_#{name}_defaults", &block Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{name} @@ -60,7 +64,7 @@ module ActionView @details, @details_key = { :handlers => default_handlers }, nil @frozen_formats, @skip_default_locale = false, false self.view_paths = view_paths - self.update_details(details, true) + self.initialize_details(details) end module ViewPaths @@ -116,11 +120,11 @@ module ActionView end def default_handlers #:nodoc: - @default_handlers ||= Template::Handlers.extensions + @@default_handlers ||= Template::Handlers.extensions end def handlers_regexp #:nodoc: - @handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/ + @@handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/ end end @@ -141,10 +145,13 @@ module ActionView end # Overload formats= to reject [:"*/*"] values. - def formats=(value) - value = nil if value == [:"*/*"] - value << :html if value == [:js] - super(value) + def formats=(values) + if values && values.size == 1 + value = values.first + values = nil if value == :"*/*" + values << :html if value == :js + end + super(values) end # Do not use the default locale on template lookup. @@ -170,14 +177,22 @@ module ActionView super(@skip_default_locale ? I18n.locale : _locale_defaults) end + def initialize_details(details) + details = details.dup + + registered_detail_setters.each do |key, setter| + send(setter, details[key]) + end + end + # Update the details keys by merging the given hash into the current # details hash. If a block is given, the details are modified just during # the execution of the block and reverted to the previous value after. - def update_details(new_details, force=false) + def update_details(new_details) old_details = @details.dup - registered_details.each do |key| - send(:"#{key}=", new_details[key]) if force || new_details.key?(key) + registered_detail_setters.each do |key, setter| + send(setter, new_details[key]) if new_details.key?(key) end if block_given? diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb index 35488c0391..6228d7ac39 100644 --- a/actionpack/lib/action_view/template/handlers.rb +++ b/actionpack/lib/action_view/template/handlers.rb @@ -19,7 +19,7 @@ module ActionView #:nodoc: @@default_template_handlers = nil def self.extensions - @@template_handlers.keys + @@template_extensions ||= @@template_handlers.keys end # Register a class that knows how to handle template files with the given diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index e14e225596..e0d2b70306 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -47,6 +47,9 @@ module ActiveSupport #:nodoc: mattr_accessor :autoloaded_constants self.autoloaded_constants = [] + mattr_accessor :references + self.references = {} + # An array of constant names that need to be unloaded on every request. Used # to allow arbitrary constants to be marked for unloading. mattr_accessor :explicitly_unloadable_constants @@ -476,9 +479,28 @@ module ActiveSupport #:nodoc: def remove_unloadable_constants! autoloaded_constants.each { |const| remove_constant const } autoloaded_constants.clear + references.each {|k,v| v.clear! } explicitly_unloadable_constants.each { |const| remove_constant const } end + class Reference + def initialize(constant, name) + @constant, @name = constant, name + end + + def get + @constant ||= Inflector.constantize(@name) + end + + def clear! + @constant = nil + end + end + + def ref(name) + references[name] ||= Reference.new(Inflector.constantize(name), name) + end + # Determine if the given constant has been automatically loaded. def autoloaded?(desc) # No name => anonymous module. @@ -572,6 +594,7 @@ module ActiveSupport #:nodoc: log "removing constant #{const}" parent.instance_eval { remove_const to_remove } + return true end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 75ff88505d..15543e07c3 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -431,6 +431,21 @@ class DependenciesTest < Test::Unit::TestCase end end + def test_references_should_work + with_loading 'dependencies' do + root = ActiveSupport::Dependencies.load_paths.first + c = ActiveSupport::Dependencies.ref("ServiceOne") + service_one_first = ServiceOne + assert_equal service_one_first, c.get + ActiveSupport::Dependencies.clear + assert ! defined?(ServiceOne) + + service_one_second = ServiceOne + assert_not_equal service_one_first, c.get + assert_equal service_one_second, c.get + end + end + def test_nested_load_error_isnt_rescued with_loading 'dependencies' do assert_raise(MissingSourceFile) do -- cgit v1.2.3 From a5f3f3ef7a10bcc3771910a63018cfd558485965 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 14:50:34 -0700 Subject: MySQL: require 2.7 or later so we can rely on result.each_hash --- .../connection_adapters/mysql_adapter.rb | 57 +++------------------- 1 file changed, 8 insertions(+), 49 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index ec25bbf18e..7c7bc5e292 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -3,48 +3,6 @@ require 'active_support/core_ext/kernel/requires' require 'active_support/core_ext/object/blank' require 'set' -module MysqlCompat #:nodoc: - # add all_hashes method to standard mysql-c bindings or pure ruby version - def self.define_all_hashes_method! - raise 'Mysql not loaded' unless defined?(::Mysql) - - target = defined?(Mysql::Result) ? Mysql::Result : MysqlRes - return if target.instance_methods.include?('all_hashes') || - target.instance_methods.include?(:all_hashes) - - # Ruby driver has a version string and returns null values in each_hash - # C driver >= 2.7 returns null values in each_hash - if Mysql.const_defined?(:VERSION) && (Mysql::VERSION.is_a?(String) || Mysql::VERSION >= 20700) - target.class_eval <<-'end_eval', __FILE__, __LINE__ + 1 - def all_hashes # def all_hashes - rows = [] # rows = [] - each_hash { |row| rows << row } # each_hash { |row| rows << row } - rows # rows - end # end - end_eval - - # adapters before 2.7 don't have a version constant - # and don't return null values in each_hash - else - target.class_eval <<-'end_eval', __FILE__, __LINE__ + 1 - def all_hashes # def all_hashes - rows = [] # rows = [] - all_fields = fetch_fields.inject({}) { |fields, f| # all_fields = fetch_fields.inject({}) { |fields, f| - fields[f.name] = nil; fields # fields[f.name] = nil; fields - } # } - each_hash { |row| rows << all_fields.dup.update(row) } # each_hash { |row| rows << all_fields.dup.update(row) } - rows # rows - end # end - end_eval - end - - unless target.instance_methods.include?('all_hashes') || - target.instance_methods.include?(:all_hashes) - raise "Failed to defined #{target.name}#all_hashes method. Mysql::VERSION = #{Mysql::VERSION.inspect}" - end - end -end - module ActiveRecord class Base # Establishes a connection to the database that's used by all Active Record objects. @@ -57,17 +15,17 @@ module ActiveRecord password = config[:password].to_s database = config[:database] - # Require the MySQL driver and define Mysql::Result.all_hashes unless defined? Mysql begin - require_library_or_gem('mysql') + require 'mysql' rescue LoadError - $stderr.puts '!!! Please install the mysql gem and try again: gem install mysql.' - raise + raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql', '2.8.1'" end - end - MysqlCompat.define_all_hashes_method! + unless defined?(Mysql::Result) && Mysql::Result.method_defined?(:each_hash) + raise "!!! Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'" + end + end mysql = Mysql.init mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey] @@ -656,7 +614,8 @@ module ActiveRecord def select(sql, name = nil) @connection.query_with_result = true result = execute(sql, name) - rows = result.all_hashes + rows = [] + result.each_hash { |row| rows << row } result.free rows end -- cgit v1.2.3 From 7ace23abacfecf6d34630bb5141faf80a8b88634 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 21:31:16 -0700 Subject: Restore flash sweep --- actionpack/lib/action_dispatch/middleware/flash.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 043966a585..18771fe782 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -170,7 +170,7 @@ module ActionDispatch end def call(env) - if (session = env['rack.session']) && session.key?('flash') + if (session = env['rack.session']) && (flash = session['flash']) flash.sweep end -- cgit v1.2.3 From 35ae42be4f9e23ae954e4705276b460998cb401b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 21:31:30 -0700 Subject: Bump i18n to 0.4.1 --- actionpack/actionpack.gemspec | 2 +- activemodel/activemodel.gemspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 0f45cb5a4a..02ff908c1c 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -22,7 +22,7 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) s.add_dependency('builder', '~> 2.1.2') - s.add_dependency('i18n', '~> 0.4.0') + s.add_dependency('i18n', '~> 0.4.1') s.add_dependency('rack', '~> 1.1.0') s.add_dependency('rack-test', '~> 0.5.4') s.add_dependency('rack-mount', '~> 0.6.3') diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec index 678007c0ef..6bd6fe49ff 100644 --- a/activemodel/activemodel.gemspec +++ b/activemodel/activemodel.gemspec @@ -21,5 +21,5 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('builder', '~> 2.1.2') - s.add_dependency('i18n', '~> 0.4.0') + s.add_dependency('i18n', '~> 0.4.1') end -- cgit v1.2.3 From fd1a5041362f5e65b813b7938d477143bd82de40 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 20:33:53 -0700 Subject: ActiveSupport::Dependencies.constantize shortcut for caching named constant lookups --- .../lib/active_support/core_ext/string/conversions.rb | 11 +++++++++++ .../lib/active_support/core_ext/string/inflections.rb | 11 ----------- activesupport/lib/active_support/dependencies.rb | 12 +++++++++--- activesupport/test/dependencies_test.rb | 6 ++++++ 4 files changed, 26 insertions(+), 14 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 6a243fe982..cd7a42ed2b 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -47,4 +47,15 @@ class String d[5] += d.pop ::DateTime.civil(*d) end + + # +constantize+ tries to find a declared constant with the name specified + # in the string. It raises a NameError when the name is not in CamelCase + # or is not initialized. + # + # Examples + # "Module".constantize # => Module + # "Class".constantize # => Class + def constantize + ActiveSupport::Inflector.constantize(self) + end end diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb index 48b028bb64..ef479d559e 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -146,15 +146,4 @@ class String def foreign_key(separate_class_name_and_id_with_underscore = true) ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore) end - - # +constantize+ tries to find a declared constant with the name specified - # in the string. It raises a NameError when the name is not in CamelCase - # or is not initialized. - # - # Examples - # "Module".constantize # => Module - # "Class".constantize # => Class - def constantize - ActiveSupport::Inflector.constantize(self) - end end diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index e0d2b70306..5091abc3a4 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -484,8 +484,10 @@ module ActiveSupport #:nodoc: end class Reference - def initialize(constant, name) - @constant, @name = constant, name + attr_reader :name + + def initialize(name, constant = nil) + @name, @constant = name, constant end def get @@ -498,7 +500,11 @@ module ActiveSupport #:nodoc: end def ref(name) - references[name] ||= Reference.new(Inflector.constantize(name), name) + references[name] ||= Reference.new(name) + end + + def constantize(name) + ref(name).get end # Determine if the given constant has been automatically loaded. diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 15543e07c3..5422c75f5f 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -446,6 +446,12 @@ class DependenciesTest < Test::Unit::TestCase end end + def test_constantize_shortcut_for_cached_constant_lookups + with_loading 'dependencies' do + assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne") + end + end + def test_nested_load_error_isnt_rescued with_loading 'dependencies' do assert_raise(MissingSourceFile) do -- cgit v1.2.3 From 9d0d6f7d261a14def6afd17568b8c8aa7c33d0b3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 22:02:49 -0700 Subject: Clear const references all at once --- activesupport/lib/active_support/dependencies.rb | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 5091abc3a4..16c3bc1142 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -479,23 +479,26 @@ module ActiveSupport #:nodoc: def remove_unloadable_constants! autoloaded_constants.each { |const| remove_constant const } autoloaded_constants.clear - references.each {|k,v| v.clear! } + Reference.clear! explicitly_unloadable_constants.each { |const| remove_constant const } end class Reference + @@constants = Hash.new { |h, k| h[k] = Inflector.constantize(k) } + attr_reader :name - def initialize(name, constant = nil) - @name, @constant = name, constant + def initialize(name) + @name = name.to_s + @@constants[@name] = name if name.respond_to?(:name) end def get - @constant ||= Inflector.constantize(@name) + @@constants[@name] end - def clear! - @constant = nil + def self.clear! + @@constants.clear end end -- cgit v1.2.3 From 509f3d7d2f346b83dfd22aec681feffbd2d25803 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 5 Jun 2010 20:34:30 -0700 Subject: Simplify middleware stack lazy compares using named const references --- actionpack/lib/action_dispatch/middleware/stack.rb | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index e3180dba77..4240e7a5d5 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -5,13 +5,13 @@ module ActionDispatch class Middleware attr_reader :args, :block - def initialize(klass, *args, &block) - @klass, @args, @block = klass, args, block + def initialize(klass_or_name, *args, &block) + @ref = ActiveSupport::Dependencies::Reference.new(klass_or_name) + @args, @block = args, block end def klass - return @klass if @klass.respond_to?(:new) - @klass = ActiveSupport::Inflector.constantize(@klass.to_s) + @ref.get end def ==(middleware) @@ -21,11 +21,7 @@ module ActionDispatch when Class klass == middleware else - if lazy_compare?(@klass) && lazy_compare?(middleware) - normalize(@klass) == normalize(middleware) - else - klass.name == normalize(middleware.to_s) - end + normalize(@ref.name) == normalize(middleware) end end @@ -39,10 +35,6 @@ module ActionDispatch private - def lazy_compare?(object) - object.is_a?(String) || object.is_a?(Symbol) - end - def normalize(object) object.to_s.strip.sub(/^::/, '') end -- cgit v1.2.3 From 0dbc732995a526354fb1e3c732af5dacdb863dda Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 6 Jun 2010 18:26:42 +0200 Subject: AS guide: first complete draft covering date/calculations.rb --- .../source/active_support_core_extensions.textile | 113 ++++++++++++++++++++- 1 file changed, 111 insertions(+), 2 deletions(-) diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index 30b2099be4..ba5c443b34 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -2691,13 +2691,13 @@ h3. Extensions to +Date+ h4. Calculations -All the following methods are defined in +active_support/core_ext/date/calculations.rb+. +NOTE: All the following methods are defined in +active_support/core_ext/date/calculations.rb+. INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, +Date.new(1582, 10, 4).tomorrow+ returns +Date.new(1582, 10, 15)+ and so on. Please check +test/core_ext/date_ext_test.rb+ in the Active Support test suite for expected behavior. h5. +Date.current+ -Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors +Time.zone_default+. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+. +Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+. h5. Named dates @@ -2800,6 +2800,115 @@ d.end_of_year # => Fri, 31 Dec 2010 +beginning_of_year+ is aliased to +at_beginning_of_year+, and +end_of_year+ is aliased to +at_end_of_year+. +h5. Other Date Computations + +h6. +years_ago+, +years_since+ + +The method +years_ago+ receives a number of years and returns the same date those many years ago: + + +date = Date.new(2010, 6, 7) +date.years_ago(10) # => Wed, 07 Jun 2000 + + ++years_since+ moves forward in time: + + +date = Date.new(2010, 6, 7) +date.years_since(10) # => Sun, 07 Jun 2020 + + +If such a day does not exist, the last day of the corresponding month is returned: + + +Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009 +Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015 + + +h6. +months_ago+, +months_since+ + +The methods +months_ago+ and +months_since+ work analogously for months: + + +Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 +Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010 + + +If such a day does not exist, the last day of the corresponding month is returned: + + +Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 +Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010 + + +h6. +advance+ + +The most generic way to jump to other days is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, and returns a date advanced as much as the present keys indicate: + + +date = Date.new(2010, 6, 6) +date.advance(:years => 1, :weeks => 2) # => Mon, 20 Jun 2011 +date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010 + + +Note in the previous example that increments may be negative. + +To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward. + +The method +advance+ advances first one month, and the one day, the result is: + + +Date.new(2010, 2, 28).advance(:months => 1, :day => 1) +# => Sun, 28 Mar 2010 + + +While if it did it the other way around the result would be different: + + +Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1) +# => Thu, 01 Apr 2010 + + +h5. Changing Date Components + +The method +change+ allows you to get a new date which is the same as the receiver except for the given year, month, or day: + + +Date.new(2010, 12, 23).change(:year => 2011, :month => 11) +# => Wed, 23 Nov 2011 + + +This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised: + + +Date.new(2010, 1, 31).change(:month => 2) +# => ArgumentError: invalid date + + +h5. Named Times + +WARNING: The following methods do not take into account the user time zone. They return timestamps in localtime. + +INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+. + +h6. +beginning_of_day+, +end_of_day+ + +The method +beginning_of_day+ returns a timestamp at the beginning of the day (00:00:00): + + +date = Date.new(2010, 6, 7) +date.beginning_of_day # => Sun Jun 07 00:00:00 +0200 2010 + + +The method +end_of_day+ returns a timestamp at the end of the day (23:59:59): + + +date = Date.new(2010, 6, 7) +date.end_of_day # => Sun Jun 06 23:59:59 +0200 2010 + + ++beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight+ + h4. Conversions h3. Extensions to +DateTime+ -- cgit v1.2.3 From 9f93de9d3dd7db8de67cb0ee10ea03cdba9b6e5c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 6 Jun 2010 12:07:40 -0700 Subject: Reset request.parameters after assigning params for functional tests --- actionpack/lib/action_controller/test_case.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 37906b79f6..21281b606e 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -139,14 +139,16 @@ module ActionController end end - params = self.request_parameters.dup + # Clear the combined params hash in case it was already referenced. + @env.delete("action_dispatch.request.parameters") + params = self.request_parameters.dup %w(controller action only_path).each do |k| params.delete(k) params.delete(k.to_sym) end - data = params.to_query + @env['CONTENT_LENGTH'] = data.length.to_s @env['rack.input'] = StringIO.new(data) end -- cgit v1.2.3 From 83729e2fe36a0a629c2a5a52a7e2970287d57036 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 6 Jun 2010 19:14:53 -0400 Subject: Formats should always be an array. --- actionpack/lib/action_view/render/layouts.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/render/layouts.rb b/actionpack/lib/action_view/render/layouts.rb index 31b09d9f0a..255c44450d 100644 --- a/actionpack/lib/action_view/render/layouts.rb +++ b/actionpack/lib/action_view/render/layouts.rb @@ -65,7 +65,7 @@ module ActionView if formats.size == 1 _find_layout(layout) else - update_details(:formats => self.formats.first){ _find_layout(layout) } + update_details(:formats => [self.formats.first]) { _find_layout(layout) } end rescue ActionView::MissingTemplate => e update_details(:formats => nil) do -- cgit v1.2.3 From ac9f8e1b7bbbfa13ff75c86ef72fe6641ba26eb3 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sun, 6 Jun 2010 14:00:09 +0430 Subject: Router accepts member routes on resource. [#4624 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 19 ++++++++++++++----- actionpack/test/dispatch/routing_test.rb | 13 +++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8a8d21c434..63c553dd07 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -622,13 +622,22 @@ module ActionDispatch end def member - unless @scope[:scope_level] == :resources - raise ArgumentError, "can't use member outside resources scope" + unless [:resources, :resource].include?(@scope[:scope_level]) + raise ArgumentError, "You can't use member action outside resources and resource scope." end - with_scope_level(:member) do - scope(':id', :name_prefix => parent_resource.member_name, :as => "") do - yield + case @scope[:scope_level] + when :resources + with_scope_level(:member) do + scope(':id', :name_prefix => parent_resource.member_name, :as => "") do + yield + end + end + when :resource + with_scope_level(:member) do + scope(':id', :as => "") do + yield + end end end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 180889ddf2..b2b8aca9b2 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -28,6 +28,10 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest post :reset resource :info + + member do + get :crush + end end match 'account/logout' => redirect("/logout"), :as => :logout_redirect @@ -352,6 +356,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_member_on_resource + with_test_routes do + get '/session/1/crush' + assert_equal 'sessions#crush', @response.body + + assert_equal '/session/1/crush', crush_session_path(1) + end + end + def test_redirect_modulo with_test_routes do get '/account/modulo/name' -- cgit v1.2.3 From d96efe63681cdf63e7c1a1448387a39af736bab9 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 6 Jun 2010 18:42:21 +0200 Subject: the order in which we apply deltas in Date#advance matters, add test coverage for that --- activesupport/test/core_ext/date_ext_test.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index a3a2f13436..55cd566738 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -198,6 +198,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.new(2005,2,28), Date.new(2004,2,29).advance(:years => 1) #leap day plus one year end + def test_advance_does_first_years_and_then_days + assert_equal Date.new(2012, 2, 29), Date.new(2011, 2, 28).advance(:years => 1, :days => 1) + # If day was done first we would jump to 2012-03-01 instead. + end + + def test_advance_does_first_months_and_then_days + assert_equal Date.new(2010, 3, 28), Date.new(2010, 2, 28).advance(:months => 1, :day => 1) + # If day was done first we would jump to 2010-04-01 instead. + end + def test_advance_in_calendar_reform assert_equal Date.new(1582,10,15), Date.new(1582,10,4).advance(:days => 1) assert_equal Date.new(1582,10,4), Date.new(1582,10,15).advance(:days => -1) -- cgit v1.2.3 From 8c7730db02b8a26c318caf98e726ee6e9f39df24 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 7 Jun 2010 07:27:51 +0200 Subject: oops, two cancelling errors made a previous test pass, fixing it --- activesupport/test/core_ext/date_ext_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index 55cd566738..3e003b3ed4 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -204,7 +204,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase end def test_advance_does_first_months_and_then_days - assert_equal Date.new(2010, 3, 28), Date.new(2010, 2, 28).advance(:months => 1, :day => 1) + assert_equal Date.new(2010, 3, 29), Date.new(2010, 2, 28).advance(:months => 1, :days => 1) # If day was done first we would jump to 2010-04-01 instead. end -- cgit v1.2.3 From b3d2080278fc2b17d64010c3bfb149a08583b667 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 7 Jun 2010 02:39:24 -0300 Subject: Observing module is using constantize --- activemodel/lib/active_model/observing.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb index 74a33d45ab..d7e3ca100e 100644 --- a/activemodel/lib/active_model/observing.rb +++ b/activemodel/lib/active_model/observing.rb @@ -2,6 +2,7 @@ require 'singleton' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/string/inflections' +require 'active_support/core_ext/string/conversions' module ActiveModel module Observing -- cgit v1.2.3 From 5273bd97e6746bd5bdc2450ad5a2d60f6a6eb7ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 7 Jun 2010 10:13:41 +0200 Subject: Make AP test suite green once again and speed up performance in layouts lookup for some cases. --- actionpack/lib/action_view/base.rb | 2 +- actionpack/lib/action_view/lookup_context.rb | 51 ++++++++++++++++--------- actionpack/lib/action_view/render/layouts.rb | 15 ++------ actionpack/test/template/lookup_context_test.rb | 16 +------- 4 files changed, 39 insertions(+), 45 deletions(-) diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 16d7d25279..7dd9dea358 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -184,7 +184,7 @@ module ActionView #:nodoc: attr_internal :captures, :request, :controller, :template, :config delegate :find_template, :template_exists?, :formats, :formats=, :locale, :locale=, - :view_paths, :view_paths=, :with_fallbacks, :update_details, :to => :lookup_context + :view_paths, :view_paths=, :with_fallbacks, :update_details, :with_layout_format, :to => :lookup_context delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers, :flash, :action_name, :controller_name, :to => :controller diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 801b08b19d..3aaa5e401c 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -19,6 +19,7 @@ module ActionView def self.register_detail(name, options = {}, &block) self.registered_details << name self.registered_detail_setters << [name, "#{name}="] + Accessors.send :define_method, :"_#{name}_defaults", &block Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{name} @@ -27,12 +28,7 @@ module ActionView def #{name}=(value) value = Array.wrap(value.presence || _#{name}_defaults) - - if value != @details[:#{name}] - @details_key = nil - @details = @details.dup if @details.frozen? - @details[:#{name}] = value.freeze - end + _set_detail(:#{name}, value) if value != @details[:#{name}] end METHOD end @@ -63,8 +59,11 @@ module ActionView def initialize(view_paths, details = {}) @details, @details_key = { :handlers => default_handlers }, nil @frozen_formats, @skip_default_locale = false, false + self.view_paths = view_paths - self.initialize_details(details) + self.registered_detail_setters.each do |key, setter| + send(setter, details[key]) + end end module ViewPaths @@ -177,11 +176,20 @@ module ActionView super(@skip_default_locale ? I18n.locale : _locale_defaults) end - def initialize_details(details) - details = details.dup - - registered_detail_setters.each do |key, setter| - send(setter, details[key]) + # A method which only uses the first format in the formats array for layout lookup. + # This method plays straight with instance variables for performance reasons. + def with_layout_format + if formats.size == 1 + yield + else + old_formats = formats + _set_detail(:formats, formats[0,1]) + + begin + yield + ensure + _set_detail(:formats, formats) + end end end @@ -195,14 +203,21 @@ module ActionView send(setter, new_details[key]) if new_details.key?(key) end - if block_given? - begin - yield - ensure - @details = old_details - end + begin + yield + ensure + @details_key = nil + @details = old_details end end + + protected + + def _set_detail(key, value) + @details_key = nil + @details = @details.dup if @details.frozen? + @details[key] = value.freeze + end end include Accessors diff --git a/actionpack/lib/action_view/render/layouts.rb b/actionpack/lib/action_view/render/layouts.rb index 255c44450d..a9dfc0cced 100644 --- a/actionpack/lib/action_view/render/layouts.rb +++ b/actionpack/lib/action_view/render/layouts.rb @@ -57,15 +57,11 @@ module ActionView # This is the method which actually finds the layout using details in the lookup # context object. If no layout is found, it checkes if at least a layout with # the given name exists across all details before raising the error. - # - # If self.formats contains several formats, just the first one is considered in - # the layout lookup. def find_layout(layout) begin - if formats.size == 1 - _find_layout(layout) - else - update_details(:formats => [self.formats.first]) { _find_layout(layout) } + with_layout_format do + layout =~ /^\// ? + with_fallbacks { find_template(layout) } : find_template(layout) end rescue ActionView::MissingTemplate => e update_details(:formats => nil) do @@ -74,11 +70,6 @@ module ActionView end end - def _find_layout(layout) #:nodoc: - layout =~ /^\// ? - with_fallbacks { find_template(layout) } : find_template(layout) - end - # Contains the logic that actually renders the layout. def _render_layout(layout, locals, &block) #:nodoc: layout.render(self, locals){ |*name| _layout_for(*name, &block) } diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index df1aa2edb2..cc71cb42d0 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -26,18 +26,6 @@ class LookupContextTest < ActiveSupport::TestCase assert_equal :en, @lookup_context.locale end - test "allows me to update details" do - @lookup_context.update_details(:formats => [:html], :locale => :pt) - assert_equal [:html], @lookup_context.formats - assert_equal :pt, @lookup_context.locale - end - - test "allows me to update an specific detail" do - @lookup_context.update_details(:locale => :pt) - assert_equal :pt, I18n.locale - assert_equal :pt, @lookup_context.locale - end - test "allows me to freeze and retrieve frozen formats" do @lookup_context.formats.freeze assert @lookup_context.formats.frozen? @@ -54,7 +42,7 @@ class LookupContextTest < ActiveSupport::TestCase end test "provides getters and setters for formats" do - @lookup_context.formats = :html + @lookup_context.formats = [:html] assert_equal [:html], @lookup_context.formats end @@ -138,7 +126,7 @@ class LookupContextTest < ActiveSupport::TestCase keys << @lookup_context.details_key assert_equal 2, keys.uniq.size - @lookup_context.formats = :html + @lookup_context.formats = [:html] keys << @lookup_context.details_key assert_equal 3, keys.uniq.size -- cgit v1.2.3 From 3f1cdb85b80b935791018e59161e527617af6f1f Mon Sep 17 00:00:00 2001 From: Tom Meier Date: Mon, 7 Jun 2010 14:18:56 +1000 Subject: Require active support/string/conversions so constantize can be used in associations.rb MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/associations.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 5b0ba86308..284ae6695b 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -2,6 +2,7 @@ require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/enumerable' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/string/conversions' module ActiveRecord class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc: -- cgit v1.2.3 From 7eedc3f3975cca2b7e729fcb67e310977b5e5dcd Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Tue, 18 May 2010 22:49:19 -0300 Subject: Fixing test class names and refactor line in autosave association MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/autosave_association.rb | 2 +- activerecord/test/cases/autosave_association_test.rb | 8 ++++---- activerecord/test/cases/nested_attributes_test.rb | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index c553e95bad..59a7bc1da1 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -243,7 +243,7 @@ module ActiveRecord if [:belongs_to, :has_one].include?(reflection.macro) return true if association.target && association.target.changed_for_autosave? else - association.target.each {|record| return true if record.changed_for_autosave? } + return true if association.target.detect { |record| record.changed_for_autosave? } end end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 063f0f0fb2..4e4f9c385c 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1149,7 +1149,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T include AutosaveAssociationOnACollectionAssociationTests end -class TestAutosaveAssociationValidationsOnAHasManyAssocication < ActiveRecord::TestCase +class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup @@ -1165,7 +1165,7 @@ class TestAutosaveAssociationValidationsOnAHasManyAssocication < ActiveRecord::T end end -class TestAutosaveAssociationValidationsOnAHasOneAssocication < ActiveRecord::TestCase +class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup @@ -1186,7 +1186,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssocication < ActiveRecord::Te end end -class TestAutosaveAssociationValidationsOnABelongsToAssocication < ActiveRecord::TestCase +class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup @@ -1206,7 +1206,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssocication < ActiveRecord: end end -class TestAutosaveAssociationValidationsOnAHABTMAssocication < ActiveRecord::TestCase +class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 57b66fb312..685b11cb03 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -734,7 +734,7 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase end end -class TestHasOneAutosaveAssoictaionWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase +class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup @@ -774,7 +774,7 @@ class TestHasOneAutosaveAssoictaionWhichItselfHasAutosaveAssociations < ActiveRe end end -class TestHasManyAutosaveAssoictaionWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase +class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase self.use_transactional_fixtures = false def setup -- cgit v1.2.3 From 634c9310e302aba0c113363ccec748460113b523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 7 Jun 2010 11:00:39 +0200 Subject: Make the logic for nested_records_changed_for_autosave? simpler. [#4648 state:resolved] --- activerecord/lib/active_record/autosave_association.rb | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 59a7bc1da1..0dcadfab5f 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/array/wrap' + module ActiveRecord # AutosaveAssociation is a module that takes care of automatically saving # your associations when the parent is saved. In addition to saving, it @@ -238,16 +240,10 @@ module ActiveRecord # go through nested autosave associations that are loaded in memory (without loading # any new ones), and return true if is changed for autosave def nested_records_changed_for_autosave? - self.class.reflect_on_all_autosave_associations.each do |reflection| - if association = association_instance_get(reflection.name) - if [:belongs_to, :has_one].include?(reflection.macro) - return true if association.target && association.target.changed_for_autosave? - else - return true if association.target.detect { |record| record.changed_for_autosave? } - end - end + self.class.reflect_on_all_autosave_associations.any? do |reflection| + association = association_instance_get(reflection.name) + association && Array.wrap(association.target).any?(&:changed_for_autosave?) end - false end # Validate the association if :validate or :autosave is -- cgit v1.2.3 From 1a8f784a236058101c6e8b6387aefc96e86a1e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 7 Jun 2010 11:20:54 +0200 Subject: member on resource should not expect an ID. --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 +--- actionpack/test/dispatch/routing_test.rb | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 63c553dd07..ae4417b56c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -635,9 +635,7 @@ module ActionDispatch end when :resource with_scope_level(:member) do - scope(':id', :as => "") do - yield - end + yield end end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index b2b8aca9b2..ffa4f50b00 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -358,10 +358,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest def test_member_on_resource with_test_routes do - get '/session/1/crush' + get '/session/crush' assert_equal 'sessions#crush', @response.body - - assert_equal '/session/1/crush', crush_session_path(1) + assert_equal '/session/crush', crush_session_path end end -- cgit v1.2.3 From ed16ec634485c34556e0df889d549c0aa9ccd393 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 7 Jun 2010 11:00:39 -0300 Subject: bump sqlite version to 1.3.0 Signed-off-by: Xavier Noria --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index d57afc8630..e91c56902b 100644 --- a/Gemfile +++ b/Gemfile @@ -29,7 +29,7 @@ gem "text-format", "~> 1.0.0" # AR if mri || RUBY_ENGINE == "rbx" - gem "sqlite3-ruby", "= 1.3.0.beta.2", :require => 'sqlite3' + gem "sqlite3-ruby", "~> 1.3.0", :require => 'sqlite3' group :db do gem "pg", ">= 0.9.0" -- cgit v1.2.3 From 3adb395da4f11693c20cc331271d5927f96acac8 Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Mon, 7 Jun 2010 21:52:56 +0430 Subject: Fixed Load Error failures in 1.9.2-head --- activesupport/lib/active_support/core_ext/load_error.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/lib/active_support/core_ext/load_error.rb b/activesupport/lib/active_support/core_ext/load_error.rb index 615ebe9588..8bdfa0c5bc 100644 --- a/activesupport/lib/active_support/core_ext/load_error.rb +++ b/activesupport/lib/active_support/core_ext/load_error.rb @@ -3,6 +3,7 @@ class LoadError /^no such file to load -- (.+)$/i, /^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i, /^Missing API definition file in (.+)$/i, + /^cannot load such file -- (.+)$/i, ] def path -- cgit v1.2.3 From eebac026060ef9a5e69e69b01df61acee7c6c07f Mon Sep 17 00:00:00 2001 From: wycats Date: Mon, 7 Jun 2010 15:29:34 -0400 Subject: Make named helpers unprotected without becoming actions [#4696 state:resolved] --- actionpack/lib/action_controller/metal/url_for.rb | 8 ++++++++ actionpack/lib/action_dispatch/routing/route_set.rb | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 10c7ca9021..c465035ca1 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -16,5 +16,13 @@ module ActionController raise "In order to use #url_for, you must include the helpers of a particular " \ "router. For instance, `include Rails.application.routes.url_helpers" end + + module ClassMethods + def action_methods + @action_methods ||= begin + super - _router.named_routes.helper_names + end + end + end end end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 750912b251..57a73dde75 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -68,6 +68,10 @@ module ActionDispatch clear! end + def helper_names + self.module.instance_methods.map(&:to_s) + end + def clear! @routes = {} @helpers = [] @@ -176,7 +180,6 @@ module ActionDispatch url_for(options) end - protected :#{selector} END_EVAL helpers << selector end -- cgit v1.2.3 From 399b493cb454e6f6dd1a310ba31adaa8e6550830 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 6 Jun 2010 02:20:45 -0300 Subject: content_tag_string shouldn't escape_html if escape param is false --- actionpack/lib/action_view/helpers/tag_helper.rb | 2 +- actionpack/test/template/tag_helper_test.rb | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index c09d01eeee..66277f79fe 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -110,7 +110,7 @@ module ActionView def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options - "<#{name}#{tag_options}>#{ERB::Util.h(content)}".html_safe + "<#{name}#{tag_options}>#{escape ? ERB::Util.h(content) : content}".html_safe end def tag_options(options, escape = true) diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index 256d9bdcde..ec5fe3d1d7 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -39,6 +39,8 @@ class TagHelperTest < ActionView::TestCase content_tag("a", "Create", :href => "create") assert_equal "

<script>evil_js</script>

", content_tag(:p, '') + assert_equal "

", + content_tag(:p, '', nil, false) end def test_content_tag_with_block_in_erb -- cgit v1.2.3 From ab764ecbfea31a3b14323283287e2fc80955ace6 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 6 Jun 2010 02:16:26 -0300 Subject: Makes text_helper methods sanitize the input if the input is not safe or :safe => true option is not provided --- actionpack/lib/action_view/helpers/text_helper.rb | 38 ++++---- actionpack/test/template/text_helper_test.rb | 102 ++++++++++++++++++++-- 2 files changed, 118 insertions(+), 22 deletions(-) diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index bfad9f8d31..4c76e9642f 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -74,6 +74,7 @@ module ActionView options.reverse_merge!(:length => 30) + text = sanitize(text) unless text.html_safe? || options[:safe] text.truncate(options.delete(:length), options) if text end @@ -105,6 +106,7 @@ module ActionView end options.reverse_merge!(:highlighter => '\1') + text = sanitize(text) unless text.html_safe? || options[:safe] if text.blank? || phrases.blank? text else @@ -244,13 +246,14 @@ module ActionView # def textilize(text, *options) options ||= [:hard_breaks] + text = sanitize(text) unless text.html_safe? || options.delete(:safe) if text.blank? "" else textilized = RedCloth.new(text, options) textilized.to_html - end + end.html_safe end # Returns the text with all the Textile codes turned into HTML tags, @@ -271,8 +274,8 @@ module ActionView # # textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.) # # => "Visit the Rails website here." - def textilize_without_paragraph(text) - textiled = textilize(text) + def textilize_without_paragraph(text, *options) + textiled = textilize(text, options) if textiled[0..2] == "

" then textiled = textiled[3..-1] end if textiled[-4..-1] == "

" then textiled = textiled[0..-5] end return textiled @@ -295,8 +298,9 @@ module ActionView # # markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")') # # => '

The ROR logo

' - def markdown(text) - text.blank? ? "" : BlueCloth.new(text).to_html + def markdown(text, options = {}) + text = sanitize(text) unless options[:safe] + (text.blank? ? "" : BlueCloth.new(text).to_html).html_safe end # Returns +text+ transformed into HTML using simple formatting rules. @@ -320,14 +324,15 @@ module ActionView # # simple_format("Look ma! A class!", :class => 'description') # # => "

Look ma! A class!

" - def simple_format(text, html_options={}) + def simple_format(text, html_options={}, options={}) + text = '' if text.nil? start_tag = tag('p', html_options, true) - text = h(text) + text = sanitize(text) unless text.html_safe? || options[:safe] text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n text.gsub!(/\n\n+/, "

\n\n#{start_tag}") # 2+ newline -> paragraph text.gsub!(/([^\n]\n)(?=[^\n])/, '\1
') # 1 newline -> br text.insert 0, start_tag - text.safe_concat("

") + text.html_safe.safe_concat("

") end # Turns all URLs and e-mail addresses into clickable links. The :link option @@ -368,7 +373,7 @@ module ActionView # # => "Welcome to my new blog at http://www.myblog.com. # Please e-mail me at me@email.com." def auto_link(text, *args, &block)#link = :all, html = {}, &block) - return '' if text.blank? + return ''.html_safe if text.blank? options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter unless args.empty? @@ -378,9 +383,9 @@ module ActionView options.reverse_merge!(:link => :all, :html => {}) case options[:link].to_sym - when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], &block), options[:html], &block) + when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], options, &block), options[:html], &block) when :email_addresses then auto_link_email_addresses(text, options[:html], &block) - when :urls then auto_link_urls(text, options[:html], &block) + when :urls then auto_link_urls(text, options[:html], options, &block) end end @@ -544,7 +549,7 @@ module ActionView # Turns all urls into clickable links. If a block is given, each url # is yielded and the result is used as the link text. - def auto_link_urls(text, html_options = {}) + def auto_link_urls(text, html_options = {}, options = {}) link_attributes = html_options.stringify_keys text.gsub(AUTO_LINK_RE) do scheme, href = $1, $& @@ -566,21 +571,22 @@ module ActionView link_text = block_given?? yield(href) : href href = 'http://' + href unless scheme - content_tag(:a, link_text, link_attributes.merge('href' => href)) + punctuation.reverse.join('') + content_tag(:a, link_text, link_attributes.merge('href' => href), !(options[:safe] || text.html_safe?)) + punctuation.reverse.join('') end - end + end.html_safe end # Turns all email addresses into clickable links. If a block is given, # each email is yielded and the result is used as the link text. - def auto_link_email_addresses(text, html_options = {}) + def auto_link_email_addresses(text, html_options = {}, options = {}) text.gsub(AUTO_EMAIL_RE) do text = $& if auto_linked?($`, $') - text + text.html_safe else display_text = (block_given?) ? yield(text) : text + display_text = sanitize(display_text) unless options[:safe] mail_to text, display_text, html_options end end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index bb808b77a5..9d7106b2e5 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -45,19 +45,42 @@ class TextHelperTest < ActionView::TestCase assert simple_format(" test with html tags ").html_safe? end - def test_simple_format_should_escape_unsafe_input - assert_equal "

<b> test with unsafe string </b>

", simple_format(" test with unsafe string ") + def test_simple_format_should_sanitize_unsafe_input + assert_equal "

test with unsafe string

", simple_format(" test with unsafe string ") end - def test_simple_format_should_not_escape_safe_input + def test_simple_format_should_not_sanitize_input_if_safe_option + assert_equal "

test with unsafe string

", simple_format(" test with unsafe string ", {}, :safe => true) + end + + def test_simple_format_should_not_sanitize_safe_input assert_equal "

test with safe string

", simple_format(" test with safe string ".html_safe) end + def test_truncate_should_be_html_safe + assert truncate("Hello World!", :length => 12).html_safe? + end + def test_truncate assert_equal "Hello World!", truncate("Hello World!", :length => 12) assert_equal "Hello Wor...", truncate("Hello World!!", :length => 12) end + def test_truncate_should_sanitize_unsafe_input + assert_equal "Hello World!", truncate("Hello World!", :length => 12) + assert_equal "Hello Wor...", truncate("Hello World!!", :length => 12) + end + + def test_truncate_should_not_sanitize_input_if_safe_option + assert_equal "Hello code!World!", :length => 12, :safe => true) + assert_equal "Hello code!World!!", :length => 12, :safe => true) + end + + def test_truncate_should_not_sanitize_safe_input + assert_equal "Hello code!World!".html_safe, :length => 12) + assert_equal "Hello code!World!!".html_safe, :length => 12) + end + def test_truncate_should_use_default_length_of_30 str = "This is a string that will go longer then the default truncate length of 30" assert_equal str[0...27] + "...", truncate(str) @@ -93,7 +116,11 @@ class TextHelperTest < ActionView::TestCase end end - def test_highlighter + def test_highlight_should_be_html_safe + assert highlight("This is a beautiful morning", "beautiful").html_safe? + end + + def test_highlight assert_equal( "This is a beautiful morning", highlight("This is a beautiful morning", "beautiful") @@ -117,6 +144,27 @@ class TextHelperTest < ActionView::TestCase assert_equal ' ', highlight(' ', 'blank text is returned verbatim') end + def test_highlight_should_sanitize_unsafe_input + assert_equal( + "This is a beautiful morning", + highlight("This is a beautiful morning", "beautiful") + ) + end + + def test_highlight_should_not_sanitize_input_if_safe_option + assert_equal( + "This is a beautiful morning", + highlight("This is a beautiful morning", "beautiful", :safe => true) + ) + end + + def test_highlight_should_not_sanitize_safe_input + assert_equal( + "This is a beautiful morning", + highlight("This is a beautiful morning".html_safe, "beautiful") + ) + end + def test_highlight_with_regexp assert_equal( "This is a beautiful! morning", @@ -163,7 +211,7 @@ class TextHelperTest < ActionView::TestCase highlight("

This is a beautiful morning, but also a beautiful day

", "beautiful") ) assert_equal( - "

This is a beautiful morning, but also a beautiful day

", + "

This is a beautiful morning, but also a beautiful day

", highlight("

This is a beautiful morning, but also a beautiful day

", "beautiful") ) end @@ -286,7 +334,17 @@ class TextHelperTest < ActionView::TestCase %{#{CGI::escapeHTML link_text}} end - def test_auto_linking + def test_auto_link_should_be_html_safe + email_raw = 'santiago@wyeworks.com' + link_raw = 'http://www.rubyonrails.org' + + assert auto_link(nil).html_safe? + assert auto_link('').html_safe? + assert auto_link("#{link_raw} #{link_raw} #{link_raw}").html_safe? + assert auto_link("hello #{email_raw}").html_safe? + end + + def test_auto_link email_raw = 'david@loudthinking.com' email_result = %{#{email_raw}} link_raw = 'http://www.rubyonrails.com' @@ -378,6 +436,21 @@ class TextHelperTest < ActionView::TestCase assert_equal %(

#{link10_result} Link

), auto_link("

#{link10_raw} Link

") end + def test_auto_link_should_sanitize_unsafe_input + link_raw = %{http://www.rubyonrails.com?id=1&num=2} + assert_equal %{http://www.rubyonrails.com?id=1&num=2}, auto_link(link_raw) + end + + def test_auto_link_should_sanitize_unsafe_input + link_raw = %{http://www.rubyonrails.com?id=1&num=2} + assert_equal %{http://www.rubyonrails.com?id=1&num=2}, auto_link(link_raw, :safe => true) + end + + def test_auto_link_should_not_sanitize_safe_input + link_raw = %{http://www.rubyonrails.com?id=1&num=2} + assert_equal %{http://www.rubyonrails.com?id=1&num=2}, auto_link(link_raw.html_safe) + end + def test_auto_link_other_protocols ftp_raw = 'ftp://example.com/file.txt' assert_equal %(Download #{generate_result(ftp_raw)}), auto_link("Download #{ftp_raw}") @@ -587,7 +660,12 @@ class TextHelperTest < ActionView::TestCase assert_equal(%w{Specialized Fuji Giant}, @cycles) end + # TODO test textilize_without_paragraph and markdown if defined? RedCloth + def test_textilize_should_be_html_safe + assert textilize("*This is Textile!* Rejoice!").html_safe? + end + def test_textilize assert_equal("

This is Textile! Rejoice!

", textilize("*This is Textile!* Rejoice!")) end @@ -600,6 +678,18 @@ class TextHelperTest < ActionView::TestCase assert_equal("

This is worded <strong>strongly</strong>

", textilize("This is worded strongly", :filter_html)) end + def test_textilize_should_sanitize_unsafe_input + assert_equal("

This is worded strongly

", textilize("This is worded strongly")) + end + + def test_textilize_should_not_sanitize_input_if_safe_option + assert_equal("

This is worded strongly

", textilize("This is worded strongly", :safe)) + end + + def test_textilize_should_not_sanitize_safe_input + assert_equal("

This is worded strongly

", textilize("This is worded strongly".html_safe)) + end + def test_textilize_with_hard_breaks assert_equal("

This is one scary world.
\n True.

", textilize("This is one scary world.\n True.")) end -- cgit v1.2.3 From 50031bf932bca7c2e0dc96e2a13d4e4db9af6a50 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Mon, 7 Jun 2010 15:30:08 -0400 Subject: Updating ActionMailer to Mail 2.2.2 (fixing two tests to suit) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionmailer/actionmailer.gemspec | 2 +- actionmailer/test/old_base/mail_service_test.rb | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index 4706b63b79..1e34352f53 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -20,5 +20,5 @@ Gem::Specification.new do |s| s.has_rdoc = true s.add_dependency('actionpack', version) - s.add_dependency('mail', '~> 2.2.1') + s.add_dependency('mail', '~> 2.2.2') end diff --git a/actionmailer/test/old_base/mail_service_test.rb b/actionmailer/test/old_base/mail_service_test.rb index 7054e8052a..e8e8fcedc9 100644 --- a/actionmailer/test/old_base/mail_service_test.rb +++ b/actionmailer/test/old_base/mail_service_test.rb @@ -674,7 +674,7 @@ The body EOF mail = Mail.new(msg) assert_equal "testing testing \326\244", mail.subject - assert_equal "Subject: =?UTF-8?Q?testing_testing_=D6=A4?=\r\n", mail[:subject].encoded + assert_equal "Subject: testing testing =?UTF-8?Q?_=D6=A4=?=\r\n", mail[:subject].encoded end def test_unquote_7bit_subject @@ -863,7 +863,7 @@ EOF def test_multipart_with_utf8_subject mail = TestMailer.multipart_with_utf8_subject(@recipient) - regex = Regexp.escape('Subject: =?UTF-8?Q?Foo_=C3=A1=C3=AB=C3=B4_=C3=AE=C3=BC?=') + regex = Regexp.escape('Subject: Foo =?UTF-8?Q?=C3=A1=C3=AB=C3=B4=?= =?UTF-8?Q?_=C3=AE=C3=BC=?=') assert_match(/#{regex}/, mail.encoded) string = "Foo áëô îü" assert_match(string, mail.subject) @@ -871,7 +871,7 @@ EOF def test_implicitly_multipart_with_utf8 mail = TestMailer.implicitly_multipart_with_utf8 - regex = Regexp.escape('Subject: =?UTF-8?Q?Foo_=C3=A1=C3=AB=C3=B4_=C3=AE=C3=BC?=') + regex = Regexp.escape('Subject: Foo =?UTF-8?Q?=C3=A1=C3=AB=C3=B4=?= =?UTF-8?Q?_=C3=AE=C3=BC=?=') assert_match(/#{regex}/, mail.encoded) string = "Foo áëô îü" assert_match(string, mail.subject) -- cgit v1.2.3 From 981f81275be8e0f38a35c397b41a209b0e14973c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 7 Jun 2010 22:22:54 +0200 Subject: Fix case when rendering a partial inside RJS with inherited layout [#4786 state:resolved] --- actionpack/lib/action_view/lookup_context.rb | 2 +- actionpack/test/controller/new_base/render_rjs_test.rb | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 3aaa5e401c..823226cb9c 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -188,7 +188,7 @@ module ActionView begin yield ensure - _set_detail(:formats, formats) + _set_detail(:formats, old_formats) end end end diff --git a/actionpack/test/controller/new_base/render_rjs_test.rb b/actionpack/test/controller/new_base/render_rjs_test.rb index b602b9f8e9..74bf865b54 100644 --- a/actionpack/test/controller/new_base/render_rjs_test.rb +++ b/actionpack/test/controller/new_base/render_rjs_test.rb @@ -2,7 +2,10 @@ require 'abstract_unit' module RenderRjs class BasicController < ActionController::Base + layout "application", :only => :index_respond_to + self.view_paths = [ActionView::FixtureResolver.new( + "layouts/application.html.erb" => "", "render_rjs/basic/index.js.rjs" => "page[:customer].replace_html render(:partial => 'customer')", "render_rjs/basic/index_html.js.rjs" => "page[:customer].replace_html :partial => 'customer'", "render_rjs/basic/index_no_js.js.erb" => "<%= render(:partial => 'developer') %>", -- cgit v1.2.3 From a210aff210616922063c89680219bb45581cc217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 7 Jun 2010 23:17:23 +0200 Subject: Add delete to middleware stack proxy. --- railties/lib/rails/configuration.rb | 4 ++++ railties/test/application/middleware_test.rb | 6 ++++++ railties/test/isolation/abstract_unit.rb | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index ee0fca6592..0becb780de 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -28,6 +28,10 @@ module Rails @operations << [:use, args, block] end + def delete(*args, &block) + @operations << [:delete, args, block] + end + def merge_into(other) @operations.each do |operation, args, block| other.send(operation, *args, &block) diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index bab17d8af5..aa75fed793 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -57,6 +57,12 @@ module ApplicationTests assert !middleware.include?("ActionDispatch::Static") end + test "can delete a middleware from the stack" do + add_to_config "config.middleware.delete ActionDispatch::Static" + boot! + assert !middleware.include?("ActionDispatch::Static") + end + test "removes show exceptions if action_dispatch.show_exceptions is disabled" do add_to_config "config.action_dispatch.show_exceptions = false" boot! diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 6f4c5d77f3..b46ac0efaf 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -232,7 +232,7 @@ Module.new do require_environment = "-r #{environment}" end - `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails #{tmp_path('app_template')}` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails new #{tmp_path('app_template')}` File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f| if require_environment f.puts "Dir.chdir('#{File.dirname(environment)}') do" -- cgit v1.2.3 From d6953cbfd3b6e06eceba715c60e288b6d7db0d49 Mon Sep 17 00:00:00 2001 From: wycats Date: Mon, 7 Jun 2010 17:00:09 -0400 Subject: regular expressions are usually ASCII-encoded, so force_encoding the content of a Node to the encoding of the regular expression is wrong. --- actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb | 1 + actionpack/lib/action_dispatch/testing/assertions/selector.rb | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb index 602411ed37..064ff3724d 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb @@ -23,6 +23,7 @@ module HTML #:nodoc: # Create a new Tokenizer for the given text. def initialize(text) + text.encode! if text.encoding_aware? @scanner = StringScanner.new(text) @position = 0 @line = 0 diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 9deabf5b3c..0e82b41590 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -267,14 +267,12 @@ module ActionDispatch if match_with = equals[:text] matches.delete_if do |match| text = "" - text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding) stack = match.children.reverse while node = stack.pop if node.tag? stack.concat node.children.reverse else content = node.content - content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding) text << content end end -- cgit v1.2.3