Rails - 在视图、控制器和模型中使用一组函数

发布于 2024-09-02 12:46:58 字数 174 浏览 4 评论 0原文

我有一个函数,可以将数组转换为哈希值,我想在 Rails 应用程序中的所有模型、控制器和视图文件中使用该函数。

这是否违反了一些核心设计原则,或者我是否遗漏了一些非常明显的东西?

更新:这实际上是一个软件工程问题。我想了解为什么rails中不允许一些“方便”的事情,我怀疑这正是因为他们不希望我们这样做

i have a function that converts an array to a hash which i would like to use across all the model, controller and view files in the rails app.

Does this violate some core design principle, or am i missing something really obvious?

UPDATE: This is actually a software engineering question. I want to understand why some "convenient" things are not allowed in rails, and i suspect it is precisely because they do not want us to do it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相权↑美人 2024-09-09 12:46:58

这实际上可能是一种不好的做法。最好始终在控制器和模型中使用数组和哈希,并在必要时将视图中的它们转换为替代方案。

也就是说,如果数据在整个应用程序中本身表示为数组,则可以以这种方式使用它,并且如果需要在视图中作为散列,请首先转换它并分配它,或者使用助手在视图中转换它。

查看全局助手进入:helpers/application_helper.rb

如果您必须从控制器调用助手,您仍然可以在那里定义它,我相信您可以这样做:

def Something
  ....
  hashData = @template.helper(arrayData)
end

在模型中调用助手确实不是一个好主意,没有意义。

最后一点,将此逻辑封装在库中可能是理想的选择,您的控制器可以调用库和库。你的视图助手也可以。

This is likely actually a bad practice. It'd likely be better to instead always work with arrays and hashes in your controllers and models and if necessary convert them in the view to the alternative.

That is, if the data is natively represented as a array throughout your application work with it that way and if required to be a hash in the view either convert it first and assign it or convert it in the view using a helper.

View global helpers go in: helpers/application_helper.rb

If you must call a helper from a controller you can still define it there and I believe you can do:

def Something
  ....
  hashData = @template.helper(arrayData)
end

Calling helpers in a model is REALLY not a good idea, there's no point.

As a final note, encapsulating this logic in a library would likely be ideal, your controllers can call a library & your view helpers can as well.

后来的我们 2024-09-09 12:46:58

我认为你是:视图不应该需要那种方法。控制器应该执行此操作并将其传递到视图进行显示。控制器,或者更好的是,服务层可能会将该方法应用于模型对象,但模型对象没有理由知道它。

I think you are: views should not need that method. The controller ought to do it and pass it along to the view for display. The controller or, better yet, service layer might apply that method to a model object, but there's little reason for a model object to know about it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文