Controller Flashcards
What is rails middleware?
Rails middleware allows you to catch request or response before it reaches Rails, and modify it. ( You are in the middle between Rack and Rails).
How to add and include your custom middleware?
create app/middlewares/sample.rb
class Sample def initialize app @app = app end
def call env puts "Middleware called"
@app.call(env) end end
and include config/environments/development.rb
config.middleware.use Sample
How to render a concrete template?
template path app/views/my_examples/sample.html.erb
def new
render ‘my_examples/sample’
end
How to use a redirect?
redirect_to ‘/animals/new’
What are the differences between render and redirect?
1) redirect is a new request, but render just draw the html
Can you tell me 6 ways to render a concrete template?
# inside Product controller render '/products/index.html.erb' render 'products/index.html.erb' render 'products/index.html' render 'products/index' render 'index' render :index
How to render partial?
# app/views/my_examples/_partial.html.erb render partial: '/my_examples/partial'
What path returns the following code “render @animal” ?
# AnimalsController app/views/animals/_animal.html.haml
How to render json/xml/text/body/ruby_code/js/html in controller? ( 7 options )
- render json: {a: 1}
- render xml: {a: 1}
- render plain: “Hello” # text
- render body: ‘AAA’
- render html: “<h1> dad </h1>“.html_safe
- render inline: “#{1 + 1}” # ruby
- render js: “alert(‘h’)”
How to add a new helper and use it inside the controller?
# app/helpers/sample_helper.rb module SampleHelper def hello p 'Hello' end end
inside contoller method
def new
helpers.hello
end
How to return nothing? Just a status?
head :ok
How to change layout? Or turn off layout?
# app/views/layouts/application.html.erb render layout: 'sample' # turn off render layout: false
How to change the response status?
render status: 401
How to redirect and send a flash message?
redirect_to ‘/animals/new’, notice: ‘hello’
#
How to add your own flash name for redirection?
class ApplicationController < ActionController::Base add_flash_types :my_notice end
redirect_to ‘/animals/new’, my_notice: ‘hello’
#