尝试使用命名空间实现模块

时间:2022-06-23 19:09:20

I am using Ruby on Rails 3 and I am trying to implement a Module using namespaces.

我正在使用Ruby on Rails 3,我正在尝试使用命名空间来实现模块。

In my lib/ folder I have the authorization.rb file with in this:

在我的lib /文件夹中,我有authorization.rb文件,其中包含:

module Authorizations
  def Authorizations.message
    return "flash_message"
  end
end

In my controller I have:

在我的控制器中,我有:

class Users::AccountsController < ApplicationController # 'Users' is the namespace
  include Authorizations

  def create
    ...
    flash.now[:notice] =  Authorizations.message
  end
end

When I run the create method I get this error:

当我运行create方法时,我收到此错误:

NoMethodError (undefined method 'message' for Authorizations:Module)

What is wrong?

哪里不对?


In the module statement I also tryed these

在模块声明中我也尝试了这些

def Authorizations::message
 ...

# or 

def message
  ...

and also those don't work.

而那些不起作用。

2 个解决方案

#1


2  

The problem is in the RAILS_ROOT/config/application.rb. Just load the lib/ folder in this way:

问题出在RAILS_ROOT / config / application.rb中。只需以这种方式加载lib /文件夹:

config.autoload_paths += %W(#{config.root}/lib)

#2


1  

module Authorizations
  def message
    return "flash_message"
  end
end

And then

Authorizations::message

or if included in the class, just

或者如果包括在课堂上,只是

... = message

#1


2  

The problem is in the RAILS_ROOT/config/application.rb. Just load the lib/ folder in this way:

问题出在RAILS_ROOT / config / application.rb中。只需以这种方式加载lib /文件夹:

config.autoload_paths += %W(#{config.root}/lib)

#2


1  

module Authorizations
  def message
    return "flash_message"
  end
end

And then

Authorizations::message

or if included in the class, just

或者如果包括在课堂上,只是

... = message