1 # frozen_string_literal: true
3 class UserNotificationPreferences
4 extend ActiveModel::Naming
5 include ActiveModel::Conversion
25 # Receives a hash in the form `event => [mechanisms...]`. Eg:
26 # `{:changeset_comment => ["email"], :new_follower => []}`
29 EVENTS.map do |event_name|
30 MECHANISMS.filter_map do |mechanism|
31 next unless new_prefs.key?(event_name)
33 record = @user.preferences.find_or_initialize_by(:k => "notification.#{event_name}.#{mechanism}")
34 record.v = Array.wrap(new_prefs[event_name]).include?(mechanism)
39 UserPreference.transaction do
40 updated_records.each(&:save!)
45 # One getter method for each event. Required by ActionView
46 # to render the form, but also generally useful to us.
47 EVENTS.each do |event_name|
48 define_method event_name do
52 .where("k LIKE 'notification.#{event_name}.%'")
55 .transform_keys { |k| k.split(".").last }
57 MECHANISMS.filter do |mechanism|
58 prefs.key?(mechanism) ? ActiveModel::Type::Boolean.new.cast(prefs[mechanism]) : true