Skip to content

Instantly share code, notes, and snippets.

@dgollahon
Created October 28, 2016 21:24
Show Gist options
  • Save dgollahon/1ca462ed2ed7460f7156940d97bf9f25 to your computer and use it in GitHub Desktop.
Save dgollahon/1ca462ed2ed7460f7156940d97bf9f25 to your computer and use it in GitHub Desktop.
A small extension to `sequel` to add a #one method to Dataset
# 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
@lkfken
Copy link

lkfken commented Mar 9, 2017

Thank you very much for the gist. I found it very useful. I reformatted it based on the instruction found here

module Sequel
  module Plugins
    module One
      module DatasetMethods
        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
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment