Doubt about creating "repeated" methods in rails

0

Person, I started using rails a short time ago and I have a question about how to improve the code below:

I have a model called User that has an attribute called Role for permissions. However, to be more readable I ended up creating the following methods:

def is_superadmin?
    if self.role.description == "super_admin"
        return true
    end 
  end

  def is_admin?
    if self.role.description == "admin"
        return true
    end 
  end

  def is_analyst?
    if self.role.description == "analyst"
        return true
    end 
  end

  def is_client?
    if self.role.description == "client"
        return true
    end 
  end

I would like to improve this, because if not every time I add a new rule, I need to remember to go in the model and create another method like this.

Thank you.

    
asked by anonymous 16.04.2016 / 21:13

1 answer

5

You can dynamically define methods using define_method :

class User

  Role.all.each do |role|
    define_method("is_#{role.description}?") do
      self.role.id == role.id
    end
  end

end
    
17.04.2016 / 03:39