Class: Mobility::Backend::ActiveRecord::Jsonb::QueryMethods

Inherits:
QueryMethods show all
Defined in:
lib/mobility/backend/active_record/jsonb/query_methods.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes, **options) ⇒ QueryMethods

Returns a new instance of QueryMethods.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/mobility/backend/active_record/jsonb/query_methods.rb', line 4

def initialize(attributes, **options)
  super
  attributes_extractor = @attributes_extractor

  define_method :where! do |opts, *rest|
    if i18n_keys = attributes_extractor.call(opts)
      m = arel_table
      locale = Arel::Nodes.build_quoted(Mobility.locale.to_s)
      opts = opts.with_indifferent_access
      infix = Arel::Nodes::InfixOperation

      i18n_query = i18n_keys.inject(nil) { |ops, attr|
        column = m[attr.to_sym]
        value = opts.delete(attr)

        op =
          if value.nil?
            infix.new(:'?', column, locale).not
          else
            predicate = Arel::Nodes.build_quoted({ Mobility.locale => value }.to_json)
            infix.new(:'@>', m[attr.to_sym], predicate)
          end
        ops ? ops.and(op) : op
      }

      opts.empty? ? where(i18n_query) : super(opts, *rest).where(i18n_query)
    else
      super(opts, *rest)
    end
  end
end

Instance Method Details

#extended(relation) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mobility/backend/active_record/jsonb/query_methods.rb', line 36

def extended(relation)
  super
  attributes_extractor = @attributes_extractor
  m = relation.model.arel_table

  mod = Module.new do
    define_method :not do |opts, *rest|
      if i18n_keys = attributes_extractor.call(opts)
        locale = Arel::Nodes.build_quoted(Mobility.locale.to_s)
        opts = opts.with_indifferent_access
        infix = Arel::Nodes::InfixOperation

        i18n_query = i18n_keys.inject(nil) { |ops, attr|
          column = m[attr.to_sym]
          has_key = infix.new(:'?', column, locale)
          predicate = Arel::Nodes.build_quoted({ Mobility.locale => opts.delete(attr) }.to_json)
          not_eq_value = infix.new(:'@>', m[attr.to_sym], predicate).not
          op = has_key.and(not_eq_value)
          ops ? ops.and(op) : op
        }

        super(opts, *rest).where(i18n_query)
      else
        super(opts, *rest)
      end
    end
  end
  relation.model.mobility_where_chain.prepend(mod)
end