Skip to content

Instantly share code, notes, and snippets.

@aviflombaum
Created March 28, 2020 22:37
Show Gist options
  • Save aviflombaum/f131dfd2bc54626d610d54ef53cc0324 to your computer and use it in GitHub Desktop.
Save aviflombaum/f131dfd2bc54626d610d54ef53cc0324 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
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)
# 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)
request.respond_with(html)
end
# In order for @post to exist within both calls to #create and #show
# those methods would have to be called on the exact same instance of
# the response instance.
# However, how many requests are actually made? 1 or 2? If it's 2, wouldn't our
# server application have instantiated 2 instances of PostsController, 1 to
# handle each request? Thus the instance variables can't be shared between the
# methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment