Permalink
Browse files

Merge pull request #12893 from javan/to-param-addendum

Addendum to #12891
  • Loading branch information...
2 parents f33ab01 + 633100b commit e15ea62b26e010d02459f8a2438f5a281cc1dd8f @rafaelfranca rafaelfranca committed Nov 14, 2013
Showing with 28 additions and 8 deletions.
  1. +10 −6 activerecord/lib/active_record/integration.rb
  2. +18 −2 activerecord/test/cases/integration_test.rb
@@ -86,12 +86,16 @@ module ClassMethods
#
# params[:id] # => "123-fancy-pants"
# User.find(params[:id]).id # => 123
- def to_param(method_name)
- define_method :to_param do
- if (default = super()) && (result = send(method_name).to_s).present?
- "#{default}-#{result.truncate(20, separator: /\s/, omission: nil).parameterize}"
- else
- default
+ def to_param(method_name = nil)
+ if method_name.nil?
+ super()
+ else
+ define_method :to_param do
+ if (default = super()) && (result = send(method_name).to_s).present?
+ "#{default}-#{result.squish.truncate(20, separator: /\s/, omission: nil).parameterize}"
+ else
+ default
+ end
end
end
end
@@ -28,19 +28,35 @@ def test_to_param_class_method
assert_equal '4-flamboyant-software', firm.to_param
end
- def to_param_class_method_uses_default_if_blank
+ def test_to_param_class_method_truncates
+ firm = Firm.find(4)
+ firm.name = 'a ' * 100
+ assert_equal '4-a-a-a-a-a-a-a-a-a', firm.to_param
+ end
+
+ def test_to_param_class_method_squishes
+ firm = Firm.find(4)
+ firm.name = "ab \n" * 100
+ assert_equal '4-ab-ab-ab-ab-ab-ab', firm.to_param
+ end
+
+ def test_to_param_class_method_uses_default_if_blank
firm = Firm.find(4)
firm.name = nil
assert_equal '4', firm.to_param
firm.name = ' '
assert_equal '4', firm.to_param
end
- def to_param_class_method_uses_default_if_not_persisted
+ def test_to_param_class_method_uses_default_if_not_persisted
firm = Firm.new(name: 'Fancy Shirts')
assert_equal nil, firm.to_param
end
+ def test_to_param_with_no_arguments
+ assert_equal 'Firm', Firm.to_param
+ end
+
def test_cache_key_for_existing_record_is_not_timezone_dependent
utc_key = Developer.first.cache_key

0 comments on commit e15ea62

Please sign in to comment.