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

Remote Debugging ใน Rails ด้วย Byebug และ Pow: คู่มือขั้นตอน

ถ้ายังไม่รู้จัก byebug แนะนำให้ลองดู มัน debugger สำหรับ Ruby 2.x ดีเยี่ยม ตามคำของผู้สร้าง:

Byebug เป็น debugger ที่ใช้ง่าย ฟีเจอร์ครบครัน สำหรับ Ruby 2 ใช้ TracePoint API สำหรับควบคุมการรัน และ Debug Inspector API สำหรับนำทาง call stack จึงไม่พึ่งพา internal core sources พัฒนาเป็น C extension จึงรวดเร็ว และมี full test suite จึงน่าเชื่อถือ

Setup พื้นฐานง่าย แค่ติดตั้ง gem ใช้เมธอด byebug ไหนในโค้ด execution จะหยุดที่จุดนั้นและ drop เข้า debug console สามารถตั้งค่าให้ใช้ pry ได้

เช่น เรียก debugger:


require 'byebug'
def my_method
  a = 1
  byebug
end
my_method()

รันไฟล์ จะ drop เข้า debugger

Remote Debugging ใน Rails ด้วย Byebug และ Pow: คู่มือขั้นตอน เมื่อ debugger trigger จะ drop คุณเข้า interactive shell

ปัญหากับ Pow

ถ้ารันแอปบรรทัดคำสั่งได้ดี แต่ถ้า develop Rails app ด้วย pow serve locally?

Pow เหมือน app servers อื่นๆ รันในพื้นหลัง แม้คุณหยุด execution และรัน debugger ได้ คุณก็ interact กับมันไม่ได้!

โชคดีที่ byebug มี mechanism สำหรับ remote debugging

ถ้าไม่คุ้นเคย remote debugging แนวคิดง่าย: เวลา byebug method ถูกเรียก แทนที่จะ dump ไป interactive shell debugger จะเริ่ม server ของมันเอง คุณต่อไป connect ไป debug server นี้ด้วย command-line client

Remote debugging long อย่างไร?

1. เรียก byebug method ใน controller action


class PagesController < ApplicationController
  def index
    if user_has_never_signed_in? && request.subdomain == "www"
      @hero_bg = ab_test("hero_bg", "control", "variable")
    else
      @hero_bg = "control"
    end
    byebug
  end
end

2. ส่ง request ไป action นั้น connection ค้าง

Remote Debugging ใน Rails ด้วย Byebug และ Pow: คู่มือขั้นตอน Web request ที่ trigger debugger ไม่โหลด

3. สลับไป byebug client แสดง debugger console ณ จุดที่ระบุ

Remote Debugging ใน Rails ด้วย Byebug และ Pow: คู่มือขั้นตอน Byebug remote debugger ในการทำงาน

Setup remote debugging กับ byebug

ยังไม่มี gem ติดตั้งไปเลย:


# Gemfile
gem "byebug", group: "development"

เพิ่ม initializer ใน Rails app เริ่ม byebug server ตอน pow เริ่ม Rails app ตัวเลือกจริงแค่ port number โค้ดด้านล่าง config ผ่าน environment variable:


# config/initializers/byebug.rb
if Rails.env.development?
  Byebug.start_server 'localhost', ENV.fetch("BYEBUG_SERVER_PORT", 1048).to_i
end

เพิ่ม initializer แล้ว restart app ให้โหลด

สุดท้าย รัน byebug client บอกหา server client จะรอ debug trigger

ถ้าใช้ port อื่น ใส่แทนที่นี่:


bundle exec byebug -R localhost:1048

เสร็จ! เริ่ม debug กันเลย