Rails modules: how to define instance methods inside a class method?

I would like to create a module called StatusesExtension that defines the has_statuses method. When a class extends StatusesExtension, it will have checks, scopes, and accessors for these statuses. Here's the module:

module StatusesExtension def has_statuses(*status_names) validates :status, presence: true, inclusion: { in: status_names } # Scopes status_names.each do |status_name| scope "#{status_name}", where(status: status_name) end # Accessors status_names.each do |status_name| define_method "#{status_name}?" do status == status_name end end end end 

Here is an example of a class that extends this module:

 def Question < ActiveRecord::Base extend StatusesExtension has_statuses :unanswered, :answered, :ignored end 

The problem I am facing is that while the scopes are determined, the instance methods (responding ?, unanswered? And ignored?) Are not. For instance:

 > Question.answered => [#<Question id: 1, ...>] > Question.answered.first.answered? => false # Should be true 

How can I use modules to define both class methods (scope, validation) and instance methods (accessors) in the context of a single class method (has_statuses) of a module?

Thanks!

+4
source share
1 answer

As stated in the comments, the method is defined, just does not work properly. I suspect this is because you are comparing a string with a character inside a method ( status_names is an array of characters, and status is a string). Try the following:

 status_names.each do |status_name| define_method "#{status_name}?" do status == status_name.to_s end end 
+4
source

Source: https://habr.com/ru/post/1479458/


All Articles