blocks and late evaluation

Discussion in 'Ruby' started by Vassilis Vatikiotis, Sep 5, 2011.

  1. hi all,

    my question is in the context of sinatra but it's a blocks question really.

    I have configure block in sinatra (configure blocks in sinatra run only once, upon initialisation). There, I want to load some database records in memory. So I do:
    configure do
    set :keys do { |record| record.field }

    Whenever I access the class level variable :keys I get a DB query. Whereas if, inside that configure block, I do:

    keys = { |record| record.field }
    set :keys, keys

    there are no DB queries, I can even stop the database daemon and my app will go on.

    Now I'm *almost* certain that it's not a sinatra issue but my ruby block ignorance. I know that Proc objects are evaluated when they are called but here we have a block returning a new Array, and not a Proc object.

    can you explain it?
    Vassilis Vatikiotis, Sep 5, 2011
    1. Advertisements

  2. I don't know Sinatra (apart from Frank, of course) but the reason must
    either be in DB.all's or in set's behavior. To debug it might be
    helpful to insert something like "$stderr.puts 'called'" inside the
    block so you can see how often the block is invoked.

    Kind regards

    Robert Klemme, Sep 5, 2011
    1. Advertisements

  3. That's correct. For Sinatra he should have used

    and $ /= in.between()

    I'm surprised somebody else didn't catch this ;-)
    Fritz Wuehler, Sep 5, 2011
  4. It's sinatra related after all. set stores the block object and every time :keys is referenced it calls the block.
    sorry for of topic and thx
    Vassilis Vatikiotis, Sep 6, 2011
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.