Module: Ginatra::Helpers

Defined in:
lib/ginatra/helpers.rb

Overview

Helpers used in the views, and not only.

Instance Method Summary collapse

Instance Method Details

#atom_feed_url(repo_param, ref = nil) ⇒ String

Spits out a HTML link to the atom feed for a given ref of a given repo

Parameters:

  • repo_param (Sting)

    the url-sanitised-name of a given repo

  • ref (String) (defaults to: nil)

    the ref to link to.

Returns:

  • (String)

    the HTML containing the link to the feed.



125
126
127
# File 'lib/ginatra/helpers.rb', line 125

def atom_feed_url(repo_param, ref=nil)
  ref.nil? ? prefix_url("#{repo_param}.atom") : prefix_url("#{repo_param}/#{ref}.atom")
end

#empty_description_hint_for(repo) ⇒ Object

Returns hint to set repository description



43
44
45
46
47
# File 'lib/ginatra/helpers.rb', line 43

def empty_description_hint_for(repo)
  return '' unless repo.description.empty?
  hint_text = "Edit `#{repo.path}description` file to set the repository description."
  "<img src='/img/exclamation-circle.svg' title='#{hint_text}' alt='hint' class='icon'>"
end

#file_icon(filemode) ⇒ Object

Returns file icon depending on filemode



50
51
52
53
54
55
56
57
58
# File 'lib/ginatra/helpers.rb', line 50

def file_icon(filemode)
  case filemode
    # symbolic link (120000)
    when 40960 then "<img src='/img/mail-forward.svg' alt='symbolic link' class='icon'>"
    # executable file (100755)
    when 33261 then "<img src='/img/asterisk.svg' alt='executable file' class='icon'>"
    else "<img src='/img/file.svg' alt='file' class='icon'>"
  end
end

#file_listing(diff) ⇒ String

Returns a HTML (+<ul>+) list of the files modified in a given commit.

It includes classes for added/modified/deleted and also anchor links to the diffs for further down the page.

Parameters:

  • commit (Rugged::Commit)

    the commit you want the list of files for

Returns:

  • (String)

    a <ul> with lots of <li> children.



137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/ginatra/helpers.rb', line 137

def file_listing(diff)
  list = []
  diff.deltas.each_with_index do |delta, index|
    if delta.deleted?
      list << "<li class='deleted'><img src='/img/minus-square.svg' alt='deleted' class='icon'> <a href='#file-#{index + 1}'>#{delta.new_file[:path]}</a></li>"
    elsif delta.added?
      list << "<li class='added'><img src='/img/plus-square.svg' alt='added' class='icon'> <a href='#file-#{index + 1}'>#{delta.new_file[:path]}</a></li>"
    elsif delta.modified?
      list << "<li class='changed'><img src='/img/edit.svg' alt='modified' class='icon'> <a href='#file-#{index + 1}'>#{delta.new_file[:path]}</a></li>"
    end
  end
  "<ul class='list-unstyled'>#{list.join}</ul>"
end

#gravatar_image_tag(email, options = {}) ⇒ String

Takes an email and returns an image tag with gravatar

Parameters:

  • email (String)

    the email address

  • options (Hash) (defaults to: {})

    alt, class and size options for image tag

Returns:

  • (String)

    html image tag



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/ginatra/helpers.rb', line 71

def gravatar_image_tag(email, options={})
  alt = options.fetch(:alt, email.gsub(/@\S*/, ''))
  size = options.fetch(:size, 40)
  url = "https://secure.gravatar.com/avatar/#{Digest::MD5.hexdigest(email)}?s=#{size}"

  if options[:lazy]
    placeholder = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
    tag = "<img data-original='#{url}' src='#{placeholder}' alt='#{h alt}' height='#{size}' width='#{size}' class='js-lazy #{options[:class]}'>"
  else
    tag = "<img src='#{url}' alt='#{h alt}' height='#{size}' width='#{size}'#{" class='#{options[:class]}'" if options[:class]}>"
  end

  tag
end

#h(text) ⇒ Object

Escapes string to HTML entities



7
8
9
# File 'lib/ginatra/helpers.rb', line 7

def h(text)
  Rack::Utils.escape_html(text)
end

#highlight_diff(hunk) ⇒ String

Highlights commit diff

Parameters:

  • diff (Rugged::Hunk)

    hunk for highlighting

Returns:

  • (String)

    highlighted HTML.code



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/ginatra/helpers.rb', line 156

def highlight_diff(hunk)
  lines = []
  lines << hunk.header

  hunk.each_line do |line|
    if line.context?
      lines << "  #{line.content}"
    elsif line.deletion?
      lines << "- #{line.content}"
    elsif line.addition?
      lines << "+ #{line.content}"
    end
  end

  formatter = Rouge::Formatters::HTML.new
  lexer     = Rouge::Lexers::Diff.new

  source   = lines.join
  encoding = source.encoding
  source   = source.force_encoding(Encoding::UTF_8)

  hd = formatter.format lexer.lex(source)
  hd.force_encoding encoding
end

#highlight_source(source, filename = '') ⇒ String

Highlights blob source

Parameters:

  • blob (Rugged::Blob)

    to highlight source

Returns:

  • (String)

    highlighted HTML.code



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/ginatra/helpers.rb', line 186

def highlight_source(source, filename='')
  source    = source.force_encoding(Encoding::UTF_8)
  formatter = Rouge::Formatters::HTML.new(line_numbers: true, wrap: false)
  lexer     = Rouge::Lexer.guess_by_filename(filename)

  if lexer == Rouge::Lexers::PlainText
    lexer = Rouge::Lexer.guess_by_source(source) || Rouge::Lexers::PlainText
  end

  formatter.format lexer.lex(source)
end

#hostnameString

Returns the Hostname of the given install, for use in the atom feeds.

Returns:

  • (String)

    the hostname of the server. Respects HTTP-X-Forwarded-For



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

def hostname
  (request.env['HTTP_X_FORWARDED_SERVER'] =~ /[a-z]*/) ? request.env['HTTP_X_FORWARDED_SERVER'] : request.env['HTTP_HOST']
end

#is_pjax?Boolean

Checks X-PJAX header

Returns:

  • (Boolean)


12
13
14
# File 'lib/ginatra/helpers.rb', line 12

def is_pjax?
  request.env['HTTP_X_PJAX']
end

#nicetime(date) ⇒ String

Reformats the date into a user friendly date with html entities

Parameters:

  • date (#strftime)

    object to format nicely

Returns:

  • (String)

    html string formatted using “%b %d, %Y &ndash; %H:%M”



91
92
93
# File 'lib/ginatra/helpers.rb', line 91

def nicetime(date)
  date.strftime("%b %d, %Y &ndash; %H:%M")
end

Returns a string including the link to download a patch for a certain commit to the repo

Parameters:

  • commit (Rugged::Commit)

    the commit you want a patch for

  • repo_param (String)

    the url-sanitised name for the repo (for the link path)

Returns:

  • (String)

    the HTML link to the patch



114
115
116
117
# File 'lib/ginatra/helpers.rb', line 114

def patch_link(commit, repo_param)
  patch_url = prefix_url("#{repo_param}/commit/#{commit.oid}.patch")
  "<a href='#{patch_url}'>Download Patch</a>"
end

#prefix_url(rest_of_url = '') ⇒ Object

Constructs the URL used in the layout’s base tag



32
33
34
35
36
37
38
39
40
# File 'lib/ginatra/helpers.rb', line 32

def prefix_url(rest_of_url='')
  prefix = Ginatra.config.prefix.to_s

  if prefix.length > 0 && prefix[-1].chr == '/'
    prefix.chop!
  end

  "#{prefix}/#{rest_of_url}"
end

#rfc_date(datetime) ⇒ String

Returns the rfc representation of a date, for use in the atom feeds.

Parameters:

  • datetime (DateTime)

    the date to format

Returns:

  • (String)

    the formatted datetime



238
239
240
# File 'lib/ginatra/helpers.rb', line 238

def rfc_date(datetime)
  datetime.strftime("%Y-%m-%dT%H:%M:%SZ") # 2003-12-13T18:30:02Z
end

#secure_mail(email) ⇒ Object

Masks original email



61
62
63
64
# File 'lib/ginatra/helpers.rb', line 61

def secure_mail(email)
  local, domain = email.split('@')
  "#{local[0..3]}...@#{domain}"
end

#simple_format(text) ⇒ String

Formats the text to remove multiple spaces and newlines, and then inserts HTML linebreaks.

Borrowed from Rails: ActionView::Helpers::TextHelper#simple_format and simplified to just use <p> tags without any options, then modified more later.

Parameters:

  • text (String)

    the text you want formatted

Returns:

  • (String)

    the formatted text



208
209
210
211
212
213
# File 'lib/ginatra/helpers.rb', line 208

def simple_format(text)
  text.gsub!(/ +/, " ")
  text.gsub!(/\r\n?/, "\n")
  text.gsub!(/\n/, "<br />\n")
  text
end

#time_tag(time) ⇒ String

Returns an html time tag for the given time

Parameters:

  • time (Time)

    object

Returns:

  • (String)

    time tag formatted using “%B %d, %Y %H:%M”



100
101
102
103
104
# File 'lib/ginatra/helpers.rb', line 100

def time_tag(time)
  datetime = time.strftime('%Y-%m-%dT%H:%M:%S%z')
  title = time.strftime('%Y-%m-%d %H:%M:%S')
  "<time datetime='#{datetime}' title='#{title}'>#{time.strftime('%B %d, %Y %H:%M')}</time>"
end

#title(*args) ⇒ Object

Sets title for pages



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ginatra/helpers.rb', line 17

def title(*args)
  @title ||= []
  @title_options ||= { headline: nil, sitename: h(Ginatra.config.sitename) }
  options = args.last.is_a?(Hash) ? args.pop : {}

  @title += args
  @title_options.merge!(options)

  t = @title.clone
  t << @title_options[:headline]
  t << @title_options[:sitename]
  t.compact.join ' - '
end

#truncate(text, options = {}) ⇒ String

Truncates a given text to a certain number of letters, including a special ending if needed.

Parameters:

  • text (String)

    the text to truncate

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :length (Integer) — default: 30

    the length you want the output string

  • :omission (String) — default: "..."

    the string to show an omission.

Returns:

  • (String)

    the truncated text.



222
223
224
225
226
227
228
229
230
231
232
# File 'lib/ginatra/helpers.rb', line 222

def truncate(text, options={})
  options[:length] ||= 30
  options[:omission] ||= "..."

  if text
    l = options[:length] - options[:omission].length
    chars = text
    stop = options[:separator] ? (chars.rindex(options[:separator], l) || l) : l
    (chars.length > options[:length] ? chars[0...stop] + options[:omission] : text).to_s
  end
end