Class: KStarter::Database::ProjectModel

Inherits:
BaseModel
  • Object
show all
Defined in:
lib/k_starter/database/project_model.rb

Overview

Handle access to project data files

Constant Summary collapse

DEFAULT_FILE_NAME =
'k_starter.projects.json'

Instance Attribute Summary

Attributes inherited from BaseModel

#backup_folder, #data, #filename, #folder

Instance Method Summary collapse

Constructor Details

#initialize(**args) ⇒ ProjectModel

@data = nil end



28
29
30
31
32
33
# File 'lib/k_starter/database/project_model.rb', line 28

def initialize(**args)
  args = { file: DEFAULT_FILE_NAME }.merge(args)
  super(**args)

  initialize_model
end

Instance Method Details

#find_project(name, variant = nil) ⇒ Object



42
43
44
45
46
# File 'lib/k_starter/database/project_model.rb', line 42

def find_project(name, variant = nil)
  index = find_project_index(name, variant)

  return project_list[index] if index
end

#find_project_index(name, variant = nil) ⇒ Object



48
49
50
# File 'lib/k_starter/database/project_model.rb', line 48

def find_project_index(name, variant = nil)
  project_list.find_index { |p| p.name == name && (variant.nil? || p.variant == variant) }
end

#project_listObject



35
36
37
38
39
40
# File 'lib/k_starter/database/project_model.rb', line 35

def project_list
  @project_list ||= begin
    projects = data[:projects]
    projects.map { |project| KStarter::Map.project(project) }
  end
end

#save_project(project, project_index = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/k_starter/database/project_model.rb', line 52

def save_project(project, project_index = nil)
  project = project.to_h unless project.is_a?(Hash)

  index = project_index || find_project_index(project[:name])

  if index.nil?
    data[:projects] << project
  else
    data[:projects][index] = project
  end

  write
  clear_memoization
end