正規表現値でハッシュを入れるフォームがあります。私の問題は、私のビューから、コントローラーを介して、Mongoid を使用して MongoDB に移動するときに、それらがめちゃくちゃになることです。正規表現を保存するにはどうすればよいですか?
入力例:
{:regex1 => "^Something \(#\d*\)$"}
{:regex2 => "\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z"}
私のformtasticビューフォームは次のようになります:
= semantic_form_for resource, :html => {:class => "form-vertical"} do |r|
= r.inputs do
= r.input :value, :as => :text
= r.actions do
= r.action :submit
私のコントローラー作成アクションはパラメーターを受け取り、次のように処理します。
class EmailTypesController < InheritedResources::Base
def create
puts params[:email_type][:value] # => {:regex1 => "^Something \(#\d*\)$"} and
# {:regex2 => "\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z"}
puts params[:email_type][:value].inspect # => "{:regex1 => \"^Something \\(#\\d*\\)$\"}" and
# "{:regex2 => \"\\A[\\w+\\-.]+@[a-z\\d\\-.]+\\.[a-z]+\\z\"}"
params[:email_type][:value] = convert_to_hash(params[:email_type][:value])
puts params[:email_type][:value] # => {"regex1"=>"^Something (#d*)$"} and
# {"regex2"=>"A[w+-.]+@[a-zd-.]+.[a-z]+z"}
create! do |success, failure|
success.html {
redirect_to resource
}
failure.html {
render :action => :new
}
end
end
def convert_to_hash(string)
if string.match(/(.*?)=>(.*)\n*/)
string = eval(string)
else
string = string_to_hash(string)
end
end
def string_to_hash(string)
values = string.split("\r\n")
output = {}
values.each do |v|
val = v.split("=")
output[val[0].to_sym] = val[1]
end
output
end
end
コンソールを起動し、Mongoid を介して入力された値を検査します。
Loading development environment (Rails 3.2.12)
1.9.3p385 :001 > EmailType.all.each do |email_type|
1.9.3p385 :002 > puts email_type.value
1.9.3p385 :003?> end
{"regex1"=>"^Something (#d*)$"}
{"regex2"=>"A[w+-.]+@[a-zd-.]+.[a-z]+z"}
=> true
1.9.3p385 :004 >