views:

64

answers:

3

Hi,

I've a file in the config directory, let's say my_policy.txt. I want to use the content of that file in my controller like a simple string.

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

How to achieve that goal, does Rails provide its own way to do that?

Thanks

A: 

Read file as string like that?!

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
Draco Ater
+3  A: 

Rails doesn't provide a way, but Ruby does:

@policy = IO.read("#{Rails.root}\config\my_policy.txt")
John Topley
I would be a little tricky here and use the fact that `Rails.root` is a `Pathname` and do this instead: `IO.read(Rails.root + "config/my_policy.txt")`
Ryan Bigg
+3  A: 
@policy = File.read(RAILS_ROOT + '/config/my_policy.txt')

To also cache the content (if you don't want to read it every time the 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.

Vlad Zloteanu