Module: Contentful::Support

Defined in:
lib/contentful/support.rb

Overview

Utility methods used by the contentful gem

Class Method Summary collapse

Class Method Details

.includes_from_response(json, raw = true) ⇒ Array

Returns combined include array from an API Response

Parameters:

  • json (Hash)

    JSON Response

  • raw (Bool) (defaults to: true)

    Response pre-proccessed?

Returns:



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/contentful/support.rb', line 66

def includes_from_response(json, raw = true)
  includes = if raw
               json['items'].dup
             else
               json['items'].map(&:raw)
             end

  %w(Entry Asset).each do |type|
    if json.fetch('includes', {}).key?(type)
      includes.concat(json['includes'].fetch(type, []))
    end
  end

  includes
end

.link?(value) ⇒ true, false

Checks if value is a link

Parameters:

  • value

Returns:

  • (true, false)


31
32
33
34
# File 'lib/contentful/support.rb', line 31

def link?(value)
  value.is_a?(::Hash) &&
    value.fetch('sys', {}).fetch('type', '') == 'Link'
end

Checks if value is an array of links

Parameters:

  • value

Returns:

  • (true, false)


41
42
43
44
45
# File 'lib/contentful/support.rb', line 41

def link_array?(value)
  return link?(value[0]) if value.is_a?(::Array) && !value.empty?

  false
end

Returns the resource that matches the link

Parameters:

  • link (Hash)
  • includes (::Array)

Returns:

  • (Hash)


53
54
55
56
57
58
# File 'lib/contentful/support.rb', line 53

def resource_for_link(link, includes)
  includes.detect do |i|
    i['sys']['id'] == link['sys']['id'] &&
      i['sys']['type'] == link['sys']['linkType']
  end
end

.snakify(object, skip = false) ⇒ String

Transforms CamelCase into snake_case (taken from zucker)

Parameters:

  • object (String)

    camelCaseName

  • skip (Boolean) (defaults to: false)

    if true, skips returns original object

Returns:

  • (String)

    snake_case_name



11
12
13
14
15
16
17
18
19
20
# File 'lib/contentful/support.rb', line 11

def snakify(object, skip = false)
  return object if skip

  String(object)
    .gsub(/::/, '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .downcase
end

.unresolvable?(value, errors) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/contentful/support.rb', line 22

def unresolvable?(value, errors)
  errors.any? { |i| i.fetch('details', {}).fetch('id', nil) == value['sys']['id'] }
end