把代码片段放在 Rails 的什么地方? [英] Where to put code snippets in Rails?

查看:34
本文介绍了把代码片段放在 Rails 的什么地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个为 POST 生成签名的代码片段.它的细节并不重要,但我想知道的是:由于它不是与模型相关的代码块,因此它确实可以在任何地方使用:在控制器中,在模型中,在视图助手中;即使在视图中.所以我不确定在哪里,甚至更大的问题,一旦我把它放在某个位置,如何激活它的使用.

I have this code snippets that generates a signature for POSTs. The detail of it is not important, but what I want to know is: since it is not a model-related chunk of code, it really can be use anywhere: in controllers, in models, in view helpers; even in views. So I am unsure where and, even bigger of a problem, how to activate the use of it once I place it in some location.

这就是那些要求"语句的全部内容吗?您可以通过您正在处理的当前文件中的require"语句获得一些功能吗?

Is it what those "require" statements are all about? That you can acquire some functionality through a "require" statement in the current file you are working on?

为了让我们有一个例子来讨论,比如说,我有一小段代码可以做立方:

Just so that we have an example to talk about, say, I have a little snippet of code that does cubing:

def cube_it(num)
  num**3
end

我知道我会在整个应用程序的不同地方使用它,那么我应该把它放在哪里?当我确实需要使用它时,我如何召唤"它?

I know that I will be using it in various places across the application, so where should I put it? and when I do need to use it, how can I "summon" it?

谢谢

推荐答案

Rails 在第一次使用时会自动加载模块和类.您可以将函数放入模块(或类)并将文件放入应用程序的 lib 目录中.require 语句在 Rails 应用中不经常使用.

Rails autoloads modules and classes when they are first used. You can put your function into a module (or class) and put the file into the lib directory in your application. require statements aren't used in Rails apps often.

这篇关于把代码片段放在 Rails 的什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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