Gareth Burrows
Gareth Burrows

Reputation: 1182

ruby comparison of time and variable

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?

Upvotes: 2

Views: 67

Answers (4)

Frederick Cheung
Frederick Cheung

Reputation: 84114

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]

Upvotes: 0

infused
infused

Reputation: 24337

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]

Upvotes: 0

usha
usha

Reputation: 29349

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)

Upvotes: 5

user229044
user229044

Reputation: 239301

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

Upvotes: 1

Related Questions