Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def change_plan
- account = Account.find(params[:id])
- old_plan = account.plan
- new_plan = Plan.find(params[:account][:plan_id])
- account.change_plan!(params[:account][:plan_id])
- SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver
- redirect_to action: "show", id: params[:id]
- end
- require 'net/http'
- class SlackService
- NAME_AND_ICON = {
- username: 'Dashboard',
- icon_emoji: ':bat:'
- }
- SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/###/###/###"
- SLACK_WEBHOOK_CHANNEL = Rails.env.production? ? "###" : "###"
- def initialize(channel = SLACK_WEBHOOK_CHANNEL)
- @uri = URI(SLACK_WEBHOOK_URL)
- @channel = channel
- end
- def plan_change(user, account, old_plan, new_plan)
- params = {
- attachments: [
- {
- author_name: "#{user.first_name} #{user.last_name}",
- text: "Account: #{account.name} (#{account.id})",
- title: 'Dashboard Plan Change',
- fields: [
- {
- title: 'Old Plan',
- value: "#{old_plan.name} (#{ActionController::Base.helpers.number_to_currency(old_plan.price)})",
- short: true
- },
- {
- title: 'New Plan',
- value: "#{new_plan.name} ($#{ActionController::Base.helpers.number_to_currency(new_plan.price)})",
- short: true
- },
- ]
- }
- ]
- }
- @params = generate_payload(params)
- self
- end
- def deliver
- begin
- Net::HTTP.post_form(@uri, @params)
- rescue => e
- Rails.logger.error("SlackService: Error when sending: #{e.message}")
- end
- end
- private
- def generate_payload(params)
- {
- payload: NAME_AND_ICON
- .merge(channel: @channel)
- .merge(params).to_json
- }
- end
- end
Add Comment
Please, Sign In to add comment