Module: WordnikRubyHelpers::ViewHelpers

Defined in:
lib/wordnik_ruby_helpers.rb

Instance Method Summary collapse

  • #embolden_substring(text, substring, options = {}) ⇒ Object
  • #enable_typekit(kit_id) ⇒ Object

    Adds the javascript embed code for Typekit.

  • #errors_for(form) ⇒ Object

    Rails 3 did away with 'error_messages', so here's a custom redo..

  • #generate_table(collection, headers = nil, options = {}) ⇒ Object

    Build an HTML table For collection, pass an array of arrays For headers, pass an array of label strings for the top of the table All other options will be passed along to the table content_tag.

  • #html_tag(element, content, properties = {}) ⇒ Object

    A shorter version of Rails' content_tag...

  • #image_url(source) ⇒ Object

    Absolute path to a local image.

  • #in_quotes(str, quote_type = :single) ⇒ Object

    Wrap strings in quotes (single by default).

  • #info_pair(label, value) ⇒ Object

    Output an easily styleable key-value pair.

  • #link(name, options = {}, html_options = {}) ⇒ Object

    This works just like link_to, but with one difference..

  • #list_model_columns(obj) ⇒ Object

    Generate a list of column name-value pairs for an AR object.

  • #options_td(record_or_name_or_array, hide_destroy = false) ⇒ Object

    Pass in an ActiveRecord object, get back edit and delete links inside a TD tag.

  • #timeago(time, *args) ⇒ Object (also: #time_ago_in_words_or_date)

    Use words if within the last week, otherwise use date (show year if not this year) Good for SEO and humans..

  • #value_or_default(value, default = "not specified") ⇒ Object

    Return a default message if value is blank.

  • Instance Method Details

    #base_urlObject

    
    
    149
    150
    151
    # File 'lib/wordnik_ruby_helpers.rb', line 149
    
    def base_url
      "#{request.protocol}#{request.host_with_port}"
    end

    #convert_to_list_items(items, *args) ⇒ Object

    Give this helper an array, and get back a string of

  • elements. The first item gets a class of first and the last, well.. last. This makes it easier to apply CSS styles to lists, be they ordered or unordered. http://zeke.tumblr.com/post/98025647/a-nice-little-view-helper-for-generating-list-items

  • 
    
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    # File 'lib/wordnik_ruby_helpers.rb', line 89
    
    def convert_to_list_items(items, *args)
      default_options = {:stripe => true}
      options = default_options.merge(args.extract_options!)
      out = []
      items.each_with_index do |item, index|
        css = []
        css << "first" if items.first == item
        css << "last" if items.last == item
        css << "even" if options[:stripe] && index%2 == 1
        css << "odd" if options[:stripe] && index%2 == 0 # (First item is odd (1))
        out << (:li, item, :class => css.join(" "))
      end
      raw out.join("\n")
    end

    #embolden_substring(text, substring, options = {}) ⇒ Object

    
    
    8
    9
    10
    11
    12
    13
    14
    15
    # File 'lib/wordnik_ruby_helpers.rb', line 8
    
    def embolden_substring(text, substring, options={})
      options.reverse_merge!(:case_sensitive => true)
      if options[:case_sensitive]
        text.gsub(/(#{substring})/, "<strong>\\1</strong>").html_safe
      else
        text.gsub(/(#{substring})/i, "<strong>\\1</strong>").html_safe
      end
    end

    #enable_typekit(kit_id) ⇒ Object

    Adds the javascript embed code for Typekit. Pass in your kit id

    
    
    161
    162
    163
    164
    # File 'lib/wordnik_ruby_helpers.rb', line 161
    
    def enable_typekit(kit_id)
      raw "<script type=\"text/javascript\" src=\"http://use.typekit.com/#{kit_id}.js\"></script>
      <script type=\"text/javascript\">try{Typekit.load();}catch(e){}</script>"
    end

    #errors_for(form) ⇒ Object

    Rails 3 did away with 'error_messages', so here's a custom redo..

    
    
    167
    168
    169
    170
    171
    172
    173
    # File 'lib/wordnik_ruby_helpers.rb', line 167
    
    def errors_for(form)
    return unless form.object.errors.present?
    out = []
    out << (:h2, "#{pluralize(form.object.errors.count, "error")} prohibited this record from being saved.")
    out << (:ul, convert_to_list_items(form.object.errors.full_messages))
      (:div, out.join("\n").html_safe, :class => "errorExplanation")
    end

    #generate_table(collection, headers = nil, options = {}) ⇒ Object

    Build an HTML table For collection, pass an array of arrays For headers, pass an array of label strings for the top of the table All other options will be passed along to the table content_tag

    
    
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    # File 'lib/wordnik_ruby_helpers.rb', line 108
    
    def generate_table(collection, headers=nil, options={})
      return if collection.blank?
      thead = (:thead) do
        (:tr) do
          headers.map {|header| (:th, header)}
        end
      end unless headers.nil?
      tbody = (:tbody) do
        collection.map do |values|
          (:tr) do
            values.map {|value| (:td, value)}
          end
        end
      end
      (:table, [thead, tbody].compact.join("\n"), options)
    end

    #html_tag(element, content, properties = {}) ⇒ Object

    A shorter version of Rails' content_tag...

    Usage: html_tag :div, "this is a div" html_tag 'span.big', 'this is big (hidden) span', :style => "display:none" html_tag 'span#bob.old.big', 'this is big old bob'

    
    
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    # File 'lib/wordnik_ruby_helpers.rb', line 34
    
    def html_tag(element, content, properties={})
      
      # Extract class and id
      css = element.to_s.scan(/\.(\w+)/).flatten.sort.join(" ")
      id = element.to_s.scan(/\#(\w+)/).flatten.first
      
      # Clean up the element
      element = element.to_s.split('#').first.split('.').first
      
      properties[:class] = css unless css.blank?
      properties[:id] = id unless id.blank?
      (element, content, properties)
    end

    #image_url(source) ⇒ Object

    Absolute path to a local image

    
    
    144
    145
    146
    # File 'lib/wordnik_ruby_helpers.rb', line 144
    
    def image_url(source)
      base_url + image_path(source)
    end

    #in_quotes(str, quote_type = :single) ⇒ Object

    Wrap strings in quotes (single by default)

    
    
    19
    20
    21
    22
    23
    24
    25
    26
    # File 'lib/wordnik_ruby_helpers.rb', line 19
    
    def in_quotes(str, quote_type = :single)
      s = str.to_s
      t = (quote_type == :single) ? 's' : 'd'
      # Remove surrounding quotes, if present
      s.gsub!(/^\"|\"$/, '')
      s.gsub!(/^\'|\'$/, '')
      "&l#{t}quo;#{s}&r#{t}quo;".html_safe
    end

    #info_pair(label, value) ⇒ Object

    Output an easily styleable key-value pair

    
    
    79
    80
    81
    82
    83
    # File 'lib/wordnik_ruby_helpers.rb', line 79
    
    def info_pair(label, value)
      value = (:span, "None", :class => "blank") if value.blank?
      label = (:span, "#{label}:", :class => "label")
      (:span, [label, value].join(" ").html_safe, :class => "info_pair")
    end

    This works just like link_to, but with one difference.. If the link is to the current page, a class of 'active' is added

    
    
    136
    137
    138
    139
    140
    141
    # File 'lib/wordnik_ruby_helpers.rb', line 136
    
    def link(name, options={}, html_options={})
      link_to_unless_current(name, options, html_options) do
        html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ")
        link_to(name, options, html_options)
      end
    end

    #list_model_columns(obj) ⇒ Object

    Generate a list of column name-value pairs for an AR object

    
    
    154
    155
    156
    157
    # File 'lib/wordnik_ruby_helpers.rb', line 154
    
    def list_model_columns(obj)
      items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) }
      (:ul, convert_to_list_items(items), :class => "model_columns")
    end

    #options_td(record_or_name_or_array, hide_destroy = false) ⇒ Object

    Pass in an ActiveRecord object, get back edit and delete links inside a TD tag

    
    
    126
    127
    128
    129
    130
    131
    132
    # File 'lib/wordnik_ruby_helpers.rb', line 126
    
    def options_td(record_or_name_or_array, hide_destroy = false)
      items = []
      items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array))
      items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy
      list = (:ul, convert_to_list_items(items))
      (:td, list, :class => "options")
    end

    #timeago(time, *args) ⇒ Object Also known as: time_ago_in_words_or_date

    Use words if within the last week, otherwise use date (show year if not this year) Good for SEO and humans.. see http://timeago.yarp.com

    Usage: timeago(Time.now) timeago(time, :relative_for => 30.days)

    
    
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    # File 'lib/wordnik_ruby_helpers.rb', line 54
    
    def timeago(time, *args)
      time = Time.parse(time) unless time.class == Time
      
      defaults = {
        :relative_for => 1.week,
        :title => time.getutc.iso8601,
        :class => ""
      }
      options = defaults.merge(args.extract_options!)
    
      # Add a 'relative' CSS class unless it's way old
      if Time.now-time < options[:relative_for]
        options[:class] = options[:class].to_s.squeeze(' ').split(' ').push('relative').join(' ')
      end
    
      # Take `relative_for` option out so it doesn't become an HTML attribute.. 
      options.delete(:relative_for)
    
      html_tag(:abbr, time.strftime('%b %e, %Y'), options)
    end

    #value_or_default(value, default = "not specified") ⇒ Object

    Return a default message if value is blank

    
    
    176
    177
    178
    # File 'lib/wordnik_ruby_helpers.rb', line 176
    
    def value_or_default(value, default="not specified")
      value.blank? ? (:span, default, :class => "blank") : value
    end