Reputation: 3036
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 ?
Upvotes: 2
Views: 624
Reputation: 121000
There is nothing special in the ending question mark within symbols:
class User
TYPES = %i(admin? normal?)
User::TYPES.each do |roleVal|
define_method(roleVal) { self.role == roleVal.to_s[0...-1] }
end
end
Upvotes: 2
Reputation: 51161
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
Upvotes: 3
Reputation: 2659
you can do as below.
class User
TYPES = %w(admin normal)
User::TYPES.each do |roleVal|
define_method("#{roleVal}?") do self.role == roleVal end
end
end
Hope, this will help you.
Upvotes: 1