I have a model User which goes like this
class User
ROLES = {
"Admin" => 1,
"Manager" => 2,
"Officer" => 3
}
def admin?
role == 1
end
def manager?
role == 2
end
def officer?
role == 3
end
end
where role is a column in users table and I was wondering whether I can use a common method to build the 3 role checking methods from the ROLES hash?
Edit
so this seems to be the answer
class User
ROLES = {
"Admin" => 1,
"Manager" => 2,
"Officer" => 3
}
# methods used to identify whether a user is a specific role
ROLES.each { |k, v| define_method("#{k.downcase}?") { role == v } }
end
I am not fully sure of your intention, but maybe like this?
or, using
ROLES,