🏵 การใช้งาน Rails::Engine เบื้องต้น
อ้างอิง Getting Started with Engines
ในบทความนี้ เป็นวิธีใช้ engines และ ฟังก์ชันเพิ่มเติม ให้กับ แอปพลิเคชันโฮสต์ ผ่านอินเทอร์เฟซที่สะอาดตา ยิ่งขึ้น ไม่มากก็น้อย
engines คือ อะไร
ในที่นี้ เราจะหมายถึง Rails::Engine โดยปกติ เว็ป หรือ host applications ของ Rails ก็จะ สืบทอด หรือ inheriting มาจาก Rails::Application และ Rails::Application ก็ สืบทอด มาจาก Rails::Engine
มาเริ่มวิธีใช้กัน
เริ่มเเรกสร้าง project มาเลยครับ
$ rails new unicorn
ต่อมา มาทำการสร้าง engine กันครับ โดย ใช้ command
$ rails plugin new blorgh --mountable
โดยจะมี options--mountable
และ--full
โดย --mountable
จะต่างกันที่
- สร้าง files (
application.js
andapplication.css
) ให้ - A namespaced
ApplicationController
stub - A namespaced
ApplicationHelper
stub - A layout view template for the engine
- Namespace isolation to
config/routes.rb
:
เมื่อสร้างเสร็จ ใน Gemfile ของเราก็ทำการเพิ่ม gem มาให้ด้วย
ต่อมาเรามาลองสร้าง Model Article ใน blorgh ที่เป็น engine ด้วยคำต่อไปนี้นะครับ โดยต้องทำการเข้าไปใน engine เราก่อน
$ cd blorgh
$ rails generate scaffold article title:string text:text
เมื่อสร้างเสร็จ ก็เข้าไป กำหนด root path กันหน่อยใน unicorn/blorgh/config/routes.rb
root to: "articles#index"
เเค่นี้ตัว engine เราก็ใช้งานได้เเล้วครับ
นั้นมาต่อกันเลยในเมื่อ engine เราเส็จเเล้ว ลองนำเอามาใช้ใน project unicorn ของเรากันดู โดยเข้าไป add route ใน unicorn/config/routes.rb ด้วย
mount Blorgh::Engine, at: "/blog"
เสร็จเเล้วเราก็จะมา install migarte กัน โดยใช้ command ดังต่อไปนี้ ที่ unicorn path
$ rails railties:install:migrations
ถ้าเรามีหลาย engine หรือ lig ก็จะทำทั้งหมดในคราวเดียว
จากนั้นก็ สั้ง migrate ได้เลยครับ
$ rails db:migrate
จากนั้น ก็ ลองมาดูผลลัพธ์ กัน สั่ง run ตัว unicorn ขึ้นมา
$ rails s
เเล้วเข้าไป path ที่เรา mount Blorgh::Engine มาคือ http://localhost:3000/blog
เย้!! ใช้งานได้ เท่านี้ ถ้า project ใหน อยากใช้ articles ก็ mount Blorgh::Engine ได้เลย
มีเพิ่มเติ่มอีกนิต ถ้าหา เราต้องการดัดแปลง Model ใน engine ก็มีด้วยกัน 2 วิธี ซึ่งอยู่ในเรื่อง Improving engine functionality
ลองมาทำกันดู กันสักนิตเริ่มที่ไป config engine ให้ overide ใน unicorn/blorgh/lib/blorgh/engine.rb path
ต่อมาเราก็ไปสร้าง override กัน ใน unicorn/app/overrides/models/blorgh/article_override.rb โดยเพิ่ม function
time_since_created ขึ้นมา
เรามาลองทดสอบใช้ function time_since_created ที่เราสร้างกัน ใช้
$ rails c
จากนั้นของมาเรียกใช้ function ดู
Blorgh::Article.first.time_since_created
เย้!! ใช้ได้ครับ
เเล้วมีอีกวิธี คือการใช้ ActiveSupport::Concern ซึ้งจะใช้งานได้เหมือนกันและใช้ในงานได้มากกว่า