Revisions

gist: 87015 Download_button fork
public
Public Clone URL: git://gist.github.com/87015.git
Embed All Files: show embed
location.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Location < ActiveRecord::Base
  has_many :opening_hours, :order => :day_of_week, :dependent => :destroy
 
 
  def hours
    out = HoursForLocation.new
    for i in 0..6 do
      out[i] = opening_hours.find :first, :conditions => "day_of_week = #{i}"
    end
    out
  end
  
  def hours=(hours)
    hours.each do |day,values|
      self.create_or_update_opening_hours(day, values)
    end
  end
  
  def closed=(days)
    hours = OpeningHour.find :all, :conditions => "location_id = #{self.id} AND day_of_week IN (#{days.keys.join(',')})"
    hours.each{|h| h.update_attribute(:closed, true)}
  end
  
  def create_or_update_opening_hours(day, values)
    values.symbolize_keys!
    hour = opening_hours.find :first, :conditions => "day_of_week = #{day}"
    hour ||= OpeningHour.new :location => self, :day_of_week => day
    hour.open, hour.close = values[:open], values[:close]
    hour.save
  end
 
end
 
class HoursForLocation < Array
end
 
opening_hour.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# == Schema Information
# Schema version: 20080627025704
#
# Table name: opening_hours
#
# id :integer(11) not null, primary key
# location_id :integer(11) not null
# day_of_week :integer(4) not null
# open :time
# close :time
# created_at :datetime
# updated_at :datetime
# closed :boolean(1)
#
 
class OpeningHour < ActiveRecord::Base
  belongs_to :location
end