开发者

Refactoring: Render buttons and wrap with div

Many of my pages contains an actions element like the example below.

I was wondering if it would be possible to refactor this into a helper or partia开发者_C百科l. At first it looks very simple - just create a helper that wraps the button div. However I can't figure out how I can wrap the actions div when all the buttons has been rendered. Guess it has to be cached or something.

<div class="actions">
  <div class="button box shadow">
    <span class="customclass1"></span>
    <a href="/">button1</a>
  </div>
  <div class="button box shadow">
    <span class="customclass2"></span>
    <a href="/">button2</a>
  </div>
  <div class="button box shadow">
    <span class="customclass3"></span>
    <a href="/">button3</a>
  </div>
  ... maybe another button
</div>

UPDATE: This is how I did it after some playing around:

view

<% button 'ui-icon-plusthick', (link_to "New", new_art_path) %>
<% button 'ui-icon-pencil', (link_to "Edit", edit_art_path(@art)) %>
<% button 'ui-icon-trash', (link_to 'Destroy', @art, method: :delete) %>
<%= display_actions %>

application_helper

def button(ui_icon_class, link)
  if @buttons.nil? then @buttons = '' end
  @buttons += ('
  <div class="unit mrm ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
    <span class="ui-icon ' + ui_icon_class + '"></span>' + link + 
  '</div>')
end

def display_actions
  unless @buttons.nil?
    ('<div class="line mlm mbm ui-accordion ui-widget ui-helper-reset ui-accordion-   icons">' +
        @buttons +
    '</div>').html_safe
  end   
end

This way I can very easy add checks - hide links that the user don't have permission to use.

<% button 'ui-icon-trash', (link_to 'Destroy', @art, method: :delete) if can? :destroy, @art %>

Best regards. Asbjørn Morell


Is this the kind of thing you're after?

Your view:

<div class="actions">
  <% render 'button', :custom_class => "customclass1", :button_text => "button1" %>
  <% render 'button', :custom_class => "customclass2", :button_text => "button2" %>
  ... etc.
</div>

_button.html.erb:

<div class="button box shadow">
  <span class="<%= custom_class %>"></span>
  <a href="/"><%= button_text %></a>
</div>

You could then refactor further if you wished by creating a helper to which you just pass options and that takes care of rendering the button partial with the correct options.

Something like:

Your view:

<% display_actions(['someclass1', 'button1'], ['someclass2', 'button2']) %>

You helper:

def display_actions(*options)
  html = '<div class="actions">'
  options.each do |opt|
    # Not tested, but you get the idea
    html += render('button', :custom_class => opt.first, :button_text => opt.last)
  end
  html += '</div>'
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜