class Lita::Handlers::Zerocater

Public Instance Methods

alias(response) click to toggle source

rubocop:enable Metrics/MethodLength

# File lib/lita/handlers/zerocater.rb, line 45
def alias(response)
  config.locations.each_key do |location|
    response.reply(fetch_menu(location, Date.today))
  end
end
menu(response) click to toggle source

rubocop:disable Metrics/MethodLength

Private Instance Methods

append_icons(item) click to toggle source

append emoji icons based on item labels

# File lib/lita/handlers/zerocater.rb, line 97
def append_icons(item)
  labels = get_label_icons(item)
  # if it's vegan, it's necessarily vegetarian. Remove redundant icon.
  if labels.include?(ICONS['vegetarian']) &&
     labels.include?(ICONS['vegan'])
    labels.delete_at(labels.index(ICONS['vegetarian']))
  end
  labels.empty? ? item['name'] : item['name'] << ' | ' << labels.join(' ')
end
fetch_meal(id) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 53
def fetch_meal(id)
  JSON.parse(http.get("https://api.zerocater.com/v3/meals/#{id}").body)
end
fetch_meals(location) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 57
def fetch_meals(location)
  JSON.parse(
    http.get("https://api.zerocater.com/v3/companies/#{location}/meals")
    .body
  )
end
fetch_menu(location, search_date) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 64
def fetch_menu(location, search_date)
  cache_key = "#{location}_#{search_date}"
  return redis.get(cache_key) if redis.exists(cache_key)

  menu = render_menu(location, search_date)
  redis.set(cache_key, menu, ex: 300)

  menu
end
find_meals(meals, search_date) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 74
def find_meals(meals, search_date)
  results = []

  meals.each do |item|
    results << item['id'] if Time.at(item['time']).to_date == search_date
  end

  results
end
find_menu(location, search_date) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 84
def find_menu(location, search_date)
  results = find_meals(fetch_meals(location), search_date)
  meals = []

  results.each do |result|
    m = fetch_meal(result)
    meals << m
  end

  meals
end
get_label_icons(item) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 107
def get_label_icons(item)
  labels = item['labels'].select do |label, value|
    value['value'] == true && ICONS.key?(label)
  end
  labels.map { |label, _| ICONS[label] }
end
render_menu(location, search_date) click to toggle source
# File lib/lita/handlers/zerocater.rb, line 114
def render_menu(location, search_date)
  menu = find_menu(config.locations[location], search_date)
  return t('error.empty') if menu.empty?

  items = menu.map { |m| m['items'].map { |item| append_icons(item) } }
  render_template('menu',
                  menu: menu,
                  items: items,
                  locale: t('menu.locale', location: location))
rescue StandardError
  t('error.retrieve')
end