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 Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rack_env: nil) ⇒ Context

Returns a new instance of Context.



14
15
16
17
18
19
20
# File 'lib/json-emitter/context.rb', line 14

def initialize(rack_env: nil)
  @rack_env = rack_env
  @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 Attribute Details

#rack_envHash (readonly)

Returns The Rack environment Hash (if present).

Returns:

  • (Hash)

    The Rack environment Hash (if present)



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

def rack_env
  @rack_env
end

Instance Method Details

#error(&handler) ⇒ Object

Add an error handler. TODO better docs and examples.



32
33
34
# File 'lib/json-emitter/context.rb', line 32

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

#execute(&inner) ⇒ Object

Execute a block within this context.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/json-emitter/context.rb', line 44

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, self) }
  raise e
end

#requestObject

Returns a Rack::Request from rack_env (if rack_env was given).



37
38
39
40
41
# File 'lib/json-emitter/context.rb', line 37

def request
  if rack_env
    @request ||= Rack::Request.new(rack_env)
  end
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.



24
25
26
27
28
# File 'lib/json-emitter/context.rb', line 24

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