I'm trying to figure out a way to calculate bonuses or penalties from a Character's Statistics, and then apply that method in other Models' views to calculate things like Fortitude saves, attack bonuses and so on. I've been working with a modifier for Constitution and here's what I've got so far.
The logic for calculating a Statistic bonus/penalty is (statistic - 10) / 2. So for a score of 14, we get 2, and for a score of 8, we get -1. Not bad so far!
So I define this method in Statistic controller:
def con_modifier
(constitution.to_i - 10) / 2
end
@con_modifier = @character.statistic.con_modifier
Here's the logic for calculating a total in my Fortitude model right now:
def total
fortitude_base.to_i + ability.to_i + magic.to_i + misc.to_i
end
def total
fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end
nil can't be coerced into Fixnum
Variables that begin with @ are instance variables, meaning they're only available to things within the same instance of that object. So setting @con_modifier in your controller means it won't be available within your Fortitude model. I think you probably want something like statistic.con_modifier instead of @con_modifier.
ReplyDeleteAll the to_i's seem like a code smell. They shouldn't be necessary and suggest that there is a deeper problem. When I get back to Indy we should get together and re-hash out the design of your app :)
@Eli I mostly have the to_i's in there per Matt's suggestion for fixing my validation, and I don't think they're necessary. Maybe a bit of paranoia on my part? The code WAS working fine without them, and the validation ensures that values entered in the form are integers, so I can likely take them out.
ReplyDeleteAnd statistic.con_modifier isn't working either. Rails complains about an "undefined local variable or method `statistic' " when I define the method in the Fortitude model. Do I also need to define it in the controller? Where IS something defined when Rails complains about undefined variables?
Also I am down for hanging out and coding and drinking beers (I assume beers is implied)