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 th开发者_运维知识库e 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/
try this:
class User < ActiveRecord::Base
def self.email_regex
@@email_regex ||= Regexp.new(Parameter.find_by_param('regex').param_value)
end
validates :email, :format => { :with => User.email_regex }
end
also, why do you need to store your validation regex in database, if you fetch it only on User class loading, ie on server start? May be I'm wrong, but you should use custom Validator, if you want to make it fetching fresh regex value from DB, but you should think twice before doing it, cause you unlikely will have so rapidly refreshing value here
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):
[a-zA-Z0-9_\.]+@[a-zA-Z0-9-]+\.[a-zA-Z]{0,4}
For use it you can do just this:
Regexp.new(Parameter.find_by_param('regex').param_value)
精彩评论