Created
October 28, 2016 21:24
-
-
Save dgollahon/1ca462ed2ed7460f7156940d97bf9f25 to your computer and use it in GitHub Desktop.
A small extension to `sequel` to add a #one method to Dataset
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
# frozen_string_literal: true | |
# | |
# The one extension adds Dataset#one which performs a LIMIT(2) query and will raise a | |
# Sequel::NoMatchingRow if exactly one row is not returned. | |
module Sequel | |
module One | |
MSG = 'Expected query to produce exactly 1 row but received %<rows>s.' | |
def one | |
rows = fetch_two | |
return rows.first if rows.one? | |
fail NoMatchingRow, format(MSG, rows: rows.size) | |
end | |
private | |
def fetch_two | |
limit(2).all | |
end | |
end # One | |
Dataset.register_extension(:one, One) | |
end # Sequel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much for the gist. I found it very useful. I reformatted it based on the instruction found here