Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

เชี่ยวชาญ Data Inspection ใน Ruby: เทคนิค Debugging สำหรับ Rails Developers

Exceptions ส่วนใหญ่เกิดจาก unexpected data ถูกส่งให้ methods ที่ทำงานปกติ ดังนั้น trace ชิ้นข้อมูลผ่าน application เพื่อหาสาเหตุ error จึงมีประโยชน์ บทความนี้เราจะครอบคลุมการ inspect ข้อมูลใน Ruby และ Rails applications

puts, #inspect และ p

puts method ของ Ruby ใช้พิมพ์ message ไป console

unknown = "This is a string"
puts unknown

เมื่อรัน script ข้างต้น value จะพิมพ์ออกมาเพื่อให้เห็นว่ามีอะไรภายใน

$ ruby puts.rb
This is a string

อย่างไรก็ตาม หากตัวแปร unknown เก็บ empty string, nil value หรือ empty hash puts จะพิมพ์ empty line ด้วยนั้น คุณจะไม่เห็น exact value และแยก empty hashes และ strings ไม่ได้

$ ruby puts_empty_string.rb

โชคดีที่มี instance method ชื่อ inspect implemented บนทุก object ที่คุณจะพบ มันคืน string representation ของ object

unknown = ""
puts unknown.inspect

สำหรับ empty string จะคืนคู่ quotes สำหรับ array จะคืนคู่ brackets

$ ruby inspect_empty_string.rb
""
$ ruby inspect_empty_array.rb
[]

เนื่องจาก combination ของ puts และ inspect ใช้บ่อยมาก มี shortcut ทำทั้งสองในครั้งเดียว ชื่อ p ทำอย่างเดียวกันแต่พิมพ์เร็วกว่า

unknown = ""
p unknown # equivalent to `puts unknown.inspect`

Inspect ข้อมูลใน Rails Views

แม้มี p shortcut ยังคงมีประโยชน์รู้จัก inspect method เมื่อต้องการ string representation ของ object โดยไม่ พิมพ์ไป console

ใน Rails view ตัวอย่าง บางครั้งพิมพ์ value ไป resulting HTML page มีประโยชน์กว่าต้องหาใน log

<%= params.inspect %>

เมื่อ inspect complex data structures บางครั้งยากหาข้อมูลที่ต้องการ เพราะ inspected value พิมพ์บน single line

Rails มี debug helper แก้ปัญหานี้ แทนที่จะแค่ inspect value มันแปลง object เป็น human readable YAML representation ใส่ใน <pre> tags เพื่อ preserve formatting

<%= debug params %>

debug helper ใช้ to_yaml method ภายใต้ hood ได้ YAML representation ก่อน wrap ใน <pre> block เพื่อแปลง object เป็น YAML representation โดยไม่ wrap ใน <pre> tag ใช้ #to_yaml บน object ใดๆ ได้โดยตรง

irb(main):004:0* puts Product.first.to_yaml
--- !ruby/object:Product
concise_attributes:
- !ruby/object:ActiveRecord::Attribute::FromDatabase
  name: id
  value_before_type_cast: 4
- !ruby/object:ActiveRecord::Attribute::FromDatabase
  name: title
  value_before_type_cast: Title
....

เหมือนคาด มี shortcut พิมพ์ YAML representation ของ object ด้วย ตัวอย่างข้างต้นเรียกได้ในครั้งเดียวด้วย y Product.first

irb(main):004:0* y Product.first # equivalent to `puts Product.first.to_yaml`
--- !ruby/object:Product
...

"puts"-debugging

มีวิธี inspect data ใน applications อีกมาก เช่น Pry library และ debugger ของ Ruby เอง แม้แน่นอนว่า check out methods อื่นๆ ของการ inspect data ดี แต่เขียน log ไป console หรือแสดงชิ้นข้อมูลใน view มักเป็น quickest way หาว่าเกิดอะไรขึ้น

เรายินดีรู้ความคิดเห็นว่าชอบบทความนี้หรือไม่ มีคำถามอะไร และอยากอ่านเรื่องไหนต่อไป อย่าลืมบอกเราที่ @AppSignal