Split between two characters - ruby-on-rails

I have this url, Being passed into javascript. I have it like this at the moment
var Link = '<%= #car.link.split('&')[1]%>';
The link has Id=63546&hjk I'm wanting to have the numbers only passed into the ticket.
So that 63546 is left. How would i go about this? It HAS to be between these two. Exactly Id= and &
Thanks

Does this split needs to done in rails side or in javascript side,. On both the sides using regex the string can be splitted to get only the numbers
On ruby side
s ="Id=63546&hjk"
s[/\d+/].to_i
=> 63546
On Javascript side
var regex = /\d+/g;
var string = "Id=63546&hjk";
var matches = string.match(regex);
document.write(matches);

Rather than try and pull apart the uri with regular expressions I would use the functions the standard library and rails give you for manipulating these things:
Rack::Utils.parse_query(URI.parse(#car.link).query)['Id']
This parse the URI, extracts the query string, uses rack to turn it into a hash of key value pairs and then extracts the one named Id. It doesn't rely on Id being exactly a certain position in the Url or anything like that.

Related

KnockoutJS mapping.fromJSON struggling with backslashes (file path values)

I am trying to pass an object structure to my html, to bind to an href. The problem becomes file path (path to an .exe) are not understood because of '\'.
example below:
var categories = ko.mapping.fromJSON('[{"Applications":[{"Documentation":null,"ApplicationId":2,"Name":"PSSE","Description":"Model software","LocalExePath":"aecies://runApp?C:\Program Files (x86)\MyApp\app.exe"}],"Name":"foobar"}]');
Sorry if i messed up some syntax, i was taking a much larger json object and compressing it for an example, may have missed a bracket somewhere. Anyway, what comes out in categories for the ExePath, in the above case, is a string with the '\'s removed. If I force it to be '\\' for every '\', it fails saying don't understand identifier P (clearly breaking at C:\Program).
Martin's answer seems to be what I want, but what i put in the question was what do I need for fromJSON. The problem is that isn't what my code actually looks like. That is what is spit out from #Html.Raw(). Below I have added my actual code. The problem is I can't just add another replace all \ with four \'s because it adds \ to every JSON title. (ends up looking like [{\\\\"Applications\\\\")
var categories = ko.mapping.fromJSON(
'#Html.Raw(JsonConvert.SerializeObject(Model.Categories,
Formatting.None,
new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml, ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
).Replace("\\u0022", "\\\"").Replace("\"", "\\\""))');
The two possible fixes I have used are string.replace in the controller to format the data there. Or to have two slashes for every one in my database record. After it goes through the serialize and the Html.Raw, it ends up with the correct 4 amount if it has 2 in the database. Is there a third option that would allow me to store the actual path string (no extra slashes, 'C:\HelloDir\') in the database, but add a line to my Razor code to replace the slashes I care about.
Edit: stackoverflow didn't like me doing double slashes, which is perfect because there is lies the majority of my problem with the mapping.
Edit2: There is more to the question
You'll actually need four backslashes because you're going through 2 layers of decoding:
JavaScript string literal (turns \\ to \)
JSON decoding (turns \\ to \)
So you'll want:
var categories = ko.mapping.fromJSON('[{"Applications": [{"Documentation":null,"ApplicationId":2,"Name":"PSSE","Description":"Model software","LocalExePath":"aecies://runApp?C:\\\\Program Files (x86)\\\\MyApp\\\\app.exe"}],"Name":"foobar"}]');
you can see some more examples at
http://jsfiddle.net/gjb4h0jy/2/
For anyone looking for the solution to the slash problem, I have figured out that clearly that EscapeHtml entry was blowing things up. If I remove that and then handle specific special characters that I want escaped with Replace statements, everything works perfectly.
var categories = ko.mapping.fromJSON(
'#Html.Raw(JsonConvert.SerializeObject(Model.Categories,
Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
).Replace(#"\r\n", "").Replace(#"'", #"\'").Replace(#"/", #"\/").Replace(#"\\", #"\\\\").Replace("\"", "\\\""))');

safe character to separate multiple urls

I am preparing a special string, in which keys are values are concatenated like below:
username=foo&age=24&email=foo#bar.com&homepage=http://foo.com
& is the separator for two key=value pairs
value is url encoded
I have a scenario where there are multiple home pages for a user.
I want to specify multiple urls for the homepage key
name=foo&age=24&email=foo#bar.com&homepage=url1<some_safe_url_separator_char>url2<some_safe_url_separator_char>url3
We have no control/idea over what url1, url2, .. may contain?
What is a good choice of some_safe_url_separator_char?
In other words I am not looking for a safe character to be used IN a url, but a safe character to be used to SEPARATE two urls in a string
well you can use URL re-writing for this .
It will make a URL that will be safe as it will hide the name of parameters
For refrence you can use URL rewriting
URL rewriting will make a url seprated by '/' and its tough to be decoded by an external person.
you can follow links i'm posting
URL rewriting for beginners

Passing array of parameters through get in rails

How do I pass array of parameters through Get method in rails? Currently my URL loocs like this:
http://localhost:3000/jobs/1017/editing_job_suites/1017/editing_member_jobs/new?ids[]=1025&ids[]=1027
How can I pass the array with Get method but avoid ?ids[]=1025&ids[]=1027 part.
Request is being sent with javascript window.open method. Is there any workaround to send not ajax Post request.
You should stick to using a GET request if you are not changing the state of anything, and all you want to to access a read only value.
To send an array of ids to rails in a GET request simply name your variable with square brackets at the end.
//angular snippet
$http.(method:'GET',
...
params: {'channel_id':2, 'product_ids[]': productIds}
//where productIds is an array of integers
...
)
Do not concatenate your ids as a comma separated list, just pass them individually redundantly. So in the url it would look something like this:
?channel_id=2&product_ids[]=6900&product_ids[]=6901
url encoded it will actually be more like this:
?channel_id=2&product_ids%5B%5D=6900&product_ids%5B%5D=6901
Rails will separate this back out for you.
Parameters: {"channel_id"=>"2", "product_ids"=>["6900", "6901"]}
No, GET can only put variables on the url itself. If you want the URL to be shorter, you have to POST. That's a limitation feature of HTTP, not Rails.
I recently wanted to do this and found a workaround that is a little less complex, and so has some complexity limitations but may also be easier to implement. Can't speak to security, etc.
If you pass your array values as a string with a delimiter, e.g.
http://example.com/controller?job_ids=2342,2354,25245
Then you can take the result and parse it back to what you want:
job_ids = params[:job_ids].split(',')
Then do whatever:
job_ids.each do |job_id|
job = Job.find(job_id.to_i)
end
etc
#Homan answer is valid for using an external client (e.g curl or angular). Inside Rails test cases though, you should not use []. Here's an example:
get get_test_cases_url(**path_params), params: {case_ids: ["NON-9450", "NON-12345", "NON-9361"]}
This is using new format where get_test_cases is name of route and you pass to the method all params needed to construct the URL path. Query params are a separate hash.
FYI if I use [] like case_ids[], then instead of ["NON-9450", "NON-12345", "NON-9361"] I'm getting it parsed to [["NON-9450"], ["NON-12345"], ["NON-9361"]]

How this URL will be decoded - Confusion in basic Http Get

Basically I need to pass three paramaters to a http as get. Here are the parameters
param1 = 3
param2 = 454
param3 = http://localhost:3000/another_test?another_param=4&another_param2=978
This transforms to
http://localhost:3000/test?param1=3&param2=454&param3=http://localhost:3000/another_test?another_param=4&another_param2=978
I am just confused whether the URL formed is correct or not. Will this work or is there anyother way to do this. I am using Rails. I did a decode and clicked on the link and I still see the above URL coming. Will this work on the receiever side, meaning will it be decoded as I had intended.
Please advise.
It should work as long as you url encode the params. In that case the & and ? will be transformed, making it possible for Rails to differentiate between the query string parameters and the query string delimiters.
To ensure that it is encoded you can use Rack::Utils.escape or Hash#to_query.
This will be decoded as:
param1=3
param2=454
param3=http://localhost:3000/another_test?another_param=4
another_param2=978
You need to encode param3, or at minimum replace the ampersands in it with the correct URL encoding, in order for it to match back up to your input parameters.

Why is this query string invalid?

In my asp.net mvc page I create a link that renders as followed:
http://localhost:3035/Formula/OverView?colorId=349405&paintCode=744&name=BRILLANT%20SILVER&formulaId=570230
According to the W3C validator, this is not correct and it errors after the first ampersand. It complains about the & not being encoded and the entity &p not recognised etc.
AFAIK the & shouldn't be encoded because it is a separator for the key value pair.
For those who care: I send these pars as querystring and not as "/" seperated values because there is no decent way of passing on optional parameters that I know of.
To put all the bits together:
an anchor (<a>) tag's href attribute needs an encoded value
& encodes to &
to encode an '&' when it is part of your parameter's value, use %26
Wouldn't encoding the ampersand into & make it part of my parameter's value?
I need it to seperate the second variable from the first
Indeed, by encoding my href value, I do get rid of the errors. What I'm wondering now however is what to do if for example my colorId would be "123&456", where the ampersand is part of the value.
Since the separator has to be encoded, what to do with encoded ampersands. Do they need to be encoded twice so to speak?
So to get the url:
www.mySite.com/search?query=123&456&page=1
What should my href value be?
Also, I think I'm about the first person in the world to care about this.. go check the www and count the pages that get their query string validated in the W3C validator..
Entities which are part of the attributes should be encoded, generally. Thus you need & instead of just &
It works even if it doesn't validate because most browsers are very, very, very lenient in what to accept.
In addition, if you are outputting XHTML you have to encode every entity everywhere, not just inside the attributes.
All HTML attributes need to use character entities. You only don't need to change & into & within script blocks.
Whatever
Anywhere in an HTML document that you want an & to display directly next to something other than whitespace, you need to use the character entity &. If it is part of an attribute, the & will work as though it was an &. If the document is XHTML, you need to use character entities everywhere, even if you don't have something immediately next to the &. You can also use other character entities as part of attributes to treat them as though they were the actual characters.
If you want to use an ampersand as part of a URL in a way other than as a separator for parameters, you should use %26.
As an example...
Hello
Would send the user to http://localhost/Hello, with name=Bob and text=you & me "forever".
This is a slightly confusing concept to some people, I've found. When you put & in a HTML page, such as in <a href="abc?def=5&ghi=10">, the URL is actually abc?def=5&ghi=10. The HTML parser converts the entity to an ampersand.
Think of exactly the same as how you need to escape quotes in a string:
// though you define your string like this:
myString = "this is \"something\" you know?"
// the string is ACTUALLY: this is "something" you know?
// when you look at the HTML, you see:
<a href="foo?bar=1&baz=2">
// but the url is ACTUALLY: foo?bar=1&bar=2

Resources