Pat Wangrungarun
Pat Wangrungarun

Reputation: 526

Non-activerecord models structure in Rails 4

My attempt looks like this, non-activerecord model with inheritance. app/models/matching_method.rb:

class MatchingMethod
  attr_accessor :name
end

class LD < MatchingMethod
end

class Soundex < MatchingMethod
end

By this I can benefit from using MatchingMethod.descendants. This works quite well. So I tried to move each class into its own folder.

models/
  - concern/
  + matching_method/
    - ld.rb
    - soundex.rb
  - matching_method.rb

And for each class:

class MatchingMethod::LD < MatchingMethod
end

However, this time MatchingMethod.descendants couldn't find inherited classes anymore.

Any suggestions? Or should I redesign this approach. Thanks!

Upvotes: 1

Views: 142

Answers (1)

Oleg K.
Oleg K.

Reputation: 1549

Rails loads ld.rb only when you request MatchingMethod::LD. It resolves the class through const_missing. You need to request MatchingMethod::LD in code or require the file matching_method/ld.rb manually. Until the class file is loaded, MatchingMethod doesn't know anything about it's descendant LD:

MatchingMethod.descendants
# => [] 

MatchingMethod::LD        
# => MatchingMethod::LD 

MatchingMethod.descendants
# => [MatchingMethod::LD] 

To load all classes from matching_method dir:

Dir['app/models/matching_method/*.rb'].each do |f| 
   require Pathname.new(f).realpath
end

To reload them again without restarting the application (like the Rails loader in development environment):

Dir['app/models/matching_method/*.rb'].each do |f| 
   load Pathname.new(f).realpath
end

It won't monitor file changes. You need to load the file manually after saving changes. And it won't remove any existing methods/variables. It will only add new or change existing ones.

Upvotes: 3

Related Questions