开发者

problem accessing namespaced class in rake task

Given a rake task that references both a namespaced and non-namespaced model:

namespace :thing do
  task :thingo => :environment do
    Klass.first.some_method
    Namespaced::Klass.first.some_other_method
  end
end

Using ruby 1.9.2, rails 3.0.9, and rake 0.9.2, this yields an exception, like so:

undefined method 'some_other_method' for #<Klass:0x007fcfafbaa6e0>

Two things:

  1. Why doesn't rails return the proper namespacing in the rake environment (in a debugger session), but it does in a console session?
  2. Why does changing the order of reference work? (That is, if the environment is already calling "Namespaced::Klass" as "Klass", then calling "Klass" should fail with undefined method 'some_method' for #<Klass:0x007fcfafbaa6e0> right?

By the way, I've trie开发者_如何转开发d ::Namespaced::Klass.first.some_other_method

If the answer isn't simple, I'll put together a test app - let me know! :-)


First, some background on metaphor shear - two different kinds of namespaces:

Although Rake Namepsaces and Ruby Namespaces share the word Namespace, they are separate concepts. Rake namespaces are just organizing containers for Rake Tasks, not Ruby namespaces/modules. So code inside your thing:thingo rake task is actually executing at the top-level Ruby namespace.

Second: If Klass is a single class not in a namespace, you can reference it directly. If the class exists as Foo::Klass then you'll need to use the fully-qualified Foo::Klass reference unless the scope of the reference is already within the Foo namespace.

Because Rake namespaces aren't Ruby modules, you are not in the context of a Ruby namespace within your task. This is why Klass.some_method works if Klass isn't in a module.

If this doesn't explain the question, please post the class definition for Klass including any module/namespace membership.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜