Last active
August 4, 2016 21:36
-
-
Save FaisalAl-Tameemi/51e450fdf8803b589e445c4ca302f02b to your computer and use it in GitHub Desktop.
ORM Breakout Notes
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
class Employee < ActiveRecord::Base | |
BILLABLE_HOURS = 1950 | |
belongs_to :store | |
validates :first_name, :last_name, | |
presence: true | |
after_create :increment_employees_count | |
after_destroy :decrement_employees_count | |
def increment_employees_count | |
if gender == "F" | |
store.female_employees += 1 | |
elsif gender == "M" | |
store.male_employees += 1 | |
end | |
# store.female_employees += 1 if gender == "F" | |
# store.male_employees += 1 if gender == "M" | |
store.save # unless gender.nil? # you can add it to skip save sometimes | |
end | |
def decrement_employees_count | |
if gender == "F" | |
store.female_employees -= 1 | |
elsif gender == "M" | |
store.male_employees -= 1 | |
end | |
store.save # unless gender.nil? # you can add it to skip save sometimes | |
end | |
def annual_salary | |
hourly_rate * BILLABLE_HOURS | |
end | |
class << self | |
def average_hourly_rate_for(gender) | |
# approach 1 | |
if gender | |
where(gender: gender).average(:hourly_rate).round(2) | |
else | |
average(:hourly_rate).round(2) | |
end | |
# approach 2 | |
# return average(:hourly_rate).round(2) if gender.nil? | |
# where(gender: gender).average(:hourly_rate).round(2) | |
# approach 3 | |
# gender = gender.nil? ? ["M", "F"] : [gender] | |
# where(gender: gender).average(:hourly_rate).round(2) | |
end | |
end | |
end |
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
class Store < ActiveRecord::Base | |
has_many :employees | |
validates :name, | |
presence: true, | |
length: { maximum: 25 } | |
validates :annual_revenue, | |
numericality: { greater_than_or_equal_to: 0 } | |
validates :male_employees, :female_employees, | |
numericality: { greater_than_or_equal_to: 0, only_integer: true } | |
def annual_expense | |
# AR style of doing things | |
employees.sum(:hourly_rate) * Employee::BILLABLE_HOURS | |
# doing it with inject | |
# employees.inject(0){|current_sum, current_employee| | |
# current_sum += current_employee.annual_salary | |
# } | |
end | |
def annual_profit | |
annual_revenue - annual_expense | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment