Module: Genius::Songs

Extended by:
Errors
Defined in:
lib/genius/api/songs.rb

Overview

Genius::Songs module provides methods to work with songs (lyrics/descriptions/etc.)

Constant Summary

Constants included from Errors

Errors::ENDPOINT

Class Method Summary collapse

Methods included from Errors

error_handle?, validate_token

Class Method Details

.get_lyrics(song_id) ⇒ String

Extracts lyrics as plain text from the Genius song page.

Parameters:

  • song_id (Integer)

    ID of the song.

Returns:

Raises:

  • (ArgumentError)

    if song_id is nil.

  • (NoMethodError)


69
70
71
72
73
74
75
76
77
78
79
# File 'lib/genius/api/songs.rb', line 69

def get_lyrics(song_id)
  raise ArgumentError, '`song_id` should be not blank!' if song_id.nil?

  response = HTTParty.get("https://genius.com/songs/#{song_id}")
  document = Nokogiri::HTML(response)
  # @todo: something wrong with lyrics attribute value
  lyrics_path = document.xpath("//*[@class='Lyrics__Container-sc-1ynbvzw-6 YYrds']")
  lyrics_path.at_css('p').content
rescue NoMethodError
  retry
end

.songs(token: nil, song_id: nil, combine: false) ⇒ Hash, ...

Returns song data by ID. Optionally merges lyrics from the Genius page when combine is true.

Parameters:

  • token (String?) (defaults to: nil)

    Token to access api.genius.com.

  • song_id (Integer?) (defaults to: nil)

    ID of the song.

  • combine (Boolean) (defaults to: false)

    If true, fetches and merges lyrics into the response.

Returns:



15
16
17
18
19
20
21
22
23
# File 'lib/genius/api/songs.rb', line 15

def songs(token: nil, song_id: nil, combine: false)
  return if token.nil? && !Auth.authorized?.nil?

  Errors.validate_token(token) unless token.nil?

  response = HTTParty.get("#{Api::RESOURCE}/songs/#{song_id}?access_token=#{token_ext(token)}").body
  response = JSON.parse response
  combine && song_id ? merge_lyrics(song_id, response) : response
end