Module: ApplicationHelper

Included in:
MirFormBuilder
Defined in:
lib/mir_utility.rb

Constant Summary collapse

SELECT_PROMPT =
'Select...'
SELECT_PROMPT_OPTION =
"<option value=''>#{SELECT_PROMPT}</option>"

Instance Method Summary collapse

Instance Method Details

#action?(expression) ⇒ Boolean

Returns:

  • (Boolean)


231
232
233
# File 'lib/mir_utility.rb', line 231

def action?( expression )
  !! ( expression.class == Regexp ? controller.action_name =~ expression : controller.action_name == expression )
end

#array_to_lines(array, delimiter = '<br />') ⇒ Object

Formats an array with HTML line breaks, or the specified delimiter.



236
237
238
239
# File 'lib/mir_utility.rb', line 236

def array_to_lines(array, delimiter = '<br />')
  return unless array.is_a?(Array)
  array.blank? ? nil : array * delimiter
end

#checkmarkObject



241
242
243
# File 'lib/mir_utility.rb', line 241

def checkmark
  %{<div class="checkmark"></div>}
end

#controller?(expression) ⇒ Boolean

Returns:

  • (Boolean)


245
246
247
# File 'lib/mir_utility.rb', line 245

def controller?( expression )
  !! ( expression.class == Regexp ? controller.controller_name =~ expression : controller.controller_name == expression )
end

Display CRUD icons or links, according to setting in use_crud_icons method.

In application_helper.rb:

def use_crud_icons
  true
end

Then use in index views like this:

<td class=“crud_links”><%= crud_links(my_model, ‘my_model’, [:show, :edit, :delete]) -%></td>



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/mir_utility.rb', line 261

def crud_links(model, instance_name, actions, args={})
  _html = ''
  _path = args.delete(:path) || model
  _edit_path = args.delete(:edit_path) || eval("edit_#{instance_name}_path(model)") if actions.include?(:edit)
  _options = args.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"

  if use_crud_icons
    _html << link_to(image_tag('icons/view.png', :class => 'crud_icon', :width => 14, :height => 14), _path, :title => "View#{_options}") if actions.include?(:show)
    _html << link_to(image_tag('icons/edit.png', :class => 'crud_icon', :width => 14, :height => 14), _edit_path, :title => "Edit#{_options}") if actions.include?(:edit)
    _html << link_to(image_tag('icons/delete.png', :class => 'crud_icon', :width => 14, :height => 14), _path, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => "Delete#{_options}") if actions.include?(:delete)
  else
    _html << link_to('View', _path, :title => 'View', :class => "crud_link#{_options}") if actions.include?(:show)
    _html << link_to('Edit', _edit_path, :title => 'Edit', :class => "crud_link#{_options}") if actions.include?(:edit)
    _html << link_to('Delete', _path, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => "crud_link#{_options}") if actions.include?(:delete)
  end

  _html
end

Display CRUD icons or links, according to setting in use_crud_icons method. This method works with nested resources. Use in index views like this:

<td class=“crud_links”><%= crud_links_for_nested_resource(@my_model, my_nested_model, ‘my_model’, ‘my_nested_model’, [:show, :edit, :delete]) -%></td>



286
287
288
# File 'lib/mir_utility.rb', line 286

def crud_links_for_nested_resource(model, nested_model, model_instance_name, nested_model_instance_name, actions, args={})
  crud_links model, model_instance_name, actions, args.merge(:edit_path => eval("edit_#{model_instance_name}_#{nested_model_instance_name}_path(model, nested_model)"), :path => [model, nested_model])
end

#legend_block(&block) ⇒ Object

DRY way to return a legend tag that renders correctly in all browsers. This variation allows for more “stuff” inside the legend tag, e.g. expand/collapse controls, without having to worry about escape sequences.

Sample usage:

<%- legend_block do -%>
  <span id="hide_or_show_backlinks" class="show_link" style="background-color: #999999;
  border: 1px solid #999999;" onclick="javascript:hide_or_show('backlinks');"></span>Backlinks (<%=
  @google_results.size -%>)
<%- end -%>


302
303
304
# File 'lib/mir_utility.rb', line 302

def legend_block(&block)
  concat (:div, capture(&block), :class => "faux_legend")
end

#legend_tag(text, args = {}) ⇒ Object

DRY way to return a legend tag that renders correctly in all browsers

Sample usage:

<%= legend_tag "Report Criteria" -%>

Sample usage with help text:

<%= legend_tag "Report Criteria", :help => "Some descriptive copy here." -%>
  <span id="hide_or_show_backlinks" class="show_link" style="background-color: #999999;
  border: 1px solid #999999;" onclick="javascript:hide_or_show('backlinks');"></span>Backlinks (<%=
  @google_results.size -%>)
<%- end -%>

Recommended CSS to support display of help icon and text:

.help_icon {
  display: block;
  float: left;
  margin-top: -16px;
  margin-left: 290px;
  border-left: 1px solid #444444;
  padding: 3px 6px;
  cursor: pointer;
}

div.popup_help {
  color: #666666;
  width: 98%;
  background: #ffffff;
  padding: 1em;
  border: 1px solid #999999;
  margin: 1em 0em;
}


341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/mir_utility.rb', line 341

def legend_tag(text, args={})
  args[:id] ||= text.downcase.gsub(/ /,'_')
  if args[:help]
    _html = %{<div id="#{args[:id]}" class="faux_legend">#{text}<span class="help_icon" onclick="$('#{args[:id]}_help').toggle();">?</span></div>\r}
    _html << %{<div id="#{args[:id]}_help" class="popup_help" style="display: none;">#{args[:help]}<br /></div>\r}
  else
    _html = %{<div id="#{args[:id]}" class="faux_legend">#{text}</div>\r}
  end
  _html.gsub!(/ id=""/,'')
  _html.gsub!(/ class=""/,'')
  _html
end

#meta_description(content = nil) ⇒ Object



354
355
356
# File 'lib/mir_utility.rb', line 354

def meta_description(content=nil)
  content_for(:meta_description) { content } unless content.blank?
end

#meta_keywords(content = nil) ⇒ Object



358
359
360
# File 'lib/mir_utility.rb', line 358

def meta_keywords(content=nil)
  content_for(:meta_keywords) { content } unless content.blank?
end

#models_for_select(models, label = 'name') ⇒ Object



362
363
364
# File 'lib/mir_utility.rb', line 362

def models_for_select( models, label = 'name' )
  models.map{ |m| [m[label], m.id] }.sort_by{ |e| e[0] }
end

Create a link that is opaque to search engine spiders.



371
372
373
374
375
376
377
# File 'lib/mir_utility.rb', line 371

def obfuscated_link_to(path, image, label, args={})
  _html = %{<form action="#{path}" method="get" class="obfuscated_link">}
  _html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>}
  args.each{ |k,v| _html << %{  <div><input id="#{k.to_s}" name="#{k}" type="hidden" value="#{v}" /></div>} }
  _html << %{</form>}
  _html
end

#options_for_array(a, selected = nil, prompt = SELECT_PROMPT) ⇒ Object



366
367
368
# File 'lib/mir_utility.rb', line 366

def options_for_array( a, selected = nil, prompt = SELECT_PROMPT )
  "<option value=''>#{prompt}</option>" + a.map{ |_e| _flag = _e[0].to_s == selected ? 'selected="1"' : ''; _e.is_a?(Array) ? "<option value=\"#{_e[0]}\" #{_flag}>#{_e[1]}</option>" : "<option>#{_e}</option>" }.to_s
end

#required_field_helper(model, element, html) ⇒ Object

Wraps the given HTML in Rails’ default style to highlight validation errors, if any.



380
381
382
383
384
385
386
# File 'lib/mir_utility.rb', line 380

def required_field_helper( model, element, html )
  if model && ! model.errors.empty? && element.is_required
    return ( :div, html, :class => 'fieldWithErrors' )
  else
    return html
  end
end

#select_tag_for_filter(model, filters, params) ⇒ Object

Use on index pages to create dropdown list of filtering criteria. Populate the filter list using a constant in the model corresponding to named scopes.

Usage:

  • item.rb:

    named_scope :active,   :conditions => { :is_active => true }
    named_scope :inactive, :conditions => { :is_active => false }
    
    FILTERS = [
      {:scope => "all",       :label => "All"},
      {:scope => "active",    :label => "Active Only"},
      {:scope => "inactive",  :label => "Inactive Only"}
    ]
    
  • items/index.html.erb:

    <%= select_tag_for_filter("items", @filters, params) -%>
    
  • items_controller.rb:

    def index
      @filters = Item::FILTERS
      if params[:show] && params[:show] != "all" && @filters.collect{|f| f[:scope]}.include?(params[:show])
        @items = eval("@items.#{params[:show]}.order_by(params[:by], params[:dir])")
      else
        @items = @items.order_by(params[:by], params[:dir])
      end
      ...
    end
    


420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/mir_utility.rb', line 420

def select_tag_for_filter(model, filters, params)
  return unless model && ! filters.blank?

  # capture and delete previous show param
  _old_show = params.delete :show

  _html = %{Show&nbsp;&nbsp;<select name="show" id="show" onchange="window.location='#{eval("#{model}_url")}?#{params.to_params}&show=' + this.value">}

  # restore previous show param
  params[:show] = _old_show

  filters.each do |pair|
    _html = %{#{_html}<option value="#{pair[:scope]}"}
    _html = %{#{_html} selected="selected"} if params[:show] == pair[:scope]
    _html = %{#{_html}>#{pair[:label]}</option>}
  end

  _html = %{#{_html}</select>}
end

Returns a link_to tag with sorting parameters that can be used with ActiveRecord.order_by.

To use standard resources, specify the resources as a plural symbol:

sort_link(:users, 'email', params)

To use resources aliased with :as (in routes.rb), specify the aliased route as a string.

sort_link('users_admin', 'email', params)

You can override the link’s label by adding a labels hash to your params in the controller:

params[:labels] = {'user_id' => 'User'}


450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/mir_utility.rb', line 450

def sort_link(model, field, params, html_options={})
  if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
    classname = "arrow-asc"
    dir = "DESC"
  elsif (field.to_sym == params[:by] || field == params[:by])
    classname = "arrow-desc"
    dir = "ASC"
  else
    dir = "ASC"
  end

  options = {
    :anchor => html_options[:anchor],
    :by => field,
    :dir => dir,
    :query => params[:query],
    :show => params[:show]
  }

  options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all'

  html_options = {
    :class => "#{classname} #{html_options[:class]}",
    :style => "color: white; font-weight: #{params[:by] == field ? "bold" : "normal"}; #{html_options[:style]}",
    :title => "Sort by this field"
  }

  field_name = params[:labels] && params[:labels][field] ? params[:labels][field] : field.titleize

  _link = model.is_a?(Symbol) ? eval("#{model}_url(options)") : "/#{model}?#{options.to_params}"
  link_to(field_name, _link, html_options)
end

#tab_body(args, &proc) ⇒ Object

Returns a tab body corresponding to tabs in a tabset. Make sure that the id of the tab_body matches the id provided to the tab_tag in the tabset block.

Usage:

<%- tab_body :id => 'ppc_ads', :label => 'PPC Ad Details' do -%>
  PPC ads form here.
<%- end -%>

<%- tab_body :id => 'budget' do -%>
  Budget form here.
<%- end -%>

<%- tab_body :id => 'geotargeting' do -%>
  Geotargeting form here.
<%- end -%>


538
539
540
541
542
543
544
# File 'lib/mir_utility.rb', line 538

def tab_body(args, &proc)
  concat %{<div id="#{args[:id]}" class="tab_block form_container" style="display: #{args[:display] || 'none'};">}
  concat %{#{legend_tag args[:label] || args[:id].titleize }}
  concat %{<a name="#{args[:id]}"></a><br />}
  yield
  concat %{</div>}
end

#tab_tag(args, *css_class) ⇒ Object

Returns the necessary HTML for a particular tab. Use inside a tabset block. Override the default tab label by specifying a :label parameter. Indicate that the tab should be active by setting its :state to ‘active’. (NOTE: You must define a corresponding CSS style for active tabs.)

Usage:

<%= tab_tag :id => 'ppc_ads', :label => 'PPC Ads', :state => 'active' %>


555
556
557
# File 'lib/mir_utility.rb', line 555

def tab_tag(args, *css_class)
  %{<li id="show_#{args[:id]}" class="tab_control #{args[:state]}" onclick="window.location='##{args[:id]}'; activate_tab('#{args[:id]}');">#{args[:label] || args[:id].to_s.titleize}</li>}
end

#tabset(&proc) ⇒ Object

Returns formatted tabs with appropriate JS for activation. Use in conjunction with tab_body.

Usage:

<%- tabset do -%>
  <%= tab_tag :id => 'ppc_ads', :label => 'PPC Ads', :state => 'active' %>
  <%= tab_tag :id => 'budget' %>
  <%= tab_tag :id => 'geotargeting' %>
<%- end -%>


495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/mir_utility.rb', line 495

def tabset(&proc)
  concat %{
    <div class="jump_links">
      <ul>
  }
  yield
  concat %{
      </ul>
    </div>
    <br style="clear: both;" /><br />
    <input type="hidden" id="show_tab" />
    <script type="text/javascript">
      function hide_all_tabs() { $$('.tab_block').invoke('hide'); }
      function activate_tab(tab) {
        $$('.tab_control').each(function(elem){ elem.className = 'tab_control'});
        $('show_' + tab).className = 'tab_control active';
        hide_all_tabs();
        $(tab).toggle();
        $('show_tab').value = tab
      }
      function sticky_tab() { if (location.hash) { activate_tab(location.hash.gsub('#','')); } }
      Event.observe(window, 'load', function() { sticky_tab(); });
    </script>
  }
end

#tag_for_collapsible_row(obj, params) ⇒ Object



561
562
563
564
565
566
567
568
569
# File 'lib/mir_utility.rb', line 561

def tag_for_collapsible_row(obj, params)
  _html = ""
  if obj && obj.respond_to?(:parent) && obj.parent
    _html << %{<tr class="#{obj.class.name.downcase}_#{obj.parent.id} #{params[:class]}" style="display: none; #{params[:style]}">}
  else
    _html << %{<tr class="#{params[:class]}" style="#{params[:style]}">}
  end
  _html
end

#tag_for_collapsible_row_control(obj) ⇒ Object



571
572
573
574
# File 'lib/mir_utility.rb', line 571

def tag_for_collapsible_row_control(obj)
  _base_id = "#{obj.class.name.downcase}_#{obj.id}"
  _html = %{<div id="hide_or_show_#{_base_id}" class="show_link" style="background-color: #999999; border: 1px solid #999999;" onclick="javascript:hide_or_show('#{_base_id}');"></div>}
end

#tag_for_label_with_inline_help(label_text, field_id, help_text) ⇒ Object

Create a set of tags for displaying a field label with inline help. Field label text is appended with a ? icon, which responds to a click by showing or hiding the provided help text.

Sample usage:

<%= tag_for_label_with_inline_help 'Relative Frequency', 'rel_frequency', 'Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.' %>

Yields:

<label for="rel_frequency">Relative Frequency: <%= image_tag "/images/help_icon.png", :onclick => "$('rel_frequency_help').toggle();", :class => 'inline_icon' %></label><br />
<div class="inline_help" id="rel_frequency_help" style="display: none;">
  <p>Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.</p>
</div>


590
591
592
593
594
595
596
597
598
599
# File 'lib/mir_utility.rb', line 590

def tag_for_label_with_inline_help( label_text, field_id, help_text )
  _html = ""
  _html << %{<label for="#{field_id}">#{label_text}}
  _html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}
  _html << %{</label><br />}
  _html << %{<div class="inline_help" id="#{field_id}_help" style="display: none;">}
  _html << %{<p>#{help_text}</p>}
  _html << %{</div>}
  _html
end

#tag_for_label_with_instructions(label_text, field_id, instructions) ⇒ Object

Create a set of tags for displaying a field label followed by instructions. The instructions are displayed on a new line following the field label.

Usage:

<%= tag_for_label_with_instructions 'Status', 'is_active', 'Only active widgets will be visible to the public.' %>

Yields:

<label for="is_active">
  Status<br />
  <span class="instructions">Only active widgets will be visible to the public.</span>
<label><br />


614
615
616
617
618
619
620
# File 'lib/mir_utility.rb', line 614

def tag_for_label_with_instructions( label_text, field_id, instructions )
  _html = ""
  _html << %{<label for="#{field_id}">#{label_text}}
  _html << %{<span class="instructions">#{instructions}</span>}
  _html << %{</label><br />}
  _html
end