summaryrefslogtreecommitdiff
path: root/app/services/users/update_service.rb
blob: dfbd6016c3fc95e38cd5bbacca11e3b52e74fb9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
module Users
  class UpdateService < BaseService
    def initialize(user, params = {})
      @user = user
      @params = params.dup
    end

    def execute(validate: true, &block)
      yield(@user) if block_given?

      assign_attributes(&block)

      if @user.save(validate: validate)
        success
      else
        error(@user.errors.full_messages.uniq.join('. '))
      end
    end

    def execute!(*args, &block)
      result = execute(*args, &block)

      raise ActiveRecord::RecordInvalid.new(@user) unless result[:status] == :success

      true
    end

    private

    def assign_attributes(&block)
      @user.assign_attributes(params) if params.any?
    end
  end
end