Simmo
Simmo

Reputation: 1729

Module/Class clash trying to namespace models in Rails

As my app is getting a bit big now, I'm trying to use namespacing to help organise my models a little better.

I've created a app/models/theme.rb file which will act as a gateway to the rest of the theme related models which will go in a theme subdirectory.

# app/models directory
theme.rb
theme/compiler.rb
theme/instance.rb
theme/revision.rb

Where instance.rb will start something like....

class Theme::Instance < ActiveRecord::Base

end

and theme.rb is simply...

class Theme

  def initialize(args)
    # some stuff here
  end
end

But anytime I create a new model using a generator, it tries to overwrite a new theme.rb as per below.

rails g model theme::revision

#new theme.rb

module Theme
  def self.table_name_prefix
    'theme_'
  end
end

I could just get rid of the module and copy the def self.table_name_prefix method to each class but that doesn't seem very DRY. I would like to use the table prefix as it keeps things more obvious in the DB. Is there a 'correct' Rails way of going about this that I've missed?

Upvotes: 1

Views: 410

Answers (1)

tal
tal

Reputation: 3433

I guess the easiest way is to define Theme as a module that all classes extends

The Theme::Instance imply that the Instance class is contained in a Theme module.

As an alternative, you can create a ThemeUtils module that contains all common method that is included in each class, like a plugin in /lib

Upvotes: 2

Related Questions