參考文章:use rails helper methods in controller
有時候在 script/console 中,或是 controller 內會用到已經寫好的 helper method,像筆者最近遇到要使用 strip_tags,但是要怎麼叫出來用呢?
一、在 controller 中,有一個叫 @template 的 instance variable 可以用來呼叫 helper method,範例程式如下:
class BlahController < ApplicationController def process_text @html = "<p><strong>fgnfgbaf</strong>gafwadsfgewrgtdfgerge</p>" @ascii = @template.strip_tags(@html) #呼叫 strip_tags 這個 helper method .. end end
這樣可以就可以得到 @ascii = "fgnfgbafgafwadsfgewrgtdfgerge" 的結果。
二、這種方法非常簡單,就是直接呼叫完整的 method 路徑
ActionController::Base.helpers.some_helper_method
要在 console 中使用必須用這種方法。
全站熱搜