Rails (3.2.7): override image_tag for asset_host

development.rb:

config.action_controller.asset_host = "assets.myserver.com" 

view script:

 <%= image_tag('header.jpg') %> 

<strong> outputs:

 <img alt="Header" src="/header.jpg" /> 

it should be:

 <img alt="Header" src="http://assets.myserver.com/header.jpg" /> 

I am using rails-api gem, which I assume disables some resource and browses rendering files.

It doesn't seem too hard to repeat the implementation (override image_tag ) to add this very small function. It may seem a little strange to do this. However, I am new to rails and would like to know how to do this as a learning experience.

Questions:

  • What is the best way to use this new code in a file structure?
  • What should I call the file new code?
  • How do rails know how to look at new code instead of looking at the old image_tag function?
+6
source share
1 answer

I tried your configuration, but when I use config.action_controller.asset_host = "assets.myserver.com" in my development.rb image_tag works as expected:

 <img alt="Header" src="http://assets.myserver.com/assets/header.jpg" /> 

I tested it in both Rails 3.2.7 and 3.2.8, but it works in both versions.

UPDATE

In my original answer, I did not use the rails-api gem. When using rails-api gem image_tag works as described in the question.

To answer the real question, you can add an initializer in config/initializers . Just create a file, say image_tag_helper.rb , with the following code:

 # config/initializers/image_tag_helper.rb module ActionView module Helpers module AssetTagHelper def image_tag(source, options = {}) options[:src] = "http://#{source}" tag("img", options) end end end end 

Basically this is reopening the module and replacing the image_tag method with your own method. All other methods in module AssetTagHelper remain unchanged. Take a look at the Rails repository on github for a complete β€œexample” image_tag method.

The name of the file does not really matter. All files in config/initializers are loaded when the application loads.

This is basically a Ruby language feature, Ruby allows you to re-open classes in your code and add or replace methods (you'll find more on this topic at rubylearning.com ).

+3
source

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


All Articles