Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Rails 7 Ra Mắt: Tính Năng Chính & Cải Tiến Sắp Tới

Rails 7 sắp ra mắt. Chúng ta không có confirmed release date, nhưng dự kiến available trước Giáng sinh, nên không còn lâu nữa. Latest version tại thời điểm bài viết là 7.0.0.rc1, release candidate đầu tiên. Basecamp, HEY, Github, và Shopify đều đã chạy Rails 7 alpha trong production, nên ta có thể expect даже release candidate cũng khá stable.

Trong bài viết này, chúng ta sẽ xem một số new features và changes mà Rails 7 mang lại.

Không Cần Node và Webpack

Đúng như bạn đọc! JavaScript trong Rails 7 sẽ không còn require NodeJS hoặc Webpack. Và bạn vẫn có thể dùng npm packages.

Transpile ES6 với Babel và bundle với Webpack đòi hỏi rất nhiều setup. Mặc dù Rails support khá tốt với gem Webpacker, điều này mang theo nhiều baggage, khó hiểu và thay đổi, đặc biệt khi maintain upgradability.

Bây giờ, default cho new apps tạo với rails new là dùng import maps qua gem importmaps-rails. Thay vì viết package.json và install dependencies với npm hoặc yarn, bạn dùng ./bin/importmap CLI để pin (hoặc unpin hoặc update) dependencies.

Ví dụ, để install date-fns:

./bin/importmap pin date-fns

Điều này sẽ thêm line trong config/importmap.rb như:

pin "date-fns", to: "https://ga.jspm.io/npm:date-fns@2.28.0/esm/index.js"

Trong JavaScript code, bạn tiếp tục dùng mọi thứ như bình thường:

import { format } from "date-fns"
format(new Date(), "yyyy-MM-dd")

Một điều cần nhớ với setup này là không có transpiling giữa những gì bạn viết và browser nhận. Phần lớn, điều này OK vì all browsers that matter giờ support ES6 out of the box.

Nhưng điều này cũng nghĩa là bạn không thể dùng TypeScript hoặc JSX vì chúng require transpilation to JS trước khi dùng.

Vậy, nếu bạn muốn dùng React với JSX, bạn vẫn phải fall back to different setup (dùng webpack/rollup/esbuild).

Rails 7 có thể làm điều đó cho bạn. Chỉ cần one command với chosen strategy:

rails new myapp --javascript=esbuild
# hoặc
rails new myapp --javascript=rollup
# hoặc
rails new myapp --javascript=webpack

Turbolinks và UJS Được Thay Thế Bởi Turbo Và Stimulus

Applications generated với Rails 7 sẽ nhận Turbo và Stimulus (từ Hotwire) by default, thay vì Turbolinks và UJS. Hotwire là approach mới deliver fast updates đến DOM bằng cách gửi HTML over the wire.

Encryption At Database Layer (Mã Hóa Ở Lớp Database)

Rails 7 cho phép mark certain database fields as encrypted dùng method encrypts trên ActiveRecord::Base. Nghĩa là sau initial setup, bạn có thể viết code như:

class User < ApplicationRecord
  encrypts :email
  encrypts :ssn, deterministic: true
end

Bạn tiếp tục dùng encrypted attributes như bất kỳ attribute nào khác. Rails 7 sẽ encrypt và decrypt tự động giữa database và application.

Nhưng đi kèm slight quirk: bạn không thể query database by field đó trừ khi pass option deterministic: true cho method encrypts. Deterministic mode kém secure hơn default non-deterministic mode, nên chỉ dùng cho attributes bạn absolutely cần query.

Asynchronous Querying (Truy Vấn Bất Đồng Bộ)

Giờ có method load_async bạn có thể dùng khi query data để fetch results in background. Đặc biệt quan trọng khi cần load several un-related queries từ controller action. Bạn có thể chạy:

def index
  @users = User.all.load_async
  @posts = Post.all.load_async
  # Cả hai queries fired cùng lúc in background
end

Điều này sẽ fire both queries in background cùng lúc. Vậy, nếu mỗi query mất 200ms, total time spent fetching data ~200ms thay vì 400ms nếu fetch serially.

Zeitwerk Mode Cho Rails 7

Đây là breaking change cho older applications vẫn chạy classic loader. Tất cả Rails 7 applications phải dùng Zeitwerk mode, nhưng switch khá dễ. Check out full Zeitwerk upgrade guide.

Các Cập Nhật Rails 7 Khác

Retry Jobs Unlimited Times

ActiveJob giờ cho phép pass :unlimited làm parameter attempts trên retry_on. Rails sẽ tiếp tục attempt job without any maximum number of attempts.

class MyJob < ApplicationJob
  retry_on StandardError, attempts: :unlimited
  def perform
    # ...
  end
end

Named Variants

Bây giờ bạn có thể name variants trên ActiveStorage thay vì specify size trên mọi access.

# config/initializers/active_storage.rb
Rails.application.config.active_storage.variants = {
  thumbnail: { resize_to_limit: [100, 100] },
  medium: { resize_to_limit: [300, 300] }
}

# Usage
user.avatar.variant(:thumbnail)
user.avatar.variant(:medium)

Hash To HTML Attributes

Có method mới tag.attributes cho views translate hash thành HTML attributes:

tag.attributes(class: "btn btn-primary", data: { controller: "tooltip" })
# produces: class="btn btn-primary" data-controller="tooltip"

Ruby debug

New default cho debugging đã thay đổi từ byebug sang gem debug.

Thay vì gọi byebug, bạn giờ cần gọi debugger trong code để enter debugging session.

Assert Single Record Với sole

Khi query records, bạn giờ có thể gọi sole hoặc find_sole_by (thay vì first hoặc find_by) khi muốn assert query should only match single record.

User.where(email: 'john@example.com').sole
# Raises ActiveRecord::RecordNotFound nếu 0 records
# Raises ActiveRecord::SoleRecordExceeded nếu > 1 record

Check Presence/Absence Của Association

Giờ có thể dùng where.associated(:association) để check nếu association present trên record thay vì join và check existence của id.

User.where.associated(:posts)
User.where.missing(:posts)

Stream Generated Files Từ Controller Actions

Bây giờ bạn có thể dùng send_stream bên trong controller action để start streaming file đang được generated on the fly.

def export
  send_stream(filename: "export-#{Date.today}.csv") do |stream|
    stream.write "header1,header2\n"
    User.find_each do |user|
      stream.write "#{user.name},#{user.email}\n"
    end
  end
end

Điều này cung cấp immediate (partial) response cho user để họ biết đang có chuyện gì xảy ra và có added benefit nếu deploy trên Heroku.

Vì file sẽ start streaming ngay lập tức, Heroku sẽ không terminate connection. Nghĩa là bạn không cần resort to background jobs để generate one-off files mất hơn 30 giây.

Upgrade Lên Rails 7

Giống previous versions của Rails, upgrading đơn giản. Mặc dù chưa có official upgrade guide, steps sẽ giữ nguyên:

  1. Thay đổi Rails version number trong Gemfile (7.0.0.rc1 tại publication date) và chạy bundle update.
  2. Chạy bundle exec rails app:update. Follow interactive CLI và add/replace/modify files as required.
  3. Chạy tests và verify mọi thứ works as expected.

Tóm Lại

Bạn có thể xem full list của bug fixes, features, và changes trong Rails 7 release notes. Chúng không comprehensive lúc này, nhưng có thể expect updated soon.

Nếu bạn vẫn chạy Rails 6 hoặc thấp hơn, hãy lưu ý rằng với final release của Rails 7, Rails 6.1 sẽ enter "security issues only" mode và không còn nhận bug fixes. Điều này cũng mark EOL cho Rails 5.2, vì nó không còn nhận fixes nào.

Have fun coding!

P.S. Nếu bạn muốn đọc các bài Ruby Magic ngay khi xuất bản, hãy đăng ký newsletter Ruby Magic để không bỏ lỡ bất kỳ bài viết nào!

Pulkit Goyal

Tác giả khách Pulkit là senior full-stack engineer và consultant. Trong free time, anh viết về experiences trên blog cá nhân.

Tất cả bài viết của Pulkit Goyal