开发者

I would like to know how can I force a model loading in development environment

I would like to know how can I force a model loading in development environment. (RAILS 2.3.10)

When I am in test or development mode, SomeProject is never initiated until used. Here is what the console says:

>   project = Project.find(:some)
    RuntimeError: Can not find 'some'
      from /path/to/rails/lib/identifier.rb:23:in `class_from_key'
      from /path/to/rails/lib/identifier.rb:8:in `find'
      from (irb):4
> Projects::SomeProject
  => Projects::SomeProject 
> project = Project.find(:some)
  => #<Projects::SomeProject:0x10810ceb8 @key="some", @full_name="Some Project"> 

The identifier method is never called. However, it does work in production mode and when I cache classes in development mode.

config.cache_classes = true

But that just eliminates the benefits of development.

Any ideas on a nice way to make sure that all the subclasses are auto loaded?

Code Details

I have a Project class

class Project
  extend Identifier

  def full_name
    @full_name
  end

  def key
    @key
  end

end

that is the base class for more specific project classes

class Projects::SomePr开发者_运维百科oject < Project
  identifier :some

  def initialize
    @key = 'some'
    @full_name = "Some Project"
  end
end

Projects extend Identifier module which should self register the sub classes and expose a find method to instantiate by a key:

module Identifier

  def find(*args)
    key = args.shift
    klass = class_from_key(key)
    if args.empty?
      klass.new 
    else 
      klass.new args
    end
  end

  private 

  def class_from_key(key)
    raise "Can not find '#{key}'" unless identifiers.has_key?(key)
    identifiers[key] 
  end

  def identifiers
    @@identifiers ||= {}
  end

  def identifier(key)
    identifiers[key] = self
  end

end


It might not hurt to add

require 'some_project'

at the top of your file if you have such needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜