DEV Community

hiko1129
hiko1129

Posted on • Originally published at note.hiko1129.com on

[Ruby][Sorbet] What to do when you can't write types in Ruby files (when meta-programming)

Translate ja to en

メタプログラミングしている(define_methodとか使っている)ときは.rb上では型を付与できない。

ex: hoge.rb

class Hoge
  define_method :hoge do
    puts 'hogehoge'
  end
end

Hoge.new.hoge
Enter fullscreen mode Exit fullscreen mode

この場合には、RBIファイルに型を書く対応をする(or 型生成するコードを書く

ex: hoge.rbi

# typed: strict

class Hoge
  sig { void }
  def hoge; end
end
Enter fullscreen mode Exit fullscreen mode

bin/tapioca gemsなどを実行して型が足りないときも同様にsorbet/rbi/shims以下に型を書く(必要な部分のみで問題ない。)

# typed: strict

class ActiveRecord::Base
  sig { void }
  def hoge; end # <- こんな感じで必要な差分のみ追記で問題ない
end
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️