views:

114

answers:

1

Hi all:

I must have done it in a wrong way: the records printed out are out of order, even though they are inserted into db one at a time. Here is the code:

get '/' do
  db = Mongo::Connection.new("localhost", 27017).db("testdb")
  @notes = db.collection('notes')
  @notelist = Set.new()
  @notes.find().each{|record| @notelist.add(record)}
  erb :list
end

post '/addnote' do
  db = Mongo::Connection.new("localhost", 27017).db("testdb")
  col1 = db.collection('notes')
  col1.insert(
  {
    "guestname" => "#{params[:post][:guestname]}",
    "note"      => "#{params[:post][:note]}",
    "datetime"  => Time.now.strftime("%I:%M %p %d-%b-%Y")
  })
redirect '/'
end

And here is the erb template:

<p><%= @notelist.size() %> notes entered by guests:</p>
<ul>
  <% @notelist.each do |record| %>
    <li><font color='blue'><%= record['guestname'].to_s() + 
    "</font> at <i>" + record['datetime'].to_s() +"</i> wrote: " + 
    record['note'].to_s() %></li>
  <% end %>
</ul>

I am trying to get all records out of the db in an order of datetime, how can I achieve that?

Thanks a lot in advance.

Updated info:

On second thought, I change the data type from time to unix epoch, so sorting them would be better and easier.

+3  A: 

A few notes here:

You can get records in order by adding a sort:

@notes.find({}, :sort => 'datetime')

You do not need to iterate before entering your template. The 'find' method returns a cursor, which itself is iterable. So

@notelist = Set.new()
@notes.find().each{|record| @notelist.add(record)}

Should read

@notelist = @notes.find({}, :sort => 'datetime')

It's very inefficient to establish a new connection on each request. You should establish the connection on a configure block, and cache the database there:

configure do
  DB = Mongo::Connection.new.db("testdb")
end

Then just use the reference to DB in your requests.

Kyle Banker
@Kyle Banker: Wow, I think that's actually more than I expected, thanks for your help!
Michael Mao
@Kyle Banker: I managed to finish all other tasks, but am still not sure about how to work with a configuration block? Any hint on that?
Michael Mao
Certainly. Have a look at this simple Sinatra app: http://github.com/banker/mongulator/blob/master/mongulator.rb
Kyle Banker