繁体   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