我有一个Rails 5应用程序和自定义模块,存储在lib/reusable.rb
中。
module Reusable
def createCharge(amount, source, description, customer)
charge_params = {
amount: amount,
source: source,
description: description,
currency: 'usd'
}
return charge_params
end
end
我已将以下内容添加到application.rb
:
config.autoload_paths << "#{Rails.root}/lib"
config.eager_load_paths << "#{Rails.root}/lib"
启动控制台时,我可以运行以下命令:
2.3.4 :002 > include Reusable
=> Object
2.3.4 :003 > x = Reusable.createCharge(100, 1, "ffwefwef")
{
:amount => 100,
:source => 1,
:description => "ffwefwef",
:currency => "usd"
}
但是在我的控制器中,我不能这样做。当我尝试以下操作时:
class ChargesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
before_action :set_client, only: [:new, :create]
before_action :set_order, only: [:create]
include Reusable
def create
charge_attempt = Reusable.createCharge(total, token, description, customer)
end
end
我得到了错误:
NoMethodError (undefined method `createCharge' for Reusable:Module):
有什么想法为什么找不到该功能?我已经重新启动了我的应用程序,并将Reusable.methods
打印到控制台上,但该功能不存在。
答案 0 :(得分:2)
有几种方法可以使您的createCharge
方法可用...
一种方法是module_function
...
module Reusable
def create_charge(amount, source, description, customer)
charge_params = {
amount: amount,
source: source,
description: description,
currency: 'usd'
}
charge_params
end
module_function :create_charge
end
另一种方法是使用自我...
def self.create_charge(amount, source, description, customer)