Class: JsonEmitter::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/json-emitter/context.rb

Overview

By using JsonEmitter.wrap and JsonEmitter.error you can wrap your streams within a special “context”.

This is probably most useful when your stream is being consumed by Rack/Rails/Sinatra/Grape/etc. Your app is probably depending on certain Rack middlewars to provide before/after behavior and error handling. All those middlewares will over by the time Rack consumes your stream, but you can use JsonEmitter.wrap and JsonEmitter.error to add critical behavior back in.

Instance Method Summary collapse

Constructor Details

#initializeContext

Returns a new instance of Context.



11
12
13
14
15
16
# File 'lib/json-emitter/context.rb', line 11

def initialize
  @wrappers = JsonEmitter.wrappers.map(&:call).compact
  @error_handlers = JsonEmitter.error_handlers
  @pass_through_errors = []
  @pass_through_errors << Puma::ConnectionError if defined? Puma::ConnectionError
end

Instance Method Details

#error(&handler) ⇒ Object

Add an error handler. TODO better docs and examples.



28
29
30
# File 'lib/json-emitter/context.rb', line 28

def error(&handler)
  @error_handlers += [handler]
end

#execute(&inner) ⇒ Object

Execute a block within this context.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/json-emitter/context.rb', line 33

def execute(&inner)
  @wrappers.reduce(inner) { |f, outer_wrapper|
    ->() { outer_wrapper.call(f) }
  }.call

rescue *@pass_through_errors => e
  raise e
rescue => e
  @error_handlers.each { |h| h.call(e) }
  raise e
end

#wrap(&block) ⇒ Object

Wrap the enumeration in a block. It will be passed a callback which it must call to continue. TODO better docs and examples.



20
21
22
23
24
# File 'lib/json-emitter/context.rb', line 20

def wrap(&block)
  if (wrapper = block.call)
    @wrappers.unshift wrapper
  end
end