Class: Skriptorium::BaseSource

Inherits:
Object
  • Object
show all
Defined in:
lib/skriptorium/base_source.rb

Direct Known Subclasses

DevTo::Source, RSS::Source

Constant Summary collapse

IMAGE_EXTENSIONS =
%w[.png .jpg .jpeg].freeze
MIN_IMAGE_WIDTH =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ BaseSource

Returns a new instance of BaseSource.



10
11
12
13
14
# File 'lib/skriptorium/base_source.rb', line 10

def initialize(config)
  @config = config
  @limit = config['limit'] || 10
  @filter = config['filter']
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/skriptorium/base_source.rb', line 8

def config
  @config
end

#limitObject (readonly)

Returns the value of attribute limit.



8
9
10
# File 'lib/skriptorium/base_source.rb', line 8

def limit
  @limit
end

Instance Method Details

#apply_filter(stream) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/skriptorium/base_source.rb', line 28

def apply_filter(stream)
  return stream unless @filter

  stream.select do |article|
    pass = @filter.all? do |name, opts|
      case name
      when 'front_matter'
        opts.all? do |k, v|
          article.front_matter(k.strip) == v.to_s.strip
        end
      else
        raise "Invalid filter #{name}: #{opts.inspect}"
      end
    end
    pass
  end
end

#enrich_article(article) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/skriptorium/base_source.rb', line 46

def enrich_article(article)
  if article.cover_image.nil? || article.cover_image.to_s.strip.empty?
    found = extract_cover_image(article.content)
    article.cover_image = found if found
  end
  article
end

#extract_cover_image(content) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/skriptorium/base_source.rb', line 54

def extract_cover_image(content)
  return nil if content.nil? || content.to_s.strip.empty?

  # 1. HTML img tags first — they may have width/height attributes
  content.scan(/<img[^>]*>/i).each do |img_tag|
    src = extract_src(img_tag)
    next unless src && image_url?(src)
    return src if image_large_enough?(src)
  end

  # 2. Markdown images
  content.scan(/!\[.*?\]\((.+?)\)/).each do |match|
    url = match[0].split(' ').first
    next unless image_url?(url)
    return url if image_large_enough?(url)
  end

  nil
end

#fetchArray<Article>

Returns:

Raises:

  • (NotImplementedError)


17
18
19
# File 'lib/skriptorium/base_source.rb', line 17

def fetch
  raise NotImplementedError, "#{self.class} must implement #fetch"
end

#fetch_latestObject



21
22
23
24
25
26
# File 'lib/skriptorium/base_source.rb', line 21

def fetch_latest
  stream = fetch
  filtered = apply_filter(stream)
  enriched = filtered.map { |article| enrich_article(article) }
  enriched.first(@limit)
end