Class: Ncn::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/ncn/repository.rb

Constant Summary collapse

CACHE_PATH =
"cache.json"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Repository

Returns a new instance of Repository.



7
8
9
# File 'lib/ncn/repository.rb', line 7

def initialize(path)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



5
6
7
# File 'lib/ncn/repository.rb', line 5

def path
  @path
end

Instance Method Details

#create(tags: [], body: "") ⇒ Object



11
12
13
14
15
16
# File 'lib/ncn/repository.rb', line 11

def create(tags: [], body: "")
  register_new_note(tags: tags, body: body).tap do |note|
    cache.set(note.id, note.meta)
    cache.set("last_id", note.id)
  end
end

#drop(id) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/ncn/repository.rb', line 36

def drop(id)
  meta = cache.fetch(id) { raise Error::NoteNotFound }
  created = Time.parse(meta.fetch("created"))
  path_builder = NotePathBuilder.new(id: id, created: created)
  FileUtils.rm_rf(File.join(path, path_builder.path))
  drop_empty_directories(path_builder.directory_names)
  cache.unset(id)
end

#find(id) ⇒ Object



22
23
24
25
26
27
# File 'lib/ncn/repository.rb', line 22

def find(id)
  meta = cache.fetch(id) { raise Error::NoteNotFound }
  created = Time.parse(meta.fetch("created"))
  relative = NotePathBuilder.new(id: id, created: created).path
  NoteLoader.new(File.join(path, relative)).load
end

#last_idInteger

Returns last cached note id; 0 means the repository is empty.

Returns:

  • (Integer)

    last cached note id; 0 means the repository is empty



50
51
52
# File 'lib/ncn/repository.rb', line 50

def last_id
  cache.fetch("last_id", 0)
end

#listObject



18
19
20
# File 'lib/ncn/repository.rb', line 18

def list
  cache.keys.filter { _1.match?(/^\d+$/) }
end

#note_path(note) ⇒ Object



45
46
47
# File 'lib/ncn/repository.rb', line 45

def note_path(note)
  File.join(path, note.path)
end

#update(id, body: nil, tags: nil) ⇒ Object



29
30
31
32
33
34
# File 'lib/ncn/repository.rb', line 29

def update(id, body: nil, tags: nil)
  note = find(id)
  note.body = body if body
  note.tags = tags if tags
  persist(note)
end