Module: Preferences::ClassMethods
- Defined in:
- lib/preferences.rb
Overview
:nodoc:
Instance Method Summary collapse
-
#build_preference_scope(preferences, inverse = false) ⇒ Object
Generates the scope for looking under records with a specific set of preferences associated with them.
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 thate 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.
235 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 |
# File 'lib/preferences.rb', line 235 def build_preference_scope(preferences, inverse = false) joins = [] statements = [] values = [] # Flatten the preferences for easier processing preferences = preferences.inject({}) do |result, (group, value)| if value.is_a?(Hash) value.each {|preference, value| result[[group, preference]] = value} else result[[nil, group]] = value end result 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 = "preferences_#{group_id}_#{group_type}_#{preference}" # Since each preference is a different record, they need their own # join so that the proper conditions can be set joins << "LEFT JOIN preferences AS #{table} ON #{table}.owner_id = #{table_name}.#{primary_key} AND " + sanitize_sql( "#{table}.owner_type" => base_class.name.to_s, "#{table}.group_id" => group_id, "#{table}.group_type" => group_type, "#{table}.name" => preference ) if inverse statements << "#{table}.id IS NOT NULL AND #{table}.value " + (value.nil? ? ' IS NOT NULL' : ' != ?') + (!is_default ? " OR #{table}.id IS NULL" : '') else statements << "#{table}.id IS NOT NULL AND #{table}.value " + (value.nil? ? ' IS NULL' : ' = ?') + (is_default ? " OR #{table}.id IS NULL" : '') end values << value unless value.nil? end sql = statements.map! {|statement| "(#{statement})"} * ' AND ' {:joins => joins, :conditions => values.unshift(sql)} end |