Shinix Shinix - 1 month ago 14
Ruby Question

Ruby dynamic Regex condition

I would like make a regex on controller (RoR). i have tried this code :

@widget_check = ClanTemplatesWidget.find(params[:id])
unless params[:config].blank?
#@widget_check.config in database value = [{"input":"string","name":"code", "label":"Code clan","validation":"^([#][A-Z0-9]{7})$"}]
JSON.parse(@widget_check.config).each do |config,i|
regexp = Regexp.new(config["validation"])
if regexp.match(params[:config][config["name"]])
@error = 0
else
@error = 1
end
end
@widget.config = params[:config].to_json
end


For information my data is on the database. If i inspect the two params i have that :

config["validation"] = /^([#][A-Z0-9]{8})$/

params[:config][config["name"]] = #2YL9GR9R

If i rewrite my code with the data it's work fine (like that) :

if /^([#][A-Z0-9]{8})$/.match("#2YL9GR9R")
@error = 0
else
@error = 1
end

Answer

Your config["validation"] contains a string that looks like a regexp, but it is not. But you can build a regexp out of a string:

regexp = Regexp.new(config["validation"])
regexp.match(params[:config][config["name"]])

Since Regexp.new expects a string without the surrounding /.../, you just might want to omit them.

Comments