Created
April 19, 2015 23:36
-
-
Save kylegrantlucas/7d1b0252b2f9060797c0 to your computer and use it in GitHub Desktop.
Metaprogrammed API Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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