3-30 flash(api),rescue_from(); logger简介

ActionDispatch::Flash Objec

pass temporary primitive-types (String, ArrayHash) between actions.

Anything you place in the flash will be exposed to the very next action and then cleared out. 

用于增加通知,警告信息,例子:

def create
 flash[:notice] = "Post successfully created"
 redirect_to @post
end 


模块ActionController::Flash里面有一个实例私有方法: 

redirect_to(options = {}, response_status_and_flash = {})可以把flash信息做参数返回到下一个action.

例子:redirect_to(store_index_path, notice: "...")


ActionDispatch::Flash::FlashHash Object 有20多个方法:

如alert, notice, 可以用chain方式写法:flash.notice = "..."

keep(k = nil):

Keeps either the entire current flash or a specific flash entry available for the next action:

flash.keep # keeps the entire flash 
flash.keep(:notice) # keeps only the "notice" entry, 
the rest of the flash is discarded
now() :只能用于在当前动作下使用

Sets a flash that will not be available to the next action, only to the current.

flash.now[:message] = "Hello current action"


ModuleActiveSupport::Rescuable::ClassMethods

用在对类的错误的营救: 

rescue_from(*klasses, with: nil, &block)

   Rescue exceptions raised in controller actions.

   参数1:a series of exception classes or class names,

    参数2: and a trailing :with option with the name of a method or a Proc object to be called to handle them. Alternatively a block can be given.

class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :deny_access # self defined exception
rescue_from ActiveRecord::RecordInvalid, with: :show_errors
rescue_from 'MyAppError::Base' do |exception|
render xml: exception, status: 500
end
private
def deny_access
...
end
def show_errors(exception)
exception.record.new_record? ? ...
end
end

 Rails 使用 ActiveSupport::Logger 类把信息写入日志。

在log文件内隐藏着development.log, test.log.

guide指导:http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger 

每一个控制器都有logger属性,可以在其中的action中增加logger.XXX()方法。 

  logger.debug "New article: #{@article.attributes.inspect}"

Sending Messages 

    To write in the current log use the logger.(debug|info|warn|error|fatal) from within a controller, model or mailer。控制器,模块,邮件模块,都可以添加logger.xxx()方法。


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