Helper

2016-01-05  本文已影响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

``

上一篇下一篇

猜你喜欢

热点阅读