4. models/post.rb
class Post < ActiveRecord::Base
def image_url
if self.image.present?
self.image.url
else
‘default.png’
end
end
end
app/views/posts/show.slim
= image_tag @post.image_url
model?
5. models/post.rb
class Post < ActiveRecord::Base
def image_url
if self.image.present?
self.image.url
else
‘default.png’
end
end
end
app/views/posts/show.slim
= image_tag @post.image_url
View用のメソッドが
Modelに入っている
キモい
model?
7. models/post.rb
class Post < ActiveRecord::Base
end
app/controllers/posts_controller.rb
SampleProject::App.controllers :posts do
get :show, with: :id do
post = Post.find(params[:id])
@post_decorator = PostDecorator.new(post)
render ‘posts/show’
end
end
app/views/posts/show.slim
- if @post_decorator.is_new_page?
= image_tag @post_decorator.image
app/decorators/posts_decorator.rb
class PostDecorator
attr_reader :post
def initialize(post)
@post = post
end
def image_url
if self.image.present?
self.image.url
else
‘default.png’
end
end
end
表示用のロジックを Decorator に移す
11. $ padrino g decorator
Usage:
padrino-gen decorator [name]
Options:
-r, [--root=ROOT] # The root destination
# Default: .
-a, [--app=APP] # The application destination path
# Default: /app
-d, [--destroy]
-n, [--namespace=NAMESPACE] # The name space of your padrino project
Description:
padrino-gen decorator generates a new Padrino decorator
つかいかた