Using the image_path helper in the user yml.erb file in the configuration directory written through the user initializer

I created a yml.erb file that will be used to configure some parts of my application. I would like to preload it with an initializer (I do not require it to change during application startup), the biggest problem is that this yml file contains a link to images that are inside the app / assets / images directory. I would like to use the image_path helper inside my yml.erb file, but I am having problems (I don’t know what I should include and where I should include it: if in the yml.erb file or in a file that parses the yml file. erb).

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 configuration)

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

home_controller.rb (internal 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?

+4
source share
3 answers

If you need to analyze ERB only from the inside, 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 %> 

This way you can control which attributes are actually being processed. In addition, all the helpers available in the view are available in yaml, due to (binding) .

+2
source

Rails.application.routes.url_helpers is a module with your url_helpers that you can include where you want to use them. You can pass this to ERB through binding

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

and then in yml

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

since when evaluating time erb self Rails.application

+1
source

The rails seem to be "insufficiently initialized" as indicated by ffoeg and clyfe. I moved the script to another part of my code where the rails are more initialized and now it works fine.

0
source

Source: https://habr.com/ru/post/1385707/


All Articles