]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/user_preferences_controller.rb
Fix new rubocop warnings
[rails.git] / app / controllers / api / user_preferences_controller.rb
1 # Update and read user preferences, which are arbitrayr 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     ##
11     # return all the preferences as an XML document
12     def index
13       @user_preferences = current_user.preferences
14
15       render :formats => [:xml]
16     end
17
18     ##
19     # return the value for a single preference
20     def show
21       pref = UserPreference.find([current_user.id, params[:preference_key]])
22
23       render :plain => pref.v.to_s
24     end
25
26     # update the entire set of preferences
27     def update_all
28       old_preferences = current_user.preferences.index_by(&:k)
29
30       new_preferences = {}
31
32       doc = XML::Parser.string(request.raw_post, :options => XML::Parser::Options::NOERROR).parse
33
34       doc.find("//preferences/preference").each do |pt|
35         if preference = old_preferences.delete(pt["k"])
36           preference.v = pt["v"]
37         elsif new_preferences.include?(pt["k"])
38           raise OSM::APIDuplicatePreferenceError, pt["k"]
39         else
40           preference = current_user.preferences.build(:k => pt["k"], :v => pt["v"])
41         end
42
43         new_preferences[preference.k] = preference
44       end
45
46       old_preferences.each_value(&:delete)
47
48       new_preferences.each_value(&:save!)
49
50       render :plain => ""
51     end
52
53     ##
54     # update the value of a single preference
55     def update
56       begin
57         pref = UserPreference.find([current_user.id, params[:preference_key]])
58       rescue ActiveRecord::RecordNotFound
59         pref = UserPreference.new
60         pref.user = current_user
61         pref.k = params[:preference_key]
62       end
63
64       pref.v = request.raw_post.chomp
65       pref.save!
66
67       render :plain => ""
68     end
69
70     ##
71     # delete a single preference
72     def destroy
73       UserPreference.find([current_user.id, params[:preference_key]]).delete
74
75       render :plain => ""
76     end
77   end
78 end