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.



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

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



86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/mobility/plugins/active_record/query.rb', line 86

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.



80
81
82
# File 'lib/mobility/plugins/active_record/query.rb', line 80

def backends
  @backends
end

#localesObject (readonly)

Returns the value of attribute locales.



80
81
82
# File 'lib/mobility/plugins/active_record/query.rb', line 80

def locales
  @locales
end

Class Method Details

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



101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/mobility/plugins/active_record/query.rb', line 101

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