oldhaven/lib/discogs.rb
2011-09-22 19:40:44 +04:00

80 lines
2.7 KiB
Ruby

class Discogs
def self.artists
self.get_nodes('tmp/data/discogs_artists.xml', 'artist') do |node|
artist = Artist.new(
:name => (node.css('name').first.text),
:pic_url => (node.css('images > image[type="primary"]').first.attr('uri') unless node.css('images > image[type="primary"]').empty?),
:status => 1
)
artist.save
node.css('namevariations > name, aliases > name').each do |v|
ArtistAlias.new(
:artist_id => artist.id,
:name => v.text
).save
end
end
end
def self.releases
self.get_nodes('tmp/data/discogs_releases_test.xml', 'release') do |node|
release = {
:pic => (node.css('images > image[type="primary"]').first.attr('uri') unless node.css('images > image[type="primary"]').empty?),
:main_artist => (node.css('artists > artist > name').first.text unless node.css('artists > artist > name').empty?),
:master => (not node.css('master_id').empty?),
:name => (node.css('title').first.text unless node.css('title').empty?),
:country => (node.css('country').first.text unless node.css('country').empty?),
:year => (node.css('released').first.text.split('-').first.to_i unless node.css('released').empty?),
:genres => [],
:styles => [],
:tracks => [],
}
unless node.css('genres > genre').empty?
node.css('genres > genre').each do |genre|
release[:genres] << Genre.find_or_create_by_name(genre.text)
end
end
unless node.css('styles > style').empty?
node.css('styles > style').each do |style|
release[:styles] << Style.find_or_create_by_name(style.text)
end
end
unless node.css('tracklist > track').empty?
node.css('tracklist > track').each do |track|
release[:tracks] << Track.new(
:name => (track.css('title').first.text unless track.css('title').empty?),
:position => (track.css('position').first.text.to_i(36) unless track.css('position').empty?),
:length => (self.duration_to_length(track.css('duration').first.text) unless track.css('duration').empty?)
)
end
end
ap release
end
end
private
def self.get_nodes filename, nodename, &block
File.open(filename) do |file|
Nokogiri::XML::Reader.from_io(file).each do |node|
if node.name == nodename and node.node_type == Nokogiri::XML::Reader::TYPE_ELEMENT
yield(Nokogiri::XML(node.outer_xml).root)
end
end
end
end
def self.duration_to_length duration
duration = duration.split(':')
duration[0].to_i * 60 + duration[1].to_i
end
end