简体   繁体   English

Rails-在视图,控制器和模型中使用一组功能

[英]Rails- Using a set of functions across the view , controller and model

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. 我有一个将数组转换为哈希的函数,我想在Rails应用程序中的所有模型,控制器和视图文件中使用它。

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 我想了解为什么某些“便利”的东西不允许在铁轨中使用,我怀疑这正是因为他们不希望我们这样做

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 查看全局帮助器,请访问: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. 最后一点,将这种逻辑封装在一个库中可能是理想的,您的控制器可以调用一个库,而视图助手也可以。

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. 控制器或更好的服务层可以将该方法应用于模型对象,但是没有理由让模型对象知道它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM