Class: Wings::Model::FileModel

Inherits:
Object
  • Object
show all
Defined in:
lib/wings/file_model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ FileModel

Returns a new instance of FileModel.



6
7
8
9
10
11
12
# File 'lib/wings/file_model.rb', line 6

def initialize(filename)
  @filename = filename

  # if filename is 'dir/3.json', @id would be 3
  @id = File.basename(filename, '.json').to_i
  @data = MultiJson.load(File.read(filename))
end

Class Method Details

.allObject



30
31
32
# File 'lib/wings/file_model.rb', line 30

def self.all
  Dir['db/quotes/*.json'].map { |f| FileModel.new(f) }
end

.create(**attrs) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/wings/file_model.rb', line 34

def self.create(**attrs)
  data = {
    quote: attrs[:quote],
    submitter: attrs[:submitter],
    attribution: attrs[:attribution],
  }

  files = Dir['db/quotes/*.json']
  existing_ids = files.map { |f| File.basename(f, '.json').to_i }
  new_id = existing_ids.max + 1

  File.open("db/quotes/#{new_id}.json", 'w') do |f|
    f.write formatted_data(data)
  end

  FileModel.new "db/quotes/#{new_id}.json"
end

.find(id) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/wings/file_model.rb', line 22

def self.find(id)
  begin
    FileModel.new("db/quotes/#{id}.json") # FIX
  rescue
    nil
  end
end

Instance Method Details

#[](name) ⇒ Object



14
15
16
# File 'lib/wings/file_model.rb', line 14

def [](name)
  @data[name.to_s]
end

#[]=(name, value) ⇒ Object



18
19
20
# File 'lib/wings/file_model.rb', line 18

def []=(name, value)
  @data[name.to_s] = value
end