diff --git a/app/controllers/stuffs_controller.rb b/app/controllers/stuffs_controller.rb index 8e0dc37..0ec2e0b 100644 --- a/app/controllers/stuffs_controller.rb +++ b/app/controllers/stuffs_controller.rb @@ -4,7 +4,7 @@ class StuffsController < ApplicationController # GET /stuffs # GET /stuffs.json def index - @stuffs = Stuff.all + @stuffs = Stuff.available @stuff = Stuff.new end @@ -57,6 +57,7 @@ def download # Use callbacks to share common setup or constraints between actions. def set_stuff @stuff = Stuff.find(params[:id]) + raise ActiveRecord::RecordNotFound if @stuff.expired? end # Never trust parameters from the scary internet, only allow the white list through. diff --git a/app/models/stuff.rb b/app/models/stuff.rb index 74e7d98..38c750e 100644 --- a/app/models/stuff.rb +++ b/app/models/stuff.rb @@ -3,6 +3,17 @@ class Stuff < ActiveRecord::Base has_secure_password validations: false + scope :available, -> { where('? < expires_at', Time.now) } + + def expired? + self.expires_at ? (Time.now >= self.expires_at) : false + end + + before_validation :assign_expires_at + def assign_expires_at + self.expires_at ||= Time.now + 1.day + end + def file end diff --git a/spec/models/stuff_spec.rb b/spec/models/stuff_spec.rb index dc1bbcd..e66059c 100644 --- a/spec/models/stuff_spec.rb +++ b/spec/models/stuff_spec.rb @@ -1,7 +1,8 @@ require 'spec_helper' describe Stuff, :type => :model do - subject(:stuff) { Stuff.new(title: 'foo') } + let(:attrs) { {title: 'foo'} } + subject(:stuff) { Stuff.new(attrs) } describe "#file=" do let(:uploaded_file) { double('uploaded_file') } @@ -34,4 +35,20 @@ expect( stuff.filepath ).to eq '/tmp/a.jpg' end end + + describe "#expired?" do + subject { stuff.expired? } + before { stuff.save } + + it { should eq false } + + context "when expired" do + let(:attrs) { {title: 'foo', expires_at: 1.day.ago} } + it { should eq true } + end + end + + it "assigns expires_at" do + expect(stuff.tap(&:save).expires_at).to be_a_kind_of(Time) + end end