<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roger Leite on Medium]]></title>
        <description><![CDATA[Stories by Roger Leite on Medium]]></description>
        <link>https://medium.com/@rogerleite?source=rss-8be35d1a8f0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xn9Vfv8xkOT9D1HY.jpg</url>
            <title>Stories by Roger Leite on Medium</title>
            <link>https://medium.com/@rogerleite?source=rss-8be35d1a8f0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:45:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rogerleite/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Migrating from Fleet to Kubernetes using Deis Workflow on AWS]]></title>
            <link>https://medium.com/@rogerleite/migrating-production-paas-deis-v1-to-workflow-at-amazon-c3fb373a260b?source=rss-8be35d1a8f0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3fb373a260b</guid>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Roger Leite]]></dc:creator>
            <pubDate>Mon, 05 Sep 2016 10:01:01 GMT</pubDate>
            <atom:updated>2016-09-05T14:15:38.903Z</atom:updated>
            <content:encoded><![CDATA[<p>Running Deis on production, more than one year, has been a good and stable experience.</p><blockquote>Deis is an open source Platform as a Service (PaaS) that makes it easy to deploy and manage applications on your own servers, with a Heroku-inspired workflow.</blockquote><p>Trying to focus on how to upgrade our <a href="http://deis.io/overview/">Deis v1</a> to <a href="https://deis.com/workflow/how-it-works/">Deis Workflow</a> and assist team in general, we sketched this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whYCRZHqYkVbbdl__ztIoA.png" /><figcaption>Deis v1 protected by Bastion host</figcaption></figure><p>As you can see, Deis v1 is inside a VPC and only <a href="https://en.wikipedia.org/wiki/Bastion_host">Bastion host</a> can use private load balance thought private DNS from route53, to do a <em>git push</em> to deploy applications. Only http and https is listened by public load balance to be responded by applications.</p><blockquote>After some researching and experiments, we decided to provision a new Kubernetes cluster in another VPC and run in parallel with our Fleet cluster.</blockquote><p>With two clusters in parallel, sharing the same resources through VPC Peer, we <strong>can switch our apps on production</strong>, just changing record entries on AWS Route53 with <strong>zero downtime</strong>.</p><p>Before start, here are the high level topics of this quest:</p><ol><li>Provision configuration of Kubernetes</li><li>Provision new Kubernetes cluster</li><li>Install Deis Workflow</li><li>Make Deis Workflow &quot;private&quot;</li></ol><h3>Provision configuration of Kubernetes</h3><p>Based on <a href="http://kubernetes.io/docs/getting-started-guides/aws/">Running Kubernetes on AWS EC2</a>, I created a very simple script to just download Kubernetes v1.3.4. Also comes with a helper to create symlinks to not break Deis install in the future steps.</p><pre>#!/bin/bash</pre><pre># Reference: <a href="http://kubernetes.io/docs/getting-started-guides/aws">http://kubernetes.io/docs/getting-started-guides/aws</a></pre><pre># download and extract kubernetes<br>function download_kube() {<br>  local version=&quot;v1.3.4&quot;<br>  echo &quot;Download releasing $version, more information at <a href="https://github.com/kubernetes/kubernetes/releases/tag/$version">https://github.com/kubernetes/kubernetes/releases/tag/$version</a>&quot;<br>  wget -c <a href="https://github.com/kubernetes/kubernetes/releases/download/$version/kubernetes.tar.gz">https://github.com/kubernetes/kubernetes/releases/download/$version/kubernetes.tar.gz</a><br>  tar -zxf kubernetes.tar.gz<br>}</pre><pre># create sym links to make helmc works<br>function create_symlinks() {<br>  cd ./kubernetes/cluster<br>  for i in `ls *.sh`; do<br>    ln -sfv $i $(echo $i | cut -d&quot;.&quot; -f1)<br>  done<br>  cd $OLDPWD<br>}</pre><p>To use the script above, you need to <em>source</em> and the functions <em>download_kube</em> and <em>create_symlinks</em> will be available at your shell. Example:</p><pre># Since the script above is saved as k8s-helper.sh</pre><pre>~$ source k8s-helper.sh<br>~$ download_kube<br>~$ create_symlinks</pre><p>After download (~ 1.4gb) and create links, you’ll find <em>kube-up.sh</em> in <em>kubernetes/cluster</em> directory. Add <em>kubernetes/cluster</em> directory to <em>PATH</em>, in order to make <em>kube-up</em> available on your shell.</p><h3>Provision new Kubernetes cluster</h3><p>To install a new Kubernetes cluster, the process is simple, you customize options using environment variables and runs <em>kube-up</em> script.</p><pre>#!/bin/bash</pre><pre># Reference: kubernetes/cluster/aws/config-default.sh</pre><pre>export KUBERNETES_PROVIDER=aws<br>export KUBE_AWS_INSTANCE_PREFIX=&quot;k8s-example&quot;</pre><pre># remember to be the same instance of SUBNET_ID<br>export KUBE_AWS_ZONE=&quot;us-east-1c&quot;<br>export KUBE_VPC_CIDR_BASE=172.16</pre><pre>export MASTER_SIZE=&quot;m3.large&quot;<br>export NODE_SIZE=&quot;m4.xlarge&quot;<br>export NUM_NODES=3<br>export MINION_ROOT_DISK_SIZE=100</pre><pre>export AWS_REGION=&quot;us-east-1&quot;<br>export AWS_S3_REGION=$AWS_REGION<br>export AWS_S3_BUCKET=&quot;$KUBE_AWS_INSTANCE_PREFIX-artifacts&quot;</pre><pre>export AWS_SSH_KEY=&quot;$HOME/.ssh/kube_$KUBE_AWS_INSTANCE_PREFIX&quot;</pre><p>Before provision, let&#39;s talk about some customizations.</p><ul><li><em>KUBE_AWS_ZONE</em> must be one of your availability zone of your region.</li><li><em>KUBE_VPC_CIDR_BASE</em>, must be a different CIDR from your current VPC. Example: given our Deis v1 VPC CIDR is &quot;172.31.0.0/16&quot;, our Kubernetes CIDR base should be &quot;<em>172.16&quot;</em>.</li><li><em>AWS_S3_BUCKET</em> will be created if necessary, don&#39;t forget to check if your aws region and credentials are ok. You can use <em>aws configure</em> to do it.</li><li>You can check <em>kubernetes/cluster/aws/config-default.sh</em> file for more options.</li></ul><pre># Since the script above is saved as config-k8s-example.sh<br># And kube-up is on $PATH<br># To provision a new Kubernetes cluster:</pre><pre>~$ source config-k8s-example.sh<br>~$ kube-up<br>#[ ... kube up logs ]</pre><p><a href="https://github.com/kubernetes/kubernetes/blob/release-1.3/docs/design/aws_under_the_hood.md">Under the hood</a>, <em>kube up</em> will do:</p><ul><li>Upload kubernetes binaries to S3.</li><li>Use (and generate if not exists) ssh key to access master and minions instances. Check your <em>~/.ssh</em>.</li><li>Create VPC, subnets, internet gateways, custom route tables.</li><li>Create master and minions security groups.</li><li>Create data volume to be used by master instance.</li><li>Allocate Elastic IP, to be used by master instance.</li><li>Start master instance and wait to be ready. After ready, attach Elastic IP and data volume.</li><li>Change master instance to subnet CIDR.</li><li>Write secrets at <em>~/.kube/config</em>. <em>kubectl</em> uses this file to know where master is.</li><li>Create autoscaling group of minions. Start autoscaling and creation of minions.</li><li>Wait for minions to be ready.</li><li>You can check <a href="https://medium.com/@canthefason/kube-up-i-know-what-you-did-on-aws-93e728d3f56a#.l1nh9y3dp">Kube-up: I know what you did on AWS!</a> for more details about <em>kube-up</em>.</li></ul><p>Some extra notes:</p><ul><li>All resources will be tagged with <em>KubernetesCluster</em> and value of <em>KUBE_AWS_INSTANCE_PREFIX</em> environment variable.</li><li>You can use <em>kubectl cluster-info</em> to see all available endpoints. Credentials are stored at <em>~/.kube/config</em>.</li><li>To access Kubernetes Dashboard credentials, look for “basic-auth” <em>at ~/.kube/config</em> file.</li></ul><p>After <em>kube-up</em> is done and you can access Kubernetes Dashboard, don&#39;t forget to put <em>https</em> on address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fb_mtgdvJwgnMy1e4FUJdA.png" /><figcaption>Kubernetes v1.3.4 dashboard kube-system</figcaption></figure><h3>Install Deis Workflow</h3><p>Follow <a href="https://deis.com/docs/workflow/installing-workflow/">Installing Deis Workflow</a> steps. After install, our new VPC would be like diagram below, an Elastic IP to access Kubernetes master and a public load balance to access Deis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKWuD-B61ofdbTmQG11qXQ.png" /><figcaption>After Deis Workflow install, scenario would be something like this.</figcaption></figure><p>Before using Deis, it&#39;s important to create a <em>type A record</em> on AWS Route53. Let’s suppose we created a public dns *.k8s.example.com, pointing to public load balance created by Deis Workflow install.</p><p>This dns entry (*.k8s.example.com) allows us:</p><ul><li>Register <a href="https://deis.com/docs/workflow/users/registration/">new users</a> (<em>deis register deis.k8s.example.com</em>)<em> </em>and use deis client to create and configure new applications.</li><li>Deploy new applications on <em>deis-builder.k8s.example.com:2222</em>.</li><li>Access deployed applications, example: <em>hello-app.k8s.example.com</em>.</li></ul><p>In order to make RDS and ElasticCache resources from Deis v1 VPC, accessible by Kubernetes VPC, we created a VPC Peer.</p><p>Suppose our vpc-default is &quot;172.31.0.0/16&quot; and vpc-k8s is &quot;172.16.0.0/16&quot;, let&#39;s create a new VPC Peer, with local vpc as &quot;172.16.0.0/16&quot; and vpc peer as &quot;172.31.0.0/16&quot;. Click on Actions and &quot;Accept Request&quot; to make it active. After this you need to edit your route tables of VPCs subnets.</p><p><a href="https://aws.amazon.com/blogs/apn/aws-networking-for-developers/?adbsc=APN_Blog_20160823_65144566&amp;adbid=768092966636298241&amp;adbpl=tw&amp;adbpr=66780587">AWS Networking for developers</a> helped me a lot to understand a VPC and VPC Peer in general.</p><p>At this point, we have a <strong>functional</strong> Deis Workflow, but <strong>&quot;open&quot; to the world</strong>. This deserves a break to some coffee or another drink.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08uto3CwAF07dIAhgCHZxA.png" /><figcaption>Deis workflow namespace on Kubernetes v1.3.4</figcaption></figure><h3>Make Deis Workflow &quot;private&quot;</h3><p>In order to make Deis client/deploy and Kubernetes, only available in <em>vpc-k8s</em>, I did some manual changes to infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V4JQ9J90WZO6lqDhSgAtg.png" /><figcaption>Deis Workflow client/deploy only available on VPC</figcaption></figure><h3>Deis client/deploy available only at VPC</h3><p>Create a private load balance like the public and make accessable via private dns, something like &quot;*.k8s.example.local&quot;.</p><p>Removes 2222 and 9090 ports from public load balance. Now, to deis client works, you need to login on <em>deis.k8s.example.local</em> and your git remotes should have <em>deis-builder.k8s.example.local:2222</em>.</p><h3>Protect your Kubernetes master</h3><p>Release Elastic IP resource. Edit security groups to allow Bastion access <em>sg-master</em>. To use <em>kubectl</em>, you need to edit your <em>~/.kube/config</em> to use the private ip on <em>server</em> node. You can test with <em>kubectl cluster-info</em> command.</p><p>To access Kubernetes Dashboard, you need to open a ssh tunnel, example:</p><blockquote>ssh bastion-from-ssh-config -nNTf -L 8080:172.16.0.9:443</blockquote><p>172.16.0.9 is the private ip of kube master machine.</p><h3>To future</h3><p>I hope that this case and diagrams help other people to migrate your Deis v1 to Deis Workflow. Here are some topics to handle on future:</p><ul><li>How to put Kubernetes cluster on more availability zones</li><li>Automate Deis isolation on scripts</li></ul><p>I&#39;d like to <strong>thank you</strong> for reading, feel free to comment about improvements or anything related. My special thanks to <strong>teammates</strong> <a href="https://medium.com/@manuwell">Well</a>, <a href="https://medium.com/@habutre">Rogério</a>, <a href="https://medium.com/@rpanachi">Panachi</a>, <a href="https://github.com/orgs/deis/people">Deis team</a> and <a href="https://deis.com/community/">Deis Community</a>.</p><p>You can find me at <a href="https://slack.deis.io/">Deis Slack channel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3fb373a260b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lendo arquivo CSV com parcimônia e Ruby]]></title>
            <link>https://medium.com/@rogerleite/lendo-arquivo-csv-ruby-eb702c6d170?source=rss-8be35d1a8f0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb702c6d170</guid>
            <category><![CDATA[brazil]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Roger Leite]]></dc:creator>
            <pubDate>Thu, 25 Aug 2016 13:07:37 GMT</pubDate>
            <atom:updated>2016-08-25T13:07:37.528Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Este é um texto que foi publicado originalmente no <strong>aposentado</strong> 1up4dev.org, no dia 17 de Novembro de 2014.</blockquote><p>Ler e escrever <a href="http://en.wikipedia.org/wiki/Comma-separated_values">arquivo csv</a> é um mal necessário de muitos sistemas, ainda mais levando em conta que esta integração será feita via Excel, em algum Windows, com quilos de texto com acentos e dados a formatar. Dado este cenário, e que ele provavelmente se repetirá no futuro, deixo aqui um post auto-ajuda para mim mesmo e provavelmente para você que está lendo. :D</p><p>Na versão 1.9.3 e superior, o Ruby incluiu a classe <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html">CSV</a> na sua <em>standard lib</em>, que facilita o trabalho de ler e/ou escrever arquivos csv. Exemplos em código abaixo.</p><h4>Conhecendo o CSV</h4><p>O modo mais simples e direto para ler um arquivo csv, é usar o <em>CSV.read</em> que retorna um Array de Arrays:</p><pre>require &#39;csv&#39; array_students <strong>=</strong> CSV<strong>.</strong>read(&#39;/tmp/mock_data.csv&#39;) <em># return an Array of Arrays</em> array_students<strong>.</strong>each { <strong>|</strong>row<strong>|</strong> puts row<strong>.</strong>inspect }  <em># =&gt; output:</em> <em># &quot;[\&quot;id\&quot;, \&quot;name\&quot;, \&quot;country\&quot;, \&quot;birthday\&quot;]&quot;</em> <em># &quot;[\&quot;1\&quot;, \&quot;Virginia Harvey\&quot;, \&quot;GB\&quot;, \&quot;01/06/1993\&quot;]&quot;</em></pre><pre>array_students = CSV.read(‘/tmp/mock_data.csv’) # return an Array of Arrays array_students.each { |row| puts row.inspect }<br># =&gt; output: # “[\”id\”, \”name\”, \”country\”, \”birthday\”]” # “[\”1\”, \”Virginia Harvey\”, \”GB\”, \”01/06/1993\”]”</pre><p>Dentro da classe CSV, existem mais duas classes que facilitam ainda mais o manuseio dos dados.</p><p>Caso necessite de mais requinte e sofisticação, o método <em>CSV.table</em> retorna uma instância de <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV/Table.html">CSV::Table</a>. Com o table, você tem acesso ao cabeçalho através do headers e acesso a cada linha do arquivo com o each, que retorna uma instância de <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV/Row.html">CSV::Row</a>.</p><pre>require ‘csv’</pre><pre>table_students = CSV.table(‘/tmp/mock_data.csv’)<br># =&gt; instance of CSV::Table</pre><pre>puts table_students.headers.inspect # =&gt; [:id, :name, :country, :birthday]</pre><pre>table_students.each { |row| puts row.inspect }<br># =&gt; output: # &lt;CSV::Row id:1 name:”Virginia Harvey” country:”GB” birthday:”01/06/1993&quot;&gt;</pre><pre>table_students.each { |row| puts row.fetch(:name) } # =&gt; output: # Virginia Harvey</pre><p>Tanto o read quanto o table, aceitam um hash de options como segundo argumento. Tem uma descrição detalhada na documentação do <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#method-c-new">método new</a>. Exemplo usando options:</p><pre>require ‘csv’</pre><pre>table_students = CSV.table(‘/tmp/mock_data2.csv’, col_sep: “;”, skip_blanks: true, converters: [])</pre><pre>table_students.each { |row| puts row.inspect }</pre><h3>CSV converters</h3><p><a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#HeaderConverters">CSV::HeaderConverters</a> contém um hash de symbol e block que são usados para converter os valores do cabeçalho. Para usá-los, você deve informar qual <em>converter</em> deseja aplicar na opção <em>header_converters</em>. Acredito que o código abaixo explica melhor.</p><pre>require ‘csv’ </pre><pre>puts CSV::HeaderConverters.keys.inspect # =&gt; [:downcase, :symbol] </pre><pre># Add new header converter <br>CSV::HeaderConverters[:remap] = lambda do |raw_value| <br>  raw_value = raw_value.to_sym <br>  case raw_value <br>  when :country :pais<br>  when :birthday :dt_nascimento<br>  else <br>    raw_value <br>  end <br>end</pre><pre>table_students = CSV.table(‘mock_data.csv’, col_sep: “,”, header_converters: :remap)<br>table_students.each do |row|<br>  puts [<br>    row.fetch(:pais),<br>    row.fetch(:dt_nascimento)<br>  ].inspect # =&gt; [“GB”, “01/06/1993”] <br>end</pre><p>No exemplo acima, criei o HeaderConverter “remap” que traduz o cabeçalho country para pais e birthday para dt_nascimento. Por padrão, o CSV disponibiliza os converters downcase e symbol, que por sinal são usados quando usamos o método table para ler csv.</p><p><a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#Converters">CSV::Converters</a> segue o mesmo padrão de symbol e block, a única diferença que este é usado para converter os valores da linha. Vamos ao código.</p><pre>require &#39;csv&#39;<br>require &#39;date&#39;</pre><pre>puts CSV::Converters.keys.inspect # =&gt; [:integer, :float, :numeric, :date, :date_time, :all]</pre><pre># Add new converter<br>CSV::Converters[:nil_to_empty] = lambda do |raw_value|<br>  raw_value.nil? ? &quot;&quot; : raw_value<br>end<br># Add new converter<br>CSV::Converters[:brazilian_date] = lambda do |raw_value|<br>  if raw_value =~ /\d{2}\/\d{2}\/\d{4}/<br>    Date.strptime(raw_value, &quot;%d/%m/%Y&quot;)<br>  else<br>    raw_value<br>  end<br>end</pre><pre># Group converters<br>CSV::Converters[:my_custom_converters] = [:nil_to_empty, :brazilian_date] <br>table_students = CSV.table(&#39;mock_data.csv&#39;, col_sep: “,”, converters: :my_custom_converters)<br>table_students.each do |row| <br>  puts [<br>    row.fetch(:country), <br>    row.fetch(:birthday)<br>  ].inspect # =&gt; [“GB”, #&lt;Date: 1993–06–01 ((2449140j,0s,0n),+0s,2299161j)&gt;] <br>end</pre><p>No exemplo acima criei dois converters. Um para trocar <em>nil</em> por <em>&quot;&quot;</em> e o outro que converte para Date caso o valor esteja no formato 99/99/9999.</p><h3>Encoding hell com Excel</h3><p>Normalmente o csv é usado como meio de integração Excel &lt;=&gt; Sistema. Acontece que o Excel não se dá muito bem com acentos especiais como ãõáé etc. Isto porque estamos em 2014. Acontece que quando há caracteres especiais, a única abordagem que funcionou foi exportar para Unicode text. Neste formato, o encoding do arquivo é UTF-16LE e separado por tab (\t). Este <a href="http://blog.plataformatec.com.br/2009/09/exportando-dados-para-excel-usando-csv-em-um-aplicativo-rails/">post de 2009 da Plataformatec</a> explica com mais detalhes este jeitinho do Excel de ser com os dados. A única diferença de 2009 pra hoje, é que podemos passar o encoding como parâmetro ao ler o arquivo, e por sorte evitar o uso do iconv. Vamos ao código:</p><pre>require &#39;csv&#39;</pre><pre>table = CSV.table(&#39;mock_unicode.txt&#39;,<br>                  col_sep: &quot;\t&quot;, # tab as delimiter<br>                  encoding: &quot;UTF-16LE:UTF-8&quot;) # read UTF-16LE and convert to UTF-8<br>table.each do |row|<br>  puts row.inspect<br>end</pre><h3>Evitando o abuso de memória</h3><p>Ao ler arquivos com <em>read</em> ou <em>table</em>, o arquivo é colocado em memória, ou seja, ao processar uma planilha de 100mb, o seu processo ruby vai pra um 100mb e pouco. Agora imagina 20 workers e cada um processando uma planilha de 100mb ou mais, facilmente o seu servidor terá um pico de consumo de memória, o no pior cenário vai dar crash no processo. Para evitar este consumo devemos usar o foreach do CSV.</p><pre>require &#39;csv&#39;</pre><pre>CSV<strong>.</strong>foreach(&quot;mock_data.csv&quot;, col_sep: &quot;,&quot;) do <strong>|</strong>row<strong>|<br>  </strong>puts row<strong>.</strong>inspect<br>end</pre><pre><em># =&gt;</em> <em># [&quot;id&quot;, &quot;name&quot;, &quot;country&quot;, &quot;birthday&quot;]</em> <em># [&quot;1&quot;, &quot;Virginia Harvey&quot;, &quot;GB&quot;, &quot;01/06/1993&quot;]</em></pre><blockquote>Tentando chegar no modelo ideal […]</blockquote><p>Desta maneira a leitura é mais otimizada, pois apenas uma linha por vez é lida. O único problema é que perdemos algumas facilidades do table, como os headers e a instância do CSV::Row por linha. Tentando chegar no modelo ideal, montei uma classe que usa o <em>foreach</em> e mesmo assim tem os headers e os rows.</p><pre>require &#39;csv&#39;</pre><pre>class SheetReader</pre><pre>attr_reader :headers</pre><pre>def initialize(filepath)<br>    # options to read unicode text file<br>    # options = {<br>    #   col_sep: &quot;\t&quot;,<br>    #   skip_blanks: true,<br>    #   encoding: &quot;UTF-16LE:UTF-8&quot;,<br>    #   converters: []<br>    # }<br>    options = {col_sep: &quot;,&quot;, converters: []}<br>    <a href="http://twitter.com/csv_reader">@csv_reader</a> = CSV.foreach(filepath, options) # gets a iterator<br>    <a href="http://twitter.com/headers">@headers</a>    = convert_headers(<a href="http://twitter.com/csv_reader">@csv_reader</a>.next) # read first line<br>  end</pre><pre># yield an instance of <a href="http://ruby-doc.org/stdlib-2.1.0/libdoc/csv/rdoc/CSV/Row.html">http://ruby-doc.org/stdlib-2.1.0/libdoc/csv/rdoc/CSV/Row.html</a><br>  def each_row(&amp;block)<br>    begin<br>      while true<br>        raw_row = <a href="http://twitter.com/csv_reader">@csv_reader</a>.next  # raise StopIteration in EOF<br>        yield CSV::Row.new(headers, raw_row)<br>      end<br>    rescue StopIteration<br>    end<br>  end</pre><pre>protected</pre><pre>  # Internal: Convert headers to Array of symbols.<br>  #<br>  # raw_headers - Array of Strings.<br>  #<br>  # Examples<br>  #<br>  #   convert_headers([&quot;ATIVO&quot;, &quot;NOME COMERCIAL&quot;])<br>  #   # =&gt; [:ativo, :nome_comercial]<br>  #<br>  # Returns Array of symbols.<br>  def convert_headers(raw_headers)<br>    raw_headers.compact! # removes nil values<br>    converter = lambda do |header|<br>      header_converters = CSV::HeaderConverters.values<br>      header_converters.inject(header) do |header, converter_proc|<br>        converter_proc.call(header)<br>      end<br>    end<br>    raw_headers.map { |header| converter.call(header) }<br>  end<br>end</pre><pre>reader = SheetReader.new(&#39;mock_data.csv&#39;)<br>reader.headers # =&gt; [:id, :name, :country, :birthday]<br>reader.each_row do |row|<br>  puts row.inspect # =&gt; #&lt;CSV::Row id:&quot;1&quot; name:&quot;Virginia Harvey&quot; country:&quot;GB&quot; birthday:&quot;01/06/1993&quot;&gt;<br>end</pre><p>Por último, uma observação importante: todo este código acima foi rodado no ruby 2.1.0. Espero que este mini guia de como ler arquivo csv com Ruby te ajude. Segue alguns links com mais informações:</p><p>Dúvidas, sugestões ou qualquer outra coisa. Deixe um comentário ou se preferir, mande um <a href="https://twitter.com/rogerleite">tweety!</a> :D</p><blockquote>Este é um texto que foi publicado originalmente no <strong>aposentado</strong> 1up4dev.org, no dia 17 de Novembro de 2014.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb702c6d170" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>