Class: Rack::EnvNotifier::BodyInjector

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/env_notifier/body_injector.rb

Constant Summary collapse

BODY_TAG_REGEX =
/<body>|<body[^(er)][^<]*>/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body, text_to_be_injected) ⇒ BodyInjector

Returns a new instance of BodyInjector.



8
9
10
11
# File 'lib/rack/env_notifier/body_injector.rb', line 8

def initialize(body, text_to_be_injected)
  @body                = body
  @text_to_be_injected = text_to_be_injected
end

Instance Attribute Details

#content_lengthObject (readonly)

Returns the value of attribute content_length.



6
7
8
# File 'lib/rack/env_notifier/body_injector.rb', line 6

def content_length
  @content_length
end

#new_bodyObject (readonly)

Returns the value of attribute new_body.



6
7
8
# File 'lib/rack/env_notifier/body_injector.rb', line 6

def new_body
  @new_body
end

#notification_addedObject (readonly)

Returns the value of attribute notification_added.



6
7
8
# File 'lib/rack/env_notifier/body_injector.rb', line 6

def notification_added
  @notification_added
end

Instance Method Details

#inject!(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/env_notifier/body_injector.rb', line 13

def inject!(env)
  @env = env
  @body.close if @body.respond_to?(:close)

  @body = [@body] if @body.is_a? String

  @new_body = []
  @body.each { |line| @new_body << line.to_s }

  @content_length     = 0
  @notification_added = false

  @new_body.each do |line|
    if !@notification_added && line['<body']
      line.gsub! (BODY_TAG_REGEX) {|match| %{#{match}\n#{@text_to_be_injected}} }

      @notification_added = true
    end

    @content_length += line.bytesize
  end
  @new_body = @body
end