1 # Update and read user preferences, which are arbitrayr key/val pairs
2 class UserPreferenceController < ApplicationController
3 skip_before_filter :verify_authenticity_token
4 before_filter :authorize
5 before_filter :require_allow_read_prefs, :only => [:read_one, :read]
6 before_filter :require_allow_write_prefs, :except => [:read_one, :read]
7 around_filter :api_call_handle_error
10 # return all the preferences as an XML document
12 doc = OSM::API.new.get_xml_doc
14 prefs = @user.preferences
16 el1 = XML::Node.new "preferences"
19 el1 << pref.to_xml_node
23 render :text => doc.to_s, :content_type => "text/xml"
27 # return the value for a single preference
29 pref = UserPreference.find([@user.id, params[:preference_key]])
31 render :text => pref.v.to_s, :content_type => "text/plain"
34 # update the entire set of preferences
36 old_preferences = @user.preferences.each_with_object({}) do |preference, preferences|
37 preferences[preference.k] = preference
42 doc = XML::Parser.string(request.raw_post).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 fail OSM::APIDuplicatePreferenceError.new(pt["k"])
50 preference = @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!)
60 render :text => "", :content_type => "text/plain"
64 # update the value of a single preference
67 pref = UserPreference.find([@user.id, params[:preference_key]])
68 rescue ActiveRecord::RecordNotFound
69 pref = UserPreference.new
71 pref.k = params[:preference_key]
74 pref.v = request.raw_post.chomp
77 render :text => "", :content_type => "text/plain"
81 # delete a single preference
83 UserPreference.find([@user.id, params[:preference_key]]).delete
85 render :text => "", :content_type => "text/plain"