Sha256: 0c5783e5f56683da566c53dc4223dda939b860e56689a48a5e2b75714f4d2e94

Contents?: true

Size: 1.86 KB

Versions: 33

Compression:

Stored size: 1.86 KB

Contents

require 'active_support'

class LHS::Record

  module Find
    extend ActiveSupport::Concern

    module ClassMethods
      # Find a single uniqe record
      def find(*args)
        args, options = process_args(args)
        data =
          if args.is_a? Array
            find_in_parallel(args, options)
          elsif args.is_a? Hash
            find_with_parameters(args, options)
          else
            find_by_id(args, options)
          end
        return data if data.is_a?(Array) || !data._record
        data._record.new(data)
      end

      private

      def process_args(args)
        if args.length == 1
          args = args.first
        elsif args.length == 2 && args.last.is_a?(Hash)
          options = args.pop if args.last.is_a?(Hash)
          args = args.first
        elsif args.last.is_a?(Hash)
          options = args.pop
        end
        options ||= nil
        [args, options]
      end

      def get_unique_item!(data)
        if data._proxy.is_a?(LHS::Collection)
          raise LHC::NotFound.new('Requested unique item. Multiple were found.', data._request.response) if data.length > 1
          data.first || raise(LHC::NotFound.new('No item was found.', data._request.response))
        else
          data
        end
      end

      def find_with_parameters(args, options = {})
        data = request(request_options(args, options))
        get_unique_item!(data)
      end

      def find_by_id(args, options = {})
        request(request_options(args, options))
      end

      def find_in_parallel(args, options)
        options = args.map { |argument| request_options(argument, options) }
        request(options)
      end

      def request_options(args, options)
        if args.is_a? Hash
          (options || {}).merge(params: args)
        else
          (options || {}).merge(params: { id: args })
        end
      end
    end
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
lhs-10.0.0 lib/lhs/concerns/record/find.rb
lhs-9.1.1 lib/lhs/concerns/record/find.rb
lhs-9.1.0 lib/lhs/concerns/record/find.rb
lhs-9.0.4 lib/lhs/concerns/record/find.rb
lhs-9.0.3 lib/lhs/concerns/record/find.rb
lhs-9.0.2 lib/lhs/concerns/record/find.rb
lhs-9.0.1 lib/lhs/concerns/record/find.rb
lhs-9.0.0 lib/lhs/concerns/record/find.rb
lhs-8.0.0 lib/lhs/concerns/record/find.rb
lhs-7.4.1 lib/lhs/concerns/record/find.rb
lhs-7.4.0 lib/lhs/concerns/record/find.rb
lhs-7.3.0 lib/lhs/concerns/record/find.rb
lhs-7.2.5 lib/lhs/concerns/record/find.rb
lhs-7.2.4 lib/lhs/concerns/record/find.rb
lhs-7.2.3 lib/lhs/concerns/record/find.rb
lhs-7.2.2 lib/lhs/concerns/record/find.rb
lhs-7.2.1 lib/lhs/concerns/record/find.rb
lhs-7.2.0 lib/lhs/concerns/record/find.rb
lhs-7.1.0 lib/lhs/concerns/record/find.rb
lhs-7.0.3 lib/lhs/concerns/record/find.rb