开发者

Retrieving YAML from a text field

开发者 https://www.devze.com 2023-02-05 20:37 出处:网络
The serialize method allows an object like a hash to be stored in the database as a YAML string.However, I recently found myself wanting to have a text field to allow a user to input their own string

The serialize method allows an object like a hash to be stored in the database as a YAML string. However, I recently found myself wanting to have a text field to allow a user to input their own string and have the controller create a hash off of that string.

<%= f.text_field :yaml, :value => '--- \nlast_name: Smith\nfirst_name: Joe\n' %开发者_开发技巧>

Yes, I want single quotes: I want to preserve the \n in the display. But the problem is that, as a result, the resultant string object gets escaped:

--- \\nlast_name: Smith\\nfirst_name: Joe\\n

I run the string through two regexes: The first replaces the double backslash with a single backslash. Then next converts \n (two characters) into \n (special single character).

So in my controller:

yhash = YAML.load(params[:form][:yaml].gsub(/\\\\/, "\\").gsub(/\\n/, "\n"))

This now works, but seems awfully convoluted. Is there a more elegant way for a user to submit yaml?


Are you saying you want the users to be able to write \n to mark the newlines in the yaml they are entering? Because in that case the way you are doing it now with regexps is very straightforward.

The escape sequence \n is a feature of Ruby strings. If you want to implement it in your web form yaml interface too, a regexp is a valid way to do that.

Are you sure you have to do the double-slash replacement? I think it should only show up as double-slash if you do .inspect.

0

精彩评论

暂无评论...
验证码 换一张
取 消