Sha256: 72665d124d91d3ee3b32c04fcefbe59706ad277a9e7634af20bce8c565a846eb

Contents?: true

Size: 1.02 KB

Versions: 24

Compression:

Stored size: 1.02 KB

Contents

require 'active_support'

class LHS::Record

  module FindBy
    extend ActiveSupport::Concern

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

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

      private

      def _find_by(params, options = {})
        raise(LHS::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?(LHS::Collection)
          data.first || raise(LHC::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

24 entries across 24 versions & 1 rubygems

Version Path
lhs-15.3.1.pre.fixlhc.1 lib/lhs/concerns/record/find_by.rb
lhs-15.3.0 lib/lhs/concerns/record/find_by.rb
lhs-15.2.5 lib/lhs/concerns/record/find_by.rb
lhs-15.2.4 lib/lhs/concerns/record/find_by.rb