Amirol Ahmad
Amirol Ahmad

Reputation: 542

RAILS JSON keep backslash in string

I have this line in my view form:

<%= hidden_field_tag "ng_b2b_configuration[value][endpoints][][patterns][]", raw(".+\\\\.runsheet\\\\..+") %>

it will produce the result:

"patterns":[".+\\.runsheet\\..+"]

which is not the one that i really want. My question is how to keep the backslash after save in my db?

This is exactly what i want: "patterns":[".+\.runsheet\..+”]

I've try with this: <%= hidden_field_tag "ng_b2b_configuration[value][endpoints][][patterns][]", raw(".+\\\\.runsheet\\\\..+"), class: "val_runsheet_all" %> and the result: "patterns":[\".+\\.runsheet\\..+\”]

UPDATE 1

Here is the html output:

<input type="hidden" name="ng_b2b_configuration[value][endpoints][][patterns][]" id="ng_b2b_configuration_value_endpoints__patterns_" value=".+\.runsheet\..+">

Upvotes: 1

Views: 793

Answers (1)

mu is too short
mu is too short

Reputation: 434665

value=".+\.runsheet\..+" in the HTML will end up as '.+\.runsheet\..+' in Ruby so you're being confused somewhere. Nothing you do will (without trickery) will give you a string like:

".+\.runsheet\..+"

in Ruby or JSON. Backslashes have special meaning in both Ruby double quoted strings and JSON formatted strings. Neither one needs a backslash to escape a . so neither will put it there. But because \ has a special meaning as an escape character in both Ruby double quoted strings and JSON, a single \ will look like \\ because both have to escape the special mean of \ by, well, escaping the escape character.

Go into irb and say:

puts ".+\.runsheet\..+"

and see what you get. Then say:

puts ".+\\.runsheet\\..+"

and see what you get. The first will give you:

.+.runsheet..+

and the second:

.+\.runsheet\..+

Then you can throw in some to_json calls (again using puts to see the results so that you avoid the escaping that inspect will use) and you'll see similar things happening.

Upvotes: 1

Related Questions