Helper

作者: 臻有一扑 | 来源:发表于2016-01-05 21:28 被阅读19次

    Helper

    What

    ActionController::Helpers

    Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.

    Advantages

    1. Extract some complexity out of the view

    2. Make view logic easier to test

    Move complexity out of the view

    把一些复杂的逻辑从view层中抽出来,放在controller里面:

    
    <% if @user && @user.email.present? %>
    
    <%= @user.email %>
    
    <% end %>
    
    

    完全可以在controller里面这样:

    
    #site_helper.rb
    
    module SiteHelper
    
    def user_email(user)
    
    user.email if user && user.email.present?
    
    end
    
    end
    
    #user_controller.rb
    
    class UserController
    
    helper SiteHelper
    
    end
    
    

    有一个method很近似,那就是helper_method

    下面来看他们两的区别

    helper vs helper_method

    helper_method可以把controller中的method share给view

    helper则是把整个Hepler 引入到view中,相当于:

    ``

    include_all_helpers

    ``

    相关文章

      网友评论

          本文标题:Helper

          本文链接:https://www.haomeiwen.com/subject/ibyzhttx.html