HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMajor

Use of a regex stored inside a YAML file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
storedfileregexuseyamlinside

Problem

I installed settingslogic and in the configuration file I put the regex for the email as follows:

#config/settings.yml
defaults: &defaults

  email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i

development:
  <<: *defaults
  # neat_setting: 800

test:
  <<: *defaults

production:
  <<: *defaults


That I load in devise configuration in this way:

#config/initializers/devise.rb
  # Regex to use to validate the email address
  # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
  config.email_regexp = eval Settings.email_regex


It works, but what do you think about that eval? Is it the correct way to convert a string to a regex?

Solution

If you want to use a regexp in a yaml file you need to use !ruby/regexp

#config/settings.yml
defaults: &defaults

  email_regex: !ruby/regexp '/^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i'


Edit:
The solution proposed by Mike Bethany is very similar to the yaml implementation.

You can take a look to what is used in Ruby 1.9.2 here (search for "!ruby/regexp"):
https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb

PS (and OT): I think, like Mike Bethany, that this basic functionality belong to the Regexp class not yaml, and need to be moved to a Regexp method. What do you think?

Code Snippets

#config/settings.yml
defaults: &defaults

  email_regex: !ruby/regexp '/^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i'

Context

StackExchange Code Review Q#159, answer score: 28

Revisions (0)

No revisions yet.