Skip to content

Instantly share code, notes, and snippets.

@adamgotterer
Last active July 26, 2016 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamgotterer/88f21ee7c01114ffe47e to your computer and use it in GitHub Desktop.
Save adamgotterer/88f21ee7c01114ffe47e to your computer and use it in GitHub Desktop.
Endpoint DSL example
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