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
10 before_action :set_request_formats
13 # return all the preferences
15 @user_preferences = current_user.preferences
17 respond_to do |format|
24 # return the value for a single preference
26 pref = UserPreference.find([current_user.id, params[:preference_key]])
28 render :plain => pref.v.to_s
31 # update the entire set of preferences
33 old_preferences = current_user.preferences.index_by(&:k)
37 doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
39 doc.find("//preferences/preference").each do |pt|
40 if preference = old_preferences.delete(pt["k"])
41 preference.v = pt["v"]
42 elsif new_preferences.include?(pt["k"])
43 raise OSM::APIDuplicatePreferenceError, pt["k"]
45 preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
48 new_preferences[preference.k] = preference
51 old_preferences.each_value(&:delete)
53 new_preferences.each_value(&:save!)
59 # update the value of a single preference
62 pref = UserPreference.find([current_user.id, params[:preference_key]])
63 rescue ActiveRecord::RecordNotFound
64 pref = UserPreference.new
65 pref.user = current_user
66 pref.k = params[:preference_key]
69 pref.v = request.raw_post.chomp
76 # delete a single preference
78 UserPreference.find([current_user.id, params[:preference_key]]).delete