I'm a Ruby on Rails / jQuery web developer. Follow me at @sikachu

Object#try ใน Rails 2.3

August 2nd, 2009 Posted in My Project, Programming, Ruby, Ruby on Rails

เคยเจอปัญหาบ้างไหมครับ กับการที่บางครั้ง object ที่เราเรียก method ไปเนี่ย มันกลายเป็น nil ขึ้นมา ทำให้เกิด exception ขึ้นมา

>> @user.username
NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.username
	from (irb):1

ซึ่งตรงนี้ เพื่อที่จะหลบ exception ในบางครั้งทำให้ Developer ต้องทำการเช็คก่อนว่า object นั้นเป็น nil หรือไม่ เช่น

>> (@user ? @user.usename : "Guest")
=> "Guest"

ซึ่งตรงนี้ทำให้โค้ดนั้นดูุวุ่นวายมากขึ้น และทำให้โค้ดนั้นดูไม่ค่อยเหมือน Ruby สักเท่าไร (ซึ่งผมก็เห็นด้วยว่า <cond> ? <if-true> : <if-false> นั้น มันดูแปลกๆ) จึงทำให้มีคนคิด Object#try ออกมา แล้วทางทีมผู้พัฒนา Ruby on Rails ถึงเอาเข้าไปเพิ่มใน Rails 2.3 ระหว่างที่ Ruby กำลังรอเพิ่ม method นี้เข้าไปอยู่

เพราะฉะนั้นหลังจากการเพิ่ม method นี้ ทำให้เราสามารถที่จะทำอย่างนี้ได้

>> @user.try(:username)
=> nil
>> @user.try(:username) || "Guest"
=> "Guest"

แล้วยังทำให้ เราสามารถทำ method chaining ได้ด้วย (เพราะทุกอย่างมี #try)

>> @user.try(:username).try(:capitalize)
=> nil
>> # Fetch @user from record
?> @user = User.first
=> #<User id: 1, email: "test@test.com", usename: "test", persistence_token: "95908c3801d55ce389af90f0909192cbda4e37c632afd6b50c2...", created_at: "2009-06-30 05:44:43", updated_at: "2009-07-16 08:56:46", crypted_password: "f37c87cb2d731c0c0710ae9c2b9721d352f6336e38e988bb907...", password_salt: "UIENYMKzDjJYgy2E89Qn", status: nil>
>> @user.try(:username).try(:capitalize)
=> "Test"

ลองปรับไปใช้กับ Application กันนะครับ คิดว่าส่วนนี้น่าจะช่วยให้ debug กันง่ายขึ้นเยอะเลย ;)

Sorry, comments for this entry are closed at this time.