Class: Stoor::TransformContent

Inherits:
Object
  • Object
show all
Includes:
Rack::Utils
Defined in:
lib/stoor/transform_content.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ TransformContent

Returns a new instance of TransformContent.



10
11
12
13
14
15
16
17
# File 'lib/stoor/transform_content.rb', line 10

def initialize(app, options)
  @app            = app
  @regexp         = options[:regexp]
  @before         = options[:before]
  @after          = options[:after]
  @content_type   = options[:content_type] || 'text/html'
  @pass_condition = options[:pass_condition] || ->(env) { false }
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



8
9
10
# File 'lib/stoor/transform_content.rb', line 8

def app
  @app
end

#content_typeObject (readonly)

Returns the value of attribute content_type.



8
9
10
# File 'lib/stoor/transform_content.rb', line 8

def content_type
  @content_type
end

#headersObject (readonly)

Returns the value of attribute headers.



7
8
9
# File 'lib/stoor/transform_content.rb', line 7

def headers
  @headers
end

#pass_conditionObject (readonly)

Returns the value of attribute pass_condition.



8
9
10
# File 'lib/stoor/transform_content.rb', line 8

def pass_condition
  @pass_condition
end

#regexpObject (readonly)

Returns the value of attribute regexp.



8
9
10
# File 'lib/stoor/transform_content.rb', line 8

def regexp
  @regexp
end

#requestObject (readonly)

Returns the value of attribute request.



7
8
9
# File 'lib/stoor/transform_content.rb', line 7

def request
  @request
end

#statusObject (readonly)

Returns the value of attribute status.



7
8
9
# File 'lib/stoor/transform_content.rb', line 7

def status
  @status
end

Instance Method Details

#call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/stoor/transform_content.rb', line 19

def call(env)
  @status, @headers, response = @app.call(env)
  @request = Rack::Request.new(env)

  if pass_condition.call(request)
    if request.logger
      request.logger.info "Skipping -- because pass condition met"
    end
  else
    @headers = HeaderHash.new(@headers)
    if has_body && not_encoded && headers['content-type'] && headers['content-type'].index(content_type)
      content = Array(response).join('')
      if match_data = content.match(regexp)
        new_body = interpolate(match_data)
        headers['Content-Length'] = new_body.bytesize.to_s
        return [status, headers, [new_body]]
      end
    end
  end

  [status, headers, response]
end