Skip to content

Instantly share code, notes, and snippets.

@kylegrantlucas
Created April 19, 2015 23:36
Show Gist options
  • Save kylegrantlucas/7d1b0252b2f9060797c0 to your computer and use it in GitHub Desktop.
Save kylegrantlucas/7d1b0252b2f9060797c0 to your computer and use it in GitHub Desktop.
Metaprogrammed API Class
class ApiName
include HTTParty
base_uri 'api_uri'
# List of endpoints to instantiate instance methods for
# format example: {users: :get, comments: [:get, :post, :delete]}
ENDPOINTS = {users: :get}
def initialize(api_key = nil, api_secret = nil, options = {})
@options = options.merge!({api_key: api_key, api_secret: api_secret})
# Metaprogramming that instantiates the methods needed to perform calls to
# the endpoints specified in the ENDPOINTS class constant hash.
# method sigatures follow the pattern of ex: get_users(options)
ENDPOINTS.each do |key, value|
value = [value] unless value.kind_of? Array
value.each do |request_type|
self.class.send(:define_method, "#{request_type}_#{key}".to_sym) do |options = {}|
@options.merge!(options)
return self.class.send(request_type, "/#{key.to_s.split('_').join}", @options).to_hash
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment