Rails, use the contents of the file in the controller

I have a file in the config directory, say my_policy.txt. I want to use the contents of this file in my controller as a simple string.

 @policy = #content of /config/my_policy.txt 

How to achieve this goal, does Rails do its own way of doing this?

thanks

+4
source share
3 answers

Rails does not provide a way, but Ruby does:

 @policy = IO.read("#{Rails.root}\config\my_policy.txt") 
+8
source
 @policy = File.read(RAILS_ROOT + '/config/my_policy.txt') 

Also cache the content (if you do not want to read it every time a variable is used):

 def policy @@policy ||= File.read(RAILS_ROOT + '/config/my_policy.txt') end 

If you need something more elegant for configuration, check configatronic .

+4
source

Read the file as a string ?!

 def get_file_as_string(filename) data = '' f = File.open(filename, "r") f.each_line do |line| data += line end return data end ##### MAIN ##### @policy = get_file_as_string 'path/to/my_policy.txt' # print out the string puts @policy 
0
source

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


All Articles