Skip to content

從 Java 與 Spring Boot 到 Ruby

Recorder:polyglot Java adapter(javac + 產生的 driver)。public static 方法,以及無狀態類別(沒有實例欄位、建構子沒有參數,典型的 @Service/@Component 輔助類別)的 public 方法都可以錄製;錄製時會移除 Spring annotation,而 target/dependency 中的相依 jar(mvn dependency:copy-dependencies)會加入 classpath。有注入相依的類別則透過 app record/replay 檢查。

從 Spring 到 Rails

Spring Rails
@RestController + @GetMapping("/x/{id}") get "x/:id" + controller action、render json:
@Controller + Thymeleaf 模板 controller action + ERB view(frontend.md)
@PathVariable、@RequestParam、@RequestBody params[:id]、params[:q]、params.expect(...) / params.require().permit()
ResponseEntity.status(201).body(x) render json: x, status: :created
@ResponseStatus(NOT_FOUND) 例外 / @ControllerAdvice 在 ApplicationController 中使用 rescue_from,回傳相同的 body 與狀態碼
@Service app/services 中的 service object
@Entity + JpaRepository ActiveRecord model;衍生查詢(findByEmail)-> find_by(email:);@Query -> scope / where
@Transactional ActiveRecord::Base.transaction do ... end
Bean Validation(@NotBlank、@Size、@Email) validates :x, presence:, length:, format:
Spring Security Rails authentication generator + before_action;保留 bcrypt 雜湊
application.properties / @Value config/*.yml、credentials、ENV.fetch
@Scheduled Solid Queue 週期性 job(config/recurring.yml)
Jackson 欄位名稱(camelCase) 在 render json: 中保留 camelCase 鍵(使用帶鍵名轉換的 as_json 或明確的 hash)

語法結構

  • 錯誤:IllegalArgumentException -> ArgumentError;IllegalStateException -> RuntimeError;NoSuchElementException(Optional.get、orElseThrow)-> KeyError 或應用程式自己的錯誤;NullPointerException -> NoMethodError(只有在錄製案例顯示時才移植)。
  • Optional -> nil 處理;orElse(d) -> || d(當 false 是合法值時改用 .nil? ? d : x)。
  • Stream:stream().filter().map().collect(toList()) -> select.map;Collectors.groupingBy -> group_by;joining(", ") -> join(", ");sorted(comparing(X::y)) -> sort_by(&:y)。
  • Record / POJO -> Data.define / Struct / 帶有 attr_reader 的一般類別。
  • 多載 -> 選用參數或關鍵字參數;請檢查每個多載版本的錄製案例。

陷阱

  • 整數溢位:int 在 2^31 時繞回(Integer.MAX_VALUE + 1 是負數);long 則在 2^63。Ruby 的整數永遠不會溢位。只有在錄製案例觸及的地方,才移植繞回行為(((x + 2**31) % 2**32) - 2**31)。
  • 整數除法向零截斷(-7 / 2 == -3);Ruby 是向下取整(-4)。請使用 (a.fdiv(b)).truncate 或 a.quo(b).truncate。% 的正負號跟隨被除數:請使用 remainder。
  • 四捨五入:Math.round(-2.5) == -2(遇到 .5 時往 +infinity 進位);使用 RoundingMode.HALF_EVEN 的 BigDecimal -> round(half: :even);HALF_UP -> round(half: :up)。
  • 以 BigDecimal 表示的金額 -> Ruby 的 BigDecimal(require "bigdecimal");金額絕不要用 Float。
  • 字串:length() 和 JS 一樣以 UTF-16 單元計算。String.format("%.2f") -> format("%.2f")。equals 與 ==:Ruby 的 == 比較的是值。
  • 正規表示式:除非使用 UNICODE_CHARACTER_CLASS,Java 的 \w 只比對 ASCII:和 Ruby 相同。matches() 會錨定整個字串(\A...\z);find() 則不會。
  • HashMap 的迭代順序未定義;LinkedHashMap 和 Ruby hash 一樣保留插入順序;TreeMap 是已排序的(sort.to_h)。在原版使用 HashMap 且錄製案例顯示出某種順序的地方,輸出前請先排序。
在 GitHub 上編輯此頁 →