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

Demystifying Ruby Gems: ทำงานยังไงและทำไมจึงสำคัญ

สิ่งทำให้ Rails ดีคือ common programming needs - authorization, site administration, ecommerce ใครสักคนเก่งกว่าคุณคิดโค้ดแก้ปัญหา package ไว้ใน gem

เพิ่ม gems ใน Gemfile ใช้ประโยชน์เต็มที่โดยไม่เข้าใจจริงๆ ว่าทำงานยังไง แต่น่าสนใจไหมว่ามัน wired up ยังไง?

ดู Ryan Bates' CanCan authorization gem ตอบคำถาม (apply ได้กับ gem ไหนก็ตาม):

  1. Code ของ CanCan เก็บอยู่ไหน?

  2. can? method defined ที่ไหน?

  3. Rails load code ของ CanCan เมื่อ/ที่ไหน/อย่างไร?

ก่อนอื่น CanCan ใน Gemfile bundle install:

# Gemfile gem "cancan", "~> 1.6.10"``` $ bundle install 

Bundler ดู gem location ง่าย bundle show:

$ bundle show cancan /Users/jasonswett/.rvm/gems/ruby-2.0.0-p0/gems/cancan-1.6.10 

ตอบคำถาม #1 ตอนนี้ can? defined ที่ไหน?

$ cd /Users/jasonswett/.rvm/gems/ruby-2.0.0-p0/gems/cancan-1.6.10 $ grep -r 'def can?' * lib/cancan/ability.rb: def can?(action, subject, *extra_args) lib/cancan/controller_additions.rb: def can?(*args) 

มี 2 can? functions ตัวที่สนใจอยู่ใน lib/cancan/ability.rb

# lib/cancan/ability.rb def can?(action, subject, *extra_args) match = relevant_rules_for_match(action, subject).detect do |rule| rule.matches_conditions?(action, subject, extra_args) end match ? match.base_behavior : false end 

เห็นว่าอยู่ใน ability.rb

ตอนนี้รู้ gem code เก็บที่ไหน และเข้าไปดูได้ Rails รู้ gem ยังไง และเมื่อไหร่ load gem code?

Covered ใน Rails initialization documentation ส่วนเกี่ยวข้อง:

In a standard Rails application, there's a Gemfile which declares all dependencies of the application. config/boot.rb sets ENV['BUNDLE_GEMFILE'] to the location of this file. If the Gemfile exists, bundler/setup is then required.

เกิดขึ้น early ใน initialization process: step ที่ 2 ถูกต้องเพราะถ้า project depend on gem ไม่รู้จะ reference ที่ไหน โหลดเร็วที่สุด code ใช้ได้ทุกที่