class Lita::Handlers::ImgflipMemes

Constants

API_URL

Public Class Methods

add_meme(template_id:, pattern:, help:) click to toggle source

START:rest

# File lib/lita/handlers/imgflip_memes.rb, line 80
def self.add_meme(template_id:, pattern:, help:)
  @@_templates << { template_id: template_id, pattern: pattern,
                    help: help }
  raise(ImgflipApiError, parsed['error_message']) if parsed.keys.include?('error_message')
  image = parsed.fetch('data', {}).fetch('url')
end
registered_templates() click to toggle source
# File lib/lita/handlers/imgflip_memes.rb, line 97
def self.registered_templates
  @@_templates
end

Public Instance Methods

extract_meme_text(match_data) click to toggle source

START:etl

# File lib/lita/handlers/imgflip_memes.rb, line 36
def extract_meme_text(match_data)
  _, line1, line2 = match_data.to_a
  return line1, line2
end
find_template(pattern) click to toggle source
# File lib/lita/handlers/imgflip_memes.rb, line 41
def find_template(pattern)
  templates = registered_templates.select do |t|
    t.fetch(:pattern) == pattern
  end
  template = templates.first

  template = registered_templates.select { |t| t.fetch(:pattern) == pattern }.first
  raise ArgumentError if template.nil?
  return template
end
make_meme(message) click to toggle source

START:make_meme

# File lib/lita/handlers/imgflip_memes.rb, line 19
def make_meme(message)
  line1, line2 = extract_meme_text(message.match_data)

  template = find_template(message.pattern)

  begin
    image = pull_image(template.fetch(:template_id), line1, line2)
  rescue ConnectionError, ImgflipApiError => err
    Lita.logger.error(err.message)
    return message.reply 'Bummer - can\'t connect to Imgflip.'
  end

  message.reply image
end
pull_image(template_id, line1, line2) click to toggle source
# File lib/lita/handlers/imgflip_memes.rb, line 52
def pull_image(template_id, line1, line2)
  username = config.api_user
  password = config.api_password

  begin
    result = http.post API_URL, { 
      template_id: template_id,
      username: username,
      password: password,
      text0: line1,
      text1: line2
    } 
  rescue Faraday::Error => err
    raise ConnectionError, err.message
  end

  # clean me up
  parsed = JSON.parse(result.body)

  if parsed.keys.include?('error_message')
    raise(ImgflipApiError, parsed['error_message'])
  end

  parsed.fetch('data', {}).fetch('url')
end
registered_templates() click to toggle source
# File lib/lita/handlers/imgflip_memes.rb, line 93
def registered_templates
  self.class.registered_templates
end