Skip to content

Từ C# và ASP.NET Core sang Ruby

Bộ ghi: adapter C# đa ngôn ngữ (dotnet + driver được tạo tự động). Có thể ghi phương thức static. analyze tìm minimal API ASP.NET Core (app.MapGet) và controller định tuyến bằng attribute.

Từ ASP.NET sang Rails

ASP.NET Core Rails
app.MapGet("/x/{id}", ...) / [HttpGet("{id}")] route + action của controller
Results.Ok(x) / return Ok(x) render json: x
Results.NotFound() / NotFound() head :not_found (khớp phần thân đã ghi)
CreatedAtAction(...) render json: x, status: :created, location: ...
Trang / view Razor (.cshtml) view ERB (frontend.md)
Entity Framework DbContext, LINQ ActiveRecord; Where/Select/OrderBy/Include -> where/select/order/includes
Data annotation ([Required], [StringLength]) validates
Identity trình tạo xác thực Rails (hash mật khẩu khác nhau: lên kế hoạch hash lại)
IOptions<T> / appsettings.json config/*.yml + credentials
BackgroundService / Hangfire Active Job + Solid Queue
Đầu ra camelCase của System.Text.Json giữ các khóa camelCase

Cấu trúc

  • Lỗi: ArgumentException/ArgumentNullException/ArgumentOutOfRangeException -> ArgumentError; InvalidOperationException -> RuntimeError; KeyNotFoundException -> KeyError; FormatException (int.Parse) -> ArgumentError.
  • Nullable int? -> nil; ?? -> .nil? ? d : x; ?. -> &..
  • LINQ trên collection -> Enumerable (Aggregate -> reduce, GroupBy -> group_by, ToDictionary -> to_h/index_by, First() phát sinh lỗi khi rỗng -> fetch(0) / raise).
  • Record / property -> Data.define / attr_reader.
  • decimal -> BigDecimal, không bao giờ dùng Float.

Điểm dễ mắc lỗi

  • Làm tròn: Math.Round(2.5) == 2 (mặc định làm tròn về số chẵn!) -> round(half: :even); MidpointRounding.AwayFromZero -> round. ToString("F2") và định dạng nội suy chuỗi dùng culture hiện tại: dấu thập phân có thể là ,.
  • Tràn số nguyên quay vòng trừ khi dùng checked; / làm tròn về 0; % lấy dấu số bị chia.
  • string.Length đếm đơn vị UTF-16. string.Split(' ') giữ phần tử rỗng (split(" ", -1) với regex trong Ruby).
  • Thứ tự duyệt Dictionary<K,V> trên thực tế là thứ tự chèn nhưng không được đảm bảo: sắp xếp khi trường hợp đã ghi cho thấy một thứ tự.
  • DateTime không có kind là giờ địa phương; tuần tự hóa theo cách bản ghi thể hiện.
Sửa trang này trên GitHub →