Module: NameTag

Defined in:
lib/nametag.rb,
lib/nametag/version.rb

Defined Under Namespace

Modules: BetterStruct Classes: Info, Options

Constant Summary collapse

RX =

default pattern; matches artist, album, track, title, ext; optionally: album_n, year; matches e.g. "Between_the_Buried_and_Me/04-Colors_(2007)/05-Ants_of_the_Sky.mp3"

%r{ / (?<artist> [^/]* )
/ (?: (?<album_n> [0-9]+ ) - )?
  (?<album> [^/]*? )
  (?: _\( (?<year> \d{4} ) \) )?
/ (?<track> [0-9]+ ) (?: - (?<title> [^/]* ) )?
  \. (?<ext> mp3 | ogg | flac )
\z }x
TR =

default character substitution

{ '_|' => ' /' }
TR_F =

substitute characters

->(o) { ->(x) {
  x && o.tr.reduce(x) { |a,y;k,v| k, v = y; a.tr k, v }
} }
PROCESS =

tr all values

->(i, o, f) { i.map { |k,v| [k, f[v]] } }
DEFAULTS =

default options

Options.new regexes: [RX], tr: TR, _process: []
VERSION =
'0.2.0'
DATE =
'2013-09-05'

Class Method Summary collapse

Class Method Details

._first_map(xs, &f) ⇒ Object

lazy xs.map(&f).first



123
124
125
# File 'lib/nametag.rb', line 123

def self._first_map(xs, &f)
  xs.each { |x| y = f[x]; return y if y }; nil
end

.configure(c = DEFAULTS, &b) ⇒ Object

configure nametag by changing DEFAULTS, which is passed to the block



81
82
83
# File 'lib/nametag.rb', line 81

def self.configure(c = DEFAULTS, &b)
  b[c]; c
end

.parse(filename, opts) ⇒ Info?

parse filename; tries each regex in turn

Returns:



89
90
91
92
# File 'lib/nametag.rb', line 89

def self.parse(filename, opts)
  m = _first_map(opts.regexes) { |rx| rx.match filename }
  m ? Info.new(Hash[m.names.map { |x| [x, m[x]] }]) : nil
end

.process(info, opts) ⇒ Info

process info object; tries each processing function in turn

Returns:



96
97
98
99
100
101
102
103
104
105
# File 'lib/nametag.rb', line 96

def self.process(info, opts)                                  # {{{1
  ps    = opts._process + [PROCESS]; tr = TR_F[opts]
  info_ = _first_map(ps) { |p| p[info, opts, tr] }
  case info_
  when Info ; info_
  when Hash ; Info.new(info_)
  when Array; Info.new(Hash[info_])
  else raise 'processing function dit not return Info|Hash|Array'
  end
end

.tag(filename, info) ⇒ Object

process file: set tags from info, save file



108
109
110
111
112
113
114
115
116
117
118
# File 'lib/nametag.rb', line 108

def self.tag(filename, info)                                  # {{{1
  TagLib::FileRef.open(filename) do |file|
    tag         = file.tag
    tag.artist  = info[:artist]
    tag.album   = info[:album]
    tag.track   = info[:track].to_i
    tag.title   = info[:title] || "[track #{info[:track]}]"
    tag.year    = info[:year].to_i
    file.save
  end
end