LoginSignup
10
9

More than 5 years have passed since last update.

RailsでYAMLに正規表現をつっこむ

Last updated at Posted at 2015-07-04

!ruby/regexpをいれるといいというのが書いてあったので、メモ。

config/reg.yml
reg:
  a: !ruby/regexp /^[a-zA-Z|\s]+$/
  n: !ruby/regexp /^[0-9]+$/
  s: !ruby/regexp /^\W+$/

configに下記のように記入して、簡単に引っ張り出せるようにする。
※編集: @scivolaさんにご指摘いただき下記コード一部修正致しました。@scivolaさんありがとうございます。

config/initializers/load_yml.rb
path = "#{Rails.root}/config/reg.yml"
REG = YAML.load_file(path).symbolize_keys

下記みたいな感じで呼び出せる。

a = 'abc'
a.match(REG[:reg]['a'])
# => #<MatchData "abc">
b = '1bc'
b.match(REG[:reg]['a'])
# => nil
10
9
4

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
10
9