是否可以从haml文件中访问模块?

问题描述 投票:0回答:1

我想在子模块中创建我的助手,以使代码更清晰。例如,我想实现这样的事情:

= UI.spawn_component(UI.alert, UI.error, "message")

我已经尝试过在我的助手模块中创建一个模块,如下所示:

module StyleguideHelper
  module UI
    def spawn_component(user, type)
      return user
    end
  end
end

我还尝试在不同的文件中创建模块,并从我的帮助文件中获取它。这两个都不起作用。

ruby-on-rails ruby haml
1个回答
1
投票

首先,确保文件名称正确,以便自动加载正常工作。如果该模块被称为StyleguideHelper,那么该文件必须命名为styleguide_helper.rb。我会把这个文件放在app/helpers中,除非你设置自动加载的lib。在这个文件中定义你的模块,如下所示:

module StyleguideHelper
  module UI
    def self.spawn_component(user, type)
      return user
    end
  end
end

然后,您应该能够在视图中使用这样的帮助:

= StyleguideHelper::UI.spawn_component(user, type)
© www.soinside.com 2019 - 2024. All rights reserved.