簡體   English   中英

Rails ActiveRecord問題,包括url助手

[英]rails activerecord concern, including url helpers

我試圖為某些模型創建一個before_save回調,該回調將向文本添加鏈接和格式並保存在特殊字段中。 它不會讓我在回調中包含URL幫助器。

這是我的代碼:

module SocialText
  extend ActiveSupport::Concern

  included do
    before_save :action_before_save
  end

  def action_before_save
    self.body_formatted = htmlizeBody(self.body)
  end

  def htmlizeBody(body)
    include Rails.application.routes.url_helpers
    include ActionView::Helpers

    #replace all \ns with <br>
    body = body.gsub(/\n/, ' <br/> ')

    words = body.split(/\s/)
    words.map! do |word|
      if word.first == '@'
        username = extractUsernameFromAtSyntax word
        user = User.find_by! username: username

        if not user.nil?
          link_to(word, profile_path(user.username))
        else
          word
        end
      else
        word
      end
    end

    words.join " "
  end

  def extractUsernameFromAtSyntax(username)
    matchData = username.match(/@(\w+)(['.,]\w*)?/)

    if not matchData.nil?
      matchData[1]
    else
      username
    end
  end
end

我越來越:

NoMethodError (undefined method `include`)

我如何獲得幫手? 有一個更好的方法嗎?

include對類實例對象進行操作,您可以像實例方法一樣調用它。

您應該將其include在方法之外。

考慮在模塊范圍內使用require

htmlizeBody函數中: include Rails.application.routes.url_helpers include ActionView::Helpers

這是在錯誤的范圍內,將其移至extend ActiveSupport::Concern下方可解決您的錯誤。

您可能會問自己的另一個問題是,為什么需要在關注級別使用視圖助手?

在修改默認的url主機選項時(通常在需要與外部API接口時),通常使用include Rails.application.routes.url_helpers 在這種情況下,可以在/lib目錄中使用它。

有關更多信息,請參見此SO帖子有關使用url幫助器的這篇文章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM