Question

Found this post Include namespace in Rails 3.1 console but it doesn't seem to work.

The following lib/task defined and it works from the command line: rake namespace_name:task_name.

How to call a method method_name in namespace_name from within the console, without calling the task?

rails console
namespace_name::task_name
NameError: undefined local variable or method 'namespace_name' for main:Object

irb namespace_name
NameError: undefined local variable or method 'namespace_name' for main:Object

Working in Rails 3.07, Ubuntu.

Was it helpful?

Solution

If you want to call a method defined inside a .rake file you do something similar to what @Nate said, but instead of calling the raketask, call the method:

require 'rake'
Rake.load_rakefile 'lib/tasks/namespace_name.rake'
method_name(arg1, arg2)

It feels kind of strange that you don't need to specify the namespaces but I just tried this and it worked.

OTHER TIPS

You're confusing two different kinds of "namespaces" - Ruby modules can perform the task of "namespacing" Ruby code; Rake namespaces are only used within Rake to categorize tasks, and they don't create a module namespace.

The page you linked only works with Ruby module namespaces.

If you want to call Rake tasks from the Rails console, it's a bit more involved...

require 'rake'
Rake.load_rakefile 'lib/tasks/namespace_name.rake'
Rake::Task['namespace_name:task_name'].invoke

Or just call it on the command line from within the Rails console -

%x[rake namespace_name:task_name]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top