Is there a way to define a model attribute, as always, html_safe?

I have a model called Feature with a variable called body_string that contains the HTML markup that I would like to display, not escape.

Every time I refer to body_string in my views, I need to use <%=raw or .html_safe . It seems redundant and not very dry.

Is there a way that I can set the body_string variable somehow and all for myself as html_safe ?

I assume that this will happen in the app/models/feature.rb , but I cannot figure out what exactly will be the correct syntax. I thought about this:

 def body_string return self.body_string.html_safe end 

But he doesn't like Rails; it throws a stack level too deep exception.

Naturally, I could define a variable / method with a different name:

 def safe_body_string return self.body_string.html_safe end 

And then just change all the links in the views from body_string to safe_body_string . But for some reason it seems almost NOT DRY, just using raw or .html_safe in the first place.

Any ideas on how best to deal with this? I feel that there must be something really elegant that I just don’t see.

+6
source share
4 answers

Just use read_attribute to avoid the recursive call to body_string :

 def body_string read_attribute(:body_string).html_safe end 

read_attribute is complemented by write_attribute to set attributes from your model.

Style Note: Do not use explicit return unless you really need them. The result of the last statement in the method is the implicit value returned from the method.

+9
source

Although @meager's answer will definitely work, I don't think this logic belongs to the model. Just because it adds presentation-level problems (HTML security) to the model layer, which should include business logic. Instead, I would recommend using a presenter for this (see http://nithinbekal.com/posts/rails-presenters/ or find a stone for this - I personally like the Case Display ). Your host can easily override the body_string method and specify the .html_safe notation when displayed in the view. This way you separate your problems and can continue to get body_string from other models without mixing them with the problem.

+1
source

Perhaps this stone is useful to you. I also wanted to stop repeating html_safe all the time when the content is fully trusted.

http://rubygems.org/gems/html_safe_attribute

0
source

Or you can also use this approach,

 def body_string super && super.html_safe end 
0
source

Source: https://habr.com/ru/post/889978/


All Articles