Sha256: 26aff24dc27c6095e666a10c899aa8788315949e7f114967579bc510f1f03562

Contents?: true

Size: 1.29 KB

Versions: 11

Compression:

Stored size: 1.29 KB

Contents

module SinatraMore
  module FormatHelpers
    
    # Returns relative time in words referencing the given date
    # relative_time_ago(Time.now)
    def relative_time_ago(date)
      date = date.to_date
      date = Date.parse(date, true) unless /Date.*/ =~ date.class.to_s
      days = (date - Date.today).to_i

      return 'today'     if days >= 0 and days < 1
      return 'tomorrow'  if days >= 1 and days < 2
      return 'yesterday' if days >= -1 and days < 0

      return "in #{days} days"      if days.abs < 60 and days > 0
      return "#{days.abs} days ago" if days.abs < 60 and days < 0

      return date.strftime('%A, %B %e') if days.abs < 182
      return date.strftime('%A, %B %e, %Y')
    end

    # Used in xxxx.js.erb files to escape html so that it can be passed to javascript from sinatra
    # escape_javascript("<h1>Hey</h1>")
    def escape_javascript(html_content)
      return '' unless html_content
      javascript_mapping = { '\\' => '\\\\', '</' => '<\/', "\r\n" => '\n', "\n" => '\n' }
      javascript_mapping.merge("\r" => '\n', '"' => '\\"', "'" => "\\'")
      escaped_string = html_content.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { javascript_mapping[$1] }
      "\"#{escaped_string}\""
    end

    alias js_escape escape_javascript
    alias escape_for_javascript escape_javascript

  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
sinatra_more-0.1.9 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.8 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.7 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.6 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.5 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.4 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.3 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.2 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.1 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.1.0 lib/sinatra_more/markup_plugin/format_helpers.rb
sinatra_more-0.0.14 lib/sinatra_more/markup_plugin/format_helpers.rb