Class: Reins::Model::FileModel

Inherits:
Object
  • Object
show all
Defined in:
lib/reins/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
13
# File 'lib/reins/file_model.rb', line 6

def initialize(filename)
  @filename = filename
  # If filename is "dir/37.json", @id is 37
  basename = File.split(filename)[-1]
  @id = File.basename(basename, ".json").to_i
  obj = File.read(filename)
  @hash = MultiJson.load(obj)
end

Class Method Details

.allObject



23
24
25
26
# File 'lib/reins/file_model.rb', line 23

def self.all
  files = Dir["db/quotes/*.json"]
  files.map { |f| FileModel.new f }
end

.create(attrs) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/reins/file_model.rb', line 36

def self.create(attrs)
  hash = {}
  hash["submitter"] = attrs["submitter"] || ""
  hash["quote"] = attrs["quote"] || ""
  hash["attribution"] = attrs["attribution"] || ""

  files = Dir["db/quotes/*.json"]
  names = files.map { |f| File.split(f)[-1] }
  highest = names.map { |b| b.to_i }.max

  id = highest + 1
  File.open("db/quotes/#{id}.json", "w") do |f|
    f.write <<TEMPLATE
{
  "submitter": "#{hash["submitter"]}",
  "quote": "#{hash["quote"]}",
  "attribution": "#{hash["attribution"]}"
}
TEMPLATE
  end

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

.find(id) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/reins/file_model.rb', line 28

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

.find_all_by_submitter(submitter) ⇒ Object



84
85
86
87
88
# File 'lib/reins/file_model.rb', line 84

def self.find_all_by_submitter(submitter)
  files = Dir["db/quotes/*.json"]
  files.map { |f| FileModel.new f }
    .select { |m| m['submitter'] == submitter }
end

.saveObject



80
81
82
# File 'lib/reins/file_model.rb', line 80

def self.save
  # TODO: use MultiJson.dump() to turn @hash into JSON
end

.update(attrs) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/reins/file_model.rb', line 60

def self.update(attrs)
  hash = {}
  hash["submitter"] = attrs["submitter"] || ""
  hash["quote"] = attrs["quote"] || ""
  hash["attribution"] = attrs["attribution"] || ""

  id = 3
  File.open("db/quotes/#{id}.json", "w") do |f|
    f.write <<TEMPLATE
{
  "submitter": "#{hash["submitter"]}",
  "quote": "#{hash["quote"]}",
  "attribution": "#{hash["attribution"]}"
}
TEMPLATE
  end

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

Instance Method Details

#[](name) ⇒ Object



15
16
17
# File 'lib/reins/file_model.rb', line 15

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

#[]=(name, value) ⇒ Object



19
20
21
# File 'lib/reins/file_model.rb', line 19

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