Do not include modules in specific models

Asked 2 years ago, Updated 2 years ago, 78 views

ApplicationRecord should include HogeModule and
If you inherit ApplicationRecord, the Module will be included.

If you don't want to include PiyoClass, please advise me on how to do it.

class ApplicationRecord <ActiveRecord::Base
  include HogeModule
e n d
class PiyoClass<ApplicationRecord
  # Do not want to include HogeModule in this class
e n d

method_missing': undefined methodinclude_class?

class ApplicationRecord <ActiveRecord::Base
  include HogeModule if include_class?

  def include_class ?
    true
  e n d
e n d
class PiyoClass<ApplicationRecord
  # Do not want to include HogeModule in this class
  def include_class ?
    false
  e n d
e n d

I want to meet the following conditions

  • Inheriting ApplicationRecord
  • Write something in the model if you do not include it
  • Rails 5.2

ruby-on-rails ruby

2022-09-30 21:46

2 Answers

As far as I know, I don't think I can uninclude a module that I included once, so

class ApplicationRecord <ActiveRecord::Base
e n d

class HogeApplicationRecord <ApplicationRecord
  include HogeModule

  self.abstract_class = true
e n d

class PiyoClass<ApplicationRecord
e n d

# Other classes inherit HogeApplicationRecord

I think it's a reasonable answer.


2022-09-30 21:46

One technique is to leverage Class#inherited.

module MyMudule
  def hello
    puts 'hello'
  e n d
e n d

class parent
  def self.inherited(subclass)
    subclass.include MyMudule if subclass.name == 'Child1'
  e n d
e n d

class Child1<Parent
e n d

class Child2<Parent
e n d

child1 = Child1.new
putschild1.respond_to?(:hello)#=>true
child2 = Child2.new
putschild2.respond_to?(:hello)#=>false

In this way, you can do include only in child classes with a specific name, or, conversely, do not do include.
The disadvantage of this approach is that the parent class must have knowledge of which class inherits (or does not) modules.This is less readable than simply dividing the parent class into two.


2022-09-30 21:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.