Sha256: b0d744e632780091bec5717ac328dccaaf57116ba63952a1b2bb99ce5ad469e4

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

module Netzke
  module ActiveRecord
    module RelationExtensions

      def extend_with(*params)
        scope = params.shift
        case scope.class.name
        when "Symbol" # model's scope
          self.send(scope, *params)
        when "String" # SQL query or SQL query with params (e.g. ["created_at < ?", 1.day.ago])
          params.empty? ? self.where(scope) : self.where([scope, *params])
        when "Array"
          self.extend_with(*scope)
        when "Hash"  # conditions hash
          self.where(scope)
        when "ActiveSupport::HashWithIndifferentAccess" # conditions hash
          self.where(scope)
        when "Proc"   # receives a relation, must return a relation
          scope.call(self)
        else
          raise ArgumentError, "Wrong parameter type for ActiveRecord::Relation#extend_with"
        end
      end

      # Non-destructively extends itself whith a hash of double-underscore'd conditions,
      # where the last part "__" is MetaWhere operator (which is required), e.g.:
      #     {:role__name__like => "%admin"}
      def extend_with_netzke_conditions(cond)
        cond.each_pair.inject(self) do |r, (k,v)|
          assoc, method, *operator = k.to_s.split("__")
          operator.empty? ? r.where(assoc.to_sym.send(method) => v) : r.where(assoc.to_sym => {method.to_sym.send(operator.last) => v}).joins(assoc.to_sym)
        end
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
netzke-basepack-0.7.7 lib/netzke/active_record/relation_extensions.rb
netzke-basepack-zh-0.7.6 lib/netzke/active_record/relation_extensions.rb
netzke-basepack-0.7.6 lib/netzke/active_record/relation_extensions.rb
netzke-basepack-0.7.5 lib/netzke/active_record/relation_extensions.rb