Mohamed Yakout Mohamed Yakout - 3 months ago 7
Ruby Question

How can I write method with question mark using define_method

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 ?

Answer

What you want is this:

define_method("#{roleVal}?") { ... }
Comments