Last active
December 13, 2022 19:22
-
-
Save AlxGolubev/b30af07fe3a0add200d1c693ac64133f to your computer and use it in GitHub Desktop.
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 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