Class: DateNamedFile::DatedFile

Inherits:
SimpleDelegator
  • Object
show all
Includes:
Comparable
Defined in:
lib/date_named_file/dated_file.rb

Direct Known Subclasses

MissingFile

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, date_ish = DateTime.now) ⇒ DatedFile

Returns a new instance of DatedFile.

Parameters:

  • template (DateNamedFile::Template)
  • date_ish (<anything date_ish>) (defaults to: DateTime.now)

    (see #forgiving_dateify)



15
16
17
18
# File 'lib/date_named_file/dated_file.rb', line 15

def initialize(template, date_ish=DateTime.now)
  @template = template
  self.datetime = date_ish
end

Instance Attribute Details

#datetimeObject

Returns the value of attribute datetime.



12
13
14
# File 'lib/date_named_file/dated_file.rb', line 12

def datetime
  @datetime
end

Class Method Details

.from_filename(template, filename) ⇒ Object

Raises:



20
21
22
23
24
25
# File 'lib/date_named_file/dated_file.rb', line 20

def self.from_filename(template, filename)
  raise Error.new("String #{filename} does not match template '#{template.template_string}'") unless template.match? filename
  newobject = self.new(template)
  newobject.datetime = newobject.extract_datetime_from_filename(filename)
  newobject
end

Instance Method Details

#<=>(other) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/date_named_file/dated_file.rb', line 43

def <=>(other)
  if self.match? other.to_s
    self.datetime <=> extract_datetime_from_filename(other)
  else
    d2 = Dateish.forgiving_dateify(other)
    z = self.datetime <=> d2
  end
end

#extract_datetime_from_filename(str) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/date_named_file/dated_file.rb', line 52

def extract_datetime_from_filename(str)
  if m = @template.matcher.match(str)
    Dateish.forgiving_dateify(m[1..-1].join(''))
  else
    DateTime.new(0)
  end
end

#match?(other) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/date_named_file/dated_file.rb', line 39

def match?(other)
  @template.match? other.to_s
end

#openObject



60
61
62
63
64
65
66
67
# File 'lib/date_named_file/dated_file.rb', line 60

def open
  raise "File #{@path.to_s} doesn't exist" unless @path.exist?
  begin
    Zlib::GzipReader.open(@path)
  rescue Zlib::GzipFile::Error
    File.open(@path)
  end
end

#pretty_print(q) ⇒ Object

Override pretty-print so it shows up correctly in pry



70
71
72
# File 'lib/date_named_file/dated_file.rb', line 70

def pretty_print(q)
  q.text "<#{self.class}:#{@path}>"
end

#to_datetimeObject

Defining to_datetime allows Dateish.forgiving_datetime to deal with it directly



29
30
31
# File 'lib/date_named_file/dated_file.rb', line 29

def to_datetime
  self.datetime
end