I am a relatively new Rails developer and doctor doing research. In my Rails based research projects I often have questionnaires for which I provide a "% complete" parameter. Here is an example. Only need to focus on the line @status down.
def percent_complete(user, patient)
score = Score.where(user_id: user.id, patient_id: self.id).first
if score.nil?
return "0"
end
@status = 0
score_array = [score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt]
score_array.each do | element|
if element == score.dx1
@status = @status + 20
elsif element == score.db1
@status = @status + 20
elsif element == score.dxcon1
@status = @status + 20
elsif element == score.dbcon1
@status = @status + 20
elsif element == score.biopsy
@status = @status + 10
elsif element == score.mgt
@status = @status + 10
end
end
@status
end
I always end up doing this sort of thing. You can see, each of the score attributes is given a value and then I can create a %. It looks awful and very un-ruby-like. I would be keen once and for all to get an experts view and give me some steerage on how tis could be cleaned up.
Many thanks
Simon
EDIT:
My apologies, this method is in the Patient class.
Each Score belongs to a Patient (the Patient has many scores). Each Score belongs to a User (a User has many scores).
score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt
These are the Score class attributes. dx1 = diagnosis1 (string), dxcon1 = diagnostic confidence1 (integer), db1 = disease behaviour1 (string), dbcon1 = confidence on disease behaviour (integer), biopsy = should you biopsy? = (boolean), mgt = management (string).
I am now trying something like this....
def percent_complete(user, patient)
score = Score.where(user_id: user.id, patient_id: self.id).first
if score.nil?
return "0"
end
score_completeness = [score.dx1, score.dxcon1, score.db1, score.dbcon1, score.biopsy, score.mgt]
@status = 0
score_completeness.each do | field |
@status += (100/6.0) unless field.blank?
end
@status
end