Permalink
Browse files

allow records to be found with a string id

  • Loading branch information...
1 parent a799422 commit 9ad4b37d3fe074bc8b2791b6ce0c0608d5ce8e8b Chad Pytel committed Apr 13, 2009
Showing with 22 additions and 2 deletions.
  1. +6 −2 lib/friendly_identifier.rb
  2. +16 −0 test/friendly_identifier_test.rb
@@ -41,9 +41,13 @@ def friendly_identifier(source, options = {})
# Adds class methods.
module SingletonMethods
-
+
+ def friendly_identifier?(id)
+ id.is_a?(String) && id.to_i.to_s != id
+ end
+
def find(*args)
- if args.first.is_a? String
+ if friendly_identifier? args.first
super(:first, :conditions => ["#{identifier_options[:identifier_column]} = ?", args.first])
else
super
@@ -63,6 +63,22 @@ def test_should_allow_user_configurable_identifier_column
flunk "Can't find an object with a different identifier column"
end
+ def test_should_also_allow_object_to_be_found_by_id
+ gadget = create_gadget(:name => "new name")
+ assert_not_nil gadget.url_slug
+ assert gadget.save, "Couldn't save object #{gadget.errors.inspect}"
+ assert_not_nil (g = Gadget.find(gadget.id)), "Can't find an object by id"
+ assert_equal gadget.name, g.name, "Gadget we found is not the same as the one we want"
+ end
+
+ def test_should_also_allow_object_to_be_found_by_string_id
+ gadget = create_gadget(:name => "test name")
+ assert_not_nil gadget.url_slug
+ assert gadget.save, "Couldn't save object #{gadget.errors.inspect}"
+ assert_not_nil (g = Gadget.find(gadget.id.to_s)), "Can't find an object by id"
+ assert_equal gadget.name, g.name, "Gadget we found is not the same as the one we want"
+ end
+
def test_should_not_mess_with_validations_and_after_save
gadget = create_gadget :required_stuff => nil
assert !gadget.valid?

0 comments on commit 9ad4b37

Please sign in to comment.