Class: Slimer::WebAction

Inherits:
Object
  • Object
show all
Defined in:
lib/slimer/web/action.rb

Overview

Everything needed for handling an HTTP request Borrowed from Sidekiq:

https://github.com/mperham/sidekiq/blob/master/lib/sidekiq/web/action.rb

Constant Summary collapse

RACK_SESSION =
"rack.session"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, block) ⇒ WebAction

Returns a new instance of WebAction.



62
63
64
65
66
# File 'lib/slimer/web/action.rb', line 62

def initialize(env, block)
  @env = env
  @block = block
  @files ||= {}
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



10
11
12
# File 'lib/slimer/web/action.rb', line 10

def block
  @block
end

#envObject

Returns the value of attribute env.



10
11
12
# File 'lib/slimer/web/action.rb', line 10

def env
  @env
end

#typeObject

Returns the value of attribute type.



10
11
12
# File 'lib/slimer/web/action.rb', line 10

def type
  @type
end

Instance Method Details

#authorized?Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
# File 'lib/slimer/web/action.rb', line 32

def authorized?
  api_key = route_params.delete(:api_key)
  return false unless api_key

  # Ensure a connection to the DB has been made and models loaded
  Slimer.db
  Slimer::ApiKey.where(token: api_key).count.positive?
end

#forbiddenObject



28
29
30
# File 'lib/slimer/web/action.rb', line 28

def forbidden
  throw :halt, [403, { "Content-Type" => "text/plain" }, ["Forbidden"]]
end

#halt(res) ⇒ Object



20
21
22
# File 'lib/slimer/web/action.rb', line 20

def halt(res)
  throw :halt, res
end

#json(payload) ⇒ Object



58
59
60
# File 'lib/slimer/web/action.rb', line 58

def json(payload)
  [200, { "Content-Type" => "application/json", "Cache-Control" => "no-cache" }, [JSON.generate(payload)]]
end

#paramsObject



41
42
43
44
45
46
47
48
# File 'lib/slimer/web/action.rb', line 41

def params
  indifferent_hash = Hash.new { |hash, key| hash[key.to_s] if Symbol === key } # rubocop:disable Style/CaseEquality

  indifferent_hash.merge! request.params
  route_params.each { |k, v| indifferent_hash[k.to_s] = v }

  indifferent_hash
end

#redirect(location) ⇒ Object



24
25
26
# File 'lib/slimer/web/action.rb', line 24

def redirect(location)
  throw :halt, [302, { "Location" => "#{request.base_url}#{location}" }, []]
end

#requestObject



16
17
18
# File 'lib/slimer/web/action.rb', line 16

def request
  @request ||= ::Rack::Request.new(env)
end

#route_paramsObject



50
51
52
# File 'lib/slimer/web/action.rb', line 50

def route_params
  env[WebRouter::ROUTE_PARAMS]
end

#sessionObject



54
55
56
# File 'lib/slimer/web/action.rb', line 54

def session
  env[RACK_SESSION]
end

#settingsObject



12
13
14
# File 'lib/slimer/web/action.rb', line 12

def settings
  Web.settings
end