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

Is it possible to access a Module from within a haml file?

我想将我的助手分类到子模块中,以使代码更清晰。例如,我想实现这样的东西:

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

我已经试过像这样在我的辅助模块中创建一个模块:

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

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

首先,确保文件命名正确,以便自动加载正常工作。如果模块名为 StyleguideHelper,则文件必须命名为 styleguide_helper.rb。我会把这个文件放在 app/helpers 中,除非你已经为自动加载设置了库。像这样在该文件中定义您的模块:

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

然后您应该可以像这样在您的视图中使用助手:

= StyleguideHelper::UI.spawn_component(user, type)