【译】把代码移到Helper中

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/26-move-code-into-helper

根据MVC的架构原理,在视图中不应该有逻辑代码, 在这个例子中, 我将介绍怎样把代码移到Helper中

丑陋的...

<%= select_tag :state, options_for_select( [[t(:draft), "draft"],
                                [t(:published), "published"]],
                               params[:default_state] ) %>

这是视图中的一个复杂的状态选择项, 让我们把它移到helper里去

重构...

<%= select_tag :state, options_for_post_state(params[:default_state]) %>

# app/helpers/posts_helper.rb
def options_for_post_state(default_state)
  options_for_select( [[t(:draft), "draft"], [t(:published), "published"]],
          default_state )
end

现在视图代码干净多了, 我们只要在需要的地方调用helper方法就可以了

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top