Sha256: c90fefe731100f98b1190cb1d6909b7bcd5d21a8da6b487870ee21ab1328c517

Contents?: true

Size: 1.06 KB

Versions: 12

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

require 'active_support'

class DHS::Record

  module FindBy
    extend ActiveSupport::Concern

    module ClassMethods
      # Fetch some record by parameters
      def find_by(params = {}, options = nil)
        _find_by(params, trace!(options))
      rescue DHC::NotFound
        nil
      end

      # Raise if no record was found
      def find_by!(params = {}, options = nil)
        _find_by(params, trace!(options))
      end

      private

      def _find_by(params, options = {})
        raise(DHS::Unprocessable.new, 'Cannot find Record without an ID') if params.any? && params.all? { |_, value| value.blank? }
        options ||= {}
        params = params.dup.merge(limit_key(:parameter) => 1).merge(options.fetch(:params, {}))
        data = request(options.merge(params: params))
        if data && data._proxy.is_a?(DHS::Collection)
          data.first || raise(DHC::NotFound.new('No item was found.', data._request.response))
        elsif data
          data._record.new(data.unwrap_nested_item)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
dhs-1.6.0 lib/dhs/concerns/record/find_by.rb
dhs-1.5.0 lib/dhs/concerns/record/find_by.rb
dhs-1.4.2 lib/dhs/concerns/record/find_by.rb
dhs-1.4.1 lib/dhs/concerns/record/find_by.rb
dhs-1.4.0 lib/dhs/concerns/record/find_by.rb
dhs-1.3.0 lib/dhs/concerns/record/find_by.rb
dhs-1.2.0 lib/dhs/concerns/record/find_by.rb
dhs-1.1.0 lib/dhs/concerns/record/find_by.rb
dhs-1.0.3 lib/dhs/concerns/record/find_by.rb
dhs-1.0.2 lib/dhs/concerns/record/find_by.rb
dhs-1.0.1 lib/dhs/concerns/record/find_by.rb
dhs-1.0.0 lib/dhs/concerns/record/find_by.rb