Reputation: 23
I'm working on project that requires different classes to have the same name like this:
lib/command.rb
class Command
end
lib/command/group.rb
class Command
class Group < Command
end
end
lib/command/group/add.rb
class Command
class Group
class Add < Group
# do something
end
end
end
and lib/group.rb
class Group
# do something
end
Rakefile
task :reload do
Dir[File.dirname(__FILE__) + '/lib/**/*.rb'].each{ |file| load file }
end
task default: 'reload'
The first three classes behaves like a helper, and last class is the model.
When I run Rakefile
to load all classes, it will raise the TypeError: superclass mismatch for class Group
indeed.
How should I solve it without renaming one of the Group
classes? Is it possible?
Upvotes: 1
Views: 7469
Reputation: 36101
lib/command/group/add.rb
may get loaded before lib/command/group.rb
. Hence in the latter, it appears as if you try to change which class Group
inherits from.
The band aid solution would be to point to the same subclass in all files. Aka in lib/command/group/add.rb
, you should add < Command
.
The real solution should be to never use a class/module for namespacing and attach functionality to it.
This issue was raised in Euruko 2016 and Matz said they might consider a special keyword for it. [Citation needed]
Upvotes: 3
Reputation: 2346
Thanks for providing further code. It's now clear that there is an error here. You define Command::Group
twice, but only one of them inherits from Command
lib/command/group.rb
class Command
class Group < Command
end
end
lib/command/group/add.rb
class Command
class Group # missing inheritance
class Add < Group
# do something
end
end
end
Upvotes: 2