Mohamed Yakout
Mohamed Yakout

Reputation: 3036

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 ?

Upvotes: 2

Views: 624

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

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

Marek Lipka
Marek Lipka

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

Hardik Upadhyay
Hardik Upadhyay

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

Michael Kohl
Michael Kohl

Reputation: 66837

What you want is this:

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

Upvotes: 5

Related Questions