Class: OpenStax::Content::Fragment::Exercise

Inherits:
OpenStax::Content::Fragment show all
Defined in:
lib/openstax/content/fragment/exercise.rb

Direct Known Subclasses

OptionalExercise

Constant Summary collapse

EXERCISE_EMBED_URL_CSS =

CSS to find the embed code attributes

'a[href^="#"]'
EXERCISE_EMBED_URL_REGEXES =

Regex to extract the appropriate tag from the embed code(s)

{
  tag: /\A#ost\/api\/ex\/([\w\s-]+)\z/,
  nickname: /\A#exercises?\/([\w\s-]+)\z/
}
ABSOLUTIZED_EMBED_URL_CSS =

CSS to find the exercise embed queries after the urls are absolutized

'a[href*="/api/exercises"]'
ABSOLUTIZED_EMBED_URL_REGEX =

Regex to extract the appropriate embed queries from the absolutized urls

/\/api\/exercises\/?\?q=(tag|nickname)(?::|%3A)(?:"|%22)?([\w\s%-]+?)(?:"|%22)?\z/

Instance Attribute Summary collapse

Attributes inherited from OpenStax::Content::Fragment

#labels, #node_id, #title

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from OpenStax::Content::Fragment

#html?

Constructor Details

#initialize(node:, title: nil, labels: []) ⇒ Exercise

Returns a new instance of Exercise.



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/openstax/content/fragment/exercise.rb', line 41

def initialize(node:, title: nil, labels: [])
  super

  @embed_queries = node.css(ABSOLUTIZED_EMBED_URL_CSS).map do |anchor|
    url = anchor.attribute('href').value
    match = ABSOLUTIZED_EMBED_URL_REGEX.match(url)
    next if match.nil?

    [ match[1].to_sym, URI.decode_www_form_component(match[2]) ]
  end.compact
end

Instance Attribute Details

#embed_queriesObject (readonly)

Returns the value of attribute embed_queries.



20
21
22
# File 'lib/openstax/content/fragment/exercise.rb', line 20

def embed_queries
  @embed_queries
end

Class Method Details

.absolutize_exercise_urls!(node) ⇒ Object

This code is run from lib/openstax/cnx/v1/page.rb during import



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/openstax/content/fragment/exercise.rb', line 23

def self.absolutize_exercise_urls!(node)
  uri = Addressable::URI.parse OpenStax::Content.exercises_search_api_url

  node.css(EXERCISE_EMBED_URL_CSS).each do |anchor|
    href = anchor.attribute('href')

    EXERCISE_EMBED_URL_REGEXES.each do |field, regex|
      embed_match = regex.match(href.value)
      next if embed_match.nil?

      uri.query_values = { q: "#{field}:\"#{embed_match[1]}\"" }
      href.value = uri.to_s
      anchor['data-type'] = 'exercise'
      break
    end
  end
end

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/openstax/content/fragment/exercise.rb', line 53

def blank?
  embed_queries.empty? && (node_id.nil? || node_id.empty?)
end