Last active
August 29, 2015 14:00
-
-
Save invisiblefunnel/11363280 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # OPEN ISSUE: https://github.com/rails/rails/issues/11957 | |
| # ActiveRecord does not validate the format of a UUID before | |
| # sending a query to the database. Postgres throws an error. | |
| # Preferably, this would raise AR::RecordNotFound. | |
| # | |
| # ActiveRecord::StatementInvalid: | |
| # PG::InvalidTextRepresentation: ERROR: invalid input syntax for uuid: "not-a-uuid" | |
| # | |
| module PrimaryKeyUUID | |
| # https://github.com/assaf/uuid/blob/1fc6dd2e3a3401aa5bce7cebd57d4af89da9ccd6/lib/uuid.rb#L196-L203 | |
| VALID_DEFAULT = /\A(urn:uuid:)?[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}\z/i.freeze | |
| VALID_COMPACT = /\A[\da-f]{32}\z/i.freeze | |
| # Use regexps from the 'uuid' gem to | |
| # determine whether to send the query to the db. | |
| # Raises AR::RecordNotFound if the given id is | |
| # not a valid uuid. Also saves a db query. | |
| def find(*ids, &block) | |
| if _valid_uuids?(*ids) | |
| super | |
| else | |
| none.find(*ids, &block) | |
| end | |
| end | |
| private | |
| def _valid_uuids?(*ids) | |
| ids.flatten.select do |id| | |
| PrimaryKeyUUID::VALID_DEFAULT === id || PrimaryKeyUUID::VALID_COMPACT === id | |
| end.uniq | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment