Save track files in new Sound model:
* Consolidate migrations * Add Sound model. Each sound can belong to a track and contains informations about one sound file.
This commit is contained in:
6
app/controllers/sounds_controller.rb
Normal file
6
app/controllers/sounds_controller.rb
Normal file
@@ -0,0 +1,6 @@
|
||||
class SoundsController < ApplicationController
|
||||
def show
|
||||
sound = Sound.find params[:id]
|
||||
send_file sound.path, :type => sound.mime_type
|
||||
end
|
||||
end
|
@@ -8,19 +8,11 @@ class TracksController < ApplicationController
|
||||
end
|
||||
|
||||
def create
|
||||
@track = Track.new(:name => params[:track][:name])
|
||||
if @track.save_with_file(
|
||||
params[:track][:file],
|
||||
params[:track][:file].content_type
|
||||
)
|
||||
@track = Track.new params[:track]
|
||||
if @track.save
|
||||
redirect_to @track
|
||||
else
|
||||
render :new
|
||||
end
|
||||
end
|
||||
|
||||
def download
|
||||
track = Track.find params[:id]
|
||||
send_file track.filepath, :type => track.mime_type
|
||||
end
|
||||
end
|
||||
|
18
app/models/sound.rb
Normal file
18
app/models/sound.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
require 'fileutils'
|
||||
|
||||
class Sound < ActiveRecord::Base
|
||||
belongs_to :track
|
||||
|
||||
validates_presence_of :sha256
|
||||
validates_presence_of :mime_type
|
||||
|
||||
def path
|
||||
"#{Rails.root}/data/sounds/#{sha256}"
|
||||
end
|
||||
|
||||
def file=(file)
|
||||
self.sha256 = Digest::SHA256.file(file.path).hexdigest
|
||||
FileUtils.cp file.path, path
|
||||
self.mime_type = file.content_type
|
||||
end
|
||||
end
|
@@ -1,19 +1,20 @@
|
||||
class Track < ActiveRecord::Base
|
||||
validates_presence_of :name
|
||||
validates_presence_of :mime_type
|
||||
validates_presence_of :sha256
|
||||
has_many :sounds
|
||||
|
||||
def filepath
|
||||
"#{Rails.root}/data/tracks/#{sha256}"
|
||||
attr_accessible :name, :file
|
||||
|
||||
validates_presence_of :name
|
||||
|
||||
def file=(file)
|
||||
sounds.build({:file => file})
|
||||
end
|
||||
|
||||
def save_with_file(file, mime_type)
|
||||
self.sha256 = Digest::SHA256.file(file.path).hexdigest
|
||||
self.mime_type = mime_type
|
||||
File.open(filepath, 'w') do |f|
|
||||
f.write file.read
|
||||
end
|
||||
save!
|
||||
def sound
|
||||
sounds.first
|
||||
end
|
||||
|
||||
def sound?
|
||||
sounds.any?
|
||||
end
|
||||
|
||||
def self.latest
|
||||
|
@@ -1,3 +1,4 @@
|
||||
%h1= @track.name
|
||||
%audio{:src => download_track_path(@track), :controls => true, :autoplay => true}
|
||||
Your browser does not support the audio element
|
||||
- if @track.sound?
|
||||
%audio{:src => sound_path(@track.sound), :controls => true, :autoplay => true}
|
||||
Your browser does not support the audio element
|
||||
|
Reference in New Issue
Block a user