2

I have two models, being an Employee and a WorkingPattern. An instance of an Employee belongs_to an Working Pattern.

The Working Pattern looks like this

 :id => :integer, :name => :string, :mon => :boolean, :tue => :boolean, :wed => :boolean, :thu => :boolean, :fri => :boolean, :sat => :boolean, :sun => :boolean 

I need to know if an Employee should be at work today. So, if today is a Tuesday and that employee's working pattern record reports that :tue = true then return true, etc. I don't have the option of renaming the fields on the WorkingPattern model to match the days names.

I know that

Time.now.strftime("%A") 

will return the name of the day. Then I figured out I can get the first 3 characters of the string by doing

Time.now.strftime("%A")[0,3] 

so now I have "Tue" returned as a string. Add in a downcase

Time.now.strftime("%A")[0,3].downcase 

and now I have "tue", which matches the symbol for :tue on the WorkingPattern.

Now I need a way of checking the string against the correct day, ideally in a manner that doesn't mean 7 queries against the database for each employee!

Can anyone advise?

4 Answers 4

5

You can use %a for the abbreviated weekday name. And use send to dynamically invoke a method

employee.working_pattern.send(Time.now.strftime("%a").downcase) 
Sign up to request clarification or add additional context in comments.

1 Comment

the method .wday also returns the week day of the date/datetime/time
1

Use send to invoke a method, stored in a variable, on an object.

Both of these are identical:

user.tue # true user.send('tue') # true 

1 Comment

thanks for this - your post was the one that enabled me to understand what was going on with send.
0

You can access an attibute using [], just like a Hash. No need to use send or even attributes.

day = Time.now.strftime("%a").downcase employee.working_pattern[day] 

Comments

0

Butchering strings makes me feel a little uneasy

Construct a hash of day numbers:

{0 => :sun 1 => :mon, 2 => :tue, ...} 

Then use Time.now.wday (or Time.zone.now.wday if you want to be timezone aware) to select the appropriate value from the hash

You can then use that string on employee.working_pattern in any of the ways described by the other answers:

employee.working_pattern.send(day_name) 

employee.working_pattern.read_attribute[day_name] enployee.working_pattern[day_name]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.