LoginSignup
8
3

More than 5 years have passed since last update.

evalとsendを使ってみたら、コードがスッキリした話

Posted at

仕事している時にevalとsendを教えてもらい、使ってみたらおお!って感動したので、書いてみようと思います。

使うまでに至った経緯

evalとかsendはメタプログラミングの一種のようです。
似たような処理をする時に共通化できるだけ共通化しようと思い、使いました。

evalは文字列をRubyのコードとしてみてくれます。
今回やりたかったのは、似たような名前のscopeを呼び出すときにまとめたかったのが始まり。

こんな感じで書いた

こんな感じで使ってみました。

class Mail
  belongs_to :user

  scope mail_a, -> {where(a: true)}
  scope mail_b, -> {where(b: true)}
  scope mail_c, -> {where(c: true)}
end
class User
  has_one :mail

  def subscribe_mail_a?
    mail.mail_a
  end

  def subscribe_mail_b?
    mail.mail_b
  end

  def subscribe_mail_c?
    mail.mail_c
  end
end

というのをevalでやると、

class User
  has_one :mail

  def subscribe_mail?(name)
    eval("mail.mail_#{name}")
  end
end

と書くことができます。とってもスッキリしました!

そして似たようなメソッドとして、sendというのもあり、これを使うと

class User
  has_one :mail

  def subscribe_mail?(name)
    mail.send("mail_#{name}")
  end
end

という感じで書けるようです。引数を渡したい時は、
send("メソッド名", "引数")と書くようです。

2つのメソッドの違い

何が違うのか、どっちを使った方がいいのかまで調べるつもりだったけど、まだよくわからないので、追記します。。。

8
3
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
8
3