Class: Multigiri::HTML

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

Direct Known Subclasses

XML

Constant Summary collapse

CONTENT_TYPE =

Ruby GC is weak

"Content-Type"
CONTENT_LENGTH =
"Content-Length"
DEFAULT_TYPES =
["text/html"]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = Hash.new, &block) ⇒ HTML



21
22
23
24
25
# File 'lib/multigiri.rb', line 21

def initialize(app, options = Hash.new, &block)
  @app, @options, @block = app, options, block
  @options[:indentation]   ||= 2
  @options[:content_types] ||= self.class::DEFAULT_TYPES
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



20
21
22
# File 'lib/multigiri.rb', line 20

def block
  @block
end

#optionsObject (readonly)

Returns the value of attribute options.



20
21
22
# File 'lib/multigiri.rb', line 20

def options
  @options
end

Instance Method Details

#call(env) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/multigiri.rb', line 27

def call(env)
  status, headers, chunks = @app.call(env)
  check_content_type(headers)
  if options[:content_types].empty? || options[:content_types].any? { |type| headers[CONTENT_TYPE].match(type) }
    run(env, status, headers, chunks)
  else
    [status, headers, chunks]
  end
end

#run(env, status, headers, chunks) ⇒ Object

convert to a Nokogiri document



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/multigiri.rb', line 38

def run(env, status, headers, chunks)
  # the only what we know about body is that it has to respond to #each
  body = String.new
  chunks.each { |chunk| body += chunk }
  document = Nokogiri::HTML(body) # before
  @stack = lambda { |env| [status, headers, document] }

  # get middlewares
  self.instance_eval(&@block) if @block

  # convert back to a [String]
  status, headers, document = @stack.call(env)
  body = document.to_html(indentation: options[:indentation]) # TODO
  headers[CONTENT_LENGTH] = body.bytesize.to_s
  return [status, headers, [body]]
end

#use(klass, *args, &block) ⇒ Object

GoogleAnalytics.new(Other.new(self), tracking_code)



56
57
58
# File 'lib/multigiri.rb', line 56

def use(klass, *args, &block)
  @stack = klass.new(@stack, *args, &block)
end