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 raise 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 do |preference|
61 new_preferences.each_value do |preference|
65 render :nothing => true, :content_type => "text/plain"
69 # update the value of a single preference
72 pref = UserPreference.find(@user.id, params[:preference_key])
73 rescue ActiveRecord::RecordNotFound
74 pref = UserPreference.new
76 pref.k = params[:preference_key]
79 pref.v = request.raw_post.chomp
82 render :nothing => true, :content_type => "text/plain"
86 # delete a single preference
88 UserPreference.find(@user.id, params[:preference_key]).delete
90 render :nothing => true, :content_type => "text/plain"