#101 Refactoring Out Helper Object

If you have complex view logic, this can easily lead to helper methods which call each other. See how to refactor this out into another object in this episode.
# application_helper.rb
def render_stars(rating)
StarsRenderer.new(rating, self).render_stars
end

# helpers/stars_renderer.rb
class StarsRenderer
def initialize(rating, template)
@rating = rating
@template = template
end

def render_stars
content_tag :div, star_images, :class => 'stars'
end

private

def star_images
(0...5).map do |position|
star_image(((@rating-position)*2).round)
end.join
end

def star_image(value)
image_tag "/images/#{star_type(value)}_star.gif", :size => '15x15'
end

def star_type(value)
if value <= 0
'empty'
elsif value == 1
'half'
else
'full'
end
end

def method_missing(*args, &block)
@template.send(*args, &block)
end
發佈了108 篇原創文章 · 獲贊 0 · 訪問量 2930
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章