4

我构建了一个 yml.erb 文件,该文件将用于配置我的应用程序的某些部分。我想用初始化程序预加载它(我不需要在应用程序运行期间更改它),最大的问题是这个 yml 文件包含指向 app/assets/images 目录内的图像的链接。我想在我的 yml.erb 文件中使用 image_path 帮助程序,但我遇到了麻烦(我不知道我应该包含什么以及应该在哪里包含它:如果在 yml.erb 文件中或在解析的文件中yml.erb 文件)。

我现在拥有的

desktop_icons.rb(在 config/initializers 中)

require 'yaml'
require 'rails'
include ActionView::Helpers::AssetTagHelper

module ManageFedertrekOrg
  class Application < Rails::Application
    def desktop_icons
      @icons ||= YAML.load(ERB.new(File.read("#{Rails.root}/config/icons.yml.erb")).result)
    end
  end
end

icons.yml.erb(内部配置)

 - 
  image: <%= image_path "rails" %>
  title: Test this title

home_controller.rb(控制器内部)

class HomeController < ApplicationController
    skip_filter :authenticate_user!

  def index
    @user_is_signed_in = user_signed_in?
    respond_to do |format|
      format.html { render :layout => false } # index.html.erb
    end
  end

  def icons
    result =
    {
      icons: MyApp::Application.desktop_icons,
      success: true,
      total: MyApp::Application.desktop_icons.count
    }

    respond_to do |format|
      format.json { render json: result }
    end
  end

end

有什么建议吗?

4

3 回答 3

2

如果 ERB 只需要从内部视图中解析,您可以执行以下操作:

控制器

@questions = YAML.load_file("#{Rails.root}/config/faq.yml.erb")

看法

<%= ERB.new(@questions[2]["answer"]).result(binding).html_safe %>

这样您就可以控制实际解析哪些属性。此外,由于(binding).

于 2012-07-23T09:56:19.247 回答
1

Rails.application.routes.url_helpers是一个带有 url_helpers 的模块,您可以将其包含在要使用它们的位置。您可以通过绑定将此传递给 ERB

class Application < Rails::Application
  def desktop_icons
    @icons ||= YAML.load(
      ERB.new(File.read("#{Rails.root}/config/icons.yml.erb")).result(binding)
    )
  end
end

然后在 yml

<% extend routes.url_helpers %>
- 
 image: <%= image_path "rails" %>
 title: Test this title

因为在 erb 评估时,自我是Rails.application

于 2011-12-11T02:24:28.387 回答
0

正如 ffoeg 和 clyfe 所说,rails 看起来“初始化不够”。我将脚本移动到我的代码的另一部分,其中 rails 被更多地初始化,现在它运行良好。

于 2011-12-12T03:38:58.147 回答