restforce / restforce

A Ruby client for the Salesforce REST API.
MIT License
813 stars 358 forks source link

Enter a variable in a query ? #249

Open Sashkan opened 8 years ago

Sashkan commented 8 years ago

Hi ! Thanks for the gem.

I've been trying to code a rake task to check if all my users were registered as SF contacts, but I'm struggling with the variable.

Basically, the idea is

User.all.each do |u|
      match = client.search('FIND {u.email} RETURNING Contact (Name)').map(&:Name)
      puts match
end

But this will look for "u.email", not for the variable.

How can I include the user email in the query ?

timrogers commented 8 years ago

In Ruby, interpolation of a variable into a string only works in double quoted strings, and looks like #{variable} - so here's an example:

User.all.each do |u|
  match = client.search("FIND #{u.email} RETURNING Contact (Name)").map(&:Name)
  puts match
end
Sashkan commented 8 years ago

Didn't work, instead it got me this error :

Faraday::ClientError: MALFORMED_SEARCH: No search term found. The search term must be enclosed in braces.
Sashkan commented 8 years ago

Ok, I found a solution :

match = client.search("FIND {#{u.email}} RETURNING Contact (Name)").map(&:Name)

Unfortnuately, if the email includes a -, it stops on this error :

Faraday::ClientError: MALFORMED_SEARCH: line 1:12 mismatched character '-' expecting '}'

Any idea how to escape this behaviour ?

timrogers commented 8 years ago

That'll be a SOQL problem - best off looking at the Salesforce docs!

drewish commented 6 years ago

Per https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_sosl_examples.htm?search_text=escaping You need to escape special characters: & | ! ( ) { } [ ] ^ “ ~ * ? : \ ' + -

drewish commented 6 years ago

Meant to add that that it would be nice to have a method to escape these built into the library.

timrogers commented 6 years ago

@drewish Fancy adding one?

drewish commented 6 years ago

I'm using something like:

def escape_search_text text
  text.gsub(/([&|!(){}\[\]^"~*?:\\'+-])/) {|match| "\\#{$1}" }
end

Happy to open up a PR if you could point me at the best place to put it.