class User
ROLES = %w(contributor manager admin)
attr_accessor :role
def is_contributor?
self.role == "contributor"
end
def is_manager?
self.role == "manager"
end
def is_admin
self.role == "admin"
end
end
user = User.new
user.role = "contributor"
user.is_admin? #--> false
user.is_contributor? #--> true
というコードを簡略にして
class User
ROLES = %w(contributor manager admin)
attr_accessor :role
ROLES.each do |role|
define_method "is_#{role}?" do
self.role == role
end
end
end
とリファクタリングできます。
No comments:
Post a Comment