2016-02-12 57 views
1

而不是幾乎有兩個類似的自定義包裝定義,是否可以將它們烘乾?對於e.g:幹掉simple_form中的自定義包裝

config.wrappers :inline_checkbox, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b| 
    b.use :html5 
    b.wrapper :tag => 'div', :class => 'controls' do |ba| 
     ba.use :label_input, :wrap_with => { :class => 'checkbox inline' } 
     ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }   
    end 
    end 

config.wrappers :inline_checkbox_two, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b| 
    b.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' } 
    # everything else should use the same definition as the above 
    end 

回答

1

使用模塊擦乾:

module WrapperHelper 

    # options: 
    # - wrapper [Hash] 
    # - label_input [Hash] 
    # - error [Hash] 
    # - use [Array] an array of arguments to pass to b.use 
    def self.inline_checkbox(b, **kwargs) 
    if kwargs[:use] 
     b.use *kwargs[:use] 
    else 
     b.use :html5 
    end 
    wrapper_opts = { 
     tag: 'div', 
     class: 'control-group' 
     error_class: 'error' 
    }.merge(kwargs[:wrapper] || {}) # merge defaults with passed `wrapper` keyword argument 
    b.wrapper(wrapper_opts) do |ba| 
     ba.use :label_input, 
     { wrap_with: { class: 'checkbox inline' } }.merge(kwargs[:label_input] || {}) 
     ba.use :error, 
     { wrap_with: { tag: 'span', class: 'help-inline' } }.merge(kwargs[:error] || {}) 
    end 
    end 
end 

config.wrappers :html5_inline_checkbox do |b| 
    WrapperHelper.inline_checkbox(b) 
end 

config.wrappers :inline_checkbox_with_helper do |b| 
    WrapperHelper.inline_checkbox(b, use: [:hint, {wrap_with: { tag: 'p', class: 'help-block' }}]) 
end 
+0

此使用比特解構和紅寶石2.0關鍵字參數。你可以在這裏閱讀更多關於它的信息:http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html和這裏:https://robots.thoughtbot.com/ruby-2-keyword-參數 – max