Module: Preferences::ClassMethods

Defined in:
lib/preferences.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#build_preference_scope(preferences, inverse = false) ⇒ Object

Generates the scope for looking under records with a specific set of preferences associated with them.

Note that this is a bit more complicated than usual since the preference definitions aren’t in the database for joins, defaults need to be accounted for, and querying for the the presence of multiple preferences requires multiple joins.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/preferences.rb', line 236

def build_preference_scope(preferences, inverse = false)
  join_statements = []
  conditions = nil

  # Flatten the preferences for easier processing
  preferences = preferences.each_with_object({}) do |(group, value), result|
    if value.is_a?(Hash)
      value.each { |preference, value| result[[group, preference]] = value }
    else
      result[[nil, group]] = value
    end
  end

  preferences.each do |(group, preference), value|
    group_id, group_type = Preference.split_group(group)
    preference = preference.to_s
    definition = preference_definitions[preference.to_s]
    value = definition.type_cast(value)
    is_default = definition.default_value(group_type) == value

    table_alias_name = "preferences_#{group_id}_#{group_type}_#{preference}"
    table_alias = Preference.arel_table.alias(table_alias_name)

    equal_primary_key = table_alias[:owner_id].eq(arel_table[primary_key])
    owner_type_equals_base_class = table_alias[:owner_type].eq(base_class)
    group_id_equals = table_alias[:group_id].eq(group_id)
    group_type_equals = table_alias[:group_type].eq(group_type)
    name_equals = table_alias[:name].eq(preference)

    join_statements << arel_table
      .join(table_alias, Arel::Nodes::OuterJoin)
      .on(equal_primary_key
        .and(owner_type_equals_base_class)
        .and(group_id_equals)
        .and(group_type_equals)
        .and(name_equals))

    condition = table_alias[:id].not_eq(nil)
    condition = inverse ? condition.and(table_alias[:value].not_eq(value)) : condition.and(table_alias[:value].eq(value))
    condition = condition.or(table_alias[:id].eq(nil)) if is_default != inverse

    conditions = conditions ? conditions.and(condition) : condition
  end

  joins(join_statements.map(&:join_sources)).where(conditions)
end