Class: Mobility::Plugins::ActiveRecord::Query::VirtualRow

Inherits:
BasicObject
Defined in:
lib/mobility/plugins/active_record/query.rb

Overview

Creates a “clean room” for manipulating translated attribute nodes in an instance-eval’ed block. Inspired by Sequel’s (much more sophisticated) virtual rows.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, global_locale) ⇒ VirtualRow

Returns a new instance of VirtualRow.



85
86
87
# File 'lib/mobility/plugins/active_record/query.rb', line 85

def initialize(klass, global_locale)
  @klass, @global_locale, @locales, @backends = klass, global_locale, [], []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/mobility/plugins/active_record/query.rb', line 89

def method_missing(m, *args)
  if @klass.mobility_attribute?(m)
    @backends |= [@klass.mobility_backend_class(m)]
    ::Mobility.validate_locale!(args[0]) if args[0]
    locale = args[0] || @global_locale
    @locales |= [locale]
    @klass.mobility_backend_class(m).build_node(m, locale)
  elsif @klass.column_names.include?(m.to_s)
    @klass.arel_table[m]
  else
    super
  end
end

Instance Attribute Details

#backendsObject (readonly)

Returns the value of attribute backends.



83
84
85
# File 'lib/mobility/plugins/active_record/query.rb', line 83

def backends
  @backends
end

#localesObject (readonly)

Returns the value of attribute locales.



83
84
85
# File 'lib/mobility/plugins/active_record/query.rb', line 83

def locales
  @locales
end

Class Method Details

.build_query(klass, locale, &block) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/mobility/plugins/active_record/query.rb', line 104

def build_query(klass, locale, &block)
  ::Mobility.validate_locale!(locale)

  row = new(klass, locale)
  query = block.arity.zero? ? row.instance_eval(&block) : block.call(row)

  if ::ActiveRecord::Relation === query
    predicates = query.arel.constraints
    apply_scopes(klass.all, row.backends, row.locales, predicates).merge(query)
  else
    apply_scopes(klass.all, row.backends, row.locales, query).where(query)
  end
end