I built a yml.erb file that will be used for configuring some parts of my application. I would like to preload it with an initializer (I don't require it to change during application running), the biggest problem is that this yml file contains link to images that are inside app/assets/images directory. I would like to use the image_path helper inside my yml.erb file but I'm having troubles (I don't know what I should include and where should I include it: if in the yml.erb file or in the file that parses the yml.erb file).
What I have at the moment
desktop_icons.rb (inside 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 (inside config)
-
image: <%= image_path "rails" %>
title: Test this title
home_controller.rb (inside controllers)
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
Any suggestion?
If the ERB only needs to be parsed from inside views, you can do something like this:
Controller
@questions = YAML.load_file("#{Rails.root}/config/faq.yml.erb")
View
<%= ERB.new(@questions[2]["answer"]).result(binding).html_safe %>
That way you can control which attributes actually get parsed. Also, all helpers available in the view are available in the yaml, due to (binding)
.