Module: Yarss::Attribute

Defined in:
lib/yarss/attribute.rb

Overview

A bunch of helpers to extract a String value out of a Hash, Array, etc.

Class Method Summary collapse

Class Method Details

Extract a String value from a given link attribute.

Examples:

Yarss::Attribute.link_value('Foo') # => 'Foo'
Yarss::Attribute.link_value('href' => 'Foo') # => 'Foo'
Yarss::Attribute.link_value([{ 'rel' => 'self', 'href' => 'Foo' }])
  # => 'Foo'
Yarss::Attribute.link_value([{ 'rel' => 'alternate', 'href' => 'Foo' }])
  # => 'Foo'

Parameters:

  • value (String, Hash, Array)

    A link attribute.

Returns:

  • (String)

Raises:

  • (ParseError)

    If type of value is not known or no link is found.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/yarss/attribute.rb', line 48

def self.link_value(value)
  value ||= ''

  case value
  when Hash
    link_value(value.fetch('href'))
  when Array
    item = value.find { |l| l.is_a?(String) } ||
           value.find { |l| l['rel'] && l['rel'] == 'self' } ||
           value.find { |l| l['rel'] && l['rel'] == 'alternate' }
    raise KeyError unless item
    link_value(item)
  when String
    value.strip
  else
    raise ParseError, "Unknown #{value.class} attribute: #{value.inspect}"
  end
rescue KeyError => e
  raise ParseError, e
end

.value(value) ⇒ String

Extract a String value from a given attribute.

Examples:

Yarss::Attribute.value('Foo') # => 'Foo'
Yarss::Attribute.value('__content__' => 'Foo') # => 'Foo'

Parameters:

  • value (String, Hash)

    An attribute.

Returns:

  • (String)

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/yarss/attribute.rb', line 18

def self.value(value)
  value ||= ''

  case value
  when Hash
    value(value.fetch('__content__'))
  when String
    value.strip
  else
    raise ParseError, "Unknown #{value.class} attribute: #{value.inspect}"
  end
rescue KeyError => e
  raise ParseError, e
end