Class: Mobility::Backend::Sequel::Table::QueryMethods

Inherits:
QueryMethods show all
Defined in:
lib/mobility/backend/sequel/table/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
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mobility/backend/sequel/table/query_methods.rb', line 4

def initialize(attributes, **options)
  super
  association_name     = options[:association_name]
  @association_name    = association_name
  foreign_key          = options[:foreign_key]
  attributes_extractor = @attributes_extractor
  translation_class    = options[:model_class].const_get(options[:subclass_name])
  @translation_class   = translation_class
  table_name           = options[:table_name]

  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

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

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