Skip to content

Instantly share code, notes, and snippets.

@aviflombaum
Created March 28, 2020 22:42
Show Gist options
  • Save aviflombaum/457db13d95df688d9e5ba8ff974c42fa to your computer and use it in GitHub Desktop.
Save aviflombaum/457db13d95df688d9e5ba8ff974c42fa to your computer and use it in GitHub Desktop.
class PostsController
def create
@post = Post.new
@post.title = params[:title]
@post.save
redirect "/posts/#{@post.id}" # The show action below.
end
def show
# What is @post in the context of this action
# 1. <#Post> - the same one created by #create
# 2. Nothing.
end
# Because we call render view after the main controller action
# is triggered, self is the instance of the controller, thus
# we can get access to the instances instance variables when
# rendering the template
def render_view
ERB.new("Hello #{self.instance_variable_get(:@post).name}")
end
end
# Imagine someone submits a POST request to your App at "/posts"
# Inside Sinatra/Rack/Rails, Imagine some code like this:
request = HTTPRequest.new(:post, "/posts")
# So now we have the raw HTTP Request.
# We want that to be handled by PostsController#create
# This will be our response
response = PostsController.new
if request.path "/posts" && request.method == :post
# Pass the request to the instance of the PostsController
# that will handle the request.
html = response.create(request).render_view
# After calling that we have the HTML
# and we send it back to the request object
# ending the request cycle.
request.respond_with(html)
elsif request.path.match(/posts\/+d/) && request.method == :get
html = response.show(request).render_view
request.respond_with(html)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment