我正在我的应用程序中开发一个导航助手,它从一个yaml文件编译当前命名空间/控制器的页面导航。我的山药是这样的:
---
manage:
- link: <%= manage_clients_path %>
icon: torsos-all
label: Clients
- link: <%= manage_users_path %>
icon: torso
label: Users
在我的助手中,我经历了几次迭代,但现在我使用的是以下代码:
require 'yaml'
require 'erb'
module NavigationHelper
include Rails.application.routes.url_helpers
def navigation
unless current_user.nil?
namepsace = params[:controller].split('/').first
compiledNav = ERB.new File.read(File.join Rails.root, 'config/navigation.yml')
nav = YAML.load compiledNav.result
if nav.has_key?(namepsace) && !nav[namespace].blank?
nav[namepsace]
else
[]
end
end
end
end
现在,我得到一个错误,即没有定义manage_clients_path(
undefined local variable or method
manage_clients_path',用于main:object), but I can guarentee that it does exist by running
rake routes`)。从
rake routes
$ ./bin/spring rake routes | grep manage_clients
manage_clients GET /manage/clients(.:format) manage/clients#index
最佳答案
这个问题似乎是由我使用haml构建视图和布局引起的。我把代码改成了以下代码,一切正常:
YAML配置:
---
manage:
- link: #{manage_clients_path}
icon: torsos-all
label: Clients
- link: #{manage_users_path}
icon: torso
label: Users
还有我的助手:
require 'yaml'
module NavigationHelper
def navigation
unless current_user.nil?
namepsace = params[:controller].split('/').first
nav = YAML.load_file File.join(Rails.root, 'config/navigation.yml')
if nav.has_key?(namepsace) && !nav[namespace].blank?
nav[namepsace]
else
[]
end
end
end
end
现在一切都正常了。
关于ruby-on-rails - 将YAML与ERB和Rails路径助手混合使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23914235/