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?
%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}")
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('=')
.
join
you can use single quote interpolation %q
or double quote interpolation %Q
without affecting the ends results: eg
['oauth_consumer_key', %q("#{var}")].join('=') == ["oauth_consumer_key", %Q("#{var}")].join('=')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.