I am using Ruby on Rails 3 and I am trying to get a regex string from an SQL database for a later in a validation method.
In a database migration I have:
create_table :profile_authorizations do |t|
t.string :param
t.string :param_value
end
In a model I have:
class User < ActiveRecord::Base
email_regex = Parameter.find_by_param('regex').param_value
validates :email,
:format => { :with => email_regex }
end
In the database I create the regex for email in this way:
Parameter.create(:param => 'regex', :param_value => '/\A[a-zA-Z0-9_\.]+@[a-zA-Z0-9-]+\.[a-zA-Z]{0,4}\z/i')
Using that code I get this error:
ArgumentError
A regular expression must be supplied as the :with option of the configuration hash
I tryed also to use these
Parameter.find_by_param('regex').param_value.to_s
Parameter.find_by_param('regex').param_value.to_i
but it doesn’t work.
What is it wrong?
This code
@email_regex = Parameter.find_by_param('regex').param_value
<%= debug @email_regex %>
will result in this output
--- /\A[a-zA-Z0-9_\.]+@[a-zA-Z0-9-]+\.[a-zA-Z]{0,4}\z/i
I tryed this:
Regexp.new(Parameter.find_by_param('regex').param_value)
It dosn’t seem to generate errors, but the validation “:with => email_regex” dosn’t recognize the regex.
In this case the debug results as
--- !ruby/regexp /\/\A[a-zA-Z0-9_\.]+@[a-zA-Z0-9-]+\.[a-zA-Z]{0,4}\z\/i/
Found the solution (reading the Regex.new guide):
In the database you must put the regex without ‘/’ or ‘\A’ (at the begin) and ‘\z’ (at the end):
For use it you can do just this: