]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/user_preferences_controller.rb
Fix various code comments
[rails.git] / app / controllers / api / user_preferences_controller.rb
1 # Update and read user preferences, which are arbitrary key/val pairs
2 module Api
3   class UserPreferencesController < ApiController
4     before_action :authorize
5
6     authorize_resource
7
8     around_action :api_call_handle_error
9
10     before_action :set_request_formats
11
12     ##
13     # return all the preferences
14     def index
15       @user_preferences = current_user.preferences
16
17       respond_to do |format|
18         format.xml
19         format.json
20       end
21     end
22
23     ##
24     # return the value for a single preference
25     def show
26       pref = UserPreference.find([current_user.id, params[:preference_key]])
27
28       render :plain => pref.v.to_s
29     end
30
31     # update the entire set of preferences
32     def update_all
33       old_preferences = current_user.preferences.index_by(&:k)
34
35       new_preferences = {}
36
37       doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
38
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"]
44         else
45           preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
46         end
47
48         new_preferences[preference.k] = preference
49       end
50
51       old_preferences.each_value(&:delete)
52
53       new_preferences.each_value(&:save!)
54
55       render :plain => ""
56     end
57
58     ##
59     # update the value of a single preference
60     def update
61       begin
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]
67       end
68
69       pref.v = request.raw_post.chomp
70       pref.save!
71
72       render :plain => ""
73     end
74
75     ##
76     # delete a single preference
77     def destroy
78       UserPreference.find([current_user.id, params[:preference_key]]).delete
79
80       render :plain => ""
81     end
82   end
83 end