1 # Update and read user preferences, which are arbitrayr key/val pairs
2 class UserPreferencesController < ApplicationController
3 skip_before_action :verify_authenticity_token
4 before_action :authorize
5 before_action :require_allow_read_prefs, :only => [:read_one, :read]
6 before_action :require_allow_write_prefs, :except => [:read_one, :read]
7 around_action :api_call_handle_error
10 # return all the preferences as an XML document
12 doc = OSM::API.new.get_xml_doc
14 prefs = current_user.preferences
16 el1 = XML::Node.new "preferences"
19 el1 << pref.to_xml_node
23 render :xml => doc.to_s
27 # return the value for a single preference
29 pref = UserPreference.find([current_user.id, params[:preference_key]])
31 render :plain => pref.v.to_s
34 # update the entire set of preferences
36 old_preferences = current_user.preferences.each_with_object({}) do |preference, preferences|
37 preferences[preference.k] = preference
42 doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
44 doc.find("//preferences/preference").each do |pt|
45 if preference = old_preferences.delete(pt["k"])
46 preference.v = pt["v"]
47 elsif new_preferences.include?(pt["k"])
48 raise OSM::APIDuplicatePreferenceError, pt["k"]
50 preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
53 new_preferences[preference.k] = preference
56 old_preferences.each_value(&:delete)
58 new_preferences.each_value(&:save!)
64 # update the value of a single preference
67 pref = UserPreference.find([current_user.id, params[:preference_key]])
68 rescue ActiveRecord::RecordNotFound
69 pref = UserPreference.new
70 pref.user = current_user
71 pref.k = params[:preference_key]
74 pref.v = request.raw_post.chomp
81 # delete a single preference
83 UserPreference.find([current_user.id, params[:preference_key]]).delete