Sha256: 4ffa24b9fa966455e534f3738475a2ce8d3b2f7ea4cd7fba9b5df31c36b80911

Contents?: true

Size: 856 Bytes

Versions: 1

Compression:

Stored size: 856 Bytes

Contents

# encoding: UTF-8

require 'forwardable'
require 'enumerator'

module ArelHelpers
  class QueryBuilder
    extend Forwardable
    include Enumerable

    attr_reader :query
    def_delegators :@query, :to_a, :to_sql, :each

    TERMINAL_METHODS = [:count, :first, :last]
    TERMINAL_METHODS << :pluck if ActiveRecord::VERSION::MAJOR >= 4

    def_delegators :@query, *TERMINAL_METHODS

    def self.not_nil(name)
      mod = Module.new do
        define_method(name) do |*args, **kwargs|
          if (value = super(*args, **kwargs))
            value
          else
            reflect(query)
          end
        end
      end

      prepend mod
      name
    end

    def initialize(query)
      @query = query
    end

    protected

    def reflect(query)
      dup.tap { |obj| obj.instance_variable_set('@query'.freeze, query) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
arel-helpers-2.12.1 lib/arel-helpers/query_builder.rb