Class: Esapiserver::Server

Inherits:
Sinatra::Application
  • Object
show all
Defined in:
lib/esapiserver.rb

Constant Summary collapse

POOL_SIZE =
5
TIMEOUT =
5

Instance Method Summary collapse

Instance Method Details

#findOne(model, id) ⇒ Object

Utility method - find one and the sreialize to Ember Friendly JSON



185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/esapiserver.rb', line 185

def findOne(model, id)
  result = $db.collection(model).find_one(toBsonId(id))
  jsonArray = []
  if result != nil
    normalizedResult = fromBsonId(result, model).to_json
    hash = JSON.parse(normalizedResult)
    jsonArray << hash[modelName(model)]
    newJson = {modelName(params[:model]) => jsonArray}
  newJson.to_json
  else
    noResults = {modelName(model) => jsonArray}
  noResults.to_json
  end
end

#fromBsonId(obj, model) ⇒ Object

Extract the BSON id, then replacing the ‘_id’ key with a ‘id’ key



165
166
167
168
169
# File 'lib/esapiserver.rb', line 165

def fromBsonId(obj, model)
  id = obj['_id'].to_s
  obj.delete("_id")
  obj.each{|t| t[1]['id'] = id}
end

#modelName(model) ⇒ Object

Very crude method to singularize the model name.



203
204
205
206
# File 'lib/esapiserver.rb', line 203

def modelName(model)
  #model.chomp("s")
  model.singularize
end

#serializeJSON(json, model) ⇒ Object

Serialize the Mongo JSON to Ember friendly JSON



174
175
176
177
178
179
180
# File 'lib/esapiserver.rb', line 174

def serializeJSON(json, model)
  hash = JSON.parse(json)
  jsonArray = []
  hash.each {|h| jsonArray << h[modelName(params[:model])]}
  newJson = {modelName(params[:model]) => jsonArray}
  newJson.to_json
end

#toBsonId(id) ⇒ Object

Convert the id to a BSON object id



158
159
160
# File 'lib/esapiserver.rb', line 158

def toBsonId(id)
  BSON::ObjectId.from_string(id)
end