ruby on rails - Working with instance variables within a model -
i want instantiate "battle" upon creation variables can manipulate without accessing database , first when method calls , calculation has been done, save battle result database. want "player" method return sorted array created in callback, @ moment returns nil
class battle < activerecord::base after_create @battlelog = "" @field = [] @conditions = [] @player = sort_by_initiative(action.character.army.members.map{ |m| [m.unit, m.amount]}) @computer = sort_by_initiative(action.instance.members.map{ |m| [m.unit, m.amount]}) end # associations belongs_to :action def sort_by_initiative(array) array.sort { |a, b| b.first.initiative <=> a.first.initiative } end def player @player end
i think looking attr_accessor :player
, (this ruby, see ruby classes more) creates accessible attribute (read , write) on model instance. attr_reader :player
give read-only attribute, used if attribute set internal operations. can call this_battle.player
on this_battle
instance of class battle
. remember though these attributes not persist if call other controller actions or render new views unless have way store them permanently.
Comments
Post a Comment