LoginSignup
2
2

More than 5 years have passed since last update.

RailsのStringクラスにemail?メソッドを追加する

Posted at

作ったもの

'hello'.email? #=> false
'hello@world.com'.email? #=> true

コード

Ruby 2.4

config/initializers/validations.rb
class String
  def email?
    self.match? /\A[^@\s]+@[^@\s]+\z/
  end
end

Ruby 2.3 以前

config/initializers/validations.rb
class String
  def email?
    self.match /\A[^@\s]+@[^@\s]+\z/
  end
end

補足

正規表現にはDevise 4.2.0にてDevise::email_regexpとして定義されている/\A[^@\s]+@[^@\s]+\z/を使っています。(.等を見ないので結構緩めです)

Deviseインストール済みなら上記のコードの該当部をself.match? Devise::email_regexpと置き換えても同じ事が出来ます。(当然ですが…汗)

Ruby 2.4 以降にはマッチしたかどうかを true or falseで返す高速な match? メソッドが追加されたので、そちらを使っています。

2
2
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
2
2