[
  {
    "path": ".gitignore",
    "content": "/.bundle/\n/.yardoc\n/Gemfile.lock\n/_yardoc/\n/coverage/\n/doc/\n/pkg/\n/spec/reports/\n/tmp/\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.\n\nWe are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.\n\nExamples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.\n\nThis Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)\n"
  },
  {
    "path": "Gemfile",
    "content": "source 'https://rubygems.org'\n\n# Specify your gem's dependencies in slackiq.gemspec\ngemspec"
  },
  {
    "path": "LICENSE.txt",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 Jason Lew\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Slackiq \n[![Gem Version](https://badge.fury.io/rb/slackiq.svg)](http://badge.fury.io/rb/slackiq)\n\nSlackiq (pronounced *slack-kick*) integrates [Slack](https://slack.com/) and [Sidekiq](http://sidekiq.org) so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack.\n\n![demo](http://i.imgur.com/4NLq2rP.gif)\n\n## Installation\n\nAdd this line to your Gemfile:\n\n```ruby\ngem 'slackiq'\n```\n\nThen run:\n\n```\nbundle install\n```\n\n## Configuration\n\nFirst, set up any number of Slack Incoming Webhooks [from your Slack](https://slack.com/services/new/incoming-webhook).\n\nThen, you only need to call the `configure` method when your application launches to configure all of the webhooks to which you want to post. If you're using Rails, create an initializer at `config/initializers/slackiq.rb`. Here's an example:\n\n```ruby\nSlackiq.configure( web_scrapes: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/lknsaHHA2323KKDKND', \n                   data_processing: 'https://hooks.slack.com/services/HA298HF2/ALSKF2451/H24dLKAHD22423')\n```\n\n`:web_scrapes` and `data_processing` are examples of keys. Use whatever keys you want.\n\n## Usage\n\nYou can call `notify` to send a nicely-formatted notification to your Slack. You can call `notify`\n\n* Inside the Sidekiq Pro `on_success` or `on_complete` callback (not available on regular Sidekiq--only Pro)\n* From inside a Sidekiq worker while it's running, in which case you should pass in the `bid` to the `perform` method of the worker\n\nThe `notify` method has a single Hash parameter. Here are the keys and values in the Hash:\n* `:webhook_name` The name of the webhook (Symbol) that you configured (eg. `:web_scrapes` or `:data_processing`)\n* `:title` The title of the notification (String)\n* `:status` An instance of `Sidekiq::Batch::Status`\n* Any other keys and values (both Strings) can be added too, and they'll be added to the Slack notification!\n\nIf you haven't used batches with Sidekiq Pro before, [read this first](https://github.com/mperham/sidekiq/wiki/Batches).\n\nHere's an example showing how you would use Slackiq to send a notification to your Slack when your Sidekiq batch completes:\n\n```ruby\nclass WebScraper\n  \n  class << self\n  \n    # Scrape the first 100 URLs in the database\n    def scrape_100\n      batch = Sidekiq::Batch.new\n      batch.description = 'Scrape the first 100 URLs!' \n      batch.on(:complete, self)\n      \n      batch.jobs do\n        \n      urls = Url.limit(100) # Url is a Rails model in this case\n      \n      urls.each do |url|\n        ScraperWorker.perform_async(url.id)\n      end\n    end\n  \n  end\n  \n  def on_complete(status, options)\n    Slackiq.notify(webhook_name: :web_scrapes, status: status, title: 'Scrape Completed!', \n    'Total URLs in DB' => URL.count.to_s, \n    'Servers' => \"#{Server.active_count} active, #{Server.inactive_count} inactive\")\n  end\n  \nend\n```\n\nNote that in this case, `'Total URLs in DB'` and `'Servers'` are custom fields that will also appear in Slack!\n\n### Want to send a message to Slack that isn't Sidekiq-related?\n\nNo prob. Just: \n\n```ruby\nSlackiq.message('Server 5 is overloaded!', webhook_name: :data_processing)\n```\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/MightySignal/slackiq. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.\n\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n\n## Blog Post about Slackiq\n\nhttps://blog.mightysignal.com/slackiq-a-ruby-gem-that-connects-slack-and-sidekiq-a2308c1974b7\n\n## More Open Source Projects\n\n* [Slacktivity](https://github.com/MightySignal/slacktivity)\n\n"
  },
  {
    "path": "Rakefile",
    "content": "require \"bundler/gem_tasks\"\n\ntask :console do\n  exec \"irb -r slackiq -I ./lib\"\nend\n\ntask c: :console"
  },
  {
    "path": "bin/console",
    "content": "#!/usr/bin/env ruby\n\nrequire \"bundler/setup\"\nrequire \"slackiq\"\n\n# You can add fixtures and/or initialization code here to make experimenting\n# with your gem easier. You can also use a different console, if you like.\n\n# (If you use this, don't forget to add pry to your Gemfile!)\n# require \"pry\"\n# Pry.start\n\nrequire \"irb\"\nIRB.start\n"
  },
  {
    "path": "bin/setup",
    "content": "#!/bin/bash\nset -euo pipefail\nIFS=$'\\n\\t'\n\nbundle install\n\n# Do any other automated setup that you need to do here\n"
  },
  {
    "path": "lib/slackiq/time_helper.rb",
    "content": "require 'date'\n\nmodule Slackiq\n  module TimeHelper\n\n    class << self\n    \n      def elapsed_time_humanized(t0, t1)\n        humanize(elapsed_seconds(t0, t1))\n      end\n  \n      def elapsed_seconds(t0, t1)\n        dt0 = t0.to_datetime\n        dt1 = t1.to_datetime\n        ((dt1-dt0)*24*60*60).to_i\n      end\n  \n      # http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails\n      def humanize(secs)\n        [[60, :s], [60, :m], [24, :h], [1000, :d]].map{ |count, name|\n          if secs > 0\n            secs, n = secs.divmod(count)\n            \"#{n.to_i}#{name}\"\n          end\n        }.compact.reverse.join(' ')\n      end\n      \n      def format(time)\n        time.strftime('%D @ %r').gsub('PM', 'pm').gsub('AM', 'am')\n      end\n  \n    \n    end\n    \n  end\nend\n\n\n\n"
  },
  {
    "path": "lib/slackiq/version.rb",
    "content": "module Slackiq\n  VERSION = \"1.1.4\"\nend\n"
  },
  {
    "path": "lib/slackiq.rb",
    "content": "require 'slackiq/version'\n\nrequire 'net/http'\nrequire 'json'\nrequire 'httparty'\n\nrequire 'slackiq/time_helper'\n\nrequire 'active_support' #for Hash#except\n\nmodule Slackiq\n  \n  class << self\n    \n    # Configure all of the webhook URLs you're going to use\n    # @author Jason Lew\n    def configure(webhook_urls={})\n      raise 'Argument must be a Hash' unless webhook_urls.class == Hash\n      @@webhook_urls = webhook_urls\n    end\n    \n    # Send a notification to Slack with Sidekiq info about the batch\n    # @author Jason Lew\n    def notify(options={})  \n      url = @@webhook_urls[options[:webhook_name]]\n      title = options[:title]\n      #description = options[:description]\n      status = options[:status]\n      \n      if (bid = options[:bid]) && status.nil?\n        raise \"Sidekiq::Batch::Status is not defined. Are you sure Sidekiq Pro is set up correctly?\" unless defined?(Sidekiq::Batch::Status)\n        \n        status = Sidekiq::Batch::Status.new(bid)\n      end\n      \n      extra_fields = options.except(:webhook_name, :title, :description, :status)\n\n      fields = []\n      \n      if status\n        created_at = status.created_at\n      \n        if created_at\n          time_now = Time.now\n          duration = Slackiq::TimeHelper.elapsed_time_humanized(created_at, time_now)\n          time_now_title = (status.complete? ? 'Completed' : 'Now')\n        end\n      \n        total_jobs = status.total\n        failures = status.failures\n        jobs_run = total_jobs - status.pending\n\n        completion_percentage = (jobs_run/total_jobs.to_f)*100\n        failure_percentage = (failures/total_jobs.to_f)*100 if total_jobs && failures\n\n        # round to two decimal places\n        decimal_places = 2\n        completion_percentage = completion_percentage.round(decimal_places)\n        failure_percentage = failure_percentage.round(decimal_places)\n        \n        description = status.description\n\n        fields += [\n                    {\n                      'title' => 'Created',\n                      'value' => Slackiq::TimeHelper.format(created_at),\n                      'short' => true\n                    },\n                    {\n                      'title' => time_now_title,\n                      'value' => Slackiq::TimeHelper.format(time_now),\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Duration\",\n                      'value' => duration,\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Total Jobs\",\n                      'value' => total_jobs,\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Jobs Run\",\n                      'value' => jobs_run,\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Completion %\",\n                      'value' => \"#{completion_percentage}%\",\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Failures\",\n                      'value' => status.failures,\n                      'short' => true\n                    },\n                    {\n                      'title' => \"Failure %\",\n                      'value' => \"#{failure_percentage}%\",\n                      'short' => true\n                    },\n                  ]\n      end\n      \n      \n      \n      # add extra fields\n      fields += extra_fields.map do |title, value|\n        {\n          'title' => title,\n          'value' => value,\n          'short' => false\n        }\n      end\n                \n      attachments = \n      [\n        {\n          'fallback' => title,\n\n          'color' => '#00ff66',\n\n          'title' => title,\n\n          'text' => description,\n\n          'fields' => fields,\n        }\n    ]\n    \n      body = {attachments: attachments}.to_json\n      \n      HTTParty.post(url, body: body)\n    end\n\n    # Send a notification without Sidekiq batch info\n    # @author Jason Lew\n    def message(text, options)\n      url = @@webhook_urls[options[:webhook_name]]\n\n      body = { 'text' => text }.to_json\n      \n      HTTParty.post(url, body: body)\n    end\n    \n  end\n  \nend"
  },
  {
    "path": "slackiq.gemspec",
    "content": "# coding: utf-8\nlib = File.expand_path('../lib', __FILE__)\n$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)\nrequire 'slackiq/version'\n\nGem::Specification.new do |spec|\n  spec.name          = \"slackiq\"\n  spec.version       = Slackiq::VERSION\n  spec.authors       = ['Jason Lew']\n  spec.email         = ['jason@mightysignal.com']\n  spec.summary       = 'MightySignal: Slack and Sidekiq Pro integration'\n  spec.description   = \"Slackiq (by MightySignal) integrates Slack and Sidekiq so that you can have vital information about your Sidekiq jobs sent directly to your team's Slack.\"\n  spec.homepage      = 'https://github.com/MightySignal/slackiq'\n  spec.license       = 'MIT'\n\n  spec.files         = `git ls-files -z`.split(\"\\x0\").reject { |f| f.match(%r{^(test|spec|features)/}) }\n  spec.bindir        = \"exe\"\n  spec.executables   = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }\n  spec.require_paths = [\"lib\"]\n\n  spec.add_dependency 'httparty'\n\n  spec.add_development_dependency \"bundler\", \"~> 1.10\"\n  spec.add_development_dependency \"rake\", \"~> 10.0\"\nend\n"
  }
]