Rails partials đã tồn tại nhiều năm, nhưng chúng có thể clunky vì chỉ là ERB snippets không có backing object structure.
Gần đây, libraries như ViewComponent và Phlex đã cố gắng improve view layer bằng cách thêm semantic structure hơn vào templates. אלו great libraries và tôi personally reach for ViewComponent trên hầu như mọi project tôi làm. That said, tôi vẫn cảm thấy humble Rails partial vẫn works great cho nhiều use cases.
Rails team luôn cố gắng improve offering, nên hãy nhìn vào feature mới introduced trong Rails 7.1: strict locals!
Rails Partials và Local Variables
Chúng ta có thể pass arbitrary local variables vào Rails partials và chúng magically available để dùng.
Điều này không ideal, vì tricky để ascertain partial chấp nhận variables nào nếu có large block of markup. Cũng vì variables dynamically created, missing variable không return nil mà cause error.
Giả sử icon optional trong partial trên:
Chúng ta render nó như:
Điều đó raise ActionView::Template::Error, với message undefined local variable or method 'icon' for #<ActionView::Base:0x00000000023078>.
Thực tế icon optional không obvious cho reader. Cho đến Rails 7.1, solution là inspect local_assigns hash chứa tất cả injected local variables.
Điều này fix error trên vì icon variable giờ luôn được set.
Rails 7.1 cố gắng address shortcomings của local variables trong partials với concept strict locals.
Strict Locals trong Rails là gì?
Bắt đầu Rails 7.1, chúng ta có thể viết magic comment ở top của partials, định nghĩa local variables nó chấp nhận và default values cho chúng.
Rails parse comment này và set defined variables trong partial. Bây giờ plainly obvious cho reader partial chấp nhận variables nào và default values.
Partial vẫn render như trên. Thử exclude title variable từ call site và xem gì xảy ra:
Bạn nhận ArgumentError với message missing local: :title: descriptive error message hơn trước!
Khi nào dùng Strict Locals
Strict locals có thể fiddly, nên không phải lúc nào cũng good idea dùng, especially trong legacy apps.
Hãy lấy use case perfect cho strict locals. Giả sử partial show user's details trong card, nhưng chỉ admins thấy khi họ last signed in:
Partial này lấy several variables và có optional variable, making it perfect case cho strict locals. Thêm magic comment sau vào file làm cho nó significantly easier để skim:
Trong case của model's associated partial (ví dụ posts/_post.html.erb), fairly obvious partial chấp nhận single post variable. Tôi không nghĩ strict locals necessarily good idea cho cases này.
Strict Locals Gotchas
Có vài gotchas cần wary, đó là tại sao tôi không recommend dùng strict locals across the board.
Implicitly Rendering a Collection
Khi implicitly rendering collection:
Rails inject _post partial với two variables ngoài post variable. Trước Rails 7.1.2, cần manually define để prevent error:
Problem này fixed trong Rails 7.1.2 và variables này giờ optional (nhưng good to know chúng exist nếu cần)!
Broadcasting Over ActionCable
Khi broadcasting partial over ActionCable từ ActiveRecord callback:
Bạn cần specify request_id local variable defaulting to nil, vì này used under the hood bởi Rails.
Không làm vậy result in error khi callback triggered.
Và đó là whistle-stop tour của chúng ta!
Một vài điều cần nhớ
Thêm strict locals vào existing partials là proposition all-or-nothing cho given file. Chúng ta không thể incrementally add variables vào magic comment as we find them. Như shown trong gotchas, tricky để ascertain all variables cần declare trong magic comment.
Given how much easier to reason about code với strict locals, tôi nghĩ chúng worth using extensively trong new apps (và progressively adding retroactively vào legacy apps).
Quan trọng ensure test suite trong legacy apps cover partials bạn add strict locals. Một omission sẽ cause exception, nên bạn cần sure bạn tested all use cases trước khi deploy changes.
Mặc dù tôi không huge fan của approach magic comment (vì tôi believe comments không bao giờ nên có functionality), tôi nghĩ strict locals là great addition cho Rails. Luôn fiddly assign locals cho partial và những cái này làm cho easier. Just beware of the gotchas!
Kết thúc
Trong bài này, chúng ta quick look tại strict locals trong Rails 7.1. Chúng ta saw how partials và local variables work trước khi explore khi nào dùng strict locals và some gotchas.
Happy coding!
P.S. Nếu bạn muốn đọc Ruby Magic posts ngay khi off the press, subscribe Ruby Magic newsletter và never miss a single post!
Ayush Newatia
Tác giả khách Ayush là freelance Ruby và Rails developer. Anh là author của The Rails and Hotwire Codex và part của Bridgetown core team. Anh cũng chạy privacy focused mailing list app gọi là Scattergun.
Tất cả bài viết của Ayush Newatia