Skip to content

Instantly share code, notes, and snippets.

@jdjkelly
Last active December 15, 2015 15:09
Show Gist options
  • Save jdjkelly/5279130 to your computer and use it in GitHub Desktop.
Save jdjkelly/5279130 to your computer and use it in GitHub Desktop.
Four attrs on a model problem
# Given a model, self, with these attributes:
# value :float
# lean_mass_value :float
# fat_mass_value :float
# fat_percentage :float
#
# User optionally inputs the last three (lean_mass, fat_mass, fat_percentage), so we can determine missing values if we have at least one of the last three in addition to the value attr.
# Is there a better way to express this?
def calculate_all_known_values
if self.lean_mass_value.nil? && self.fat_mass_value.present? || self.fat_percentage.present?
self.lean_mass_value = self.fat_mass_value.present? ? self.value - self.fat_mass_value : self.value - (self.value * self.fat_percentage)
elsif self.fat_mass_value.nil? && self.lean_mass_value.present? || self.fat_percentage.present?
self.fat_mass_value = self.lean_mass_value.present? ? self.value - self.lean_mass_value : self.value - (self.value * self.fat_percentage)
elsif fat_percentage.nil? && self.lean_mass_value.present? || self.fat_mass_value.present?
self.fat_percentage = self.lean_mass_value.present? ? (self.value - self.lean_mass_value) / self.value * 100 : self.fat_mass_value / self.value * 100
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment