Class: Ditty::Middleware::AcceptExtension

Inherits:
Object
  • Object
show all
Defined in:
lib/ditty/middleware/accept_extension.rb

Overview

Allow requests to be responded to in JSON if the URL has .json at the end. The regex and the content_type can be customized to allow for other formats. Some inspiration from gist.github.com/tstachl/6264249

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, regex = %r{\A(.*)\.json(/?)\Z}, content_type = 'application/json') ⇒ AcceptExtension

Returns a new instance of AcceptExtension.



11
12
13
14
15
16
# File 'lib/ditty/middleware/accept_extension.rb', line 11

def initialize(app, regex = %r{\A(.*)\.json(/?)\Z}, content_type = 'application/json')
  # @mutex = Mutex.new
  @app = app
  @regex = regex
  @content_type = content_type
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



9
10
11
# File 'lib/ditty/middleware/accept_extension.rb', line 9

def content_type
  @content_type
end

#envObject (readonly)

Returns the value of attribute env.



9
10
11
# File 'lib/ditty/middleware/accept_extension.rb', line 9

def env
  @env
end

#regexObject (readonly)

Returns the value of attribute regex.



9
10
11
# File 'lib/ditty/middleware/accept_extension.rb', line 9

def regex
  @regex
end

Instance Method Details

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ditty/middleware/accept_extension.rb', line 18

def call(env)
  @env = env

  request = Rack::Request.new(env)
  if request.path&.match?(regex)
    request.path_info = request.path_info.gsub(regex, '\1\2')
    env = request.env
    env['ACCEPT'] = content_type
    env['CONTENT_TYPE'] = content_type
  end

  @app.call env
end