Last active
December 11, 2015 11:59
-
-
Save hollanddd/4598005 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Given a hash of business hours that looks like: | |
{ | |
"wed"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"sun"=>{ | |
"endtime"=>"06:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"thu"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"tue"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"mon"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"fri"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
}, | |
"sat"=>{ | |
"endtime"=>"08:00pm", | |
"starttime"=>"10:00am" | |
} | |
} | |
When a user wants to retrive the start or end time | |
Then method missing to the rescue | |
=end | |
def start_time(hash) | |
#takes in a hash and returns the value at the starttime key | |
return nil unless hash["starttime"].present? | |
return hash["starttime"] unless hash["starttime"][0] == "0" | |
#trim leading zero | |
#return 9:00am instead of 09:00am | |
hash["starttime"][1..-1] | |
end | |
def end_time(hash) | |
#takes a hash and returns the value at the endtime key | |
return nil unless hash["endtime"].present? | |
return hash["endtime"] unless hash["endtime"][0] == "0" | |
#trim leading zero | |
hash["endtime"][1..-1] | |
end | |
=begin | |
can take: | |
self.monday_end or self.mon_end | |
self.monday_start or self.mon_start | |
self.monday_open or self.mon_opened or self.mon_opens | |
self.monday_close or self.mon_closed or self.mon_closed | |
=end | |
def method_missing(method, *args, &block) | |
# don't alter the method parameter before call super | |
# no method.gsub | |
# method is a symbol at this point | |
# convert to string and downcase | |
name = method.to_s.downcase | |
# split the name by the underscore and take the first three char | |
day = name.split('_').first[0..2] | |
# split the name by the undersore, should be start or end | |
period = name.split('_').last | |
return super unless %w[ mon tue wed thu fri sat sun ].include?(day) | |
if %w[ start open opens opened ].include?(period) | |
# pass it to start_time if period is start | |
start_time(hours[day]) | |
elsif %w[ end close closes closed ].include?(period) | |
# pass it to end_time if period is end | |
end_time(hours[day]) | |
else | |
# don't get too deep in the stack | |
super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment