ruby-on-railsvalidationacts-as-state-machine

AASM: Verifying which object is moving a state forward


I'm using AASM from http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk

In my example, I have a Karate dojo rails site. On the site, Teachers can manage the classes they instruct and move their students to the next logical belt.

My "Student" model use AASM for belt progression and it's defined like this:

class Student < ActiveRecord::Base
  acts_as_state_machine :initial => :White_Belt
  state :White_Belt
  state :Yellow_Belt
  state :Green_Belt
  state :Purple_Belt
  state :Brown_Belt
  state :Black_Belt

  event :Graduate do
    transitions :from => :White_Belt, :to => :Yellow_Belt
    ...
    transitions :from => :Brown_Belt, :to => :Black_Belt
  end
end

...and the Teacher model is defined like this...

class Teacher < ActiveRecord::Base
   def Promote_Student(pupil)
      pupil.Graduate!
   end
end

Is there a way ensure that only Teachers can call "Student.Graduate!"? I've seen ":guard" command, but that seems that I can only have functions that check the current object (the Student) and not the object that called the function (the Teacher).

It also appears that I can't add a param to my event like...

event :Gradate(teacher_id) do
   ...
end

...which would be ideal.


Solution

  • I think this kind of enforcement is not needed provided that you code correctly. You enforce this by yourself in the code.

    You can write a function such as Teacher#promote(student), and then write some comments on the graduate event stating not to call it directly, but calling Teacher#promote instead.

    also camel_case whitout first letter capitalization is preferred on methods and symbols.