Module: Parliament::Grom::Decorator::Helpers::Utils

Defined in:
lib/parliament/grom/decorator/helpers/utils.rb

Overview

Namespace for utility methods

Since:

  • 0.1.0

Class Method Summary collapse

Class Method Details

.type_safe_first(enumerable, klass) ⇒ String

Checks that a collection responds to first and that the first element is of the given class

Examples:

When the first element is of the expected class

Parliament::Grom::Decorator::Helpers::Utils.type_safe_first(['hello'], String) #=> 'hello'

When the first element is not of the expected class

Parliament::Grom::Decorator::Helpers::Utils.type_safe_first(['hello'], Fixnum) #=> nil

When the enumerable does not respond to first

Parliament::Grom::Decorator::Helpers::Utils.type_safe_first('hello', String) #=> nil

Parameters:

  • enumerable (Enumerable)

    object which responds to #first

  • klass (Class)

    the class we expect the first element to be

Returns:

  • (String)

    formatted date range

Since:

  • 0.1.0



23
24
25
26
27
28
29
30
31
# File 'lib/parliament/grom/decorator/helpers/utils.rb', line 23

def type_safe_first(enumerable, klass)
  return nil unless enumerable.respond_to?(:first)

  first_element = enumerable.first

  return nil unless first_element.is_a?(klass)

  first_element
end