Reducing boilerplate
This controller has a ton of boilerplate code that we can reduce into more concise code thatβs easier to follow and modify.
class PostsController < ApplicationController
layout false
before_action do
@blog = current_user.blog
@posts = @blog.posts
end
class View < Phlex::HTML
# Wraps the view with a layout
def around_template(&content)
super do
render Layouts::Post.new(title:)
end
end
end
class Index < View
def initialize(posts:)
@posts = posts
end
def template
h1 "Posts"
ul do
@posts.each do |post|
li do
a href: post_path(post), post.title
end
end
end
end
end
def index
render Index.new(posts: @posts)
end
# ...
end
π Unlock content
Pre-order this course to unlock this video, source code, and content. You'll also get to work with Brad to fine tune the course cirriculum.
Move layout false
to a base controller
ββββββ βββ ββββ ββ ββββ ββ ββββββ ββββββ βββββ ββ β ββββββββββββββββ ββ βββββββββ ββββββββββ βββββ βββββ ββ ββββ ββββββββββ ββββββββββ
class PhlexController < βββββββββββββββββββββ
ββββββ false
end
Implicit actions
βββ ββ βββ βββββ ββββββ βββββ βββ βββββ ββ βββ ββ ββββ βββββββββββ ββ ββββββ βββ βββββ ββββββ ββ βββ ββββββββββββββββββββββββββββββββ βββββ βββ βββ βββββββββ βββ ββ ββββ βββ ββ ββ βββββββββββ βββ βββββββ ββββ βββββββ ββ βββββββββββ
Variable assignment via attr_writer
methods.
βββββββββ βββββββ βββ βββββ βββββββββ ββ βββββββββββ ββ βββ ββββ βββ βββββββββββ βββββββ ββ βββββ βββββ βββββββ ββββ βββββββββββ βββββββββββ ββ βββββ βββ ββββ βββββββ βββ βββββββββ ββββββ ββ ββββββββ
Installation
βββ ββββββ βββ βββββββββ ββ βββββββ ββ ββ βββ βββββββ ββββ βββ ββββ ββ ββββ βββββ ββββββββ ββββ βββ βββ βββββββββ ββ ββββ ββββββββββββββββ
class PhlexController < βββββββββββββββββββββ
ββββββ false
include βββββββββ::βββββββ
end
Cleaning up the controller
βββββ ββββ ββββ ββ βββ βββββββββββββββ βββ βββββ ββββββ ββ β ββββ
class PostsController < βββββββββββββββ
β ββββββ βββ βββββββ ββββββ βββββββ
βββββββββββββ do
βββββ = ββββββββββββ.ββββ
ββββββ = βββββ.βββββ
end
class View < βββββ::ββββ
β ββββββ ββ βββ ββββ ββββ βββββ ββ ββ βββββ ββββ ββ βββββ ββ ββ βββββ ββββ
attr_writer :blog, :posts
def βββββββββββββββ(&βββββββ)
super do
ββββββ βββββββ::ββββ.βββ(βββββ:)
end
end
end
class Index < ββββ
β ββββββ βββ βββββββββββ βββββ βββ ββββ βββββ ββ βββ βββββββββββ βββββββ
def βββββ = "posts"
def ββββββββ
ββ do
ββββββ.ββββ do |ββββ|
ββ do
β href: βββββββββ(ββββ), ββββ.βββββ
end
end
end
end
end
β βββ
end