Class: Genius

Inherits:
Wiki
  • Object
show all
Defined in:
lib/wiki/genius.rb

Overview

Fetches the lyrics from Genius (formerly known as Rap Genius) Lyrics are stored accessed via the URL schema genius.com/ARTIST-SONG-lyrics They are inside //div[starts-with(@class, “Lyrics__Container”)]

Instance Method Summary collapse

Methods inherited from Wiki

#fetch, #prepare_url, #set_lyrics

Instance Method Details

#get_lyrics(artist, song, limit = 10) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/wiki/genius.rb', line 9

def get_lyrics(artist, song, limit = 10)
  artist = artist.tr(' ', '-').gsub(/('|`|´|’)/, '').gsub(/(?:\(?feat.*\)?)/, '').parameterize
  song = song.tr(' ', '-').gsub(/('|`|´|’)/, '').gsub(/(?:\(?feat.*\)?)/, '').parameterize

  res = fetch("https://genius.com/#{artist.downcase}-#{song.downcase}-lyrics", limit)
  return nil unless res.is_a? Net::HTTPSuccess

  lyrics = Nokogiri::HTML(res.body).xpath("//div[starts-with(@class, 'lyrics') or starts-with(@class, 'Lyrics__Container')]")
  lyrics.inner_html.gsub('<br>', "\r").gsub(%r{</?[^>]+>}, '').delete("\n").strip
end