我在lib/thing.rb
中有一个文件,在那里我需要在ApplicationHelper
的类方法内调用thing.rb
中定义的方法
换句话说,在Thing.some_method()
中,它在format_me()
中调用ApplicationHelper
我已经尝试过所有可以想到的方法extend ApplicationHelper
或extend ActionView::Helpers::ApplicationHelper
,但它一直在说未初始化的常量。我也尝试过Rails.application.helpers
,但我不知道如何在其中访问该方法...
答案 0 :(得分:0)
如果您收到有关未初始化常量的错误,则可以通过moving lib/
into app/
解决此问题。给定以下文件和布局,使用Ruby 2.6.3和Rails 5.2.3:
# app/helpers/application_helper.rb
module ApplicationHelper
def baz
SecureRandom.uuid
end
end
和:
# app/lib/foo.rb
class Foo
extend ApplicationHelper
def self.bar
baz
end
end
呼叫Foo.bar
返回:
=> "b6322675-47b2-4ae8-a19a-ffd4af8d6f84"