Rails-如何从lib目录中调用方法? [英] Rails - how to call methods from lib directory?

查看:60
本文介绍了Rails-如何从lib目录中调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在lib dir(文件my_class_name.rb)中有此方法:

I have this method in the lib dir (file my_class_name.rb):

class MyClassName
  def doSomething
    ...
  end
  ...
end

在控制器中:

class UsersController < ApplicationController
  require 'my_class_name'

  def show_stats
    ::MyClassName.doSomething()
  end
end

返回

MyClassName:Class的未定义方法`doSomething'

undefined method `doSomething' for MyClassName:Class

如何正确调用此方法?

推荐答案

您已经使用实例方法编写了一个类,因此,如果您想用它的编写方式来调用它,则需要编写:

You've written a class with an instance method, so if you want to call it how you've written it you'll need to write:

  mcn = MyClassName.new
  mcn.doSomething

(通过创建一个实例,然后在该实例上调用该方法)

(by creating an instance, and then calling the method on that instance)

如果您想要的是一个类方法,请将其定义为:

If what you want is a class method, define it as:

class MyClassName
  def self.doSomething
    ...
  end
  ...
end

并像这样调用它:MyClassName.doSomething

这篇关于Rails-如何从lib目录中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆