在哪里定义可以直接从 rails 控制台访问的方法 [英] Where to define method to be accessible directly from rails console

查看:44
本文介绍了在哪里定义可以直接从 rails 控制台访问的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以想法是定义

def foo
  puts "Works!"
end

直接从控制台而不加载我写的任何东西

and directly from the console without loading anything I write

irb(main):001:0>foo()
=> "Works!"
irb(main):002:0>

我在 Windows 上使用 1.9.3.我想使用这个方法来重新加载 lib/* 以便我不需要重新启动控制台.谢谢.

I am using 1.9.3 on Windows. I want to use this in order to have a method which will reload lib/* so that I don't need to restart the console. Thank you.

推荐答案

我想这就是你要问的...我在初始化程序中有以下代码:

I think this is what you're asking... I have the following code in an initializer:

if defined?(Rails::Console)
  require "util/console_extensions"
  include ConsoleExtensions
end

以及我想要在 lib/util/console_extensions.rb

module ConsoleExtensions
  def foo
    puts "Works!"
  end
end

这会在加载 rails 控制台时自动要求并包含 ConsoleExtension 模块,并使其中定义的方法可用,而无需手动加载任何内容.

This automatically requires and includes the ConsoleExtension module when loading the rails console and makes the methods defined in it available without the need to manually load anything.

这篇关于在哪里定义可以直接从 rails 控制台访问的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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