Last active
January 13, 2016 23:50
-
-
Save joshuaflanagan/e32decd3ce885ab62537 to your computer and use it in GitHub Desktop.
Simplify working with UUID primary keys in Rails console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActiveRecord::Base | |
# Find a record by UUID primary key prefix | |
# | |
# Example: | |
# > User.fish "1245" | |
# # User Load (0.3ms) SELECT "users".* FROM "users" WHERE ("users"."id" BETWEEN '12450000000000000000000000000000' AND '1245ffffffffffffffffffffffffffff') LIMIT $1 [["LIMIT", 2]] | |
# => #<User id: "12451304-761d-4e1d-8281-40aa6213b633", name: "josh"> | |
def self.fish(partial_id) | |
return find(partial_id) unless partial_id.is_a?(String) | |
scrubbed = partial_id.gsub(/[^a-fA-F0-9]/, "") | |
missing_length = 32 - scrubbed.length | |
raise "Invalid UUID: #{scrubbed}" if missing_length < 0 | |
return find(partial_id) if missing_length == 0 | |
lower = "#{scrubbed}#{'0' * missing_length}" | |
upper = "#{scrubbed}#{'f' * missing_length}" | |
matches = where(id: (lower..upper)).take(2) | |
raise "Ambiguous id prefix: #{scrubbed}. Be more specific" if matches.length > 1 | |
matches[0] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment