Module: MirExtensions::HelperExtensions

Defined in:
lib/mir_extensions.rb

Instance Method Summary collapse

Instance Method Details

#action?(expression) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/mir_extensions.rb', line 39

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.



44
45
46
# File 'lib/mir_extensions.rb', line 44

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

#checkmarkObject



48
49
50
# File 'lib/mir_extensions.rb', line 48

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

#controller?(expression) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/mir_extensions.rb', line 52

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>



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/mir_extensions.rb', line 68

def crud_links(model, instance_name, actions, args={})
  _html = ""
  _options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"
  
  if use_crud_icons
    if actions.include?(:show)
      _html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}")
    end
    if actions.include?(:edit)
      _html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}")
    end
    if actions.include?(:delete)
      _html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}")
    end
  else
    if actions.include?(:show)
      _html << eval("link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}")
    end
    if actions.include?(:edit)
      _html << eval("link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}")
    end
    if actions.include?(:delete)
      _html << eval("link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}")
    end
  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>



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/mir_extensions.rb', line 102

def crud_links_for_nested_resource(model, nested_model, model_instance_name, nested_model_instance_name, actions, args={})
  _html = ""
  if use_crud_icons
    if actions.include?(:show)
      _html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), #{model_instance_name}_#{nested_model_instance_name}_path(model, nested_model), :title => 'View'")
    end
  
    if actions.include?(:edit)
      _html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{model_instance_name}_#{nested_model_instance_name}_path(model, nested_model), :title => 'Edit'")
    end
  
    if actions.include?(:delete)
      _html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), #{model_instance_name}_#{nested_model_instance_name}_path(model, nested_model), :method => :delete, :confirm => 'Are you sure? This action cannot be undone.', :title => 'Delete'")
    end
  end
  _html
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 -%>


132
133
134
# File 'lib/mir_extensions.rb', line 132

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



137
138
139
140
141
142
# File 'lib/mir_extensions.rb', line 137

def legend_tag(text, args={})
  _html = %{<div id="#{args[:id]}" class="faux_legend">#{text}</div>\r}
  _html.gsub!(/ id=""/,'')
  _html.gsub!(/ class=""/,'')
  _html
end

#meta_description(content = nil) ⇒ Object



144
145
146
# File 'lib/mir_extensions.rb', line 144

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

#meta_keywords(content = nil) ⇒ Object



148
149
150
# File 'lib/mir_extensions.rb', line 148

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

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



152
153
154
# File 'lib/mir_extensions.rb', line 152

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.



161
162
163
164
165
166
167
# File 'lib/mir_extensions.rb', line 161

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



156
157
158
# File 'lib/mir_extensions.rb', line 156

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.



170
171
172
173
174
175
176
# File 'lib/mir_extensions.rb', line 170

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_promptObject



178
179
180
# File 'lib/mir_extensions.rb', line 178

def select_prompt
  "Select..."
end

#select_prompt_optionObject



182
183
184
# File 'lib/mir_extensions.rb', line 182

def select_prompt_option
  "<option value=''>#{select_prompt}</option>"
end

#select_tag_for_filter(model, nvpairs, 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:

    scope :active,   :conditions => { :is_active => true }
    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
    


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/mir_extensions.rb', line 218

def select_tag_for_filter(model, nvpairs, params)
  return unless model && nvpairs && ! nvpairs.empty?
  options = { :query => params[:query] }
  _url = url_for(eval("#{model}_url(options)"))
  _html = %{<label for="show">Show:</label><br />}
  _html << %{<select name="show" id="show" onchange="window.location='#{_url}' + '?show=' + this.value">}
  nvpairs.each do |pair|
    _html << %{<option value="#{pair[:scope]}"}
    if params[:show] == pair[:scope] || ((params[:show].nil? || params[:show].empty?) && pair[:scope] == "all")
      _html << %{ selected="selected"}
    end
    _html << %{>#{pair[:label]}}
    _html << %{</option>}
  end
  _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'}


245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/mir_extensions.rb', line 245

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] || nil,
    :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 -%>


333
334
335
336
337
338
339
# File 'lib/mir_extensions.rb', line 333

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' %>


350
351
352
# File 'lib/mir_extensions.rb', line 350

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 -%>


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/mir_extensions.rb', line 290

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



356
357
358
359
360
361
362
363
364
# File 'lib/mir_extensions.rb', line 356

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



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

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>


385
386
387
388
389
390
391
392
393
394
# File 'lib/mir_extensions.rb', line 385

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 />


409
410
411
412
413
414
415
# File 'lib/mir_extensions.rb', line 409

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