Module: DemoLorem::Helpers::NonaiApiHelper

Included in:
Generator
Defined in:
lib/demo_lorem/helpers/nonai_api_helper.rb

Overview

NonaiApiHelper module currently fetches wikipedia content for a given topic and length

Returns:

  • (String)

    content fetched from Wikipedias

Instance Method Summary collapse

Instance Method Details

#fetch_wikipedia_content(topic, length) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/demo_lorem/helpers/nonai_api_helper.rb', line 14

def fetch_wikipedia_content(topic, length)
  puts 'Please wait while we fetch your content... (this may take 2-10 seconds)'
  sleep(rand(2..10)) # Simulate wait time

  variations = [topic, topic.tr('_', ' ')]
  variations.each do |variation|
    url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exchars=#{length}&explaintext=true&format=json&titles=#{CGI.escape(variation)}"
    response = HTTParty.get(url)
    pages = response.dig('query', 'pages')
    next if pages.nil? || pages.empty?

    page = pages.values.first
    extract = page.dig('extract')
    return extract unless extract.nil? || extract.empty?
  end

  'No content found for the given topic'
rescue StandardError => e
  "An error occurred while fetching Wikipedia content: #{e.message}"
end