Last active
December 20, 2015 08:08
-
-
Save adamkleingit/6097795 to your computer and use it in GitHub Desktop.
500Tech / Rails Riddles #2
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
# Improve / Fix as many things in the code below | |
# Answers should be sent to [email protected] | |
# Good luck | |
class User < ActiveRecord::Base | |
validates_presence_of :name, :email, :date_of_birth, :age_category | |
before_save do | |
age = (Time.now - date_of_birth).year | |
if age < 10 age_category = 'child' | |
elsif age < 18 age_category = 'teenager' | |
elsif age < 24 age_category = 'young' | |
elsif age < 54 age_category = 'adult' | |
else age_category = 'senior' | |
end | |
end | |
Improvement number 4 - define age_category as a method so that whenever we use it it's correct (and not just after we save):
def age_category
CATEGORIES.take_while { |category| category[0] < age}.last[1]
end
def set_age_category
self[:age_category] = age_category
end
Fix number 2 - don't validate age_category (because it is a calculated field)
validates_presence_of :name, :email, :date_of_birth
```ruby
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvement number 3 - use array and loop over a hash to set the age category (many other possible solutions for this):