diff options
34 files changed, 460 insertions, 135 deletions
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index aaa2223d9e..4266ec042e 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -23,7 +23,6 @@ module ActionDispatch end def url_for(options = {}) - path = "" path << options.delete(:script_name).to_s.chomp("/") path << options.delete(:path).to_s diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index d924f21fad..ec15a2a715 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -5,11 +5,14 @@ module ActionDispatch # IP addresses that are "trusted proxies" that can be stripped from # the comma-delimited list in the X-Forwarded-For header. See also: # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces + # http://en.wikipedia.org/wiki/Private_network#Private_IPv6_addresses. TRUSTED_PROXIES = %r{ ^127\.0\.0\.1$ | # localhost + ^::1$ | ^(10 | # private IP 10.x.x.x 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255 - 192\.168 # private IP 192.168.x.x + 192\.168 | # private IP 192.168.x.x + fc00:: # private IP fc00 )\. }x @@ -19,13 +22,13 @@ module ActionDispatch @app = app @check_ip = check_ip_spoofing @proxies = case custom_proxies - when Regexp - custom_proxies - when nil - TRUSTED_PROXIES - else - Regexp.union(TRUSTED_PROXIES, custom_proxies) - end + when Regexp + custom_proxies + when nil + TRUSTED_PROXIES + else + Regexp.union(TRUSTED_PROXIES, custom_proxies) + end end def call(env) @@ -34,6 +37,31 @@ module ActionDispatch end class GetIp + + # IP v4 and v6 (with compression) validation regexp + # https://gist.github.com/1289635 + VALID_IP = %r{ + (^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4 + (^( + (([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated + (([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end + (([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6 + (([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with + (([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon + (([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle + (([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + ([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4 + (::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the begining + (([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending + )$) + }x + def initialize(env, middleware) @env = env @middleware = middleware @@ -44,25 +72,31 @@ module ActionDispatch # but will be wrong if the user is behind a proxy. Proxies will set # HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR, so we prioritize those. # HTTP_X_FORWARDED_FOR may be a comma-delimited list in the case of - # multiple chained proxies. The last address which is not a known proxy - # will be the originating IP. + # multiple chained proxies. The first address which is in this list + # if it's not a known proxy will be the originating IP. + # Format of HTTP_X_FORWARDED_FOR: + # client_ip, proxy_ip1, proxy_ip2... + # http://en.wikipedia.org/wiki/X-Forwarded-For def calculate_ip - client_ip = @env['HTTP_CLIENT_IP'] - forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR') - remote_addrs = ips_from('REMOTE_ADDR') + client_ip = @env['HTTP_CLIENT_IP'] + forwarded_ip = ips_from('HTTP_X_FORWARDED_FOR').first + remote_addrs = ips_from('REMOTE_ADDR') check_ip = client_ip && @middleware.check_ip - if check_ip && !forwarded_ips.include?(client_ip) + if check_ip && forwarded_ip != client_ip # We don't know which came from the proxy, and which from the user raise IpSpoofAttackError, "IP spoofing attack?!" \ "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \ "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}" end - not_proxy = client_ip || forwarded_ips.first || remote_addrs.first - - # Return first REMOTE_ADDR if there are no other options - not_proxy || ips_from('REMOTE_ADDR', :allow_proxies).first + client_ips = remove_proxies [client_ip, forwarded_ip, remote_addrs].flatten + if client_ips.present? + client_ips.first + else + # If there is no client ip we can return first valid proxy ip from REMOTE_ADDR + remote_addrs.find { |ip| valid_ip? ip } + end end def to_s @@ -71,12 +105,24 @@ module ActionDispatch @ip = calculate_ip end - protected + private - def ips_from(header, allow_proxies = false) - ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : [] - allow_proxies ? ips : ips.reject{|ip| ip =~ @middleware.proxies } + def ips_from(header) + @env[header] ? @env[header].strip.split(/[,\s]+/) : [] end + + def valid_ip?(ip) + ip =~ VALID_IP + end + + def not_a_proxy?(ip) + ip !~ @middleware.proxies + end + + def remove_proxies(ips) + ips.select { |ip| valid_ip?(ip) && not_a_proxy?(ip) } + end + end end diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index ffb1afa089..81f856feda 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -64,6 +64,9 @@ module ActionView # distance_of_time_in_words(to_time, from_time, true) # => about 6 years # distance_of_time_in_words(Time.now, Time.now) # => less than a minute # + # distance_of_time_in_words(70) # => 1 minute + # distance_of_time_in_words(60*60) # => about 1 hour + # def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {}) from_time = from_time.to_time if from_time.respond_to?(:to_time) to_time = to_time.to_time if to_time.respond_to?(:to_time) diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index ad097f2eb7..8e7224937d 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -902,7 +902,7 @@ module ActionView # # Let's say that @post.validated? is 1: # check_box("post", "validated") # # => <input name="post[validated]" type="hidden" value="0" /> - # # <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> + # # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" /> # # # Let's say that @puppy.gooddog is "no": # check_box("puppy", "gooddog", {}, "yes", "no") diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 6c8b22c47f..94d0e09842 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -35,37 +35,40 @@ class RequestTest < ActiveSupport::TestCase assert_equal '1.2.3.4', request.remote_ip request = stub_request 'REMOTE_ADDR' => '1.2.3.4', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'REMOTE_ADDR' => '127.0.0.1', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,unknown' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' - assert_equal 'unknown', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 9.9.9.9, 10.0.0.1, 172.31.4.4' assert_equal '3.4.5.6', request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address' + assert_equal nil, request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', 'HTTP_CLIENT_IP' => '2.2.2.2' e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) { @@ -89,6 +92,68 @@ class RequestTest < ActiveSupport::TestCase assert_equal '9.9.9.9', request.remote_ip end + test "remote ip v6" do + request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip + + request = stub_request 'REMOTE_ADDR' => '::1', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => '::1, ::1, fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,::1' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, fc00::' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', + 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334' + e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) { + request.remote_ip + } + assert_match(/IP spoofing attack/, e.message) + assert_match(/HTTP_X_FORWARDED_FOR="fe80:0000:0000:0000:0202:b3ff:fe1e:8329"/, e.message) + assert_match(/HTTP_CLIENT_IP="2001:0db8:85a3:0000:0000:8a2e:0370:7334"/, e.message) + + # Turn IP Spoofing detection off. + # This is useful for sites that are aimed at non-IP clients. The typical + # example is WAP. Since the cellular network is not IP based, it's a + # leap of faith to assume that their proxies are ever going to set the + # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', + 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', + :ip_spoofing_check => false + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, 2001:0db8:85a3:0000:0000:8a2e:0370:7334' + assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip + end + test "remote ip when the remote ip middleware returns nil" do request = stub_request 'REMOTE_ADDR' => '127.0.0.1' assert_equal '127.0.0.1', request.remote_ip @@ -97,29 +162,47 @@ class RequestTest < ActiveSupport::TestCase test "remote ip with user specified trusted proxies String" do @trusted_proxies = "67.205.106.73" - request = stub_request 'REMOTE_ADDR' => '67.205.106.73', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + request = stub_request 'REMOTE_ADDR' => '3.4.5.6', + 'HTTP_X_FORWARDED_FOR' => '67.205.106.73' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'REMOTE_ADDR' => '172.16.0.1,67.205.106.73', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip + 'HTTP_X_FORWARDED_FOR' => '67.205.106.73' + assert_equal '172.16.0.1', request.remote_ip - request = stub_request 'REMOTE_ADDR' => '67.205.106.73,172.16.0.1', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - assert_equal '3.4.5.6', request.remote_ip - - request = stub_request 'REMOTE_ADDR' => '67.205.106.74,172.16.0.1', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + request = stub_request 'REMOTE_ADDR' => '67.205.106.73,3.4.5.6', + 'HTTP_X_FORWARDED_FOR' => '67.205.106.73' assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,67.205.106.73' - assert_equal 'unknown', request.remote_ip + assert_equal nil, request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 9.9.9.9, 10.0.0.1, 67.205.106.73' assert_equal '3.4.5.6', request.remote_ip end + test "remote ip v6 with user specified trusted proxies String" do + @trusted_proxies = 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + + request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,::1', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal nil, request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334' + assert_equal nil, request.remote_ip + end + test "remote ip with user specified trusted proxies Regexp" do @trusted_proxies = /^67\.205\.106\.73$/i @@ -128,7 +211,18 @@ class RequestTest < ActiveSupport::TestCase assert_equal '3.4.5.6', request.remote_ip request = stub_request 'HTTP_X_FORWARDED_FOR' => '67.205.106.73, 10.0.0.1, 9.9.9.9, 3.4.5.6' - assert_equal '10.0.0.1', request.remote_ip + assert_equal nil, request.remote_ip + end + + test "remote ip v6 with user specified trusted proxies Regexp" do + @trusted_proxies = /^fe80:0000:0000:0000:0202:b3ff:fe1e:8329$/i + + request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334', + 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' + assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip + + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, 2001:0db8:85a3:0000:0000:8a2e:0370:7334' + assert_equal nil, request.remote_ip end test "domains" do diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc index 7d13a0123b..9b05384792 100644 --- a/activemodel/README.rdoc +++ b/activemodel/README.rdoc @@ -26,7 +26,7 @@ to integrate with Action Pack out of the box: <tt>ActiveModel::Model</tt>. person = Person.new(:name => 'bob', :age => '18') person.name # => 'bob' person.age # => 18 - person.valid? # => false + person.valid? # => true It includes model name introspections, conversions, translations and validations, resulting in a class suitable to be used with Action Pack. @@ -116,9 +116,6 @@ behavior out of the box: person.errors.full_messages # => ["Name can not be nil"] - person.errors.full_messages - # => ["Name can not be nil"] - {Learn more}[link:classes/ActiveModel/Errors.html] * Model name introspection diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb index a6b6dfafe7..35b1a1f0c7 100644 --- a/activemodel/lib/active_model/observing.rb +++ b/activemodel/lib/active_model/observing.rb @@ -5,6 +5,7 @@ require 'active_support/core_ext/module/remove_method' require 'active_support/core_ext/string/inflections' require 'active_support/core_ext/enumerable' require 'active_support/deprecation' +require 'active_support/core_ext/object/try' require 'active_support/descendants_tracker' module ActiveModel @@ -212,11 +213,7 @@ module ActiveModel # The class observed by default is inferred from the observer's class name: # assert_equal Person, PersonObserver.observed_class def observed_class - if observed_class_name = name[/(.*)Observer/, 1] - observed_class_name.constantize - else - nil - end + name[/(.*)Observer/, 1].try :constantize end end diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb index ff2213231f..8711b24124 100644 --- a/activemodel/lib/active_model/secure_password.rb +++ b/activemodel/lib/active_model/secure_password.rb @@ -58,7 +58,8 @@ module ActiveModel BCrypt::Password.new(password_digest) == unencrypted_password && self end - # Encrypts the password into the password_digest attribute. + # Encrypts the password into the password_digest attribute, only if the + # new password is not blank. def password=(unencrypted_password) unless unencrypted_password.blank? @password = unencrypted_password diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb index 4323ee1e09..a5828476b1 100644 --- a/activemodel/lib/active_model/serialization.rb +++ b/activemodel/lib/active_model/serialization.rb @@ -26,17 +26,18 @@ module ActiveModel # person.serializable_hash # => {"name"=>"Bob"} # # You need to declare an attributes hash which contains the attributes - # you want to serialize. When called, serializable hash will use + # you want to serialize. Attributes must be strings, not symbols. + # When called, serializable hash will use # instance methods that match the name of the attributes hash's keys. # In order to override this behavior, take a look at the private - # method read_attribute_for_serialization. + # method +read_attribute_for_serialization+. # # Most of the time though, you will want to include the JSON or XML # serializations. Both of these modules automatically include the - # ActiveModel::Serialization module, so there is no need to explicitly + # +ActiveModel::Serialization+ module, so there is no need to explicitly # include it. # - # So a minimal implementation including XML and JSON would be: + # A minimal implementation including XML and JSON would be: # # class Person # include ActiveModel::Serializers::JSON @@ -63,7 +64,12 @@ module ActiveModel # person.to_json # => "{\"name\":\"Bob\"}" # person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person... # - # Valid options are <tt>:only</tt>, <tt>:except</tt> and <tt>:methods</tt> . + # Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and <tt>include</tt>. + # The following are all valid examples: + # + # person.serializable_hash(:only => 'name') + # person.serializable_hash(:include => :address) + # person.serializable_hash(:include => { :address => { :only => 'city' }}) module Serialization def serializable_hash(options = nil) options ||= {} @@ -78,8 +84,7 @@ module ActiveModel hash = {} attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) } - method_names = Array(options[:methods]).select { |n| respond_to?(n) } - method_names.each { |n| hash[n.to_s] = send(n) } + Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) } serializable_add_includes(options) do |association, records, opts| hash[association.to_s] = if records.is_a?(Enumerable) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 1d713e472b..c6faae77cc 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -163,11 +163,6 @@ module ActiveRecord # QUOTING ================================================== - # Override to return the quoted table name. Defaults to column quoting. - def quote_table_name(name) - quote_column_name(name) - end - # Returns a bind substitution value given a +column+ and list of current # +binds+ def substitute_at(column, index) @@ -299,7 +294,7 @@ module ActiveRecord raise exception end - def translate_exception(e, message) + def translate_exception(exception, message) # override in derived class ActiveRecord::StatementInvalid.new(message) end diff --git a/activesupport/lib/active_support/core_ext/kernel/debugger.rb b/activesupport/lib/active_support/core_ext/kernel/debugger.rb index d5b590e9f0..2073cac98d 100644 --- a/activesupport/lib/active_support/core_ext/kernel/debugger.rb +++ b/activesupport/lib/active_support/core_ext/kernel/debugger.rb @@ -1,8 +1,8 @@ module Kernel unless respond_to?(:debugger) - # Starts a debugging session if ruby-debug has been loaded (call rails server --debugger to do load it). + # Starts a debugging session if the +debugger+ gem has been loaded (call rails server --debugger to do load it). def debugger - message = "\n***** Debugger requested, but was not available (ensure ruby-debug19 is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n" + message = "\n***** Debugger requested, but was not available (ensure the debugger gem is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n" defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message) end alias breakpoint debugger unless respond_to?(:breakpoint) diff --git a/guides/assets/images/favicon.ico b/guides/assets/images/favicon.ico Binary files differnew file mode 100644 index 0000000000..e0e80cf8f1 --- /dev/null +++ b/guides/assets/images/favicon.ico diff --git a/guides/assets/images/getting_started/index_action_with_edit_link.png b/guides/assets/images/getting_started/index_action_with_edit_link.png Binary files differnew file mode 100644 index 0000000000..6e58a13756 --- /dev/null +++ b/guides/assets/images/getting_started/index_action_with_edit_link.png diff --git a/guides/code/getting_started/Gemfile b/guides/code/getting_started/Gemfile index ab4e34b2d0..670a8523b0 100644 --- a/guides/code/getting_started/Gemfile +++ b/guides/code/getting_started/Gemfile @@ -35,4 +35,4 @@ gem 'jquery-rails' # gem 'capistrano' # To use debugger -# gem 'ruby-debug19', :require => 'ruby-debug' +# gem 'debugger' diff --git a/guides/code/getting_started/README.rdoc b/guides/code/getting_started/README.rdoc index d2014bd35f..b5d7b6436b 100644 --- a/guides/code/getting_started/README.rdoc +++ b/guides/code/getting_started/README.rdoc @@ -86,8 +86,8 @@ programming in general. 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-debug19 to run the server in debugging -mode. With gems, use <tt>sudo gem install ruby-debug19</tt>. Example: +resume execution! You need to install the 'debugger' gem to run the server in debugging +mode. Add gem 'debugger' to your Gemfile and run <tt>bundle</tt> to install it. Example: class WeblogController < ActionController::Base def index diff --git a/guides/code/getting_started/app/controllers/posts_controller.rb b/guides/code/getting_started/app/controllers/posts_controller.rb index 947cd2a767..fc71e9b4e8 100644 --- a/guides/code/getting_started/app/controllers/posts_controller.rb +++ b/guides/code/getting_started/app/controllers/posts_controller.rb @@ -21,4 +21,18 @@ class PostsController < ApplicationController render 'new' end end + + def edit + @post = Post.find(params[:id]) + end + + def update + @post = Post.find(params[:id]) + + if @post.update_attributes(params[:post]) + redirect_to :action => :show, :id => @post.id + else + render 'edit' + end + end end diff --git a/guides/code/getting_started/app/helpers/home_helper.rb b/guides/code/getting_started/app/helpers/welcome_helper.rb index eeead45fc9..eeead45fc9 100644 --- a/guides/code/getting_started/app/helpers/home_helper.rb +++ b/guides/code/getting_started/app/helpers/welcome_helper.rb diff --git a/guides/code/getting_started/app/views/posts/_form.html.erb b/guides/code/getting_started/app/views/posts/_form.html.erb index 18cb29f335..46ec257b91 100644 --- a/guides/code/getting_started/app/views/posts/_form.html.erb +++ b/guides/code/getting_started/app/views/posts/_form.html.erb @@ -1,4 +1,4 @@ -<%= form_for :post, :url => { :action => :create } do |f| %> +<%= form_for :post, :url => { :action => :update, :id => @post.id }, :method => :put do |f| %> <% if @post.errors.any? %> <div id="errorExplanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> diff --git a/guides/code/getting_started/app/views/posts/edit.html.erb b/guides/code/getting_started/app/views/posts/edit.html.erb index 720580236b..911a48569d 100644 --- a/guides/code/getting_started/app/views/posts/edit.html.erb +++ b/guides/code/getting_started/app/views/posts/edit.html.erb @@ -2,5 +2,4 @@ <%= render 'form' %> -<%= link_to 'Show', @post %> | -<%= link_to 'Back', posts_path %> +<%= link_to 'Back', :action => :index %> diff --git a/guides/code/getting_started/app/views/posts/index.html.erb b/guides/code/getting_started/app/views/posts/index.html.erb index 455a74b17f..3ba7091c15 100644 --- a/guides/code/getting_started/app/views/posts/index.html.erb +++ b/guides/code/getting_started/app/views/posts/index.html.erb @@ -7,6 +7,7 @@ <th>Title</th> <th>Text</th> <th></th> + <th></th> </tr> <% @posts.each do |post| %> @@ -14,6 +15,7 @@ <td><%= post.title %></td> <td><%= post.text %></td> <td><%= link_to 'Show', :action => :show, :id => post.id %> + <td><%= link_to 'Edit', :action => :edit, :id => post.id %> </tr> <% end %> </table> diff --git a/guides/code/getting_started/app/views/posts/show.html.erb b/guides/code/getting_started/app/views/posts/show.html.erb index a79fadfe4c..aea28cd5a2 100644 --- a/guides/code/getting_started/app/views/posts/show.html.erb +++ b/guides/code/getting_started/app/views/posts/show.html.erb @@ -9,3 +9,4 @@ </p> <%= link_to 'Back', :action => :index %> +| <%= link_to 'Edit', :action => :edit, :id => @post.id %> diff --git a/guides/code/getting_started/config/routes.rb b/guides/code/getting_started/config/routes.rb index 10009a35cf..b0973c62d5 100644 --- a/guides/code/getting_started/config/routes.rb +++ b/guides/code/getting_started/config/routes.rb @@ -7,6 +7,8 @@ Blog::Application.routes.draw do get "posts/new" post "posts/create" get "posts/:id" => "posts#show" + get "posts/:id/edit" => "posts#edit" + put "posts/:id/update" => "posts#update" # The priority is based upon order of creation: # first created -> highest priority. diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 58eae2ee0f..98937266ba 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -388,6 +388,8 @@ The field name can also be a string: Client.where('locked' => true) </ruby> +NOTE: The values cannot be symbols. For example, you cannot do +Client.where(:status => :active)+. + h5(#hash-range_conditions). Range Conditions The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section. diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index 57c7786636..903ed59e7b 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -191,7 +191,7 @@ Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localh Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia. -h3. Debugging with +ruby-debug+ +h3. Debugging with the +debugger+ gem When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. @@ -199,17 +199,13 @@ The debugger can also help you if you want to learn about the Rails source code h4. Setup -The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just run: +Rails uses the +debugger+ gem to set breakpoints and step through live code. To install it, just run: <shell> -$ sudo gem install ruby-debug +$ gem install debugger </shell> -TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install ruby-debug19+ - -In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. - -Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. +Rails has had built-in support for debugging since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. Here's an example: @@ -238,11 +234,11 @@ $ rails server --debugger ... </shell> -TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if it was started without +--debugger+. +TIP: In development mode, you can dynamically +require \'debugger\'+ instead of restarting the server, if it was started without +--debugger+. h4. The Shell -As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. +As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at the debugger's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request. @@ -270,7 +266,7 @@ continue edit frame method putl set tmate where TIP: To view the help menu for any command use +help <command-name>+ in active debug mode. For example: _+help var+_ -The next command to learn is one of the most useful: +list+. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. +The next command to learn is one of the most useful: +list+. You can abbreviate any debugging command by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+. @@ -347,7 +343,7 @@ h4. The Context When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack. -ruby-debug creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. +The debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. At any time you can call the +backtrace+ command (or its alias +where+) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then +backtrace+ will supply the answer. @@ -463,7 +459,7 @@ h4. Step by Step Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution. -Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to ruby-debug. +Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to the debugger. TIP: You can also use <tt>step<plus> n</tt> and <tt>step- n</tt> to move forward or backward +n+ steps respectively. @@ -485,12 +481,12 @@ class Author < ActiveRecord::Base end </ruby> -TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method. +TIP: You can use the debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. <shell> $ rails console Loading development environment (Rails 3.1.0) ->> require "ruby-debug" +>> require "debugger" => [] >> author = Author.first => #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10"> @@ -603,7 +599,7 @@ A simple quit tries to terminate all threads in effect. Therefore your server wi h4. Settings -There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available options: +The +debugger+ gem can automatically show the code you're stepping through and reload it when you change it in an editor. Here are a few of the available options: * +set reload+: Reload source code when changed. * +set autolist+: Execute +list+ command on every breakpoint. @@ -612,7 +608,7 @@ There are some settings that can be configured in ruby-debug to make it easier t You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly. +TIP: You can save these settings in an +.rdebugrc+ file in your home directory. The debugger reads these global settings when it starts. Here's a good start for an +.rdebugrc+: @@ -637,7 +633,7 @@ If a Ruby object does not go out of scope, the Ruby Garbage Collector won't swee To install it run: <shell> -$ sudo gem install bleak_house +$ gem install bleak_house </shell> Then setup your application for profiling. Then add the following at the bottom of config/environment.rb: @@ -703,11 +699,12 @@ There are some Rails plugins to help you to find errors and debug your applicati h3. References * "ruby-debug Homepage":http://www.datanoise.com/ruby-debug +* "debugger Homepage":http://github.com/cldwalker/debugger * "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/ * "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/ -* "Ryan Bate's ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug -* "Ryan Bate's stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace -* "Ryan Bate's logger screencast":http://railscasts.com/episodes/56-the-logger +* "Ryan Bates' debugging ruby (revised) screencast":http://railscasts.com/episodes/54-debugging-ruby-revised +* "Ryan Bates' stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace +* "Ryan Bates' logger screencast":http://railscasts.com/episodes/56-the-logger * "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html * "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/ * "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging diff --git a/guides/source/generators.textile b/guides/source/generators.textile index 920ff997ae..e9d713d91d 100644 --- a/guides/source/generators.textile +++ b/guides/source/generators.textile @@ -451,6 +451,27 @@ Adds a specified source to +Gemfile+: add_source "http://gems.github.com" </ruby> +h4. +inject_into_file+ + +Injects a block of code into a defined position in your file. + +<ruby> +inject_into_file 'name_of_file.rb', :after => "#The code goes below this line. Don't forget the Line break at the end\n" do <<-'RUBY' + puts "Hello World" +RUBY +end +</ruby> + +h4. +gsub_file+ + +Replaces text inside a file. + +<ruby> +gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code' +</ruby + +Regular Expressions can be used to make this method more precise. You can also use append_file and prepend_file in the same way to place code at the beginning and end of a file respectively. + h4. +application+ Adds a line to +config/application.rb+ directly after the application class definition. diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index f184004f80..88d5ce6d9b 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -516,7 +516,7 @@ end A couple of things to note. We use +Post.find+ to find the post we're interested in. We also use an instance variable (prefixed by +@+) to -hold our reference to the post object. We do this because Rails will pass all instance +hold a reference to the post object. We do this because Rails will pass all instance variables to the view. Now, create a new file +app/view/posts/show.html.erb+ with the following @@ -577,8 +577,8 @@ end h4. Adding links -You can now create, show, and list posts. But it's difficult to navigate -through pages, so let's add some links. +You can now create, show, and list posts. Now let's add some links to +navigate through pages. Open +app/views/welcome/index.html.erb+ and modify it as follows: @@ -619,19 +619,7 @@ Let's add links to the other views as well. # app/views/posts/new.html.erb <%= form_for :post do |f| %> - <p> - <%= f.label :title %><br> - <%= f.text_field :title %> - </p> - - <p> - <%= f.label :text %><br> - <%= f.text_area :text %> - </p> - - <p> - <%= f.submit %> - </p> + ... <% end %> <%= link_to 'Back', :action => :index %> @@ -657,11 +645,9 @@ controller by default. TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop -and restart the web server. - -Congratulations, you're riding the rails! Now it’s time to see how it all works. +and restart the web server when a change is made. -h4. The Model +h4. Adding Some Validation The model file, +app/models/post.rb+ is about as simple as it can get: @@ -676,8 +662,6 @@ your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. -h4. Adding Some Validation - Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it: @@ -730,7 +714,7 @@ something went wrong. To do that, you'll modify +app/views/posts/index.html.erb+ to check for error messages: <erb> -<%= form_for :post do |f| %> +<%= form_for :post, :url => { :action => :create } do |f| %> <% if @post.errors.any? %> <div id="errorExplanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited @@ -780,6 +764,172 @@ Now you'll get a nice error message when saving a post without title: !images/getting_started/form_with_errors.png(Form With Errors)! +h4. Updating Posts + +We've covered the "CR" part of CRUD. Now let's focus on the "U" part, +updating posts. + +The first step we'll take is adding a +edit+ action to ++posts_controller+. + +Start by adding a route to +config/routes.rb+: + +<ruby> +get "posts/:id/edit" => "posts#edit" +</ruby> + +And then add the controller action: + +<ruby> +def edit + @post = Post.find(params[:id]) +end +</ruby> + +The view will contain a form similar to the one we used when creating +new posts. Create a file called +app/views/posts/edit.html.erb+ and make +it look as follows: + +<erb> +<h1>Editing post</h1> + +<%= form_for :post, :url => { :action => :update, :id => @post.id }, +:method => :put do |f| %> + <% if @post.errors.any? %> + <div id="errorExplanation"> + <h2><%= pluralize(@post.errors.count, "error") %> prohibited + this post from being saved:</h2> + <ul> + <% @post.errors.full_messages.each do |msg| %> + <li><%= msg %></li> + <% end %> + </ul> + </div> + <% end %> + <p> + <%= f.label :title %><br> + <%= f.text_field :title %> + </p> + + <p> + <%= f.label :text %><br> + <%= f.text_area :text %> + </p> + + <p> + <%= f.submit %> + </p> +<% end %> + +<%= link_to 'Back', :action => :index %> +</erb> + +This time we point the form to the +update+ action (not defined yet). +The +:method => :put+ option tells Rails that we want this form to be +submitted via +put+, which is the http method you're expected to use to +*update* resources according to the REST protocol. + +TIP: By default forms built with the +form_for_ helper are sent via +POST+. + +Moving on, we need to add the +update+ action. The file ++config/routes.rb+ will need just one more line: + +<ruby> +put "posts/:id/update" +</ruby> + +And the +update+ action in +posts_controller+ itself should not look too complicated by now: + +<ruby> +def update + @post = Post.find(params[:id]) + + if @post.update_attributes(params[:post]) + redirect_to :action => :show, :id => @post.id + else + render 'edit' + end +end +</ruby> + +The new method +update_attributes+ is used when you want to update a record +that already exists, and it accepts an hash containing the attributes +that you want to update. As before, if there was an error updating the +post we want to show the form back to the user. + +TIP: you don't need to pass all attributes to +update_attributes+. For +example, if you'd call +@post.update_attributes(:title => 'A new title')+ +Rails would only update the +title+ attribute, leaving all other +attributes untouched. + +Finally, we want to show a link to the +edit+ action in the +index+ and ++show+ views: + +<erb> +# app/view/posts/index.html.erb + +<table> + <tr> + <th>Title</th> + <th>Text</th> + <th></th> + <th></th> + </tr> + +<% @posts.each do |post| %> + <tr> + <td><%= post.title %></td> + <td><%= post.text %></td> + <td><%= link_to 'Show', :action => :show, :id => post.id %></td> + <td><%= link_to 'Edit', :action => :edit, :id => post.id %></td> + </tr> +<% end %> +</table> + +# app/view/posts/show.html.erb + +... + +<%= link_to 'Back', :action => :index %> +| <%= link_to 'Edit', :action => :edit, :id => @post.id %> +</erb> + +And here's how our app looks so far: + +!images/getting_started/index_action_with_edit_link.png(Index action +with edit link)! + +h4. Using partials to clean up duplication in views + ++partials+ are what Rails uses to remove duplication in views. Here's a +simple example: + +<erb> +# app/views/user/show.html.erb + +<h1><%= @user.name %></h1> + +<%= render 'user_details' %> + +# app/views/user/_user_details.html.erb + +<%= @user.location %> + +<%= @user.about_me %> +</erb> + +The +show+ view will automatically include the content of the ++_user_details+ view. Note that partials are prefixed by an underscore, +as to not be confused with regular views. However, you don't include the +underscore when including them with the +helper+ method. + +TIP: You can red more about partials in the "Layouts and Rendering in +Rails":layouts_and_rendering.html guide. + +Our +edit+ action looks very similar to the +new+ action, in fact they +both share the same code for displaying the form. Lets clean them up by +using a +_form+ partial. + h4. Using the Console To see your validations in action, you can use the console. The console is a diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 35b6fc7014..0a8daf7ae5 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -14,6 +14,8 @@ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" /> + +<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> </head> <body class="guide"> <% if @edge %> diff --git a/guides/source/plugins.textile b/guides/source/plugins.textile index 97b4eca779..95e38db483 100644 --- a/guides/source/plugins.textile +++ b/guides/source/plugins.textile @@ -25,16 +25,14 @@ endprologue. h3. Setup -Before you continue, take a moment to decide if your new plugin will be potentially shared across different Rails applications. +_"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in +Rails 3.2, and will not be available in the future. -* If your plugin is specific to your application, your new plugin will be a _vendored plugin_. -* If you think your plugin may be used across applications, build it as a _gemified plugin_. +Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared accross +different rails applications using RubyGems and Bundler if desired. h4. Generate a gemified plugin. -Writing your Rails plugin as a gem, rather than as a vendored plugin, - lets you share your plugin across different rails applications using - RubyGems and Bundler. Rails 3.1 ships with a +rails plugin new+ command which creates a skeleton for developing any kind of Rails extension with the ability diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb index d7c9e820dc..cd6a03fe51 100644 --- a/railties/lib/rails/commands/console.rb +++ b/railties/lib/rails/commands/console.rb @@ -27,7 +27,7 @@ module Rails opt.on("-e", "--environment=name", String, "Specifies the environment to run this console under (test/development/production).", "Default: development") { |v| options[:environment] = v.strip } - opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v } + opt.on("--debugger", 'Enable the debugger.') { |v| options[:debugger] = v } opt.parse!(arguments) end @@ -73,10 +73,10 @@ module Rails def require_debugger begin - require 'ruby-debug' + require 'debugger' puts "=> Debugger enabled" rescue Exception - puts "You need to install ruby-debug19 to run the console in debugging mode. With gems, use 'gem install ruby-debug19'" + puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again." exit end end diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 721a47a974..4c4caad69f 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -17,7 +17,7 @@ module Rails opts.on("-c", "--config=file", String, "Use custom rackup configuration file") { |v| options[:config] = v } opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:daemonize] = true } - opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true } + opts.on("-u", "--debugger", "Enable the debugger") { options[:debugger] = true } opts.on("-e", "--environment=name", String, "Specifies the environment to run this server under (test/development/production).", "Default: development") { |v| options[:environment] = v } diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README index d2014bd35f..b5d7b6436b 100644 --- a/railties/lib/rails/generators/rails/app/templates/README +++ b/railties/lib/rails/generators/rails/app/templates/README @@ -86,8 +86,8 @@ programming in general. 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-debug19 to run the server in debugging -mode. With gems, use <tt>sudo gem install ruby-debug19</tt>. Example: +resume execution! You need to install the 'debugger' gem to run the server in debugging +mode. Add gem 'debugger' to your Gemfile and run <tt>bundle</tt> to install it. Example: class WeblogController < ActionController::Base def index diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile index d316b00c43..9399c9cb77 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile +++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile @@ -20,4 +20,4 @@ gem "jquery-rails" <% end -%> # To use debugger -# gem 'ruby-debug19', :require => 'ruby-debug' +# gem 'debugger' diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb index 5a78da1731..902361ce77 100644 --- a/railties/lib/rails/rack/debugger.rb +++ b/railties/lib/rails/rack/debugger.rb @@ -6,13 +6,13 @@ module Rails ARGV.clear # clear ARGV so that rails server options aren't passed to IRB - require 'ruby-debug' + require 'debugger' ::Debugger.start ::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings) puts "=> Debugger enabled" rescue LoadError - puts "You need to install ruby-debug19 to run the server in debugging mode. With gems, use 'gem install ruby-debug19'" + puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again." exit end diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index a14bc95912..abafcefde5 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -56,7 +56,7 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase run_generator assert_file "config/routes.rb", /get "account\/foo"/, /get "account\/bar"/ end -# + def test_invokes_default_template_engine_even_with_no_action run_generator ["account"] assert_file "app/views/test_app/account" |