Here is a solution:
Overriding the getter method with a regex parsing method that you define on the model will work. So now if you enter in a regex through the UI like /\d+/ it will serialize to "/\\d+/" to store in the database. But when you call the instance of user.regex it will be parsed into a Regexp object which you can call match on.
Example:
u = User.create(regex: "/\\d+/")
u.regex => /\d+/
u.regex.class => Regexp
u.regex.match("12345") => #<MatchData "12345">
u.regex.match("12345abc") => #<MatchData "12345">
Model:
class User < ActiveRecord::Base
def regex
parse_regex(self[:regex])
end
def parse_regex(string)
pieces = string.split("/")
pattern = pieces[1]
flags = pieces[2]
arg_two = 0
if flags.present?
flags.length.times do |i|
case flags[i, 1]
when "i"
arg_two |= Regexp::IGNORECASE
when "m"
arg_two |= Regexp::MULTILINE
when "x"
arg_two |= Regexp::EXTENDED
end
end
end
Regexp.new(pattern, arg_two)
end
end
Controller:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params).save
end
private
def user_params
params.require(:user).permit(:regex)
end
end
View:
<%= form_for @user do |f| %>
<%= f.label :regex %>
<%= f.text_field :regex %>
<%= f.submit %>
<% end %>