1 # Update and read user preferences, which are arbitrayr key/val pairs
 
   3   class UserPreferencesController < ApiController
 
   4     before_action :authorize
 
   8     around_action :api_call_handle_error
 
  11     # return all the preferences as an XML document
 
  13       doc = OSM::API.new.get_xml_doc
 
  15       prefs = current_user.preferences
 
  17       el1 = XML::Node.new "preferences"
 
  20         el1 << pref.to_xml_node
 
  24       render :xml => doc.to_s
 
  28     # return the value for a single preference
 
  30       pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  32       render :plain => pref.v.to_s
 
  35     # update the entire set of preferences
 
  37       old_preferences = current_user.preferences.each_with_object({}) do |preference, preferences|
 
  38         preferences[preference.k] = preference
 
  43       doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
 
  45       doc.find("//preferences/preference").each do |pt|
 
  46         if preference = old_preferences.delete(pt["k"])
 
  47           preference.v = pt["v"]
 
  48         elsif new_preferences.include?(pt["k"])
 
  49           raise OSM::APIDuplicatePreferenceError, pt["k"]
 
  51           preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
 
  54         new_preferences[preference.k] = preference
 
  57       old_preferences.each_value(&:delete)
 
  59       new_preferences.each_value(&:save!)
 
  65     # update the value of a single preference
 
  68         pref = UserPreference.find([current_user.id, params[:preference_key]])
 
  69       rescue ActiveRecord::RecordNotFound
 
  70         pref = UserPreference.new
 
  71         pref.user = current_user
 
  72         pref.k = params[:preference_key]
 
  75       pref.v = request.raw_post.chomp
 
  82     # delete a single preference
 
  84       UserPreference.find([current_user.id, params[:preference_key]]).delete