Why ruby controller would escape the parameters itself?

孤街醉人 提交于 2021-02-11 14:30:18

问题


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

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

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

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?


回答1:


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

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:

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

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.



来源:https://stackoverflow.com/questions/60426316/why-ruby-controller-would-escape-the-parameters-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!