从文本字段检索 YAML

发布于 2024-10-13 11:42:58 字数 575 浏览 3 评论 0原文

Serialize 方法允许像哈希这样的对象作为 YAML 字符串存储在数据库中。然而,我最近发现自己想要一个文本字段来允许用户输入自己的字符串,并让控制器创建该字符串的哈希值。

<%= f.text_field :yaml, :value => '--- \nlast_name: Smith\nfirst_name: Joe\n' %>

是的,我想要单引号:我想在显示中保留 \n。但问题是,结果,生成的字符串对象被转义:

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

我通过两个正则表达式运行字符串:第一个用单个反斜杠替换双反斜杠。然后接下来将 \n (两个字符)转换为 \n (特殊单个字符)。

所以在我的控制器中:

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

现在可以工作了,但看起来非常复杂。用户提交 yaml 是否有更优雅的方式?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝色星空 2024-10-20 11:42:58

您是说您希望用户能够编写 \n 来标记他们输入的 yaml 中的换行符吗?因为在这种情况下,您现在使用正则表达式执行此操作的方式非常简单。

转义序列 \n 是 Ruby 字符串的一项功能。如果您也想在 Web 表单 yaml 界面中实现它,则正则表达式是一种有效的方法。

您确定必须执行双斜杠替换吗?我认为如果你执行.inspect,它应该只显示为双斜杠。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文