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.reduce({}) do |preferences, preference|
37 preferences[preference.k] = preference
43 doc = XML::Parser.string(request.raw_post).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 fail OSM::APIDuplicatePreferenceError.new(pt["k"])
51 preference = @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!)
61 render :text => "", :content_type => "text/plain"
65 # update the value of a single preference
68 pref = UserPreference.find([@user.id, params[:preference_key]])
69 rescue ActiveRecord::RecordNotFound
70 pref = UserPreference.new
72 pref.k = params[:preference_key]
75 pref.v = request.raw_post.chomp
78 render :text => "", :content_type => "text/plain"
82 # delete a single preference
84 UserPreference.find([@user.id, params[:preference_key]]).delete
86 render :text => "", :content_type => "text/plain"