title: Rails - Add custom headers to response based on API version
body: <p>What I am trying to do is pretty simple. There are multiple versions of a Rails REST API. So, there are routes like:</p>
  
  <pre><code>http://www.example.com/v1/user.json
  http://www.example.com/v2/user.json
  http://www.example.com/v3/user.json 
  </code></pre>
  
  <p>What I want to do is add custom http headers to the response based on the API version endpoint that is requested.</p>
  
  <p>In my config/application.rb file, I tried:</p>
  
  <pre><code>config.action_dispatch.default_headers.merge!('my_header_1' =&gt; 'my_value_1', 'my_header_2' =&gt; 'my_value_2')
  </code></pre>
  
  <p>I have also tried this in my config/routes.rb file:</p>
  
  <pre><code>scope path: "v1", controller: :test do
      get "action_1" =&gt; :action_1
      get "action_2" =&gt; :action_2
      Rails.application.config.action_dispatch.default_headers.merge!('my_header_1' =&gt; 'my_value_1', 'my_header_2' =&gt; 'my_value_2')
  end
  </code></pre>
  
  <p>But both of these snippets append custom headers to the response irrespective of the API version endpoint.</p>
  
  <p>I think I can write a middleware that checks the request url and appends the response headers based on that but it sounds a bit hackish.</p>
  
  <p>Is there a better way to achieve this? Preferably via config or some central piece of code?</p>