Last active
July 26, 2016 22:05
-
-
Save adamgotterer/88f21ee7c01114ffe47e to your computer and use it in GitHub Desktop.
Endpoint DSL example
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
module DSL | |
# We put our DSL syntax (methods) in a separate module (ClassMethods) because it | |
# will be converted to class methods once a class includes it. | |
module ClassMethods | |
attr_reader :routes | |
##### SUPPORTED DSL SYNTAX | |
def get(uri, &block) | |
save_route(:get, uri, block) | |
end | |
def post(uri, &block) | |
save_route(:post, uri, block) | |
end | |
##### END DSL METHODS | |
# A private helper method that is only available to these two methods | |
private | |
def save_route(http_method, uri, block) | |
@routes[http_method][uri] = block | |
end | |
end | |
end | |
module DSL | |
module ClassMethods | |
... | |
end | |
# This method will be automatically executed anytime a class includes the DSL module | |
def self.included(base) | |
# Our DSL methods which are in the ClassMethods module will be | |
# extended as class methods to the base class once mixed in | |
base.send :extend, ClassMethods | |
# Declare a class variable in the base class for us to store our routes. If this was a class | |
# variable in the DSL module every class mixing it in would end up sharing the same routes | |
base.class_eval do | |
@routes = { get: {}, post: {} } | |
end | |
end | |
end | |
module DSL | |
module ClassMethods | |
... | |
end | |
def self.included(base) | |
... | |
end | |
# List all the routes | |
def routes | |
self.class.routes | |
end | |
def execute_route(http_method, uri, params = nil) | |
block = self.class.routes[http_method][uri] | |
# Execute our method in the context of the instance class so we have access | |
# to variables and local methods | |
instance_exec(params, &block) | |
end | |
end | |
class UsersEndpoint | |
include DSL | |
def initialize | |
# An array to store users in | |
@users = [] | |
end | |
# Endpoint to list all users | |
get '/users' do | |
@users | |
end | |
# Endpoint to create a new user | |
post '/users' do |id: nil, name: nil| | |
create_user(id, name) | |
end | |
private | |
def create_user(id, name) | |
@users << { id: id, name: name } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment