Skip to content

Instantly share code, notes, and snippets.

@AlxGolubev
Last active December 13, 2022 19:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlxGolubev/b30af07fe3a0add200d1c693ac64133f to your computer and use it in GitHub Desktop.
Save AlxGolubev/b30af07fe3a0add200d1c693ac64133f to your computer and use it in GitHub Desktop.
module Resource
def connection(routes)
if routes.nil?
puts "No route matches for #{self}"
return
end
loop do
print 'Choose verb to interact with resources (GET/POST/PUT/DELETE) / q to exit: '
verb = gets.chomp
break if verb == 'q'
action = nil
if verb == 'GET'
print 'Choose action (index/show) / q to exit: '
action = gets.chomp
break if action == 'q'
end
action.nil? ? routes[verb].call : routes[verb][action].call
end
end
end
class PostsController
extend Resource
def initialize
@posts = []
end
def index
puts 'index'
end
def show
puts 'show'
end
def create
puts 'create'
end
def update
puts 'update'
end
def destroy
puts 'destroy'
end
end
class Router
def initialize
@routes = {}
end
def init
resources(PostsController, 'posts')
loop do
print 'Choose resource you want to interact (1 - Posts, 2 - Comments, q - Exit): '
choise = gets.chomp
PostsController.connection(@routes['posts']) if choise == '1'
break if choise == 'q'
end
puts 'Good bye!'
end
def resources(klass, keyword)
controller = klass.new
@routes[keyword] = {
'GET' => {
'index' => controller.method(:index),
'show' => controller.method(:show)
},
'POST' => controller.method(:create),
'PUT' => controller.method(:update),
'DELETE' => controller.method(:destroy)
}
end
end
router = Router.new
router.init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment