Clean up your rails controllers with presenters

Nice example about how to use controllers in #rails

class HomepageController < ApplicationController
def index
@popular_videos = Videos.order('views DESC').limit(30)
@recommended_videos = Videos.recommended_for(current_user)
@categories = Category.all
end
end
class Video < ActiveRecord::Base
# This can't go in a helper because it needs to be accessible from as_json
def thumbnail_url
"http://hardcoded.domain.com/images/vid_thumb_#{self.id}.jpg"
end
end
- @popular_videos.each do |video|
= link_to image_tag(@video.thumbnail_url), video_path(video)

and turn it into this:

class HomepageController < ApplicationController
def index
@presenter = HomepagePresenter.new(current_user)
end
end
class HomepagePresenter
attr_reader :popular_videos, :recommended_videos, :categories
def initialize(current_user)
@popular_videos = VideoDecorator.decorate(Videos.order('views DESC').limit(30))
@recommended_videos = VideoDecorator.decorate(Videos.recommended_for(current_user))
@categories = Category.all
end
end
class Video < ActiveRecord::Base
end
class VideoDecorator < ApplicationDecorator
def thumbnail_url
h.image_url("vid_thumb_#{model.id}.jpg")
end
end
- @presenter.popular_videos.each do |video|
= link_to image_tag(@video.thumbnail_url), video_path(video)

thanks to https://github.com/michaelfairley

Show your support

Clapping shows how much you appreciated phil’s story.