Search code examples
ruby-on-railshelperaasm

Rails AASM helper for links for which state it may go to. Prefix to method call


In AASM you can call the may_run? as in the example code in the AASM.

object:

class Job
  include AASM

  aasm do
    state :sleeping, :initial => true
    state :running, :cleaning

    event :run do
      transitions :from => :sleeping, :to => :running
    end

    event :clean do
      transitions :from => :running, :to => :cleaning
    end

    event :sleep do
      transitions :from => [:running, :cleaning], :to => :sleeping
    end
  end

end

Example

job = Job.new
job.sleeping? # => true
job.may_run?  # => true
job.run
job.running?  # => true
job.sleeping? # => false
job.may_run?  # => false
job.run       # => raises AASM::InvalidTransition

How do I create a helper which tests the may_ for the action if I pass the object and the action in as parameters. Essentially I want to add a prefix to the method call using the helper similar to this:

def state_action_url(job, state)
   if job.may_state?
      #link_to action
   else
      #render disabled link text
   end
end

Solution

  • You can use smth like this:

    def state_action_url(job, state)
       if job.public_send("may_#{state}?")
          #link_to action
       else
          #render disabled link text
       end
    end