为什么红宝石控制器会逃避参数本身? [英] Why ruby controller would escape the parameters itself?

查看:42
本文介绍了为什么红宝石控制器会逃避参数本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为后端服务编写Ruby应用程序.有一个控制器可以接受来自前端的请求.

I am writing Ruby application for the back end service. There is a controller which would accept request from front-end.

在这种情况下,存在一个带有包含字符"\ n"的参数的GET请求.

Here is the case, there is a GET request with a parameter containing character "\n".

    def register
        begin
            request = {
                id: params[:key]
            }
            .........
        end
    end

"key"参数从AngularJs传递为"---- BEGIN ----- \ n abcd \ n ---- END ---- \ n",但是在Ruby控制器中,该参数变为

The "key" parameter is passing from AngularJs as "----BEGIN----- \n abcd \n ----END---- \n", but in the Ruby controller the parameter became "----BEGIN----- \\n abcd \\n ----END---- \\n" actually.

有人对此有很好的解决方案吗?

Anyone has a good solution for this?

推荐答案

是的,这是因为使用红宝石方式读取了转义字符.您可以在此处阅读说明:转义字符在Ruby中

Yes, this is because of the ruby way to read the escape character. You can read the explanation right here: Escaping characters in Ruby

我曾经遇到过这个问题,我只是使用 gsub! \\ n 更改为 \ n .您应该做的是:

I got this issue once, and I just use gsub! to change the \\n to \n. What you should do is:

def register
  begin
    request = {
      id: params[:key].gsub!("\\n", "\n")
    }
    .........
  end
end

请记住,您必须使用双引号"而不是单引号'.在我给的链接中:

Remember, you have to use double quotation " instead of single quotation '. From the link I gave:

Ruby中单引号和双引号字符串之间的区别在于字符串定义表示转义序列的方式.

The difference between single and double quoted strings in Ruby is the way the string definitions represent escape sequences.

在双引号字符串中,您可以编写转义序列,并且Ruby将输出其翻译后的含义.\ n成为换行符.但是,在单引号引起来的字符串中,转义序列被转义并返回其字面定义.\ n仍然是\ n.

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n.

这篇关于为什么红宝石控制器会逃避参数本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆