簡體   English   中英

在Rails內部調試調用者

[英]debugging the caller inside rails

在Rails應用程序中,使用byebug在控制器的操作方法中設置斷點后,當我鍵入一些gibberesh時,我發現在打印出“未定義的局部變量或方法”之前,將自動執行application_controller.rb中的方法。

這種魔術是怎么發生的? 我該如何跟蹤...鍵入亂碼時我不希望此方法運行...

(byebug) abcd1234abcd1234
  WpPost Load (4.8ms)  SELECT  `wp_posts`.`post_title`, `wp_posts`.`post_date`, `wp_posts`.`post_name` FROM `wp_posts` WHERE `wp_posts`.`post_status` = 'publish' AND (post_date_gmt >= '2017-01-30 23:31:52.437270')  ORDER BY post_date DESC LIMIT 3
*** NameError Exception: undefined local variable or method `abcd1234abcd1234' for #<FooController:0x007fa717745bd8>

nil
(byebug) 

一些代碼

# foo_controller.rb
class FooController < ApplicationController

  def show
    byebug  # I type abcd1234abcd1234 at this prompt
    # ...

# application_controller.rb
class ApplicationController < ActionController::Base
  before_filter :something
  before_filter :something2
  before_filter :load_blog_posts, :something3

  def ....
  end

  def load_blog_posts
    @wp_posts = WpPost.where(post_status: 'publishh')
                  .where("post_date_gmt >= ?", Time.now - 1.week )
                  .order("post_date DESC")
                  .limit(3)
                  .select(:post_title, :post_date, :post_name)
  end

編輯2:

我認為SQL語句只是在晚些時候才打印到日志中。

如果您abcd1234abcd1234鍵入abcd1234abcd1234是否會第二次發生? 我認為不會。

另外,您可以嘗試更改語句以對對象進行某種良性更改,如果您同時運行rails c控制台,則一旦更改到byebug語句,您將看到更改已經發生。 ,它只是還沒有打印到STDOUT上。

通過使用如下代碼加載整個數據庫表,我能夠在測試應用程序中對此進行測試:

def show
  User.all
  Thing.all
  byebug
end

我會得到這個:

(byebug) ksjdfiisddjfj
  User Load (0.5ms)  SELECT "users".* FROM "users"
  Thing Load (0.5ms)  SELECT "things".* FROM "things"

*** NameError Exception: undefined local variable or method `ksjdfiisddjfj' for #<ThingsController:0x007ff7cbe771e0>

nil
(byebug) sdfsdf
*** NameError Exception: undefined local variable or method `sdfsdf' for #<ThingsController:0x007ff7cbe771e0>

nil
(byebug) 

編輯:

過濾器的行為是繼承的,因此application_controller中的每個before_action將在從該控制器繼承的類的每個方法之前運行。

這是文檔的鏈接: http : //edgeguides.rubyonrails.org/action_controller_overview.html

請參閱第8 Filters節“ 8 Filters

如果您只是不希望在show方法之前執行該操作,則可以僅添加一個skip_before_action :load_blog_posts, only:[:show]

我想您想做的是將您的byebug調用作為第一個before_action引入:

    1: class SomethingController < ApplicationController
=>  2:   before_action { byebug }
    3:   before_action :validate_current_something
    4:   before_action :validate_permissions_for_something, only: [ :edit, :update, :destroy ]

這將使您獲得所需的狀態...

暫無
暫無

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

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