0

We are migrating from Rails 4.2 to 5.2. The following code works fine in 4.2 but not in 5

require 'action_view'

module OurModule
  class CheckReport
    include ActionView::Helpers::DateHelper

    def self.our_method
      start_time = Time.current
      LOGGER.info "OurModule::CheckReport.our_method finished in #{distance_of_time_in_words(start_time, Time.current)}"
    end
  end
end

But in Rails 5 we are getting:

NoMethodError: undefined method `distance_of_time_in_words' for OurModule::CheckReport:Class

This seems to be because these are class methods and not instance methods.

So, why did it work in Rails 4 (same ruby version - 2.4.9) and what can we do to fix it (apart from making all these cases instance methods?)

phil
  • 4,668
  • 4
  • 33
  • 51
  • I think this question had answer. https://stackoverflow.com/questions/9573628/how-can-i-use-the-rails-helper-distance-of-time-in-words-in-plain-old-ruby-no/9573793 – Bùi Nhật Duy Jan 07 '20 at 07:59
  • This may help. https://stackoverflow.com/questions/489641/using-helpers-in-model-how-do-i-include-helper-dependencies/7593347#answer-489910 – Int'l Man Of Coding Mystery Jan 07 '20 at 08:42
  • Thanks but neither of those questions addresses either question (why the code above works perfectly in Rails 4 and what to do in Rails 5). The first question/answer (https://stackoverflow.com/questions/9573628/how-can-i-use-the-rails-helper-distance-of-time-in-words-in-plain-old-ruby-no/9573793) is where I got the above code. The second question/answer basically (https://stackoverflow.com/questions/489641/using-helpers-in-model-how-do-i-include-helper-dependencies/7593347#answer-489910) says don't 'include' but call the helpers directly, which is a totally different way of doing things. – phil Jan 07 '20 at 10:59
  • @phil Did you happen to find a solution for your problem? I just upgraded my rails to 5.2 as well and all the helper methods in the views are failing, the error `NoMethodError - undefined method for #<#:0x00007f998a87da68>` – Kedarnag Mukanahallipatna Jan 05 '21 at 06:31
  • @KedarnagMukanahallipatna - I posted an answer. Hope that helps – phil Jan 06 '21 at 08:23

1 Answers1

0

Seeing as some people are coming here to find the answer, here is what I did:

require 'action_view'

module OurModule
  class CheckReport

    def self.our_method
      start_time = Time.current
      LOGGER.info "OurModule::CheckReport.our_method finished in #{ActionController::Base.helpers.distance_of_time_in_words(start_time, Time.current)}"
    end
  end
end
phil
  • 4,668
  • 4
  • 33
  • 51
  • Thanks!, here's what I did. I added the helper call in the controller that renders it something like `helper OurModule`. I am not sure if what I have done is good practice, I'll try what you have done. – Kedarnag Mukanahallipatna Jan 06 '21 at 15:35