Richard Wonson
Richard Wonson

Reputation: 15

How to check if the user should be assigned the role admin

The goal of this method is to check when a user signs up, if they are on the list of users that should be admins.

I am new to Ruby and think it is just a syntax error:

  def set_role
    if self[:email] == ("[email protected]" || "[email protected]" || "[email protected]")
        self[:role] = "admin" 
    else
      self[:role] = "customer"
    end
  end

Upvotes: 0

Views: 66

Answers (2)

the Tin Man
the Tin Man

Reputation: 160571

This would be a good time to use a case statement:

def set_role
  self[:role] = case self[:email]
                when "[email protected]", "[email protected]", "[email protected]"
                  'admin'
                else
                  'customer'
                end
end

It's easy to add new values to the when test.

Upvotes: 1

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

You want to check if an array of emails includes the current email like this:

def set_role
  if ["[email protected]", "[email protected]", "[email protected]"].include?(self[:email])
    self[:role] = "admin" 
  else
    self[:role] = "customer"
  end
end

This code could also be improved:

def set_role
  admin_emails = ["[email protected]", "[email protected]", "[email protected]"]
  self[:role] = if admin_emails.include?(self[:email])
    "admin" 
  else
    "customer"
  end
end

Upvotes: 0

Related Questions