Method: Feet::Model::FileModel.create

Defined in:
lib/feet/file_model.rb

.create(attrs) ⇒ Object



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
70
71
# File 'lib/feet/file_model.rb', line 44

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

  # Find highest id
  files = Dir['db/quotes/*.json']
  names = files.map { |f| File.split(f)[-1] } # transform to_i here?
  highest = names.map(&:to_i).max
  id = highest + 1

  # Open and write the new file
  new_filename = "db/quotes/#{id}.json"
  File.open("db/quotes/#{id}.json", 'w') do |f|
    f.write "      {\n          \"submitter\": \"\#{hash['submitter']}\",\n          \"quote\": \"\#{hash['quote']}\",\n          \"attribution\": \"\#{hash['attribution']}\"\n      }\n    TEMPLATE\n  end\n\n  # Create new FileModel instance with the new file\n  FileModel.new new_filename\nend\n"