reservation.rb 1.51 KB
Newer Older
Tyler Lemburg's avatar
Tyler Lemburg committed
1
require 'active_record'
Tyler Lemburg's avatar
Tyler Lemburg committed
2
require 'models/resource'
3
require 'icalendar'
Tyler Lemburg's avatar
Tyler Lemburg committed
4
5
6
7
8
9
10
11
12
13
14
15

class Reservation < ActiveRecord::Base
	belongs_to :resource
	belongs_to :event
	belongs_to :user

	scope :in_day, ->(time) {
		today = time.in_time_zone.midnight
		tomorrow = (time.in_time_zone.midnight + 1.day + 1.hour).in_time_zone.midnight
		where('(start_time >= ? AND start_time < ?) OR (end_time >= ? AND end_time < ?)', today.getutc, tomorrow.getutc, today.getutc, tomorrow.getutc)
	}

Tyler Lemburg's avatar
Tyler Lemburg committed
16
17
18
19
20
21
	scope :in_week, ->(time) {
		last_sunday = time.in_time_zone.week_start
		next_sunday = (time.in_time_zone.week_start + 1.week + 1.hour).in_time_zone.week_start
		where('(start_time >= ? AND start_time < ?) OR (end_time >= ? AND end_time < ?)', last_sunday.getutc, next_sunday.getutc, last_sunday.getutc, next_sunday.getutc)
	}

Tyler Lemburg's avatar
Tyler Lemburg committed
22
23
24
25
26
27
28
	# returns length in minutes. If start or end is nil, returns 0
	def length
		if end_time.nil? || start_time.nil?
			return 0
		end
		((end_time - start_time) / 60).to_i
	end
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

	def to_ics
		calendar = Icalendar::Calendar.new
		ical = Icalendar::Event.new
		ical.dtstart = self.start_time.in_time_zone.strftime("%Y%m%dT%H%M%S")
		ical.dtend = self.end_time.in_time_zone.strftime("%Y%m%dT%H%M%S")
		ical.summary = self.title
		ical.description = self.description
		ical.location = self.resource.name
		ical.uid = "unl_resource_scheduler_#{ENV['RACK_ENV']}_reservation_#{self.id}"
		calendar.add_event(ical)
		calendar.to_ical
	end

	def download_link
		"/#{resource.service_space.url_name}/resources/#{resource.id}/reservation/#{id}/reservation.ics"
	end
Tyler Lemburg's avatar
Tyler Lemburg committed
46
end