• Stars
    star
    106
  • Rank 325,871 (Top 7 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 14 years ago
  • Updated about 13 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Provides a fun interface to quickly build API libraries using Typhoeus.

monster_mash

  • Typhoeus is an ancient monster.
  • A monster mash is a dance party.
  • This library inspired by John Nunemaker's awesomely useful HTTParty.
  • By law, all Ruby libraries have to have dumbass names.

This library wraps Typhoeus and Typhoeus::Hydra and exposes an easy-to-use DSL for quickly building libraries to interact with HTTP resources. Every method you write will automatically export serial (blocking) and parallel (non-blocking) methods, so you can easily parallelize your HTTP code when possible.

Writing a method

monster_mash has a Sinatra-like syntax, and lets you build client API methods using the 4 HTTP verbs:

  • get(method_name, &definition_block)
  • post(method_name, &definition_block)
  • put(method_name, &definition_block)
  • delete(method_name, &definition_block)

Within each definition_block, you can set various Typhoeus options.

  • uri (required) - the URI to hit
  • handler (required) - a block to handle an HTTP response
  • params - hash of URI params
  • body - post body
  • headers - hash of HTTP headers to send
  • timeout - how long to timeout
  • cache_timeout - how long to keep HTTP calls cached
  • user_agent - a User-Agent string to send
  • max_redirects - max number of redirects to follow
  • disable_ssl_peer_verification - whether to disable SSL verification

Example: Google JSON search

class GoogleJson < MonsterMash::Base
  VERSION = '1.0'

  # Creates a method called +search+ that takes
  # a single +query+ parameter.
  get(:search) do |query|
    uri "http://ajax.googleapis.com/ajax/services/search/web"
    params 'v' => VERSION,
           'q' => query,
           'rsz' => 'large'
    handler do |response|
      json = JSON.parse(response.body)

      # returns results
      json['responseData']['results']
    end
  end
end

To make serial (blocking) calls using this code, you would then call the class method:

# blocks
results = GoogleJson.search("my search query")
results.each do |result|
  puts result['unescapedUrl']
  # do other stuff with the response
end

The search(query) method returns whatever your handler block returns.

To make parallel (non-blocking) calls, you need an instance of Typhoeus::Hydra:

hydra = Typhoeus::Hydra.new
google = GoogleJson.new(hydra)
10.times do
  google.search("my query") do |results, error|
    if error
      # handle error
    else
      results.each do |result|
        puts result['unescapedUrl']
      end
    end
  end
end

# blocks until all 10 queries complete.
hydra.run

Calling helper methods from a handler block

monster_mash will correctly delegate method calls from your handler block to your API class. Example:

class GoogleJson < MonsterMash::Base
  VERSION = '1.0'

  # Creates a method called +search+ that takes
  # a single +query+ parameter.
  get(:search) do |query|
    uri "http://ajax.googleapis.com/ajax/services/search/web"
    params 'v' => VERSION,
           'q' => query,
           'rsz' => 'large'
    handler do |response|
      json = JSON.parse(response.body)

      # Calls the correct method on GoogleJson.
      parse_results(json)
    end
  end

  def self.parse_results(json)
    json['responseData']['results']
  end
end

Setting defaults

If you have Typhoeus settings you want to happen for every request, you can set them in a defaults block:

class GoogleJson < MonsterMash::Base
  defaults do
    user_agent "GoogleJson Ruby Library"
    disable_ssl_peer_verification true
  end

  # ...
end

If all of your requests share a common base URI, you can set that in your defaults block:

class GoogleJson < MonsterMash::Base
  defaults do
    base_uri "http://google.com"
  end

  get(:search) do
    uri "/search" # expands to http://google.com/search
  end

  post(:authenticate) do
    uri "https://auth.google.com" # ignores the base_uri
  end
end

As well, if you set params or headers in the defaults block, any params or headers added later will be merged into the hash.

class GoogleJson < MonsterMash::Base
  defaults do
    params 'api_key' => 'fdas'
  end

  # The full params hash will look like:
  #   :q => +query+,
  #   :v => '1.0',
  #   :api_key => 'fdas'
  get(:search) do |query|
    params 'q' => query,
           'v' => '1.0'
    uri "..."
    handler do |response|
      # ...
    end
  end
end

Error Handling

  • All serial (blocking) methods will simply raise an error if anything wrong happens. You just need to rescue said error.
  • When interacting with Hydra requests, the block you pass to it will receive an error to it if any error was caught during the handler's run. You need to check for the error in your block and handle it there.

Example Projects using monster_mash

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Copyright

Copyright (c) 2010 David Balatero. See LICENSE for details.

More Repositories

1

VimMode.spoon

Adds vim keybindings to all OS X inputs
Lua
600
star
2

dotfiles

πŸ’»dotfiles for: tmux, neovim, git, zsh, osx
Shell
57
star
3

capybara-chromedriver-logger

Enables console.log/error/info output from Javascript feature specs running with Chromedriver
Ruby
54
star
4

lingua

This is a GitHub hosted version of the Ruby lingua library.
Ruby
38
star
5

SkyRocket.spoon

Resize and move windows using the mouse and modifier keys. A Hammerspoon clone of Zooom/2 functionality.
Lua
38
star
6

cypress-plugin-stripe-elements

A small Cypress plugin that assists you in filling in Stripe Elements inputs
JavaScript
34
star
7

alchemy_api

Provides a client API library for AlchemyAPI's awesome NLP services. Allows you to make parallel or serial requests.
Ruby
31
star
8

musician_analytics

Provides tools for programmer/musicians to quickly collect stats about their band.
Ruby
21
star
9

evri_rpx

This is an API wrapper for the RPXNow.com login service (canonical repo).
Ruby
20
star
10

work-cli

Awesome command line tools for managing the lifecycle of Github pull requests.
Shell
18
star
11

HyperKey.spoon

This library allows you to bind keys to a modifier, and shows you a popup overlay of all your key binds when you hold down the modifier key.
Lua
18
star
12

light-phone-sms-gateway

A basic SMS gateway that a Light Phone 2 can text useful commands to and get responses!
Ruby
14
star
13

cirklon

Instrument definitions for the Sequentix Cirklon
Shell
10
star
14

horse

Ruby
7
star
15

signal-native

Builds a wrapped native Signal client for Mac 64-bit
JavaScript
7
star
16

musician_analytics_app

App for collecting band stats, designed to push to Heroku.
Ruby
6
star
17

queue_stick

This library allows you to write the minimal amount of code to process queue messages. Supports SQS out of the box, but it's trivial to support other queues.
Ruby
6
star
18

mac-vim-mode

Quick installer for adding Vim motions/operators to every input in OS X
Shell
5
star
19

signed_request

A simple gem that allows you to sign HTTP requests between two parties with a shared secret key.
Ruby
5
star
20

transcriptions

WHERE THE TABZ AT?!?!
4
star
21

GoogleDocsCodePaste.spoon

Hammerspoon plugin to paste syntax highlighted code into Google Docs
Lua
4
star
22

pitchspork

Right on, brotha.
3
star
23

drinking_games

Various executable drinking games.
3
star
24

uwrake

Ruby UW extension implementation of Rake
Ruby
3
star
25

uwweek5

Week 5 homework
Ruby
2
star
26

deadlinez

Makes it easy to handle After the Deadline AJAX proxying and their API.
Ruby
2
star
27

hubot-poplife

CoffeeScript
2
star
28

simple_client

Simple tcp server/client
Ruby
2
star
29

html5-metronome

A quick and dirty html5 metronome.
2
star
30

uw_log_processor

Week 4 homework for Advanced Ruby
2
star
31

fixiebotbot

Retweets fixiebot.
2
star
32

audioinfo

Quick repo for playing around with synths + MIDI.
C++
2
star
33

typhoeus_spec_cache

A plugin to help you dynamically manage HTTP caching for your specs.
Ruby
2
star
34

resume

Ohwillie's resume, not yours! Will not respond to pull requests (unless they're really good)
Ruby
1
star
35

yarr

Yarr finds album art quickly and politely and is your friend to extend.
Ruby
1
star
36

typescript-interview

JavaScript
1
star
37

fpswax

A library for interfacing with Amazon FPS, without any "cleverness".
Ruby
1
star
38

patchbay

JavaScript
1
star
39

bald-eagle-chef

The Bald Eagle Chef game.
1
star
40

opid-rotation

the op id rotations
Ruby
1
star
41

poser

A Ruby gem to assist working with the POS-IM point-of-sale system.
Ruby
1
star
42

upswax

UPS shipping wrappers.
Ruby
1
star
43

try_git

1
star
44

aid

Ruby
1
star
45

vim_fu

Vim exercises for Vim-fu.
1
star
46

kexp

A KEXP stats crawler.
Ruby
1
star
47

sqswax

An up-to-date (API version 2009-02-01) implementation of Amazon SQS.
Ruby
1
star
48

Ethan-Test

1
star