You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails:如何为请求头生成带引号的字符串?

Fixing the OAuth Header Quote Issue in Your Twitter Client

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:

  1. Wrap the value in quotes inside %Q
    You can explicitly include the double quotes within the %Q block, 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.

  2. Direct string interpolation without %Q
    You can skip %Q entirely 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:46:28