Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve a static JSON file in rails?

I have a file on my server that's outside of my app directory. It's a text file that holds a json object, /path/to/data.json.

What's the simplest way to serve this file in Rails, e.g. to return it in response to a GET request?

Here's what I've tried so far, inspired by this answer and others. (This may be way off-base -- I'm new to rails.)

  1. added this line to routes.rb resources :data

  2. Wrote the following data_controller.rb

class DataController < ApplicationController

@data = File.read("/path/to/data.json")

def index
  render :json => @data
 end
end

This doesn't work. When I direct my browser to http://myserver.com/data.json I just see "null" instead of the data.json file.

Any idea what I'm doing wrong?

like image 577
dB' Avatar asked Jun 22 '12 02:06

dB'


3 Answers

I think this is a scope issue; your outer @data is not the same as the @data in a method. That is, you can't use instance variables as expected outside of methods because there is no instance yet.

It should work if you use a class variable, eg

@@data = File.read("/path/to/data.json")

then

render :json => @@data
like image 179
Tim Peters Avatar answered Oct 18 '22 16:10

Tim Peters


Put it in public/assets/javascripts. Or app/assets/javascripts. The server may even return the correct content-type.

like image 10
Dean Brundage Avatar answered Oct 18 '22 16:10

Dean Brundage


  • put data.json file into your project directory ( for example public/data.json)
  • @data = File.read("#{Rails.root}/public/data.json")
  • At last but not least render :json => @data
like image 5
Viet Anh Do Avatar answered Oct 18 '22 14:10

Viet Anh Do