I want to write Rails helper method better

Asked 1 years ago, Updated 1 years ago, 56 views

  • View content if all CMS content is listed
    In order to create this specification, we have created the following helper methods:

cm cms_fragment_content(:text_1) is a helper method used to build CMS using a gem called compatible-mexican-sofa to retrieve the registered text from it.

The method all_contents? is working without any problems with the code below, but I posted a question because I thought it would be a little less smart because it was repeated like a similar code.

I searched many things, but Ruby was a beginner, so I couldn't write anything with a smart way of writing that worked well.

I would appreciate it if you could give me advice if there is a simpler way to write.

def all_contents?
  cms_fragment_content(:text_1).present?\
  &cms_fragment_content(:text_2).present?\
  &cms_fragment_content(:text_3).present?\
  &cms_fragment_content(:text_4).present?\
  &cms_fragment_content(:text_5).present?
end

view side

-if all_contents?
  .contents-class
  (omitted hereinafter)

ruby-on-rails ruby html slim

2022-09-30 19:30

2 Answers

Simply reduce repetition a little

%i(text_1text_2text_3text_4text_5).all?{|text_n|cms_fragment_content(text_n).present?}

I think I can write it like this (I haven't tried it)

(1..5).all?{|n|~} might be fine.


2022-09-30 19:30

How do you feel about the following?

def all_contents?
  (1..5) .all?{|i|cms_fragment_content(:"text_#{i}").present?}
end


2022-09-30 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.