Class: Locomotive::Steam::UrlFinderService

Inherits:
Object
  • Object
show all
Defined in:
lib/locomotive/steam/services/url_finder_service.rb

Overview

This service is used for the following use cases:

  • get an url of a link encoded by the RichTextEditor component in the engine

  • get an url of a link created through the UrlPicker component in the engine

Instance Method Summary collapse

Instance Method Details

Decode a link



61
62
63
64
# File 'lib/locomotive/steam/services/url_finder_service.rb', line 61

def decode_link(encoded_value)
  decoded_value = Base64.decode64(encoded_value)
  JSON.parse(decoded_value)
end

#decode_url_for(encoded_value) ⇒ Object

Same behavior as for url_for except the parameter is a JSON string encoded in Base64



47
48
49
# File 'lib/locomotive/steam/services/url_finder_service.rb', line 47

def decode_url_for(encoded_value)
  url_for(decode_link(encoded_value))
end

#decode_urls_for(text) ⇒ Object

Apply the decode_url_for method for each link of a text



52
53
54
55
56
57
58
# File 'lib/locomotive/steam/services/url_finder_service.rb', line 52

def decode_urls_for(text)
  return text if text.blank?

  text.gsub(Locomotive::Steam::SECTIONS_LINK_TARGET_REGEXP) do
    decode_url_for($~[:link])[0]
  end
end

#url_for(resource) ⇒ Object

Return an array with the following elements: [<URL>, <NEW_WINDOW>]

Example: url_for(

'type'        => 'page',
'value'       =>  '42', # id of the home page
'locale'      => 'en',
'new_window'  => true,
'anchor'      => 'portfolio'

)

will return: [‘/#portfolio’, true]



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/locomotive/steam/services/url_finder_service.rb', line 25

def url_for(resource)
  return [resource, false] if resource.is_a?(String)

  _resource   = resource || {}
  page_or_url = find_page(_resource['type'], _resource['value']) || page_finder.find('404')

  url = if page_or_url.is_a?(String)
    page_or_url
  elsif !page_or_url.not_found?
    [url_builder.url_for(page_or_url), _resource['anchor'].presence].compact.join('#')
  else
    url_builder.url_for(page_or_url)
  end

  [
    url,
    _resource['new_window'] || false
  ]
end