Doubt about creating "repeated" methods in Rails

Asked

Viewed 47 times

0

Person, I started to use Rails a little while ago and I have a question of 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

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

Thank you.

1 answer

5

You can define the methods dynamically using define_method:

class User

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

end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.