Ruby on Rails:如何为请求头生成带引号的字符串?
Hey there! Let's break down why your current approach isn't adding those required quotes to the OAuth header values, and how to fix it.
The Problem with Your %Q Usage
You assumed %Q would wrap your value in double quotes, but that's not quite how it works in Ruby. %Q(...) is just an alternative syntax for creating a double-quoted string—it doesn't automatically add quotes around the content inside it. So when you write %Q(Figaro.env.TWITTER_ACCESS_TOKEN), it simply returns the raw value of Figaro.env.TWITTER_ACCESS_TOKEN as a string, no extra quotes included. That's why your output ends up as oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog instead of the required oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog".
Simple Fixes for Adding Quotes
Here are a couple of straightforward ways to get the quoted format you need:
Wrap the value in quotes inside %Q
You can explicitly include the double quotes within the%Qblock, using string interpolation to insert your environment variable:["oauth_consumer_key", %Q("#{Figaro.env.TWITTER_ACCESS_TOKEN}")].join('=')This will output
oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog"as expected.Direct string interpolation without %Q
You can skip%Qentirely and build the string directly with interpolation and escaped quotes:"oauth_consumer_key=\"#{Figaro.env.TWITTER_ACCESS_TOKEN}\""
A More Maintainable Approach
Since you have multiple OAuth parameters to handle (nonce, signature, timestamp, etc.), it's better to organize them in a hash and generate the header string in one go. This keeps your code clean and easier to update:
# First, define all your OAuth parameters oauth_params = { oauth_consumer_key: Figaro.env.TWITTER_CONSUMER_KEY, oauth_nonce: SecureRandom.hex(16), # Generate a random nonce oauth_signature: your_generated_signature, # Replace with your signature logic oauth_signature_method: "HMAC-SHA1", oauth_timestamp: Time.now.to_i.to_s, oauth_token: Figaro.env.TWITTER_ACCESS_TOKEN, oauth_version: "1.0" } # Format each key-value pair into "key=\"value\"" and join with commas auth_header = "OAuth " + oauth_params.map { |key, value| "#{key}=\"#{value}\"" }.join(", ")
This will generate a properly formatted Authorization header that matches Twitter's requirements.
内容的提问来源于stack exchange,提问作者Edvaldo Silva de Almeida Jr

