Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 287
Mohamed Yakout Avatar asked Feb 17 '26 14:02

Mohamed Yakout


2 Answers

What you want is this:

define_method("#{roleVal}?") { ... }
like image 74
Michael Kohl Avatar answered Feb 19 '26 03:02

Michael Kohl


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
like image 31
Marek Lipka Avatar answered Feb 19 '26 02:02

Marek Lipka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!