简体   繁体   English

Rails 5 API - 服务

[英]Rails 5 API - Services

I refactored one of my controllers to move the update logic into a service我重构了我的一个控制器以将更新逻辑移动到服务中

so the controller looks like this所以 controller 看起来像这样

  #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

So as I said before I moved the entire logic into a service that takes care of the update logic and the redirects.因此,正如我之前所说,我将整个逻辑移到了一个负责更新逻辑和重定向的服务中。 I know there might be a debate in leaving the redirects in the controller.我知道将重定向留在 controller 中可能存在争议。

#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

If I use the Awesome Print in the call method I can the user and params properly being passed but I'm getting a如果我在调用方法中使用 Awesome Print,我可以正确传递用户和参数,但我得到一个

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

and I can't figure out why我不知道为什么

Looks like it caused by airbrake gem.看起来它是由空气制动宝石引起的。 You should add environment condition to airbrake (or errbit) initializer.您应该将环境条件添加到 airbrake(或 errbit)初始化程序。

config/initializers/airbrake.rb配置/初始化程序/airbrake.rb

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

and add gem airbrake to the production group.并将gem airbrake添加到production组。

Gemfile宝石文件

group :production do
  gem 'airbrake'
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM