onkeldittmeyer
onkeldittmeyer

Reputation: 27

return json from ruby using rack

i'm still fairly new to server side scripts and try myself a little bit on ruby to write me little helpers and to learn some new things.

I currently try to write a small ruby app which sends a json file of all images within a specific folder to my page where i can use those to handle them further in js.

I read quite a few introductions to ruby and rails and got a recommendation to look into rack as a lightweight communicator between server and app.

While the ruby part works fine, i have difficulties to understand how to send out the generated JSON as a reaction to a future ajax call (e.g.). Hope someone can give me a few hints or sources to look into for further understanding. Thanks!

require 'json'

class listImages
def call(env)
    imageDir = Dir.chdir("./img");
    files = Dir.glob("img*")

    n = 0
    tempHash = {}

    files.each do |i|
      tempHash["img#{n}"] = i
      n += 1
    end

   File.open("temp.json","w") do |f|
     f.write(tempHash.to_json)
   end

  [200,{"Content-Type" => "application/javascript"}, ["temp.json"]] 
   end
   puts "All done!"
end

run listImages.new


if $0 == __FILE__
  require 'rack'
  Rack::Handler::WEBrick.run MyApp.new
end

Upvotes: -1

Views: 585

Answers (1)

zwippie
zwippie

Reputation: 15515

You don't have to save the JSON to a file before you can send it. Just send it directly:

[200, {"Content-Type" => "application/json"}, [tempHash.to_json]]

With your current code, you are only sending the String "temp.json".

That said, the rest of your code looks a little bit messy/not conform Ruby coding standards:

  • Start your classnames with an uppercase: class ListImages, not class listImages.
  • Use underscores, not camelcase for variable names: image_dir, not imageDir.
  • The puts "All done!" statement is outside the method definition and will be called early, when the class is loaded.
  • You define a class ListImages but in the last line of your code you refer to MyApp.

Upvotes: 4

Related Questions