Its not available because its use in the model (as a rule) violates MVC (and this seems to be the case for you). You take data and manipulate it for presentation. This, by definition, belongs to opinion, not to the model.
Here are some solutions:
Use the presenter or view model object to mediate between the model and the view. It almost certainly requires more initial work than other solutions, but it is almost always a better design. Using helpers in a presentation / view-model does not violate MVC, as they are at the presentation level, replacing traditional Rails user-defined helpers and filled with presentation logic.
Explicitly include ActionView::Helpers::NumberHelper in JobsHelper instead of Rails- JobsHelper so that it magically loads it for you. This is still not very convenient, since you do not need to contact the assistant from the model.
Violate MVC and SRP . See fguillens answer for how to do this. I will not repeat it here because I do not agree with this. However, do I disagree with the pollution of your model using presentation methods, as in Sams Answer .
If you think: βBut I really need this to write my to_csv and to_pdf in my model!β, Then your whole premise is wrong. After all, you don't have a to_html method, do you? And still your object is very often displayed as HTML. Consider creating a new class to generate output instead of your data model knowing what CSV is ( because it shouldn't ).
Regarding the use of helpers for ActiveModel validation errors in the model, well, I'm sorry, but ActiveModel / Rails pinned us all there, forcing error messages to be implemented in the data layer, instead of returning the semantic idea of ββthe error to be realized later - a sigh. You can get around this, but basically it means that you no longer use ActiveModel :: Errors. Ive done it, it works well.
Alternatively, this is a useful way to include helpers in a presentation / presentation model without polluting its set of methods (because the ability to make, for example, MyPresenterOrViewModel.new.link_to(...) does not make sense):
class MyPresenterOrViewModel def some_field helper.number_to_currency(amount, :precision => 0) end private def helper @helper ||= Class.new do include ActionView::Helpers::NumberHelper end.new end end
Andrew Marshall Mar 03 2018-11-11T00: 00Z
source share