Rails 5 API - Services



>我重构了一个控制器以将更新逻辑移动到服务中

所以控制器看起来像这样

  #user_controller.rb
  def update
    UserManagement::UserUpdatePassword.new(@user, user_params).call
  end
  def user_params
    params.require(:user).permit(:password, :password_confirmation)
  end
  def get_user
    @user ||= User.find_by_password_reset_token(params[:id])
  end

因此,正如我之前所说,我将整个逻辑移动到处理更新逻辑和重定向的服务中。我知道在控制器中保留重定向可能会有争议。

#user management service
module UserManagement
 class UserUpdatePassword
  attr_reader :user, :params
  def initialize(get_user, user_params)
    @user = get_user
    @params = user_params
  end
  def call
    if user.password_reset_token < 2.hours.ago
      redirect_to new_password_reset_path, :alert => "Password reset has expired."
    elsif user.update_attributes(params)
      redirect_to confirmation_password_resets_path, :notice => "Congratulations! Your Password has been reset."
    else
      render :edit
    end
  end
 end
end

如果我在调用方法中使用真棒打印,我可以正确传递用户和参数,但我得到了一个

NoMethodError (undefined method "build_notice" for nil:NilClass):

我不知道为什么

看起来像是由空气制动宝石引起的。应将环境条件添加到空气制动器(或 errbit(初始值设定项。

config/initializers/airbrake.rb

if Rails.env.production?
  Airbrake.configure do |config|
    # your configuration here
  end
end

并将gem airbrake添加到production组。

宝石文件

group :production do
  gem 'airbrake'
end

最新更新