1 # Update and read user preferences, which are arbitrary key/val pairs
 
   3   class UserPreferencesController < ApiController
 
   4     before_action :check_api_writable, :only => [:update_all, :update, :destroy]
 
   5     before_action :authorize
 
   9     before_action :set_request_formats
 
  12     # return all the preferences
 
  14       @user_preferences = current_user.preferences
 
  16       respond_to do |format|
 
  23     # return the value for a single preference
 
  25       pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  27       render :plain => pref.v.to_s
 
  30     # update the entire set of preferences
 
  32       old_preferences = current_user.preferences.index_by(&:k)
 
  36       doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
 
  38       doc.find("//preferences/preference").each do |pt|
 
  39         if preference = old_preferences.delete(pt["k"])
 
  40           preference.v = pt["v"]
 
  41         elsif new_preferences.include?(pt["k"])
 
  42           raise OSM::APIDuplicatePreferenceError, pt["k"]
 
  44           preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
 
  47         new_preferences[preference.k] = preference
 
  50       old_preferences.each_value(&:delete)
 
  52       new_preferences.each_value(&:save!)
 
  58     # update the value of a single preference
 
  61         pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  62       rescue ActiveRecord::RecordNotFound
 
  63         pref = UserPreference.new
 
  64         pref.user = current_user
 
  65         pref.k = params[:preference_key]
 
  68       pref.v = request.raw_post.chomp.force_encoding("UTF-8")
 
  75     # delete a single preference
 
  77       UserPreference.find([current_user.id, params[:preference_key]]).delete