Class: BusinessTime::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/business_time/config.rb

Overview

controls the behavior of this gem. You can change the beginning_of_workday, end_of_workday, and the list of holidays manually, or with a yaml file and the load method.

Constant Summary collapse

DEFAULT_CONFIG =
{
  holidays:              [],
  beginning_of_workday:  '9:00 am',
  end_of_workday:        '5:00 pm',
  work_week:             %w(mon tue wed thu fri),
  work_hours:            {},
  work_hours_total:      {},
  _weekdays:             nil,
}

Class Method Summary collapse

Class Method Details

.beginning_of_workday(day = nil) ⇒ Object


85
86
87
88
89
90
91
92
# File 'lib/business_time/config.rb', line 85

def beginning_of_workday(day=nil)
  if day
    wday = work_hours[int_to_wday(day.wday)]
    wday ? wday.first : config[:beginning_of_workday]
  else
    config[:beginning_of_workday]
  end
end

.default_configObject


141
142
143
# File 'lib/business_time/config.rb', line 141

def default_config
  deep_dup(DEFAULT_CONFIG)
end

.end_of_workday(day = nil) ⇒ Object


76
77
78
79
80
81
82
83
# File 'lib/business_time/config.rb', line 76

def end_of_workday(day=nil)
  if day
    wday = work_hours[int_to_wday(day.wday)]
    wday ? (wday.last =~ /^0{1,2}\:0{1,2}$/ ? "23:59:59" : wday.last) : config[:end_of_workday]
  else
    config[:end_of_workday]
  end
end

.load(file) ⇒ Object

loads the config data from a yaml file written as:

business_time:
  beginning_od_workday: 8:30 am
  end_of_workday: 5:30 pm
  holidays:
    - Jan 1st, 2010
    - July 4th, 2010
    - Dec 25th, 2010

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/business_time/config.rb', line 117

def load(file)
  reset
  data = YAML::load(file.respond_to?(:read) ? file : File.open(file))
  config = (data["business_time"] || {})

  # load each config variable from the file, if it's present and valid
  config_vars = %w(beginning_of_workday end_of_workday work_week work_hours)
  config_vars.each do |var|
    send("#{var}=", config[var]) if config[var] && respond_to?("#{var}=")
  end

  (config["holidays"] || []).each do |holiday|
    holidays << Date.parse(holiday)
  end
end

.weekdaysObject


99
100
101
102
103
104
105
106
# File 'lib/business_time/config.rb', line 99

def weekdays
  return _weekdays unless _weekdays.nil?

  self._weekdays = (!work_hours.empty? ? work_hours.keys : work_week).each_with_object([]) do |day_name, days|
    day_num = wday_to_int(day_name)
    days << day_num unless day_num.nil?
  end
end

.with(config) ⇒ Object


133
134
135
136
137
138
139
# File 'lib/business_time/config.rb', line 133

def with(config)
  old = config().dup
  config.each { |k,v| send("#{k}=", v) } # calculations are done on setting
  yield
ensure
  self.config = old
end

.work_week=(days) ⇒ Object


94
95
96
97
# File 'lib/business_time/config.rb', line 94

def work_week=(days)
  config[:work_week] = days
  self._weekdays = nil
end