/
file_mirror.rb
69 lines (58 loc) · 1.6 KB
/
file_mirror.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require "digest/sha1"
module Redcar
class Project
# Represents a local file. Implements the EditView::Mirror interface so it
# can be used as a mirror for a Redcar::Document. This is how files are
# loaded in Redcar. EditView contains a Document which contains a Mirror
# which reflects a file.
class FileMirror
include Redcar::EditView::Mirror
# @param [String] a path to a file
def initialize(path)
@path = path
end
# Load the contents of the file from disk
#
# @return [String]
def read
contents = load_contents
@hash = Digest::SHA1.hexdigest(contents)
contents
end
# Does the file exist?
#
# @return [Boolean]
def exists?
File.exists?(@path)
end
# Has the file changed since the last time it was read or commited?
# If it has never been read then this is true by default.
#
# @return [Boolean]
def changed?
@hash != Digest::SHA1.hexdigest(load_contents)
end
# Save new file contents.
#
# @param [String] new contents
# @return [unspecified]
def commit(contents)
save_contents(contents)
@hash = Digest::SHA1.hexdigest(contents)
end
# The filename.
#
# @return [String]
def title
@path.split("/").last
end
private
def load_contents
File.read(@path)
end
def save_contents(contents)
File.open(@path, "w") {|f| f.print contents }
end
end
end
end