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 => [
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!
source share