Archive for กุมภาพันธ์ 2009
NameError เมื่อเพิ่ม profile route ใน RailsSpace
เมื่อไรที่เจอ error เกี่ยวกับ route ว่า
NameError
undefined local variable or method `show' for main:Object
...
config/routes.rb:38 config/routes.rb:1
และถ้าลองรีเฟรชเบราเซอร์อีกทีหลัง error แรกก็จะเจอ error ที่สอง:
Routing Error
No route matches "/profile/foobar" with {:method => :get}
ให้ลองเช็ค syntax ของ route ของคุณใน routes.rb ดูดีๆ ว่าคุณได้ escape string ชื่อ action ด้วย ” หรือ “” แล้วหรือเปล่า…error นี้จะเกิดถ้าคุณใช้โค้ดผิดๆแบบนี้
map.connect ‘profile/:screen_name’, :controller => ‘profile’, :action => show
block_given? ใน Ruby
ได้ลองเปิดซอร์สโค้ด Rack ดูเล่นๆ เห็นมีใช้ OptionParser อยู่…ด้วยความที่เป็นมือใหม่อยากรู้ว่ามันทำงานยังไงเลยลอง google ดู API ซึ่งมี initializer ที่รับ argument แค่ 3 ตัวเท่านั้น แต่ไม่เห็นมีรับ block เลย หลังอ่านโค้ดดูเลยเห็นว่าทริกมันอยู่ที่บรรทัดสุดท้าย:
# File optparse.rb, line 777
def initialize(banner = nil, width = 32, indent = ' ' * 4)
...
yield self if block_given?
end
block_given? เป็น method ของ Kernel ที่เอาไว้เช็คว่า yield มี block อะไรต้อง execute หรือเปล่า เจ๋งจริง