Module: Helper

Included in:
CoreApi, NumberFormatter, RubygemsDownloadShieldsApp
Defined in:
lib/helper.rb

Overview

module that is used for formatting numbers using metrics

Class Method Summary collapse

Class Method Details

.available_extension?(extension) ⇒ Boolean

Checks if a extension is currently supported by the application, by checking if it is in the list of supported extension

Parameters:

  • extension (String)

    The extension that will be used

Returns:

  • (Boolean)

    Returns true if valid, otherwise false


165
166
167
# File 'lib/helper.rb', line 165

def available_extension?(extension)
  %w[png svg json jpg jpeg].include?(extension)
end

.clean_image_label(label) ⇒ String?

Sanitizes a string, by replacing unsafe characters with other characters Returns nil if string is blank

Parameters:

  • label (String)

    The string that will be used

Returns:

  • (String, nil)

    Returns the sanitized string, or nil if string is blank


175
176
177
178
# File 'lib/helper.rb', line 175

def clean_image_label(label)
  return if label.blank?
  label.gsub(/[\s]+/, ' ').gsub(/[\_\-]+/, '_')
end

.dispatch_http_response(res, options) ⇒ void

This method returns an undefined value.

Dispatches the response either to the final callback or to the block that will use the response and then call the callback

Parameters:

  • res (String)

    The response string that will be dispatched

  • options (Hash)

    The callback that is used to dispatch further the response


209
210
211
212
# File 'lib/helper.rb', line 209

def dispatch_http_response(res, options)
  callback = options.fetch('callback', nil)
  res.blank? && callback.present? ? callback.call(res, nil) : yield(res)
end

.display_totalBoolean

Method that checks if we need to display the total downloads

Returns:

  • (Boolean)

    Returns true if we need to display the total downloads


192
193
194
# File 'lib/helper.rb', line 192

def display_total
  display_type.present? && display_type == 'total'
end

.display_typeString?

Returns the display_type from the params , otherwise nil

Returns:

  • (String, nil)

    Returns the display_type from the params , otherwise nil


146
147
148
# File 'lib/helper.rb', line 146

def display_type
  @params.fetch('type', nil)
end

.env_production?Boolean

Method used to determine if application is running in production environment by checking ENV

Returns:

  • (Boolean)

    Returns true if RACK_ENV is equal to production, otherwise false


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

def env_production?
  ENV['RACK_ENV'] == 'production' || ENV['APP_ENV'] == 'production'
end

.fetch_content_type(extension = 'svg') ⇒ String

Returns the corect mime type for the given extension ( suported extension are SVG, PNG, JPG, JPEG)

Parameters:

  • extension (String) (defaults to: 'svg')

    The extension that will be used to determine the coorect MimeType that needs to be set before the response is outputted (Default: 'svg')

Returns:

  • (String)

    Returns the mime type that the browser will use in order to know what output to expect


154
155
156
157
158
# File 'lib/helper.rb', line 154

def fetch_content_type(extension = 'svg')
  extension = extension.present? && available_extension?(extension) ? extension : 'svg'
  mime_type = Rack::Mime::MIME_TYPES[".#{extension}"]
  "#{mime_type};Content-Encoding: gzip; charset=utf-8"
end

.find_version(versions, number) ⇒ Hash

Method to search for a version number in all gem versions and return the hash object

Parameters:

  • versions (Array<Hash>)

    The array of gem versions that we will use for searching

  • number (string)

    The version number used for searching

Returns:

  • (Hash)

    Returns the version object that has the number specified


314
315
316
# File 'lib/helper.rb', line 314

def find_version(versions, number)
  number.blank? ? {} : versions.find { |val| val['number'] == number }
end

.force_utf8_encoding(msg) ⇒ String

Returns utf8 encoding of the msg

Parameters:

  • msg (String)

Returns:

  • (String)

    ReturnsReturns utf8 encoding of the msg


183
184
185
186
187
# File 'lib/helper.rb', line 183

def force_utf8_encoding(msg)
  msg.respond_to?(:force_encoding) && msg.encoding.name != 'UTF-8' ? msg.force_encoding('UTF-8') : msg
rescue
  nil
end

.format_error(error) ⇒ String

Method used to format a exception for displaying (usually used for logging only)

Parameters:

  • error (Exception)

    The error that will be formatted

Returns:

  • (String)

    Returns the formatted exception that will be used in further processing


139
140
141
# File 'lib/helper.rb', line 139

def format_error(error)
  "#{error.inspect} \n #{error.backtrace}"
end

.get_latest_stable_version_details(http_response) ⇒ Hash

Method that is used to filter the versions, sort them and find the latest stable version

Parameters:

  • http_response (Array<Hash>)

    The array with all the versions of the gem

Returns:

  • (Hash)

    Returns the latest stable version

See Also:

  • #stable_gem_versions
  • #sorted_versions
  • #last_version
  • #find_version

335
336
337
338
339
340
# File 'lib/helper.rb', line 335

def get_latest_stable_version_details(http_response)
  versions = stable_gem_versions(http_response)
  sorted_versions = sorted_versions(versions)
  last_version_number = last_version(sorted_versions)
  find_version(versions, last_version_number)
end

checks if a CookieHash instance is not expired and returns the cookie value , otherwise nil

Parameters:

  • cookie_h (CookieHash)

    The CookieHash instance that will be verified if not expired

Returns:

  • (String, nil)

    Returns the cookie value from the Cookie data if is not expired, or nil otherwise

See Also:


264
265
266
# File 'lib/helper.rb', line 264

def get_string_from_cookie_data(cookie_h)
  cookie_h.to_cookie_string if cookie_h.expire_time >= Time.zone.now
end

.http_valid_content_types?(http, content_types = ['text/html']) ⇒ Boolean

Method used to check if the content type returned by the http client is not included in the list of invalid content types (e.g. text/html )

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for content type

  • content_types (Array<String>) (defaults to: ['text/html'])

    The content types that are considered invalid ( e.g. text/html )

Returns:

  • (Boolean)

    Returns true if valid, otherwise false


118
119
120
121
# File 'lib/helper.rb', line 118

def http_valid_content_types?(http, content_types = ['text/html'])
  content_types = content_types.is_a?(Array) ? content_types : [content_types]
  !content_types.include?(http.response_header[EM::HttpClient::CONTENT_TYPE])
end

.http_valid_status_code?(http, status_codes = [200]) ⇒ Boolean

Method used to check if the status code returned by http client is in the list of valid status codes

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for status code

  • status_codes (Array<String>) (defaults to: [200])

    The status codes that are considered valid ( e.g 200 )

Returns:

  • (Boolean)

    Returns true if valid, otherwise false


129
130
131
132
# File 'lib/helper.rb', line 129

def http_valid_status_code?(http, status_codes = [200])
  status_codes = status_codes.is_a?(Array) ? status_codes : [status_codes]
  status_codes.include?(http.response_header.http_status)
end

.last_version(sorted_versions) ⇒ string

Method that is used to return the last item from an array of strings. Will return empty string if array is blank

Parameters:

  • sorted_versions (Array<String>)

    describe sorted_versions

Returns:

  • (string)

    description of returned object


323
324
325
# File 'lib/helper.rb', line 323

def last_version(sorted_versions)
  sorted_versions.blank? ? '' : sorted_versions.last
end

.metric_powerArray<Number>

Returns the metric powers of all metric prefixes . This method is used in metric display of numbers

Returns:

  • (Array<Number>)

    An array of metric powers that correspont to each metric prefix

See Also:

  • #metric_prefixes

217
218
219
# File 'lib/helper.rb', line 217

def metric_power
  metric_prefixes.map.with_index { |_item, index| (1000**(index + 1)).to_i }
end

.metric_prefixesArray<String>

The prefixes that can be used in metric display

Returns:

  • (Array<String>)

    Returns the metric prefixes array that can be used in metric display


199
200
201
# File 'lib/helper.rb', line 199

def metric_prefixes
  %w[k M G T P E Z Y]
end

.non_empty_http_response?(http) ⇒ Boolean

Method used to determine if the reponse form the http client is valid

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for response

Returns:

  • (Boolean)

    Returns true if valid, otherwise false


58
59
60
# File 'lib/helper.rb', line 58

def non_empty_http_response?(http)
  http.response.present?
end

.options_base_url(options, request_url) ⇒ String

returns the request name used for persisting cookies, by checking the options received or falling back to the URL received

Parameters:

  • options (Hash)

    The options that will be used to retrive the request_name ( for shield.io we are only interested in the gem name )

  • request_url (String)

    The URL that is used to fetch data from ( used as fallback if the options don't contain a request_name key)

Returns:

  • (String)

    returns the request name either from the options or it returns the request_url if a request name is not provided


239
240
241
242
# File 'lib/helper.rb', line 239

def options_base_url(options, request_url)
  request_name = options['request_name']
  request_name.present? ? request_name : request_url
end

.parse_gem_version(gem_version) ⇒ String?

Method that tries to check if the version provided is a valid versin sintactical and semantical. it does not check if the gem actually has that version published or not. if the parsing of the version fails will return nil, otherwise will return the parsed version

Parameters:

  • gem_version (String)

    The string that represents the gem version that we want to check

Returns:

  • (String, nil)

    Returns nil if the version is blank or 'stable' or the parsing has failed, otherwise will return the parsed version

See Also:

  • Versionomy#parse

286
287
288
289
290
291
# File 'lib/helper.rb', line 286

def parse_gem_version(gem_version)
  return if gem_version.blank? || gem_version == 'stable'
  Versionomy.parse(gem_version)
rescue Versionomy::Errors::ParseError
  return nil
end

.parse_json(res) ⇒ Hash?

Method that is used to parse a string as JSON , if it fails will return nil

Parameters:

  • res (string)

    The string that will be parsed as JSON

Returns:

  • (Hash, nil)

    Returns Hash object if the json parse succeeds or nil otherwise

See Also:

  • JSON#parse

225
226
227
228
229
230
# File 'lib/helper.rb', line 225

def parse_json(res)
  return if res.blank?
  JSON.parse(res)
rescue JSON::ParserError
  nil
end

.parsed_url_property(url, property = 'host') ⇒ String?

Method used for parsing a URL and fetching a specific property of the URL (By default , the 'host' property)

Parameters:

  • url (String)

    The URL that will be parsed

  • property (String) (defaults to: 'host')

    The property of the URL that we want to get (Default: 'host')

Returns:

  • (String, nil)

    The property value or nil if there is a exception in parsing the URL or the property does not exist

See Also:

  • Addressable::URI#parse

19
20
21
22
23
24
25
# File 'lib/helper.rb', line 19

def parsed_url_property(url, property = 'host')
  return if url.blank? || !url.is_a?(String)
  uri = Addressable::URI.parse(url)
  uri.present? && property.present? ? uri.send(property) : uri
rescue
  nil
end

Method that is used to print to a stream . If the stream is already closed will return nil otherwise will append the response to the stream and close the stream

Parameters:

  • response (String)

    THe string that will be appended to the stream

  • output_buffer (Sinatra::Stream)

    The sinatra stream that will be used to append information

Returns:

  • (nil)

    The method will return nil even if is success or not, the only thing that is affected is the stream


274
275
276
277
278
# File 'lib/helper.rb', line 274

def print_to_output_buffer(response, output_buffer)
  return if output_buffer.closed?
  output_buffer << response
  output_buffer.close
end

.rootString

Method used to determine the root of the application, that might be helpful when trying to construct file paths relative to this value

Returns:

  • (String)

31
32
33
# File 'lib/helper.rb', line 31

def root
  File.expand_path(File.dirname(__dir__))
end

.rubygems_valid_response?(http, url) ⇒ Boolean

Method used to determine if URL is from Rubygems and if has valid status code ( 200 or 404) 404 are considered valid, because it determines if a gem exists or not.

We don't check the content type for this, becasue if JSON is not returned, the JSON parsing will return nil , because the parsed exception is rescued, and will call the success callback with nil value, which will still show a badge that is 'invalid' ( this happens also for 404 statuses, since we receive HTML format, but we can still display a badge, letting people know that either there is a problem with the service itself, or the requested gem does not exist )

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for response

  • url (String)

    The URL that was used by the client to make the request

Returns:

  • (Boolean)

    Returns true if valid, otherwise false

See Also:

  • #http_valid_status_code?

78
79
80
# File 'lib/helper.rb', line 78

def rubygems_valid_response?(http, url)
  url.include?(RubygemsApi::BASE_URL) && http_valid_status_code?(http, [200, 404])
end

.setup_options_for_url(options, request_url) ⇒ void

This method returns an undefined value.

INitializes the head key in the options received with a empty hash if not instantiated already and sets the url fetched to the url received

Parameters:

  • options (Hash)

    The options used for settning the head key ( needed for setting the connection options)

  • request_url (String)

    The URL that is being used currently to fetch data from


251
252
253
254
# File 'lib/helper.rb', line 251

def setup_options_for_url(options, request_url)
  options['head'] ||= {}
  options['url_fetched'] = request_url
end

.shields_io_valid_response?(http, url) ⇒ Boolean

Method used to determine if URL is from Shields.io and if has valid status code ( 200) and if the content type returned is valid ( in some cases we can receive 200 status code but with invalid status code, e.q. when shields.io is down or under maintenance )

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for response

  • url (String)

    The URL that was used by the client to make the request

Returns:

  • (Boolean)

    Returns true if valid, otherwise false

See Also:

  • #http_valid_status_code?
  • #http_valid_content_types?

93
94
95
# File 'lib/helper.rb', line 93

def shields_io_valid_response?(http, url)
  url.include?(BadgeApi::BASE_URL) && http_valid_status_code?(http, 200) && http_valid_content_types?(http)
end

.sorted_versions(versions) ⇒ Array<String>

method that will return nil if the array of versions is empty or will return the versions sorted

Parameters:

  • versions (Array<Hash>)

    The versions that have to be sorted

Returns:

  • (Array<String>)

    Will return nil if the array is blank or will return an array with only the version numbers sorted


305
306
307
# File 'lib/helper.rb', line 305

def sorted_versions(versions)
  versions.blank? ? [] : versions.map { |val| val['number'] }.version_sort
end

.stable_gem_versions(http_response) ⇒ Array<Hash>

Given an aray of gem versions , will filter them and return only the stable versions

Parameters:

  • http_response (Array<Hash>)

    The HTTP response as a array of Hash

Returns:

  • (Array<Hash>)

    Will return only the items from the array that have the key 'prerelease' with value false


297
298
299
# File 'lib/helper.rb', line 297

def stable_gem_versions(http_response)
  http_response.blank? ? [] : http_response.select { |val| val['prerelease'] == false }
end

.valid_http_code_returned?(http_client, url) ⇒ Boolean

Method used to detect bad responses from services, used by the middleware to log invalid responses in production.

Parameters:

  • http_client (EventMachine::HttpRequest)

    The http client that will be verified for response

  • url (String)

    The URL that was used by the client to make the request

Returns:

  • (Boolean)

    Returns true if valid, otherwise false

See Also:

  • #rubygems_valid_response?
  • #shields_io_valid_response?

107
108
109
# File 'lib/helper.rb', line 107

def valid_http_code_returned?(http_client, url)
  rubygems_valid_response?(http_client, url) || shields_io_valid_response?(http_client, url)
end

.valid_http_response?(http) ⇒ Boolean

Method used to determine if a object is a valid HTTP client and has a response

Parameters:

  • http (EventMachine::HttpRequest)

    The http client that will be verified for response

Returns:

  • (Boolean)

    Returns true if valid, otherwise false

See Also:

  • #non_empty_http_response

49
50
51
# File 'lib/helper.rb', line 49

def valid_http_response?(http)
  http.is_a?(EM::HttpClient) && non_empty_http_response?(http)
end