1 # Update and read user preferences, which are arbitrary key/val pairs
3 class UserPreferencesController < ApiController
4 before_action :check_api_readable
5 before_action :check_api_writable, :only => [:update_all, :update, :destroy]
6 before_action :authorize
10 around_action :api_call_handle_error
12 before_action :set_request_formats
15 # return all the preferences
17 @user_preferences = current_user.preferences
19 respond_to do |format|
26 # return the value for a single preference
28 pref = UserPreference.find([current_user.id, params[:preference_key]])
30 render :plain => pref.v.to_s
33 # update the entire set of preferences
35 old_preferences = current_user.preferences.index_by(&:k)
39 doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
41 doc.find("//preferences/preference").each do |pt|
42 if preference = old_preferences.delete(pt["k"])
43 preference.v = pt["v"]
44 elsif new_preferences.include?(pt["k"])
45 raise OSM::APIDuplicatePreferenceError, pt["k"]
47 preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
50 new_preferences[preference.k] = preference
53 old_preferences.each_value(&:delete)
55 new_preferences.each_value(&:save!)
61 # update the value of a single preference
64 pref = UserPreference.find([current_user.id, params[:preference_key]])
65 rescue ActiveRecord::RecordNotFound
66 pref = UserPreference.new
67 pref.user = current_user
68 pref.k = params[:preference_key]
71 pref.v = request.raw_post.chomp.force_encoding("UTF-8")
78 # delete a single preference
80 UserPreference.find([current_user.id, params[:preference_key]]).delete