Class: FaradayMiddleware::Reddit::Modhash

Inherits:
Faraday::Middleware
  • Object
show all
Includes:
ModhashHelpers
Defined in:
lib/faraday_middleware/reddit/use/modhash.rb

Overview

Middleware that keeps track of and sets modhash-related HTTP headers.

Reddit uses modhashes as a form of XSS protection and requires them for most POST and PUT requests. Modhashes are currently provided in response to listing GET requests.

Instance Method Summary collapse

Methods included from ModhashHelpers

#extract_modhash, included

Constructor Details

#initialize(app, options = nil) ⇒ Modhash

Returns a new instance of Modhash.



15
16
17
18
19
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 15

def initialize(app, options = nil)
  super(app)
  @options = options || {}
  @modhash = @options[:modhash]
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 21

def call(env)
  @modhash = env[:modhash] if env[:modhash]
  env[:request_headers]['X-Modhash'] = @modhash if @modhash
  @app.call(env).on_complete do |response_env|
    update_modhash(response_env)
  end
end

#update_modhash(env) ⇒ Object



29
30
31
32
33
# File 'lib/faraday_middleware/reddit/use/modhash.rb', line 29

def update_modhash(env)
  @modhash = extract_modhash(env)
rescue JSON::JSONError
  # Ignore -- modhash can be acquired lazily.
end