在使用byebug
的控制器操作方法内设置断点后,在rails应用程序中,
当我输入一些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
答案 0 :(得分:0)
编辑2:
我认为SQL语句只是迟到了。
如果您第二次输入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
。
如果您只是在show
方法之前没有执行该操作,那么您可以添加skip_before_action :load_blog_posts, only:[:show]
。
我认为您想要做的是将byebug
电话作为第一个事前行动:
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 ]
这样您就可以获得您正在寻找的状态......