Rails6新特性actionable Error

视频:https://gorails.com/episodes/actionable-errors-in-rails-6?autoplay=1

这篇视频介绍了Rails6的一个新功能:

actionable error

这个模块定义一个action来解决各种错误类型。通过在❌提示网页上添加了一个button按钮。一键处理相关的❌。

用法:

定义了一个"Run pending migrations" , 当遇到PendingMigrationError后,执行action块内的命令。

      #   class PendingMigrationError < MigrationError
      #     include ActiveSupport::ActionableError
      #
      #     action "Run pending migrations" do
      #       ActiveRecord::Tasks::DatabaseTasks.migrate
      #     end
      #   end

解释:

这个功能用在了rails遇到错误时的渲染一个按键,用来对错误进行处理:

<% actions = ActiveSupport::ActionableError.actions(exception) %>

<% if actions.any? %>
  <div class="actions">
    <% actions.each do |action, _| %>
      <%= button_to action, ActionDispatch::ActionableExceptions.endpoint, params: {
        error: exception.class.name,
        action: action,
        location: request.path
      } %>
    <% end %>
  </div>
<% end %>

button_to生成一个带一个button的form。用于提交由一系列options创建的URL。

ActionableExceptions

这个模块的call调用ActionableError.dispatch方法执行自定义的块内的命令。

    def call(env)
      request = ActionDispatch::Request.new(env)
      return @app.call(env) unless actionable_request?(request)

      ActiveSupport::ActionableError.dispatch(request.params[:error].to_s.safe_constantize, request.params[:action])

      redirect_to request.params[:location]
    end

案例:

//1
rails g scaffold Post title
//2 打开本地网页localhost:300,由于没有执行rails db:migrate会报❌
//ActiveRecord::PendingMigrationError
//Migrations are pending. To resolve this issue, run: rails db:migrate RAILS_ENV=development
//然后附加一个按钮 "Run pending migrations"

点击这个按钮后会执行:migrate命令,可以在terminal上看到Migrating to CreatePosts (20190509031430).

 

利用actionable error可以自定义错误处理

在PostsController内添加一个对NoDataError类型错误的一键处理。

class PostsController < ApplicationController
  ...

  class NoDAtaError < StandardError
    include ActiveSupport::ActionableError

    action "Run seeds" do
      Rails.application.load_seed
    end
  end

  def index
   @posts = Post.all
    raise NoDataError if @posts.none?
  end 

进入localhost:3000/posts, 如果没有数据post就会进入❌页面,并添加一个button。

添加种子:在seeds.rb内添加:Post.create(title:"hello Error!")。

点击button,后会运行块内的load_seed命令。并重新渲染网页。

原文地址:https://www.cnblogs.com/chentianwei/p/10840522.html