Sha256: dc87b45981241ac65c56d8bcf5bf05bb8d3aad1c8bd543454f3235de9db0fbee

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 KB

Contents

module Ahoy
  module Properties
    extend ActiveSupport::Concern

    module ClassMethods
      def where_properties(properties)
        relation = self
        column_type = columns_hash["properties"].type
        adapter_name = connection.adapter_name.downcase
        case adapter_name
        when /mysql/
          if column_type == :json
            properties.each do |k, v|
              if v.nil?
                v = "null"
              elsif v == true
                v = "true"
              end

              relation = relation.where("JSON_UNQUOTE(properties -> ?) = ?", "$.#{k.to_s}", v.as_json)
            end
          else
            properties.each do |k, v|
              relation = relation.where("properties REGEXP ?", "[{,]#{{k.to_s => v}.to_json.sub(/\A\{/, "").sub(/\}\z/, "")}[,}]")
            end
          end
        when /postgres/
          if column_type == :jsonb || column_type == :json
            properties.each do |k, v|
              relation =
                if v.nil?
                  relation.where("properties ->> ? IS NULL", k.to_s)
                else
                  relation.where("properties ->> ? = ?", k.to_s, v.as_json.to_s)
                end
            end
          elsif column_type == :hstore
            properties.each do |k, v|
              relation =
                if v.nil?
                  relation.where("properties -> ? IS NULL", k.to_s)
                else
                  relation.where("properties -> ? = ?", k.to_s, v.to_s)
                end
            end
          else
            properties.each do |k, v|
              relation = relation.where("properties SIMILAR TO ?", "%[{,]#{{k.to_s => v}.to_json.sub(/\A\{/, "").sub(/\}\z/, "")}[,}]%")
            end
          end
        else
          raise "Adapter not supported: #{adapter_name}"
        end
        relation
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ahoy_matey-1.5.3 lib/ahoy/properties.rb
ahoy_matey-1.5.2 lib/ahoy/properties.rb
ahoy_matey-1.5.1 lib/ahoy/properties.rb
ahoy_matey-1.5.0 lib/ahoy/properties.rb
ahoy_matey-1.4.2 lib/ahoy/properties.rb