5

I have a Rails/Mongoid app that displays data client-side using highcharts. Right now, to pass the data to Javascript, I use a Mongoid query and Rails' as_json/to_json in the template file. This seems very inefficient to me because the json data has to be parsed into ruby structures, and then re-converted to JSON. This is okay when there is a small amount of data, but in my case, there can be a lot.

So my question is, how can I do a raw mongodb query, and just write the output directly to the Rails response buffer without going through Ruby JSON serialization/deserialization?

1
  • can you provide some examples? Commented Apr 23, 2011 at 12:34

1 Answer 1

3

The data in MongoDB is stored in BSON, which is not JSON. The ruby driver does deserialization (BSON::BSON_CODER.deserialize) in read_documents method. If you'd like to roll your own BSON-to-JSON, you'll need your implementation of BSON::BSON_coder.deserialize, and, probably, rewrite more parts in mongo-ruby driver. If, however, this is a overhead that's acceptable, then you'll just subclass ActionController::Metal and do something like this:

class ChartController < ActionController::Metal
  def chart
    res = fetch_data_from_mongodb
    self.content_type = 'application/json'
    self.response_body = res.to_json
  end
end

Another alternative might be using the MongoDB's REST HTTP interface, which provides JSON. But you'll have to have some access control in your application, and, basically, proxy requests.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.