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 method
include_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
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.
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.
582 PHP ssh2_scp_send fails to send files as intended
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
916 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
578 Understanding How to Configure Google API Key
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.