Class: Rackables::DefaultCharset

Inherits:
Object
  • Object
show all
Defined in:
lib/rackables/default_charset.rb

Overview

Adds the specified charset to the Content-Type header, if one isn’t already there.

Ideal for use with Sinatra, which by default doesn’t set charset

Constant Summary collapse

HAS_CHARSET =
/;\s*charset\s*=\s*/i

Instance Method Summary collapse

Constructor Details

#initialize(app, value = 'utf-8') ⇒ DefaultCharset

Returns a new instance of DefaultCharset.



11
12
13
14
# File 'lib/rackables/default_charset.rb', line 11

def initialize(app, value = 'utf-8')
  @app = app
  @value = value
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/rackables/default_charset.rb', line 16

def call(env)
  status, headers, body = @app.call(env)
  headers = ::Rack::Utils::HeaderHash.new(headers)
  content_type = headers['Content-Type']
  if content_type && content_type !~ HAS_CHARSET
    headers['Content-Type'] = "#{content_type}; charset=#{@value}"
  end
  [status, headers, body]
end