How do i remove 'quotes' from strings that can contain single quotes? - ruby-on-rails

I have params that is returning 4, 36, 'new tag', 52, 'Mcdonald\'s', 25 as a string.
I then split them by , and then i need to do some work on them.
First, I need to create a new tag based on that, but i need to somehow gsub (or something?) the outside quotes, but not the inner ones (if the tag contains it, like McDonald's above)
Second, I need to unescape the \ that the token input adds. I'm not sure how to do that second step so its the best security-wise
PS. I have validations on that model so I'm hoping that's good enough and i dont have to worry about some kind of SQL injection thing

params.split(/,\s+/).map{|s| s.start_with?("'") && s.end_with?("'") ? s[1..-2] : s }
That should clear up the first part about quotes.

Related

What language is this Salesforce code that I need to wrap?

I'm working on a Salesforce coding issue. Let me preface this by saying I'm not a developer or Salesforce expert.
What language is this?
Data Type FormulaThis formula references multiple objects
IF (Fulfillment_Submission_Form_URL__c <> "" && CONTAINS(Fulfillment_Submission_Form_URL__c, "qualtrics"),
Fulfillment_Submission_Form_URL__c &
(IF (CONTAINS(Fulfillment_Submission_Form_URL__c,"?SID="), "&", "?")) &
(IF (CONTAINS(TEXT(Type__c), "Site Visit"),
"ContactId="&Statement_of_Work__r.Contractor_Contact__c&
"&CoachType="&SUBSTITUTE(Statement_of_Work__r.Work_Type__r.Name," ","%20")&
"&CoachName="&SUBSTITUTE(Statement_of_Work__r.Contractor_Name__c," ","%20")&
"&InitPartId="&Initiative_Participation__r.Id&
"&InstitutionName="&substitute(substitute(SUBSTITUTE(Institution_Name__c," ","%20"),")",""),"(","")&
"&AccountId="&Initiative_Participation__r.Participating_Institution__r.Id&
"&TodaysDate="&TEXT(TODAY())&
"&SOWLineItemId="&Id&
"&LeaderCollege="&Initiative_Participation__r.ATD_Leader_College_Status__c&
"&SVRCompleted="&TEXT(Count_of_Site_Visit_Fulfillments__c)&
"&SVRRequired="&TEXT(Number_of_Work_Units_Allocated__c),
IF (CONTAINS(TEXT(Type__c), "Feedback"),
"InitPartId="&Initiative_Participation__r.Id&
"&SOWLineItemId="&Id&
"&ReportYear="&Statement_of_Work__r.SOW_Year__c&
"&UserId="&Contractor_User_Id__c&
"&InstitutionName="&substitute(substitute(SUBSTITUTE(Institution_Name__c," ","%20"),")",""),"(",""),
"")
))
,"")
Essentially it's pulling a link from another product we've integrated it with. We then take the basic link and reformat it to add parameters.
The problem is when it pulls in some parameters (ex: CoachName) the Coach entered their name in strange formats like: John (Coach) Doe.
So when the script outputs a URL that includes parameters it breaks at the &CoachName=John%20(Coach)% portion of the URL. Any easy way to work around this by modifying the script? Unfortunately we DO need that (Coach) identifier because the system we push to grabs that as well.
It's formula syntax, I'd compare it to Excel-like formulas. There's self-paced training if you don't want to read documentation. And as it's not exactly code-related you may have more luck on dedicated site, https://salesforce.stackexchange.com/. More admins lurk there.
So you do want that "(Coach)" to go through but it breaks the link? Looks like ( is a special character. It's not technically wrong to have unescaped parentheses, if it breaks that other site you might want to contact them and get their act together. RFC doesn't force us to encode them but looks like you'll have to to solve it at least in the short term: https://webmasters.stackexchange.com/questions/78110/is-it-bad-to-use-parentheses-in-a-url
Instead of poor man's encoding (SUBSTITUTE(Statement_of_Work__r.Contractor_Name__c," ","%20") try using proper URLENCODE(Statement_of_Work__r.Contractor_Name__c).
Or there's bit more "pro" function called URLFOR but the documentation doesn't make it very clear how powerful the 3rd parameter is with the braces [key1 = value1, key2 = value2] syntax. Basically just pass the parameters and let SF worry about encoding special characters etc.
Read my answer https://salesforce.stackexchange.com/a/46445/799 and there are some examples on the net like https://support.docusign.com/s/articles/DFS-URL-buttons-for-Lightning-basic-setup-limitations?language=en_US&rsc_301

Ruby on Rails: How may create a quoted string to a request header?

I am writing from scratch a Twitter client and one of the requisites is not using Twitter gems, so I must create my own requests.
Twitter API documentation says here that I must have a Authorization header like this:
Authorization:
OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318622958",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"
As you may see I must have something like oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog" with the second part in quotes. I tried using %Q like in
["oauth_consumer_key",%Q( Figaro.env.TWITTER_ACCESS_TOKEN )].join('=')
assuming %Q would return a quoted string. but when I inspect the value, all I get is
oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog
which, obviously, is different from the required result.
What am I missing?
1. My solution:
'oauth_consumer_key="#{Figaro.env.TWITTER_ACCESS_TOKEN}"'
2. Why:
%Q() basically replaces the variable with double quotes "", it is literally the same as if you wrote "Figaro.env.TWITTER_ACCESS_TOKEN"
In fact, to display the content of a variable, you have to use interpolation
instead of the name itself, using "#{var}".
You can also use %Q directly with interpolation using %Q{var} (note {} instead of ()).
Your problem is elsewhere: with the join() method. It's getting rid of double quotes. In that case doing ["var", var].join('=') and ["var", %Q{var}].join('=') ends doing exactly the same thing but more complicated.
#Artem Ignatiev's solution should works. But if you need to be more readable, you don't even need to join, imho, it makes sense only when you are using more than two variables.
For instance, I will use something like 'oauth_consumer_key="#{var}"' mixing single and double quote to make sure it causes no confusions.
If you do need to use %Q() and join, you can still use ["oauth_consumer_key", %Q("#{Figaro.env.TWITTER_ACCESS_TOKEN})].join('=').
Note that because of the join you can use single quote interpolation %q or double quote interpolation %Q without affecting the ends results:
e.g
['oauth_consumer_key', %q("#{var}")].join('=') == ["oauth_consumer_key", %Q("#{var}")].join('=')
%Q(x) is basically the same as "x".
To achieve the desired result you have to manually introduce quotes into %Q expression, like this: %Q("#{Figaro.env.TWITTER_ACCESS_TOKEN}")

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("\"", "\\\""))');

Difference between these three URL's?

Can somebody explain how does it matter to pass different parameters in a url,
e-g
1: www.domain.com/folder1/folder2/file.html?param=9?val=ty5?test
2: www.domain.com/folder1/folder2/file.html#param=93#val=t5y5?test=9
3: www.domain.com/folder1/folder2/file.html&param=9?val=ty5&test=90#poiu
Basically I want to know what do these three characters (#, &, ?) do in the url. I have seen them most of the times? can I use some thing other than that
e-g: www.domain.com/folder1/folder2/file.html*param=9_val+ty5#test
? indicates the start of the query string
& separates key value pairs of the querystring
# indicates an anchor. Here's more on anchor links.
Note that all three of your urls are incorrect.
Valid url:
http://domain/path/file?name=value&name=value#anc
I notice you've edited your question with an additional question
can I use some thing other than that e-g:
www.domain.com/folder1/folder2/file.html*param=9_val+ty5#test
You can use whatever you like in the part of the querystring or anchor as long as it is url encoded.
This Wikipedia article goes in to the detail and gives some good examples.
A ? indicates the start of the query
A & separates the parameters in the query
A # identifies a fragment in the HTML resource to be rendered. It's often used to identify which but if the page the browser should ensure is in view eg a heading etc
? represents that the URL contains QueryString values.
& is used to for multiple querystring values. Example
www.abc.com/page?id=abc&pwd=def
and # is new for me I first time saw it.
1: ? is used for separating back end code to its arguments. Notice the file extension is html doesn't necessarily says that the back end code is in HTML
2: # is used to link to anchors within the html page
3: & is used for separating arguments with other arguments. in this case, the file.html is also an argument itself, while the backend code is the "/", which can be anything. e.g. index.php, default.asp, index.do. it all depends on your URL rewrite.

How to get regex to ignore URL strings?

I have the following Regexp to create a hash of values by separating a string at a semicolon:
Hash["photo:chase jarvis".scan(/(.*)\:(.*)/)]
// {'photo' => 'chase jarvis'}
But I also want to be able to have URL's in the string and recognize it so it maintains the URL part in the value side of the hash i.e:
Hash["photo:http://www.chasejarvis.com".scan(/(.*)\:(.*)/)]
// Results in {'photo:http' => '//www.chasejarvis.com'}
I want, of course:
Hash["photo:chase jarvis".scan(/ ... /)]
// {'photo' => 'http://www.chasejarvis.com'}
If you only want to match up to first colon you could change (.*)\:(.*) to ([^:]*)\:(.*).
Alternatively, you could make it a non-greedy match, but I prefer saying "not colon".
How do figure out a person's family name and first name?
Changing chasejarvis to chase and jarvis might not be possible unless you have a solution for that.
Do you already know everyone's name in your project? Nobody is having the initial of a middle name like charvisdjarvis (assuming the name is "Charvis D. Jarvis".)?

Resources