-
Notifications
You must be signed in to change notification settings - Fork 0
New APIs
Adding new APIs to Lyracyst is pretty straightforward. Consult gli's wiki to add commands, subcommands, and options to the cli folder.
Here's the Urban Dictionary command block as a simple example:
desc 'Fetches definitions from Urban Dictionary'
arg_name 'word'
command :urb do |c|
c.action do |global_options, options, args|
search = args[0]
ur = Lyracyst::Urban::Define.new
ur.get_def(search)
end
end
This gli command takes no flags or switches, it just passes the first argument to the Define class.
In the lyracyst folder create newcommand.rb (and if necessary, a newcommand subfolder and separate newsubcommand.rb files for each subcommand. Once again, here's the Urban class:
require 'httpi'
require 'multi_json'
module Lyracyst
# Urban Dictionary is a crowd-sourced dictionary that focuses on slang and colloquialisms.
class Urban
# Fetches URL.
#
# @param search [String] The word or phrase to search for.
# @param result [String] The search response.
def get_word(search, result)
prefix = 'http://api.urbandictionary.com/v0/define?term='
url = "#{prefix}#{search}"
request = HTTPI::Request.new(url)
getter = HTTPI.get(request)
result = getter.body
end
# Fetches definitions and examples from Urbandictionary.com.
class Define
# @param search [String] The word or phrase to search for.
def get_def(search)
label, result = 'Urban Dictionary', nil
ur = Lyracyst::Urban.new
result = ur.get_word(search, result)
result = MultiJson.load(result)
tags = result['tags']
rtype = result['result_type']
list = result['list']
Lyracyst.label(label)
print Rainbow("|Tags|#{tags}|Type|#{rtype}").bright
st = { 'searchterm' => search }
Lyracyst.tofile(st)
type = { 'type' => 'urban' }
tags = { 'tags' => tags }
rtype = { 'result type' => rtype }
Lyracyst.tofile(type)
Lyracyst.tofile(tags)
Lyracyst.tofile(rtype)
e = Lyracyst::Urban::Define.new
e.urban_extra(list)
end
# Extra reptetive tasks
#
# @param list [Array] List of hashes to process
def urban_extra(list)
x, y = 0, list.length - 1
while x <= y
obj = list[x]
author = obj['author']
link = obj['permalink']
defi = obj['definition']
ex = obj['example']
puts "|#{defi}|#{ex}|#{author}|#{link}"
author = { 'author' => author }
link = { 'link' => link }
defi = { 'definition' => defi }
ex = { 'example' => ex }
Lyracyst.tofile(defi)
Lyracyst.tofile(ex)
Lyracyst.tofile(author)
Lyracyst.tofile(link)
x += 1
end
end
end
end
end
The Lyracyst::Urban.get_word
method handles fetching the URL and returns the JSON result. The Lyracyst::Urban::Define.get_def
method runs the command logic. The Lyracyst.label
method prints an ANSI-colored label for each element, and the Lyracyst.tofile
method adds an element to the hash that is encoded as a JSON or XML outfile. Keeping each command set structured in this way allows you to easily consume just about any JSON or XML API.