Class: Drum::FileService

Inherits:
Service show all
Includes:
Log, YAMLUtils
Defined in:
lib/drum/service/file.rb

Overview

A service that reads/writes playlists to/from YAML files.

Instance Method Summary collapse

Methods included from Log

#log

Methods included from YAMLUtils

#from_yaml

Instance Method Details

#download(playlist_ref) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/drum/service/file.rb', line 43

def download(playlist_ref)
  base_path = playlist_ref.resource_location

  if base_path.directory?
    Dir.glob("#{base_path}/**/*.{yaml,yml}").map do |p|
      path = Pathname.new(p)
      playlist = Playlist.deserialize(from_yaml(path.read))
      playlist.path = path.relative_path_from(base_path).parent.each_filename.to_a
      playlist
    end
  else
    [Playlist.deserialize(from_yaml(base_path.read))]
  end
end

#nameObject



15
16
17
# File 'lib/drum/service/file.rb', line 15

def name
  'file'
end

#parse_ref(raw_ref) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/drum/service/file.rb', line 19

def parse_ref(raw_ref)
  if raw_ref.is_token
    return nil
  end

  raw_path = if raw_ref.text.start_with?('file:')
    URI(raw_ref.text).path
  else
    raw_ref.text
  end

  path = Pathname.new(raw_path)
  Ref.new(self.name, :any, path)
end

#remove(playlist_ref) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/drum/service/file.rb', line 34

def remove(playlist_ref)
  path = playlist_ref.resource_location
  if path.directory?
    raise 'Removing directories is not supported!'
  end
  log.info "Removing #{path}..."
  path.delete
end

#upload(playlist_ref, playlists) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/drum/service/file.rb', line 58

def upload(playlist_ref, playlists)
  base_path = playlist_ref.resource_location

  playlists.each do |playlist|
    path = base_path
    dict = playlist.serialize

    # Strip path from serialized playlist
    dict.delete('path')

    if !path.exist? || path.directory?
      unless playlist.path.empty?
        path = path / playlist.path.map { |n| Pathname.new(n) }.reduce(:/)
      end

      playlist_path = lambda do |length|
        path / "#{playlist.name.kebabcase}-#{playlist.id[...length]}.yaml"
      end

      length = 6
      while playlist_path[length].exist? && Playlist.deserialize(from_yaml(playlist_path[length].read)).id != playlist.id
        length += 1
      end

      path = playlist_path[length]
    end

    path.parent.mkpath
    path.write(dict.to_yaml)
  end
end