2

I have a file in lib/thing.rb, and in there I need to call a method defined in ApplicationHelper inside a class method in thing.rb

In other words in Thing.some_method() it calls format_me() in ApplicationHelper

I've tried every conceivable way I can think of to extend ApplicationHelper or extend ActionView::Helpers::ApplicationHelper and it just keeps saying uninitialized constant. Ive also tried Rails.application.helpers but I don't know how to access the method in there...

Tallboy
  • 12,847
  • 13
  • 82
  • 173
  • I can't reproduce this. Can you give some more info, such as _when_ are you calling this, and what the code looks like? – max pleaner May 26 '19 at 02:24
  • 1
    I am not fully aware of Rails autoloading crap, but I am pretty sure old good plain ruby `require_relative "../app/helpers/..."` would do. – Aleksei Matiushkin May 26 '19 at 05:12

1 Answers1

1

If you're getting errors about uninitialized constants then you can probably resolve the issue by moving lib/ into app/. Using Ruby 2.6.3 and Rails 5.2.3, given the following files and layout:

# app/helpers/application_helper.rb
module ApplicationHelper
  def baz
    SecureRandom.uuid
  end
end

and:

# app/lib/foo.rb
class Foo
  extend ApplicationHelper

  def self.bar
    baz
  end
end

Calling Foo.bar returns:

=> "b6322675-47b2-4ae8-a19a-ffd4af8d6f84"
anothermh
  • 9,815
  • 3
  • 33
  • 52