module SE::Realtime

Constants

VERSION

Public Class Methods

batch(size, **opts, &handler) click to toggle source
# File lib/se/realtime.rb, line 21
def batch(size, **opts, &handler)
  posts = []
  json(**opts) do |e|
    posts << e
    if posts.length >= size
      handler.call(posts)
      posts = []
    end
  end
end
json(site: nil, &handler) click to toggle source
# File lib/se/realtime.rb, line 14
def json(site: nil, &handler)
  ws do |e|
    data = clean_keys(JSON.parse(e['data']))
    handler.call(data) if data[:site] == site || site.nil?
  end
end
on_post(&handler) click to toggle source
# File lib/se/realtime.rb, line 7
def on_post(&handler)
  ws do |e|
    data = JSON.parse e['data']
    handler.call(data)
  end
end
ws(&block) click to toggle source
# File lib/se/realtime.rb, line 32
def ws(&block)
  WSClient.new("https://qa.sockets.stackexchange.com", cookies, &block)
end

Private Class Methods

clean_keys(json) click to toggle source
# File lib/se/realtime.rb, line 38
def clean_keys(json)
  {
    'apiSiteParameter' => :site,
    'titleEncodedFancy' => :title,
    'bodySummary' => :body,
    'lastActivityDate' => :last_active,
    'siteBaseHostAddress' => :site_url
  }.each do |old_key, new_key|
    json[new_key] = json.delete(old_key) if json.key?(old_key)
  end
  json.map do |k,v|
    if k.is_a? String
      [k.gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase.to_sym,v]
    else
      [k.to_sym,v]
    end
  end.to_h
end
cookies() click to toggle source
# File lib/se/realtime.rb, line 57
def cookies
  agent = Mechanize.new
  agent.get("https://stackexchange.com/questions?realtime")
  cookie_array = agent.cookies.map do |cookie|
    "#{cookie.name}=#{cookie.value}" if cookie.domain.end_with? "stackexchange.com"
  end
  (cookie_array - [nil]).join("; ")
end