Skip to content

Instantly share code, notes, and snippets.

@vasspilka
Last active June 14, 2016 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasspilka/888a8082e3b605586b83782fc0a92f0c to your computer and use it in GitHub Desktop.
Save vasspilka/888a8082e3b605586b83782fc0a92f0c to your computer and use it in GitHub Desktop.
Ruby helpers for tracking and reporting events from rails (with modification anywhere else) to slack (Requires slack webhooks)

A data tracker that knows when to report.

All you need to do is add items to it and eventually it will report when the time has come! You can add objects or strings.

e.g. DailyStats.get.add(@rock) , DailyStats.get.add('rock'), WeeklyStats.get.add('big rock')

Also you can add items to all trackers and and each tracker will report and reset then its time is due with Stats.add_to_all('rock solid butter')

require 'slack-notifier'
class SlackNotifier
WEBHOOK = ENV['SLACK_WEBHOOK_KEY'].freeze
def initialize(item = User, options={ channel: '#feedback' })
announcer_name = item.to_s.downcase + "_announer"
@notifier = Slack::Notifier.new WEBHOOK, channel: options[:channel], username: announcer_name
end
def call(allow = false)
(return unless Rails.env.production?) unless allow
@notifier.ping yield
end
end
class Stats
def self.get
@current ||= new
end
def self.add_to_all(item)
HourlyStats.get.add(item)
DailyStats .get.add(item)
WeeklyStats.get.add(item)
end
def initialize
@report_type = self.class.to_s.sub('Stats','')
@started_at = DateTime.now
@active_users = User.active.count
@total_conversations = Conversation.count
end
def add(item)
(report && clear) unless active?
item_name = naming(item).pluralize
create_accessor(item_name)
eval "@#{item_name} += 1"
end
def report
SlackNotifier.new(self.class).call do
"#{@report_type} report started at #{@started_at}\n" +
attr_messages.inject(&:+)
end
end
def to_json
to_hash.to_json
end
private
def clear
reporting_vars.each do |var|
eval "#{var} = 0"
end
initialize
end
def active?
DateTime.now < expires_at
end
def naming(item)
return item.gsub(' ', '_') if item.kind_of? String
item.class.to_s.downcase
end
def create_accessor(name)
class_eval "attr_accessor :#{name}"
eval "@#{name} ||= 0"
end
def attr_messages
reporting_vars.map do |var|
"#{var}: #{eval var.to_s}\n"
end
end
def reporting_vars
instance_variables - [:@report_type, :@started_at]
end
def expires_at
@started_at
end
def to_hash
Hash[ *reporting_vars.collect { |v| [ v.to_s, (eval v.to_s) ] }.flatten ]
end
end
class HourlyStats < Stats
def expires_at
@started_at + 1.hour
end
end
class DailyStats < Stats
def expires_at
@started_at + 1.day
end
end
class WeeklyStats < Stats
def expires_at
@started_at + 1.week
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment