Frage

I would like user to input regex using form and text_field tag. But as I understand it is being sanitized by default. If I store regexs directly in DB via seed.rb or console, it works. But I cannot do it using UI:

<div class="control-group">
  <%= f.label :regexp, :class => 'control-label' %>
  <div class="controls">
    <%= f.text_field :regexp, :class => 'text_field' %>
  </div>
</div>

How to fix it?

War es hilfreich?

Lösung

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 %>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top