Quick overview of the decorator pattern, and the implementation of that pattern in Rails in the form of the gem Draper. Also, dinosaurs and lasers.
Decoratorsin Railsby Miles Z. Sterrett
View Slide
Get that HTMLout of yourmodel, you jerkby Miles Z. Sterrett
Dinosaurs,Lasers, and theDecoratorPatternby Miles Z. Sterrett
Wikipedia says:“In object-oriented programming, the decorator patternis a design pattern that allows behaviour to be added toan existing object dynamically.”
DraperView Models for Railshttps://github.com/jcasimir/draper
1 require File.join(Rails.root, 'lib', 'slug')2 class Job < ActiveRecord::Base3 include IndyHackers::Slug45 has_many :job_views6 has_many :viewers, :through => :job_views7 belongs_to :user89 after_update :notify_if_published1011 scope :published, lambda {12 where("jobs.published_at IS NOT NULL AND jobs.published_at<= ?", Time.zone.now)13 }1415 def notify_if_published16 if published_at_changed? && published_at.present? &&published_at <= Time.now17 SystemMailer.job_post_published(self.user, self).deliver18 else19 Rails.logger.info "OMG WTF BBQ"20 end21 end22 end
1 require File.join(Rails.root, 'lib', 'slug')2 class Job < ActiveRecord::Base3 include IndyHackers::Slug45 has_many :job_views6 has_many :viewers, :through => :job_views7 belongs_to :user89 after_update :notify_if_published1011 # ...1213 def pretty_job_date14 published_at.strftime("%B %d %h:%m%P")15 end1617 def viewers_total18 "#{viewers.size} People Have Viewed This Post"19 end20 end
1 .grid_10.prefix_12 %section.readable3 %article.job#single-job4 %h1= @job.title5 %p= @job.pretty_published_at6 %p= @job.viewers_total7 .job-description8 = MARKDOWN.render(@job.description).html_safe
1 class JobDecorator < ApplicationDecorator2 decorates :job34 def published_at5 # 'h' exposes Rails helpers w/i your decorator6 # 'model' exposes the actual object you're decorating7 h.l(model.published_at, :format => :murican_time)8 end910 def total_viewers11 "#{model.viewers.size} People Have Viewed This Post"12 end1314 def description_html15 MARKDOWN.render(model.description).html_safe16 end17 end
1 .grid_10.prefix_12 %section.readable3 %article.job#single-job4 %h1= @job.title5 %p= @job.published_at6 %p= @job.total_viewers7 .job-description8 = @job.description_html
12 class JobsController < ApplicationController3 def index4 @jobs = JobDecorator.decorate(Job.published)5 end67 def show8 @job = JobDecorator.find(params[:id])910 # or11 # @job = Job.find(params[:id]12 # @job = JobDecorator.new(@job)13 end14 end
Other Decorators• Active Presenter• Viewtastic• Delegate Presenter
La FinMiles Z. SterrettThe Guy, Nearsitedhttp://nearsited.nethttp://mileszs.com@mileszs