`
CaiDeHen
  • 浏览: 90531 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

#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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics