aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/integration.rb
diff options
context:
space:
mode:
authorRob Biedenharn <Rob@AgileConsultingLLC.com>2016-02-11 14:22:09 -0500
committerRob Biedenharn <Rob@AgileConsultingLLC.com>2016-07-08 17:12:14 -0400
commit3b49d792231f8051a82cee37c46ac5b23de844db (patch)
tree34cf9e4e67ca8a59ba78111fb5c6881c8993b579 /activerecord/lib/active_record/integration.rb
parentc62ac07be86a747f9b40ad25f60003e4f6022d26 (diff)
downloadrails-3b49d792231f8051a82cee37c46ac5b23de844db.tar.gz
rails-3b49d792231f8051a82cee37c46ac5b23de844db.tar.bz2
rails-3b49d792231f8051a82cee37c46ac5b23de844db.zip
fix to_param to maximize content
The documentation states that parameter values longer than 20 characters will be truncated by words, but the example shows that a parameter based on "David Heinemeier Hansson" (with id: 125) becomes "125-david" when "David Heinemeier".length == 16 so why so short? The answer lies in the use of the #truncate option omission: nil which seems to have been intended to mean "nothing", but which actually causes the default string "..." to be used. This causes #truncate to cleave words until the "..." can be added and still remain within the requested size of 20 characters. The better option is omission: '' (which is probably what was originally intended). Furthermore, since the use of #parameterize will remove non-alphanumeric characters, we can maximize the useful content of the output by calling parameterize first and then giving truncate a separator: /-/ rather than a space.
Diffstat (limited to 'activerecord/lib/active_record/integration.rb')
-rw-r--r--activerecord/lib/active_record/integration.rb4
1 files changed, 2 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb
index 466c8509a4..d729deb07b 100644
--- a/activerecord/lib/active_record/integration.rb
+++ b/activerecord/lib/active_record/integration.rb
@@ -86,7 +86,7 @@ module ActiveRecord
#
# user = User.find_by(name: 'David Heinemeier Hansson')
# user.id # => 125
- # user_path(user) # => "/users/125-david"
+ # user_path(user) # => "/users/125-david-heinemeier"
#
# Because the generated param begins with the record's +id+, it is
# suitable for passing to +find+. In a controller, for example:
@@ -100,7 +100,7 @@ module ActiveRecord
define_method :to_param do
if (default = super()) &&
(result = send(method_name).to_s).present? &&
- (param = result.squish.truncate(20, separator: /\s/, omission: nil).parameterize).present?
+ (param = result.squish.parameterize.truncate(20, separator: /-/, omission: '')).present?
"#{default}-#{param}"
else
default