0
0

Sorbet, tapiocaを導入して、Ruby On Railsで型チェックを行う。

Posted at

環境

  • WSL2
  • Rails 7.1.3
  • ruby 3.2.2
  • sorbet (0.5.11255)
  • sorbet-runtime (0.5.11255)
  • tapioca (0.12.0)

目的

Sorbet, tapiocaを導入して、Ruby On Railsで型チェックをできるようにする。

注意

tapiocaを使ってRBIファイルを生成する。sorbet-railsはサポートが終了するので使用しない。

sorbet-railsレポジトリ

This repository is no longer maintained and will be sunset. The Sorbet community has endorsed the Tapioca gem for generating RBI's, including those for Rails. Please consider migrating over!

手順

テストページを作ってrailsを起動する

railsプロジェクトを作成し、アプリを起動する。デフォルトページ(http://localhost:3000/)にアクセスして、無事にアプリが起動していることを確認する。

> rails my_sorbet
> cd my_sorbet
> rails server

テストページを作ってみる

下記のようにファイルを設定して、「rails server」でアプリを起動して、http://localhost:3000/tests にアクセスすれば、テストページが表示されるはず。

routes.rb
get "tests", to: "tests#home", as: "tests"
controller/tests_controller.rb
class TestsController < ApplicationController
    def home()
        #特に何も書かなくていい
    end
end
views/tests/home.html.erb
<!DOCTYPE html>
<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h4>ここはテストページです。。。<h4>
</body>
</html>

Sorbet, tapiocaをインストール

下記のコマンドでSorbet, tapiocaをインストールする。

Sorbetの初期の設定はエラーを無視しているので、下記のようにエラーはないはず。

#Gemfile
gem 'sorbet', :group => :development
gem 'sorbet-runtime'
gem 'tapioca', require: false, :group => [:development, :test]
> bundle exec srb
[help output]

> bundle exec srb typecheck -e 'puts "Hello, world!"'
No errors! Great job.

> bundle exec ruby -e 'puts(require "sorbet-runtime")'
true
> bundle exec tapioca init
> bundle exec srb tc
No errors! Great job.

静的型チェックをして、エラーを検出してみる

型のエラーをつくり、正確に検出してくれるかどうかを確かめる。

下記は、Symbol型が入るべきところにString型が入っているので、エラーが検出される。

controller/tests_controller.rb
# typed: true

class TestsController < ApplicationController
  extend T::Sig

  def home
    log_env({timeout_len: 7777}, :timeout_len) # 正確な型となっている
    log_env({timeout_len: 7777}, 'timeout_len') # 型が違反している
  end

  sig {params(env: T::Hash[Symbol, Integer], key: Symbol).void}
  def log_env(env, key)
    puts "LOG: #{key} => #{env[key]}"
  end
end
> bundle exec srb tc
...Expected Symbol but found String("timeout_len")...
...log_env({timeout_len: 2000}, 'timeout_len')
...

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0