<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Levy Carneiro</title>
	<atom:link href="http://levycarneiro.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://levycarneiro.com</link>
	<description></description>
	<lastBuildDate>Sun, 19 Jun 2011 22:33:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Webcast: Como melhorar a performance do meu site?</title>
		<link>http://levycarneiro.com/2010/04/webcast-como-melhorar-a-performance-do-meu-site/</link>
		<comments>http://levycarneiro.com/2010/04/webcast-como-melhorar-a-performance-do-meu-site/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 14:10:11 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Browser]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[client-side]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[pagespeed]]></category>
		<category><![CDATA[performance web]]></category>
		<category><![CDATA[souders]]></category>
		<category><![CDATA[yslow]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=248</guid>
		<description><![CDATA[Galera, estou postando aqui um Webcast que gravei para o blog da Locaweb. Trabalho na equipe de desenvolvimento Front-End / UX da Locaweb. O que você pode fazer hoje para deixar seu site mais rápido? Um site pode levar por volta de 200ms para gerar o HTML que será recebido pelo browser. Mas o tempo [...]]]></description>
			<content:encoded><![CDATA[<p>Galera, estou postando aqui um Webcast que gravei para o blog da Locaweb. Trabalho na equipe de desenvolvimento Front-End / UX da Locaweb.</p>
<p><strong>O que você pode fazer hoje para deixar seu site mais rápido?</strong></p>
<p>Um site pode levar por volta de 200ms para gerar o HTML que será recebido pelo browser. Mas o tempo de “montagem” desta página no browser leva diversos segundos, tendo casos extremos com mais de 10 segundos.</p>
<p>Então <strong>a mudança que você pode fazer hoje</strong>, que vai impactar mais seu usuário ou cliente, <strong>é otimizar o tempo de carregamento de seu site no browser</strong>. Não é gastar horas e horas otimizando seu código server-side como Ruby on Rails, PHP ou .NET. Mesmo que seu site já tenha milhares de acessos por hora, a primeira coisa a ser feita é otimizar a performance de seu site no browser, e depois partir para a otimização de server-side.</p>
<p>Nesse Webcast falo sobre várias técnicas e dicas para melhorar a <strong>performance client-side</strong> de seu site:</p>
<p><object width="480" height="385" data="http://www.youtube.com/p/72B544896CDB8137&amp;hl=pt_BR&amp;fs=1" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/p/72B544896CDB8137&amp;hl=pt_BR&amp;fs=1" /><param name="allowfullscreen" value="true" /></object></p>
<p>Enviem dúvidas nos comentários abaixo.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2010/04/webcast-como-melhorar-a-performance-do-meu-site/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tag it! Tag suggestions, editor and autocomplete in a jQuery UI plugin</title>
		<link>http://levycarneiro.com/2010/03/tag-it-tag-suggestions-editor-and-autocomplete-in-a-jquery-ui-plugin/</link>
		<comments>http://levycarneiro.com/2010/03/tag-it-tag-suggestions-editor-and-autocomplete-in-a-jquery-ui-plugin/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 20:32:50 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery UI]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jqueryui]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=240</guid>
		<description><![CDATA[After looking for a jQuery plugin for handling a tag suggestion form field, also with a autocomplete feature &#8211; in much the same way ZenDesk.com does &#8211; I ended up developing a customization of jQuery UI that does the same interaction. UPDATE June 19th, 2011: due to other pressing priorities I delegated the development/support of [...]]]></description>
			<content:encoded><![CDATA[<p>After looking for a jQuery plugin for handling a <strong>tag suggestion</strong> form field, also with a <strong>autocomplete</strong> feature &#8211; in much the same way ZenDesk.com does &#8211; I ended up developing a customization of jQuery UI that does the same interaction.</p>
<p><strong>UPDATE June 19th, 2011</strong>: due to other pressing priorities I delegated the development/support of this plugin to Alex Ehlke who is now doing an amazing job keeping this plugin up to date. Links below are now pointing to his repository. Thanks for your amazing help, Alex!</p>
<p>Official page for the project: <a href="http://aehlke.github.com/tag-it/">http://aehlke.github.com/tag-it/</a></p>
<p>See the <a href="http://github.com/aehlke/tag-it/raw/master/screenshot.png" target="_blank">screenshot</a></p>
<p>See the <a href="http://aehlke.github.com/tag-it/" target="_blank">Demo</a></p>
<p>Fork <a href="http://github.com/aehlke/tag-it" target="_blank">Tag it! on Github</a></p>
<p>Download the <a href="http://github.com/aehlke/tag-it/zipball/master" target="_blank">Tag it! plugin</a></p>
<p>Cheers! <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2010/03/tag-it-tag-suggestions-editor-and-autocomplete-in-a-jquery-ui-plugin/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Gerador de CPF e CNPJ mais rápido no browser</title>
		<link>http://levycarneiro.com/2010/03/gerador-de-cpf-e-cnpj-mais-rapido-no-browser/</link>
		<comments>http://levycarneiro.com/2010/03/gerador-de-cpf-e-cnpj-mais-rapido-no-browser/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 18:34:25 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Bookmarklets]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[cnpj]]></category>
		<category><![CDATA[cpf]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=228</guid>
		<description><![CDATA[Na linha de automatizar tudo que faço manualmente, criei um bookmarklet que gera um CPF ou CNPJ diretamente do browser. Assim você não precisa mais procurar por &#8220;gerador de CPF e CNPJ&#8221; no Google Como usar: - abra esta página e arraste os 2 links para a barra de Bookmarks de seu browser; - clique [...]]]></description>
			<content:encoded><![CDATA[<p>Na linha de automatizar tudo que faço manualmente, criei um bookmarklet que gera um CPF ou CNPJ diretamente do browser.</p>
<p>Assim você não precisa mais procurar por &#8220;gerador de CPF e CNPJ&#8221; no Google <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Como usar:</p>
<p>- abra <a href="http://levycarneiro.com/projects/cpf-cnpj-bookmarklet/cpf-cnpj-bookmarklets.htm" target="_blank">esta página</a> e arraste os 2 links para a barra de Bookmarks de seu browser;<br />
- clique em um dos favoritos e pronto, um novo CPF ou CNPJ é gerado sem você precisar sair da página que você estava usando <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>O projetinho está no <a href="http://github.com/levycarneiro/cpf-cnpj-bookmarklet">Github</a> &#8211; caso você queira fazer um fork <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2010/03/gerador-de-cpf-e-cnpj-mais-rapido-no-browser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An elegant way to log with a Ruby block</title>
		<link>http://levycarneiro.com/2010/01/an-elegant-way-to-log-with-a-ruby-block/</link>
		<comments>http://levycarneiro.com/2010/01/an-elegant-way-to-log-with-a-ruby-block/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 02:16:49 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=216</guid>
		<description><![CDATA[Imagine you created a generator much like Rails. It creates a series of directories and copy a set of files to a specific location. Some things may fail, and you need a nice way to show what&#8217;s going on behind the scenes. I was browsing some code on GitHub and found an elegant approach to [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine you created a generator much like Rails. It creates a series of directories and copy a set of files to a specific location. Some things may fail, and you need a nice way to show what&#8217;s going on behind the scenes.</p>
<p>I was browsing some code on GitHub and found an elegant approach to this problem.</p>
<pre><code class="ruby">
module Glue
  module Generator
    extend self
    extend Glue::Helper

    def generate!(options={})
      templates = File.expand_path(File.dirname(__FILE__) + "/../../templates")
      output = File.expand_path(options[:path])

      # create root directory
      run "creating #{Colorize.yellow(output, :style =&gt; :underscore)} directory" do
        FileUtils.mkdir_p(output)
      end

      # create javascripts directory
      run %(creating #{Colorize.yellow("public/javascripts")} directory) do
        FileUtils.mkdir_p File.join(output, "public/javascripts")
      end

      # create images directory
      run %(creating #{Colorize.yellow("public/images")} directory) do
        FileUtils.mkdir_p File.join(output, "public/images")
      end

      # create views directory
      run %(creating #{Colorize.yellow("views/layouts")} directory) do
        FileUtils.mkdir_p File.join(output, "views/layouts")
      end
    end
  end
end

module Glue
  module Helper
    def run(message, &amp;block)
      $stdout &lt;&lt; "\n#{message}... "

      begin
        yield
        $stdout &lt;&lt; Colorize.green("done!")
      rescue Exception =&gt; e
        $stdout &lt;&lt; Colorize.red("error ~ #{e.message}")
      end
    end
  end
end
</code></pre>
<p>This code does a few interesting things:</p>
<ul>
<li>the &#8220;run&#8221; method is defined inside a helper module. It begins by receiving a message (what are you doing right now?) and a block. It starts by giving control to the caller with a <em>yield</em> (now the execution inside the &#8220;run&#8221; method is halted). So the block passed to the run method is now executed. This block is actually the lines you see above between &#8220;run &#8230; / end&#8221;;</li>
<li>So in this block you can &#8220;do your thing&#8221;. For example, create a directory, request some info from a remote API, or whatever;</li>
<li>When the block is finished running, the lines after <em>yield</em> (in the &#8220;run&#8221; method) are executed. If no exception is raised a Ok message is printed, otherwise we&#8217;ll see what went wrong with the specific exception message.</li>
</ul>
<p>This is very cool. You can now execute failure-prone tasks in a very elegant way, and with a really nice syntax <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>This code was created by <a href="http://simplesideias.com.br/">Nando Vieira</a> in an interesting project called <a href="http://github.com/fnando/glue">Glue</a>, which is a simple static site generator for Ruby that uses Haml, Sass and Textile/Markdown. The documentation is <a href="http://fnando.github.com/public/glue.html">here</a>.</p>
<p>You can see the code samples above, <a href="http://github.com/fnando/glue/blob/master/lib/glue/generator.rb">here</a> and <a href="http://github.com/fnando/glue/blob/master/lib/glue/helper.rb">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2010/01/an-elegant-way-to-log-with-a-ruby-block/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reasons to use a no-sql database like mongoDB</title>
		<link>http://levycarneiro.com/2009/12/reasons-to-use-a-no-sql-database-like-mongodb/</link>
		<comments>http://levycarneiro.com/2009/12/reasons-to-use-a-no-sql-database-like-mongodb/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 20:55:35 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[databases]]></category>
		<category><![CDATA[mongoDB]]></category>
		<category><![CDATA[Scaling]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[database design]]></category>
		<category><![CDATA[database scaling]]></category>
		<category><![CDATA[no-sql]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=174</guid>
		<description><![CDATA[In this article I&#8217;ll talk about reasons to use mongoDB and other no-sql databases. Relational databases are often used in many web apps. But usually when the time comes to scale the app to a few millions users, you have to make choices on your architecture. For instance, a common practice to handle high load [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I&#8217;ll talk about reasons to use mongoDB and other no-sql databases.</p>
<p>Relational databases are often used in many web apps. But usually when the time comes to <strong>scale the app to a few millions users</strong>, you have to make choices on your architecture.</p>
<p>For instance, a common practice to handle high load is to put one or more of the most used tables in separate servers. In order to use this technique, a developer will have to resolve the issue of join queries. How do you query tables that aren&#8217;t in the same location and yet have <strong>high performance</strong>?</p>
<p>One solution is to denormalize data, thus duplicating content in all tables that may have a query that needs to know about it. Think of 2 tables: contacts and users. The tables are separated into 2 different servers. And you have a feature in your app, in which you show all contacts from a specific user. You need a join query, but you can&#8217;t use it. So you duplicate some of the fields from the contacts table, right inside your users table. For instance, you create a field called contact_names, in which you put only the names, of all contacts from that user, separated by commas. It&#8217;s a easy way to solve the problem, but it comes with a cost. You have to worry about syncing the contacts in all tables that know something about contacts.</p>
<p>Bottom line? You started developing your app with join queries, but at some point you had to give up on it.</p>
<p>So, if using a traditional database forces you to stop using some of its features somewhere down the road, why not start with a kind of database that avoids the things that are <strong>not scalable and sustainable in the long run</strong>?</p>
<p>In mongoDB a solution for this problem would be creating a document Contacts, and embed it inside the document Users. So, each user will have its contacts right there, inside each one of the User records. No need to use join queries.</p>
<p>However, there are times when you need to have a model that is connected to several others.</p>
<p>For example, let&#8217;s say you need to relate Contacts to several models such as Clients, Suppliers and Employees. So you create 4 collections: Clients, Suppliers, Employees and Contacts. You connect them all together via a <strong>db reference</strong>. This acts like a foreign key. But, this is not the <strong>mongoDB way</strong> to do things. Performance will penalized.</p>
<p>So the general question should always be &#8220;<strong>Why can&#8217;t I embed this document?</strong>&#8220;. Or even better: &#8220;<strong>Does this object merit its own collection, or rather should it embed in objects in other collections?</strong>&#8220;.</p>
<p>There are some general rules on when to embed, and when to reference (grabbed from <a title="mongodb database design" href="http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference">mongodb website</a>):</p>
<ul>
<li>&#8220;First class&#8221; objects, that are at top level, typically have their own collection;</li>
<li>Line item detail objects typically are embedded;</li>
<li>Objects which follow an object modelling &#8220;contains&#8221; relationship should generally be embedded;</li>
<li>Many to many relationships are generally by reference;</li>
<li>Collections with only a few objects may safely exist as separate collections, as the whole collection is quickly cached in application server memory;</li>
<li>Embedded objects are harder to reference than &#8220;top level&#8221; objects in collections, as you cannot have a DBRef to an embedded object (at least not yet);</li>
<li>It is more difficult to get a system-level view for embedded objects. For example, it would be easier to query the top 100 scores across all students if Scores were not embedded;</li>
<li>If the amount of data to embed is huge (many megabytes), you may reach the limit on size of a single object;</li>
<li>If performance is an issue, embed;</li>
</ul>
<p>The way I see it, you can still have more or less the best of both worlds: the <strong>flexibility of documents</strong> and the <strong>performance of embedded documents</strong>. And you still have a way to <strong>emulate foreign keys</strong>, like a relational database &#8211; but not without a penalty on performance. I don&#8217;t know how mongoDB and MySQL compare to each other in the long run, for the usual web app. It&#8217;d be cool if someone did some benchmarks on this subject.</p>
<p>Read more about <a title="mongodb database schema design" href="http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference"><strong>mongoDB database schema design</strong></a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/12/reasons-to-use-a-no-sql-database-like-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing with mongoDB</title>
		<link>http://levycarneiro.com/2009/12/playing-with-mongodb/</link>
		<comments>http://levycarneiro.com/2009/12/playing-with-mongodb/#comments</comments>
		<pubDate>Fri, 25 Dec 2009 14:19:34 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[databases]]></category>
		<category><![CDATA[mongoDB]]></category>
		<category><![CDATA[document database]]></category>
		<category><![CDATA[no-sql]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=149</guid>
		<description><![CDATA[It&#8217;s been a long time I hear about mongoDB and its awesomeness, so now&#8217;s the time to play with it! In this article I&#8217;ll try to summarize what&#8217;s mongoDB, why it&#8217;s so cool, and how to start playing with it. What is mongoDB? mongoDB is one of the new NO-SQL databases. It means it&#8217;s not [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a long time I hear about mongoDB and its awesomeness, so now&#8217;s the time to play with it! <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this article I&#8217;ll try to summarize what&#8217;s mongoDB, why it&#8217;s so cool, and how to start playing with it.<strong></strong></p>
<p><strong>What is mongoDB?</strong></p>
<p>mongoDB is one of the new <strong>NO-SQL databases</strong>. It means it&#8217;s not record-oriented like relational databases. Instead, it&#8217;s <strong>schema-free</strong> and collection oriented. And also, it&#8217;s a <strong>document database</strong>.</p>
<p>So what&#8217;s a document? It&#8217;s the first unit of data in a mongoDB. A document is simply an array of key-value pairs like this:</p>
<pre><code class="javascript">
{
     name: "John Doe",
     age: 40
}
</code></pre>
<p>Note: we call this notation BSON, which stands for &#8220;Binary Serialized dOcument Notation&#8221;.</p>
<p>Back to the document. This &#8220;document&#8221; is similar to a record in a usual relational database. You can use Strings, Integers and many other data types, including arrays and other Documents. You have the ability to nest Documents, like, Person -&gt; Children -&gt; Toys.</p>
<p>So what&#8217;s a table then?<em> C</em><em>ollections</em> act more or like tables. A collection holds one or more documents.</p>
<p>And ultimately a database is a group of collections. Each collection has a unique name inside a database.</p>
<p>With the document stuff out of the way, let&#8217;s see why this database seems to cool.</p>
<p><strong>Why is mongoDB so cool?</strong></p>
<p>Working with a no-SQL database means you have several advantages over a traditional database. Here are some of them:</p>
<ul>
<li>there is no schema. You don&#8217;t have to use Rails migrations for creating tables and columns. You simply start using them, and the database creates them on the fly. When using the gem mongomapper, for example, you simply declare the keys inside your model, and that&#8217;s it. Simple like that;</li>
<li>the data is formatted using a JSON-like format, giving greater flexibility and at the same time simplicity. New data types can be added, depending on how your format your Document before saving it into the database;</li>
<li>storage of binary files such as videos and photos on the database is possible and more important, efficient;</li>
</ul>
<p>Basically, mongoDB bridges the gap between key-value stores (which are highly scalable) and traditional RDBMS (which provide structured schemas and powerful queries).</p>
<p>Other than these things, mongoDB also supports some types of <strong>database replication</strong>. It also offers <strong>auto-sharding</strong>, a feature that allows one to build a large horizontally scalable database cluster that can incorporate additional machines dinamically. It also supports <strong>map-reduce</strong>.</p>
<p><strong>Installing mongoDB</strong></p>
<p>Simply download the <a title="mongoDB download" href="http://www.mongodb.org/display/DOCS/Downloads">binaries</a>. Unpack the tar.gz to /usr/local/bin/mongo and add &#8216;/usr/local/bin/mongo/bin&#8217; to your PATH. Create the directory to which the database files will be saved to:</p>
<p><code>mkdir -p /data/db</code></p>
<p>Start the server with:</p>
<p><code>mongod</code></p>
<p>It listens for connections on port 27017 by default. Open another shell and start the mongo shell with:</p>
<p><code>mongo</code></p>
<p>Interesting enough, the mongo shell uses Javascript as its language <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>No need to create a database</strong></p>
<p>One important note. You never have to create a database or collection.</p>
<p>The moment you try to access a database or collection, the underlying database and/or collection is created automatically.</p>
<p><strong>Let&#8217;s add some data</strong></p>
<p>In your mongo shell, type the following:</p>
<pre><code class="javascript">
&gt; a = { brand: "Toyota", model: "Corolla" };
&gt; b = { name: "John", age: 40 }
&gt; db.things.save(a);
&gt; db.things.save(b);</pre>
<p>Now to query all saved documents inside the collection <em>things</em>, run:</p>
<pre>&gt; db.things.find();
{ "_id" : ObjectId("4b33dee3844fab562308bb5f"), "brand" : "Toyota", "model" : "Corolla" }
{ "_id" : ObjectId("4b33dee5844fab562308bb60"), "name" : "John", "age" : 40 }
</code></pre>
<p>Important things to note:</p>
<ul>
<li>the collection <em>things</em> is created automatically;</li>
<li>the documents inside a collection may have different scructures, as you can see these 2 documents have different fields;</li>
<li>upon being inserted into the database, objects are assigned an object ID in the field _id;</li>
<li>when you run these commands above, the object IDs will be different.</li>
</ul>
<p><strong>Adding more data</strong></p>
<p>You noticed by now we are using Javascript inside the mongo client/shell. This means you can use something you already know to interact with mongoDB.</p>
<pre><code class="javascript">
&gt; <span class="code-keyword">for</span>( <span class="code-keyword">var</span> i = 1; i &lt; 10; i++ ) db.things.save( { x:4, j:i } );
&gt; db.things.find();
{ "_id" : ObjectId("4b33dee3844fab562308bb5f"), "brand" : "Toyota", "model" : "Corolla" }
{ "_id" : ObjectId("4b33dee5844fab562308bb60"), "name" : "John", "age" : 40 }
{ "_id" : ObjectId("4b33df5b844fab562308bb61"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("4b33df5b844fab562308bb62"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("4b33df5b844fab562308bb63"), "x" : 4, "j" : 3 }
{ "_id" : ObjectId("4b33df5b844fab562308bb64"), "x" : 4, "j" : 4 }
{ "_id" : ObjectId("4b33df5b844fab562308bb65"), "x" : 4, "j" : 5 }
{ "_id" : ObjectId("4b33df5b844fab562308bb66"), "x" : 4, "j" : 6 }
{ "_id" : ObjectId("4b33df5b844fab562308bb67"), "x" : 4, "j" : 7 }
{ "_id" : ObjectId("4b33df5b844fab562308bb68"), "x" : 4, "j" : 8 }
{ "_id" : ObjectId("4b33df5b844fab562308bb69"), "x" : 4, "j" : 9 }
</code></pre>
<p><strong>Iterating the data using the cursor</strong></p>
<p>When we ran <em>db.things.find();</em> in the last example, the shell automatically showed all data from the collection. But if we assign a variable to the <em>find()</em> method, we can iterate the data it as we wish:</p>
<pre><code class="javascript">
var cursor = db.things.find();
&gt; cursor.next()
{
        "_id" : ObjectId("4b33dee3844fab562308bb5f"),
        "brand" : "Toyota",
        "model" : "Corolla"
}
&gt; cursor.next()
{
        "_id" : ObjectId("4b33dee5844fab562308bb60"),
        "name" : "John",
        "age" : 40
}
&gt; cursor.next()
{ "_id" : ObjectId("4b33df5b844fab562308bb61"), "x" : 4, "j" : 1 }
&gt; cursor.next()
{ "_id" : ObjectId("4b33df5b844fab562308bb62"), "x" : 4, "j" : 2 }
</code></pre>
<p>Or we can use iterate programmatically:</p>
<pre><code class="javascript">
&gt; var cursor = db.things.find();
&gt; while (cursor.hasNext()) {print (tojson(cursor.next())); }
{
	"_id" : ObjectId("4b33dee3844fab562308bb5f"),
	"brand" : "Toyota",
	"model" : "Corolla"
}
{
	"_id" : ObjectId("4b33dee5844fab562308bb60"),
	"name" : "John",
	"age" : 40
}
{ "_id" : ObjectId("4b33df5b844fab562308bb61"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("4b33df5b844fab562308bb62"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("4b33df5b844fab562308bb63"), "x" : 4, "j" : 3 }
{ "_id" : ObjectId("4b33df5b844fab562308bb64"), "x" : 4, "j" : 4 }
{ "_id" : ObjectId("4b33df5b844fab562308bb65"), "x" : 4, "j" : 5 }
{ "_id" : ObjectId("4b33df5b844fab562308bb66"), "x" : 4, "j" : 6 }
{ "_id" : ObjectId("4b33df5b844fab562308bb67"), "x" : 4, "j" : 7 }
{ "_id" : ObjectId("4b33df5b844fab562308bb68"), "x" : 4, "j" : 8 }
{ "_id" : ObjectId("4b33df5b844fab562308bb69"), "x" : 4, "j" : 9 }
</code></pre>
<p>Or use it like an array:</p>
<pre><code class="javascript">
&gt; var cursor = db.things.find();
&gt; cursor[5]
{ "_id" : ObjectId("4b33df5b844fab562308bb64"), "x" : 4, "j" : 4 }
</code></pre>
<p>Important note: <strong>mongoDB cursors are not snapshots</strong>. For instance, if your cursor has 10 documents, and another user removes one of them from the collection, your cursor will return only 9 documents. You have to use explicit locking to prevent this.</p>
<p><strong>How to query data</strong></p>
<p>Let's see how to query the database for specific things we need to find.</p>
<p>The important thing to know is that queries, in a mongoDB database, are documents themselves. Let's have a look:</p>
<p><strong>SELECT * FROM things WHERE model='Corolla';</strong></p>
<p>will be:</p>
<pre><code class="javascript">
&gt; db.things.find(
     {model:'Corolla'}).forEach(
     function(x) { print (tojson(x));});
{
        "_id" : ObjectId("4b33dee3844fab562308bb5f"),
        "brand" : "Toyota",
        "model" : "Corolla"
}
</code></pre>
<p>Now, if we want to specify what fields we need, instead of running a "SELECT *" query, mongoDB lets you return "partial documents". To do this, you supply a second argument to the find() method, specifying what elements you need it to return:</p>
<p><strong>SELECT brand FROM things WHERE model='Corolla';</strong></p>
<pre><code class="javascript">
&gt; db.things.find(
     {model:'Corolla'}, {brand:true}).forEach(
     function(x) { print (tojson(x));});
{ "_id" : ObjectId("4b33dee3844fab562308bb5f"), "brand" : "Toyota" }
</code></pre>
<p>As you see, the query only returned the field 'brand' along with the object ID.</p>
<p>So, how to limit how many documents the database will return? Use the limit() method:</p>
<p><strong>SELECT j FROM things WHERE x=4 LIMIT 2;</strong></p>
<pre><code class="javascript">
&gt; db.things.find({x:4}, {j:true}).limit(2).forEach(
     function(x) { print (tojson(x));});
{ "_id" : ObjectId("4b33df5b844fab562308bb61"), "j" : 1 }
{ "_id" : ObjectId("4b33df5b844fab562308bb62"), "j" : 2 }
</code></pre>
<p>Or you can use the helper method findOne, if you want to return only 1 document:</p>
<pre><code class="javascript">
&gt; db.things.findOne({x:4})

{ "_id" : ObjectId("4b33de25ba7e40276b83ad53"), "x" : 4, "j" : 1 }
</code></pre>
<p>Note that in this case, all fields will be returned.</p>
<p><strong>Conclusion</strong></p>
<p>mongoDB is easy to learn. Its features are useful for web apps, specially having the need to build something scalable right from the beginning. Being a document database, it provides greater flexibility never before offered by traditional databases. mongoDB and its friends like CouchDB are definitely worth a look.</p>
<p>In the next article we'll see how to start playing with mongoDB in Rails. Stay tuned! <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/12/playing-with-mongodb/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Portraits and Photography</title>
		<link>http://levycarneiro.com/2009/09/portraits-and-photography/</link>
		<comments>http://levycarneiro.com/2009/09/portraits-and-photography/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 01:32:24 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[portrait]]></category>
		<category><![CDATA[strobist]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=139</guid>
		<description><![CDATA[Clique aqui para a versão em Português. My latest passion has been portraiture and photography in general. From an old hobby, the interest only grew even more after I discovered the Strobist website. David Hobby teaches everything about lighting your little flash unit, and the secret is: use it off your camera. A photographer named [...]]]></description>
			<content:encoded><![CDATA[<p><a href="#portuguese">Clique aqui para a versão em Português</a>.</p>
<p>My latest passion has been portraiture and photography in general.<a href="http://www.flickr.com/photos/levycarneiro/sets/72157622468546652/"><img class="alignright size-medium wp-image-142" style="margin:3px;" title="_dsc0600-flickr" src="http://levycarneiro.com/wp-content/uploads/2009/09/_dsc0600-flickr-210x300.jpg" alt="_dsc0600-flickr" width="210" height="300" /></a></p>
<p>From an old hobby, the interest only grew even more after I discovered the <a title="Strobist Blog" href="http://strobist.blogspot.com">Strobist</a> website. David Hobby teaches everything about lighting your little flash unit, and the secret is: use it off your camera.</p>
<p>A photographer named Jeremy Cowart created a movement called Help Portrait, check the video <a href="http://www.scottkelby.com/blog/2009/archives/6301">here</a> and the <a href="http://www.help-portrait.com/">Help Portrait website</a>. On December 12th photographers from around the world will go out in the streets and reach people in need, and simply take their photographs. This is to help people that would never been able to pay for a photograph. The idea is: shoot and deliver the prints later. Just that. Connections will be made and you&#8217;ll learn a lot about people.</p>
<p>Inspired by a <a href="http://www.zarias.com/?p=450">post on Zack Arias blog</a>, I started to take some portraits right away. This is in preparation for the Help Portrait official day. So I went ahead and asked if a local retirement home would open their doors so I could photograph (for free) all of their 60 residents, elderly ladies and men. They were very happy to get this offer and yesterday I could do the photo session.</p>
<p>I&#8217;m really happy with the results. Many of the ladies and men were very happy about the photos. Some were not excited about having a photo taken, so for these I&#8217;d just showed some of the previous photos and let them decide. After this, some got excited and let me take their photos. Soon I&#8217;ll be able to see their joy when I deliver them the prints.</p>
<p>I started to process some of the images, and the best ones I posted on Flickr. I&#8217;ll be printing all photos and giving to them.</p>
<p>I learned that from very small things we can make people in need a little more happier. I saw a phrase written on their car that read &#8220;Love never gets old&#8221;.</p>
<p>Check some of the <a href="http://www.flickr.com/photos/levycarneiro/sets/72157622468546652/">elderly portraits</a> I shot on the retirement home.</p>
<hr/>
<div id="portuguese"></div>
<p>Minha recente paixão tem sido retratos e fotografia em geral.</p>
<p>A partir de um hobby antigo, o interesse cresceu ainda mais depois que descobri o site <a title="Strobist Blog" href="http://strobist.blogspot.com">Strobist</a>. David Hobby ensina tudo sobre como iluminação com flashs portáteis, e no final das contas o segredo é: use ele fora de sua câmera.</p>
<p>Um fotógrafo chamado Jeremy Cowart criou um movimento, o Help Portrait. Confira o vídeo <a href="http://www.scottkelby.com/blog/2009/archives/6301">aqui</a> e o site do <a href="http://www.help-portrait.com/">Help Portrait</a>. Em 12 de dezembro fotógrafos do mundo inteiro vão sair nas ruas, encontrar pessoas com algum tipo de necessidade (seja pessoas sem-teto, crianças órfãs, ou qualquer tipo de necessidade), e simplesmente vão dar um presente: tirar uma fotografia delas e depois levar a foto impressa. Isto será feito para ajudar aqueles que talvez nunca poderiam pagar por uma fotografia. Conexões serão feitas e você vai aprender bastante coisas sobre pessoas.</p>
<p>Inspirado por um <a href="http://www.zarias.com/?p=450">post no blog de Zack Arias</a>, comecei a tirar alguns retratos imediatamente. Esta é uma preparação para o dia oficial do Help Portrait. Fui em frente e perguntei em uma casa de repouso da cidade, se eu poderia visitá-los e tirar fotos (gratuitas) de todos seus 60 residentes. Eles ficaram muito felizes com a oferta e ontem eu pude fazer a sessão de fotos.</p>
<p>Estou muito feliz com os resultados. Muitos das senhoras e senhores ficaram felizes com a idéia de tirar fotos. Alguns não ficaram muito animados com a idéia, mas nestes casos eu mostrava as fotos de outras senhoras e alguns se animavam depois disso. Em breve vou poder ver a alegria deles ao receberem as fotos em mãos. </p>
<p>Comecei a processar algumas das imagens, e postei algumas das melhores no Flickr. Vou imprimir todas as fotos e dar de presente para eles.</p>
<p>Aprendi que com pequenas coisas você pode fazer pessoas em necessidades um pouco mais felizes. Vi uma frase escrita em um carro deles escrita assim &#8220;O amor nunca envelhece&#8221;.</p>
<p>Confira alguns dos <a href="http://www.flickr.com/photos/levycarneiro/sets/72157622468546652/">retratos das senhoras</a> da casa de repouso.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/09/portraits-and-photography/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Palestra: Web Performance Client Side</title>
		<link>http://levycarneiro.com/2009/09/palestra-web-performance-client-side/</link>
		<comments>http://levycarneiro.com/2009/09/palestra-web-performance-client-side/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 12:26:03 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Browser]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[client-side]]></category>
		<category><![CDATA[fast]]></category>
		<category><![CDATA[faster]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=129</guid>
		<description><![CDATA[Há algumas semanas tive a oportunidade de palestrar internamente em dois eventos aqui na Locaweb: Locaweb Tech Day: um evento de dia inteiro que ocorre a cada 2 meses, onde cada pessoa pode palestrar sobre um assunto de interesse; Palestras Técnicas: ocorre às quintas-feiras, durando 1 hora. Uma pessoa por semana palestra sobre um assunto [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-133" title="215987893_f665d2fa1d" src="http://levycarneiro.com/wp-content/uploads/2009/09/215987893_f665d2fa1d-150x150.jpg" alt="215987893_f665d2fa1d" width="150" height="150" />Há algumas semanas tive a oportunidade de palestrar internamente em dois eventos aqui na Locaweb:</p>
<ul>
<li>Locaweb Tech Day: um evento de dia inteiro que ocorre a cada 2 meses, onde cada pessoa pode palestrar sobre um assunto de interesse;</li>
<li>Palestras Técnicas: ocorre às quintas-feiras, durando 1 hora. Uma pessoa por semana palestra sobre um assunto técnico.</li>
</ul>
<p>Nas duas oportunidades palestrei sobre como fazer um site ficar mais rápido, e abrir num &#8220;estalo&#8221;. O título das palestras foi: <strong>Web Performance Client Side</strong>.</p>
<p>Se você já parou pra pensar em otimização de um website, vai perceber que o lado server side (sua aplicação Rails, PHP, etc) conta na velocidade de carregamento, mas na prática representa muito pouco. Isto acontece porque uma requisição é processada pelo servidor em 200 milisegundos, digamos, enquanto o mesmo site pode levar 10 segundos para carregar no browser. Então qualquer otimização que ocorra em server-side só vai afetar a quantidade de pessoas que podem acessar seu site ao mesmo tempo. Não afeta a velocidade individual que cada pessoa vai ter ao navegar nas páginas de seu site.</p>
<p>E para melhorar a velocidade client-side, a que realmente importa na maioria das vezes, existem várias técnicas inteligentes e interessantes. Na apresentação que coloquei no SlideShare, você pode pegar um apanhado com as últimas técnicas para desenvolvimento web com vistas à performance no browser.</p>
<p>Existe muita coisa mesmo na apresentação, e é imperdível pra quem trabalha com Desenvolvimento Web.</p>
<p>Veja a apresentação sobre <a title="Web Performance Client Side" href="http://www.slideshare.net/levycarneiro/web-performance-client-side" target="_blank">Web Performance Client Side</a> no SlideShare. Ou baixe o <a title="Web Performance Client Side: PDF" href="http://www.slideshare.net/levycarneiro/web-performance-client-side/download">PDF</a>, mas para isso você precisa ter conta no SlideShare.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/09/palestra-web-performance-client-side/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick and dirty way to find broken links on your website</title>
		<link>http://levycarneiro.com/2009/07/quick-and-dirty-way-to-find-broken-links-on-your-website/</link>
		<comments>http://levycarneiro.com/2009/07/quick-and-dirty-way-to-find-broken-links-on-your-website/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 17:55:53 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Systems Administration]]></category>
		<category><![CDATA[404]]></category>
		<category><![CDATA[broken links]]></category>
		<category><![CDATA[wget]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=123</guid>
		<description><![CDATA[These days I had to find if there was any broken link (error 404) in a group of sites. I found this to be very useful: wget &#8211;recursive &#8211;spider http://levycarneiro.com This command will download everything from the URL, and generate a report like this: Found 13 broken links. http://levycarneiro.com/levy@levycarneiro.com referred by: http://levycarneiro.com/ http://levycarneiro.com/images/posts/Multiple_models_one_form_NewProject.jpg referred by: [...]]]></description>
			<content:encoded><![CDATA[<p>These days I had to find if there was any broken link (error 404) in a group of sites.</p>
<p>I found this to be very useful:</p>
<p>wget &#8211;recursive &#8211;spider http://levycarneiro.com</p>
<p>This command will download everything from the URL, and generate a report like this:</p>
<blockquote><p>Found 13 broken links.</p>
<p>http://levycarneiro.com/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/</p>
<p>http://levycarneiro.com/images/posts/Multiple_models_one_form_NewProject.jpg referred by:</p>
<p>http://levycarneiro.com/category/ruby-on-rails/</p>
<p>http://levycarneiro.com/tag/twitter/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/twitter/</p>
<p>http://levycarneiro.com/tag/rails/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/rails/</p>
<p>http://levycarneiro.com/tag/portfolio/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/portfolio/</p>
<p>http://levycarneiro.com/2009/04/transito-nao-an-experiment-with-twitter-traffic-jams-and-ruby-on-rails/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/2009/04/transito-nao-an-experiment-with-twitter-traffic-jams-and-ruby-on-rails/</p>
<p>http://levycarneiro.com/tag/traffic/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/traffic/</p>
<p>http://levycarneiro.com/tag/projects/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/projects/</p>
<p>http://levycarneiro.com/category/projects/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/category/projects/</p>
<p>http://levycarneiro.com/tag/ruby/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/ruby/</p>
<p>http://levycarneiro.com/category/ruby-on-rails/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/category/ruby-on-rails/</p>
<p>http://levycarneiro.com/category/twitter/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/category/twitter/</p>
<p>http://levycarneiro.com/tag/ruby-on-rails/levy@levycarneiro.com referred by:</p>
<p>http://levycarneiro.com/tag/ruby-on-rails/</p></blockquote>
<p>I&#8217;ve got some work to do then <img src='http://levycarneiro.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/07/quick-and-dirty-way-to-find-broken-links-on-your-website/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Chrome prefetches DNS for speed up browser performance</title>
		<link>http://levycarneiro.com/2009/06/google-chrome-prefetches-dns-for-speed-up-browser-performance/</link>
		<comments>http://levycarneiro.com/2009/06/google-chrome-prefetches-dns-for-speed-up-browser-performance/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 09:00:06 +0000</pubDate>
		<dc:creator>Levy Carneiro Jr.</dc:creator>
				<category><![CDATA[Browser]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[page speed]]></category>

		<guid isPermaLink="false">http://levycarneiro.com/?p=116</guid>
		<description><![CDATA[Browser performance problems? Simple tricks to the rescue: &#8220;To speed up browsing, Google Chrome resolves domain names before the user navigates, typically while the user is viewing a web page. This is done using your computer&#8217;s normal DNS resolution mechanism; no connection to Google is used. As a result, user navigation time in Google Chrome [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_118" class="wp-caption alignright" style="width: 160px"><img class="size-thumbnail wp-image-118" title="Google Chrome" src="http://levycarneiro.com/wp-content/uploads/2009/06/chrome-150x150.jpg" alt="Google Chrome" width="150" height="150" /><p class="wp-caption-text">Google Chrome</p></div>
<p>Browser performance problems? Simple tricks to the rescue:</p>
<blockquote><p>&#8220;To <strong>speed up browsing</strong>, Google Chrome resolves domain names before the user navigates, typically while the user is viewing a web page. This is done using your computer&#8217;s normal <strong>DNS resolution</strong> mechanism; no connection to Google is used. As a result, user navigation time in Google Chrome when first visiting a domain is on average about 250ms faster than traditional browsing, and the occasional but painful 1-second-plus delays are almost never experienced.&#8221;</p></blockquote>
<p>And how it works:</p>
<p>&#8220;<strong>DNS prefetching</strong> just resolves domain names before a user tries to navigate, so that there will be no effective user delay due to DNS resolution. The most obvious example where prefetching can help is when a user is looking at a page with many links to various unexplored domains, such as a search results page. Google Chrome automatically scans the content of each rendered page looking for links, extracting the domain name from each link, and resolving each domain to an IP address. All this work is done in parallel with the user&#8217;s reading of the page, hardly using any CPU power. When a user clicks on any of these pre-resolved names to visit a new domain, they will save an average of over 250ms in their navigation.&#8221;</p>
<p>Check the <a title="DNS prefetching pre-resolving" href="http://blog.chromium.org/2008/09/dns-prefetching-or-pre-resolving.html">full article</a>.</p>
<p>Very clever and efficient.</p>
]]></content:encoded>
			<wfw:commentRss>http://levycarneiro.com/2009/06/google-chrome-prefetches-dns-for-speed-up-browser-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
