I have user model that has many types (admin, normal, ..). And I make loop to define methods like admin? or normal? as the following:
class User
TYPES = %w(admin normal)
User::TYPES.each do |roleVal|
define_method(roleVal.to_sym) { self.role == roleVal }
end
end
The above code is working for example User.first.admin, But I need to call it as User.first.admin?.
What's the syntax of define_method with question mark ?
And if that's not possible using define_method, How to create methods with question mark in meta-programming ?
What you want is this:
define_method("#{roleVal}?") { ... }
It's pretty straightforward to define this kind of method with define_method. It's enough to pass symbol or string that ends with the question mark.
define_method(:admin?) do
# code
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With