簡體   English   中英

創建時進行Ruby(Rails)字符串操作

[英]Ruby (Rails) string manipulation upon create

我正在研究類似Twitter的應用程序。 用戶創建帖子,並且我要添加功能,以便用戶可以通過在帖子的開頭放置要標記的用戶的@email來標記其他用戶。

in_reply_to是在Micropost中被標記的用戶的ID。

這是在我的Micropost_controller.rb中

@reply_regex = /(\A@[^@ ]+(@)\w+(\.[a-z]{2,3}){1,2}.*\z)/i
def create
  @micropost = current_user.microposts.build(params[:micropost])
  if @micropost.content =~ @reply_regex
    email = @micropost.content.scan(/([^@ ]+(@)\w+(\.[a-z]{2,3}){1,2})/i).first.first
    @micropost.in_reply_to = User.find_by_email(email).id
  end
  if @micropost.save 
    flash[:success] = "Micropost created!"
    redirect_to root_path

當我在控制台中的字符串上運行電子郵件提取部分時,它可以完美工作並返回電子郵件。 但是,當我創建新的微博時,in_reply_to始終保持為零。

像這樣:

class C
  @a = 11
end

創建命名實例變量@a的實例C 當您達到@a = 11self將是類本身,因此@a將成為對象C的實例變量。 如果將以上內容放入irb並查看C.instance_variables ,則會看到以下內容:

>> C.instance_variables
=> [:a]

但是當您查看C的實例時:

>> C.new.instance_variables
=> []

同樣,實例變量在首次使用時會自動創建,並初始化為nil

結合以上內容,我們知道您在對象MicropostController有一個@reply_regex實例變量,但在實例中卻沒有。 您的def create是一個實例方法,因此它將使用@reply_regex實例變量; 但是您沒有@reply_regex作為MicropostController對象的實例變量,因此它將在if語句中創建並初始化為nil 結果是您的if最終是這樣的:

if @micropost.content =~ nil

@micropost.content =~ nil將計算為nil並且由於nil在布爾上下文中為false,因此永遠不會輸入if塊,並且永遠不會為@micropost.in_reply_to分配值。

您可以為您的正則表達式使用類變量:

@@reply_regex = /(\A@[^@ ]+(@)\w+(\.[a-z]{2,3}){1,2}.*\z)/i
def create
  @micropost = current_user.microposts.build(params[:micropost])
  if @micropost.content =~ @@reply_regex
    #...

因為類變量對於實例方法是可見的,或者更好,只需使用一個常量即可:

REPLY_REGEX = /(\A@[^@ ]+(@)\w+(\.[a-z]{2,3}){1,2}.*\z)/i
def create
  @micropost = current_user.microposts.build(params[:micropost])
  if @micropost.content =~ REPLY_REGEX
    #...

順便說一句,我認為您應該將回復檢查轉移到模型中。 您可以使用before_validation回調來刪除content任何前導和尾隨空格,並提取並保存答復:

class Micropost < ActiveRecord::Base
  before_validate :process_content, :if => :content_changed?
  #...
  private
  def process_content
    # Strip leading/trailing whitespace from self.content
    # Extract the reply-to from self.content and save it in self.in_reply_to
  end
end

這樣做的好處是,如果在不經過控制器的情況下更改或創建內容(例如在Rails控制台中手動進行遷移,一些通知用戶的系統任務等),您仍然可以獲得所有內容完成。

暫無
暫無

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

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