Class: Mobility::Backends::Sequel::Table::QueryMethods

Inherits:
QueryMethods
  • Object
show all
Defined in:
lib/mobility/backends/sequel/table/query_methods.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes, association_name: nil, model_class: nil, subclass_name: nil, **options) ⇒ QueryMethods

Returns a new instance of QueryMethods.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/mobility/backends/sequel/table/query_methods.rb', line 6

def initialize(attributes, association_name: nil, model_class: nil, subclass_name: nil, **options)
  super
  translation_class = model_class.const_get(subclass_name)

  define_join_method(association_name, translation_class, **options)
  define_query_methods(association_name, translation_class, **options)

  attributes.each do |attribute|
    define_method :"first_by_#{attribute}" do |value|
      where(attribute => value).select_all(model.table_name).first
    end
  end
end

Instance Method Details

#define_join_method(association_name, translation_class, table_name: nil, foreign_key: nil) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mobility/backends/sequel/table/query_methods.rb', line 20

def define_join_method(association_name, translation_class, table_name: nil, foreign_key: nil, **)
  define_method :"join_#{association_name}" do |**options|
    return self if (@__mobility_table_joined || []).include?(table_name)
    (@__mobility_table_joined ||= []) << table_name
    join_type = options[:outer_join] ? :left_outer : :inner
    join_table(join_type,
               translation_class.table_name,
               {
                 locale: Mobility.locale.to_s,
                 foreign_key => ::Sequel[model.table_name][:id]
               })
  end
end

#define_query_methods(association_name, translation_class) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mobility/backends/sequel/table/query_methods.rb', line 34

def define_query_methods(association_name, translation_class, **)
  attributes_extractor = @attributes_extractor

  # See note in AR Table QueryMethods class about limitations of
  # query methods on translated attributes when searching on nil values.
  #
  %w[exclude or where].each do |method_name|
    define_method method_name do |*conds, &block|
      if i18n_keys = attributes_extractor.call(conds.first)
        cond = conds.first.dup
        outer_join = method_name == "or" || i18n_keys.all? { |key| cond[key].nil? }
        i18n_keys.each { |attr| cond[::Sequel[translation_class.table_name][attr]] = cond.delete(attr) }
        super(cond, &block).send("join_#{association_name}", outer_join: outer_join)
      else
        super(*conds, &block)
      end
    end
  end
end