ruby 和 rails 调试方法

本文介绍了Ruby on Rails应用中进行调试的各种方法,包括使用console(如`rails console`)、查看元信息、利用logger进行日志记录、在控制器和视图中调试Active Record查询等。此外,还讲解了如何不打印返回值、获取请求头信息以及配置日志级别等实用技巧。

1. console

命令行输入 irb

1.1. rails console

1
2
3
bundle exec rails console
或者
bundle exec rails dbconsole

1.2. 不打印返回值:在命令后面加上分号和0:“; 0”

1
your-command; 0

2. meta information

  • self # 当前对象,打印出类名
  • class 类型
  • included_modules 所有包含的Module
  • ancestors 祖先(继承自)

  • 类名.constants
  • methods 所有方法
  • instance_methods 实例方法
    • instance_methods(false) 不要包含继承来的方法
  • instance_variables # 打印出当前实例的所有变量

  • 例子
1
2
3
4
5
6
# 查找类是否包含方法
ActiveRecord.methods.each {|m| p m if m.to_s.include?('version')}
ActiveRecord::Base.instance_methods.each {|m| p m if m.to_s.include?('version')}

# 查找数组的方法是否包含,re开头的
[].methods.grep /^re/ # => [:reverse_each, :reverse, ..., :replace, ...]
1
2
# 查找方法是继承自哪里
puts Car.ancestors.inspect
1
2
3
4
Issue.ancestors.each { |a| p a if a.instance_methods.include?(:your-wanna-method) }
String.ancestors.grep(Class)
object.method(:your-method)
object.method(:your-method).source_location
1
some-class.methods    # 打印出对应类的方法

3. logger

1
2
3
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

4. 字符编码

1
2
3
4
5
String#force_encoding("utf-8")    # 强制编码 UTF-8
String#encode("utf-8")            # 当前编码转换为 UTF-8
String#unpack("C*")               # 将字符串转换为 无符号整数数组
String#unpack("C*").map {|b| b.to_s(16)} # 展示为十六进制
Array.pack("C*")                  # 将无符号整数数组 转换为 字符串

5. rails

5.1. 进入rails 执行环境,测试语句

1
rails console

5.2. 查看 route

app.entities_path 打印 route path

5.3. 在 controller 中调试

参考: http://guides.rubyonrails.org/debugging_rails_applications.html

5.4. 调试 Activie Record 使用 explain , 能打印出SQL

1
2
User.where(:id => 1).joins(:posts).explain
User.where(:id => 1).includes(:posts).explain

5.5. 获取 header,request.env

request.env[‘HTTP_ACCEPT_LANGUAGE’] # 获取 Accept-Language

5.6. View 里面打印调试

5.6.1. debug

<%= debug @post %>

5.6.2. inspect

<%= [1, 2, 3, 4, 5].inspect %>

5.7. Logger

The available log levels are: :debug, :info, :warn, :error, and :fatal,
corresponding to the log level numbers from 0 up to 4 respectively.

The default Rails log level is info in production mode and debug in development and test mode.

5.7.1. 如何配置
1
2
config.log_level = :warn # In any environment initializer, or
Rails.logger.level = 0 # at any time

5.8. 写日志

1
2
3
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值