新手问题 求教 rails 如何调试?

dume2007 · 2013年11月01日 · 最后由 chitsaou 回复于 2013年11月05日 · 7969 次阅读

比如我在 model 里想临时打印出某个变量值,我直接 puts 是无效的,我该如何看到这个变量值呢?

@dume2007 开发模式下是可以 puts 变量值的,估计是您环境有问题。

#1 楼 @david_he puts 后在哪里可以看到?网页上没显示,server log 也没有啊?

我习惯用 pry gem 'pry'

require 'pry'

需要断点的地方 binding.pry

当然,如果不是用rails s运行的话,可能就要悲剧了

puts 运行不显示可能是你用其它方式运行的,让 stdout 输出到其它地方了 用 Rails.logger.info('xxx') 来输出吧

#4 楼 @xjz19901211 用这个 Rails.logger.info('xxx'),在 rails s 后面的滚动日志列表里还是看不到任何信息,这跟环境有关系?还是 rails s 后要加什么参数?

看下 config/environments/development.rb 配置了没

貌似 byebug 这个好用!!

#6 楼 @putty 在 development.rb 下需要配置什么参数?我的是:

JazzHands::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Log error messages when you accidentally call methods on nil.
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger
  config.active_support.deprecation = :log

  # Only use best-standards-support built into browsers
  config.action_dispatch.best_standards_support = :builtin

  # Raise exception on mass assignment protection for Active Record models
  config.active_record.mass_assignment_sanitizer = :strict

  # Log the query plan for queries taking more than this (works
  # with SQLite, MySQL, and PostgreSQL)
  config.active_record.auto_explain_threshold_in_seconds = 0.5

  # Do not compress assets
  config.assets.compress = false

  # Expands the lines which load the assets
  config.assets.debug = true
end

可以再开一个命令行窗口,tail -f log/development.log ,这样就能看到 puts 出来的部分了……

@dume2007 你本地运行的 rails 程序是不是用 apache 来跑的还是用 rails s 来启动的?

logger.debug "something ."

#10 楼 @david_he rails s,有时候是用 RubyMine 启动工具

开发模式下,超爱 debugger,呵呵可以卡在那里,然后单步运行你的代码.............

最近有一篇日文的文章 debug - Rails4 今のところ最強なデバッグツール達 - Qiita ,我看不懂日文,但是看裡面的 code 和工具,也可以略知一二,重點是:

  • 專門為 Ruby 2.0 設計的 pry-byebug 和 pry-stack_explorer
  • .pryrc 設置的方式
  • 利用 guard 跑全自動測試

我另外還會使用 better_errors,在瀏覽器裡面打開有 exception 的頁面時,會出現互動式的 debugger

需要 登录 后方可回复, 如果你还没有账号请 注册新账号