Elvio Viçosa Junior

Dumps and Thoughts about what I am living and learning

0 notes &

Rails - core extensions - Date

Have you ever thought about how would be living in the future? It’s difficult to predict what’s going to happen and I think everyone is a bit curious to know how the earth will be in 300 years… Well, maybe you prefer to think about the past instead of the future. Sometimes I get myself thinking about how nice would be to live 500 years ago, but every time that I think about it, I remember they didn’t have antibiotics nor painkillers, so I force myself to think about something else.

Even if you have never thought about future or past, sometimes we have to deal with them. I mean, in the code. Sometimes we have to figure out if something happened in the past or if it’s going to happen in the future and using the same explanation I did in my previous post Rails - core extensions - Array, I decided to talk about Date and how Rails extends it to help us to have a better life.


today / tomorrow / yesterday

Today (the date this post was written) is Sat, 03 Mar 2012. And Rails give us a nice way to have this information, using the “today” method.

> Date.today
=> Sat, 03 Mar 2012 

In the same way, we can also discover which day would be tomorrow or which day was yesterday, using “tomorrow” and “yesterday”:

> Date.tomorrow
=> Sun, 04 Mar 2012 

> Date.yesterday
=> Fri, 02 Mar 2012

beginning_of… / end_of…

Which day was in the beginning of the X (where X could be: week, month, year)? You might also want to know which day will be in the end of X (the same X). We have a set of methods ready to help us out.

Using the same date

> today = Date.today
=> Sat, 03 Mar 2012 

You can ask a date instance information about the beginning/ending of: week, month and year:

> today.beginning_of_week
=> Mon, 27 Feb 2012 

> today.end_of_week
=> Sun, 04 Mar 2012 

> today.beginning_of_month
=> Thu, 01 Mar 2012 

> today.end_of_month
=> Sat, 31 Mar 2012 

> today.beginning_of_year
=> Sun, 01 Jan 2012 

> today.end_of_year
=> Mon, 31 Dec 2012 

With the same name pattern, but with a slightly different result, Rails defines the methods “beginning_of_day” and “end_of_day”. It will return an ActiveSupport::TimeWithZone instance, instead of a Date, containing time details.

> today.beginning_of_day
=> Sat, 03 Mar 2012 00:00:00 UTC +00:00 

> today.end_of_day
=> Sat, 03 Mar 2012 23:59:59 UTC +00:00 

advance

What would be the first thing you would do if you had a time travel machine? I bet you are thinking about lots of things just right now, but before you continue, let me explain why I did this question. Rails defines a method that allow you travel to a specific date, just like a time travel machine. Rails defines it as “advance” and we are going to play with it.

Our initial date will be today:

> today 
=> Sat, 03 Mar 2012 

Let’s travel to the future, 1 year from now:

> today.advance(:years => 1)
=> Sun, 03 Mar 2013 

Maybe one year is too much, let’s use 1 month instead:

> today.advance(:months => 1)
=> Tue, 03 Apr 2012 

Well, you can define your own trip using different combinations of: years, months, weeks and days. It allows us to do things like:

> today.advance(:years => 42, :months => 42, :weeks => 42, :days => 42)
=> Mon, 04 Aug 2058 

change

My grandmother always said: “The use of a time travel machine can make you dizzy” and I have to agree with her. Perhaps you are looking for a simple way to change the date. Let’s say you have an specific date and you want to change its year. For times like this, you have “change”:

> today
=> Sat, 03 Mar 2012

> today.change(:year => 2000)
=> Fri, 03 Mar 2000

You can change pretty much everything and have a complete new date.

I hope this post can help you to have a great time when working with Rails and dates. Don’t forget, this is a limited list of extensions that Rails does to the Date class, based on the methods that I am using more often. Rails defines more extensions to Date class and you can check all of them at http://api.rubyonrails.org/classes/Date.html. It’s also available in the active_support code at: activesupport-3.1.3/lib/active_support/core_ext/date file.

1 note &

Rails - core extensions - Array

I can still remember the early days that I decided to teach myself Rails. I was really excited, ‘cause I was bombarded of new information. A lot of concepts, conventions and “magic” things that I was not used to see. It also brings to my memory the time that I spent a whole afternoon dealing with my custom helpers methods to handle Array grouping and displaying operations. Well, this event happened some time ago, but is not rare to see nowadays, pieces of code, including gems, defining its own methods to solve problems that were already solved.

Do you know Rails extends Ruby core built-in classes? You are probably shaking your head answering me “yes, of course I know”. Well, most people are aware about those extensions, but I had chance to see different applications not taking advantage of them.

This post will share the Array extension methods that Rails defines that I am used to use when I am working. Just to be clear, that’s not a complete list of extensions to the Array class, it’s a list with the methods that I use most.


from / to

There is times when You have to get Array elements from/to a defined point. Let’s say you have the following array:

> list = [:apple, :banana, :chocolate, :milk, :cow, :singer, :vim] 

And lets imagine that You want to get all the elements from index 5th position to the end. You could use the following code to get it done:

> list[5..-1]
=> [:singer, :vim] 

And that’s OK, it would work perfectly, but Rails defines a method named “from” that does the same:

> list.from(5)
=> [:singer, :vim]

You can use the same approach to get elements from the beginning to a defined point. Let’s say now you want to get all the element til the 2nd position (elements 0, 1 and 2). You can the following code to do that:

> list[0..2]
=> [:apple, :banana, :chocolate] 

Same as above, you have a method to it, named “to”:

> list.to(2)
=> [:apple, :banana, :chocolate] 

first / last / second /third / fourth / fifth / forty_two

There is times when you want to get a specific element in an array. You may want to get the first or the last element and use the conventional indexation to get them, just like:

> list = ["Paul", "Matthew", "John", "Peter", "Luke"]

The first element of the array:

> list[0]
=> "Paul" 

The last element of the array:

> list[-1]
=> "Luke" 

And that works really well, but what about using some already defined methods that help you getting the same behavior and also make your code cleaner? Then you can use “first” and “last” methods to get the same behavior:

The first element of the array:

> list.first
=> "Paul" 

The last element of the array:

> list.last
=> "Luke" 

You have also the methods “second”, “third”, “fourth”, “fifth” and “forty_two” that are self-explanatory. You may think that’s already known by people using Rails, but based in what I have seen, I am going to disagree with you.


to_sentence

Using the same array:

> list = ["Paul", "Matthew", "John", "Peter", "Luke"]

Sometimes you have to display the items in a human-style list. So, you could maybe use the following code to create this behavior:

> last = list.pop
=> "Luke" 

> list.join(", ") + [" and ", last].join
=> "Paul, Matthew, John, Peter and Luke" 

You’ve just created a sentence built from the array elements. But this problem is really common and not surprisingly, Rails defines a way to do it, using the “to_sentence” method:

> list.to_sentence
=> "Paul, Matthew, John, Peter and Luke" 

in_groups_of

One of the things that I am always using, is breaking arrays into a grouping organization. I have seen lots of different implementations to solve this problem, including my own solutions (in my early Rails experiments). Let’s use the following array:

> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

What would you do if you wanted to group those elements in groups of 2 elements? Maybe you are wondering about a fancy combination about map, zip, collect, but for now we are going to use the “in_groups_of” method, just like:

> list.in_groups_of(2)
=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 

now you have your Array elements organized in groups of 2 elements. What if you want to have groups of 3 elements?

> list.in_groups_of(3)
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, nil, nil]]

Rails tries to fit everything, but as it was not able to get enough elements to create the latest group, then it fills with nil value. But you can override it, defining what you want to use to fill the empty spots:

> list.in_groups_of(3, 0)
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 0, 0]]

or maybe you want just get rid of them, so let’s do it:

> list.in_groups_of(3, false)
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

in_groups

Using in_groups_of you can define the number of elements inside a group you want to create. But what happens when you want to create a specific number of groups (not the # of elements inside it) ? Well, for those times, you have the “in_groups” method. Let’s use the same array used in the example above:

> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And let’s create 3 groups with those elements:

> list.in_groups(3)
=> [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]

And you can define the default element to fit the nil spots:

> list.in_groups(3, "empty")
=> [[1, 2, 3, 4], [5, 6, 7, "empty"], [8, 9, 10, "empty"]]

Or completely take the elements that don’t fit away:

> list.in_groups(3, false)
=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]

sample

Have you ever needed to get random elements of an array? Well, I think everyone had already to do something like it. Aiming to get it done, you maybe created code like:

> list.sort_by { rand }.slice(0, 3)
=> [4, 7, 9]

> list.shuffle.slice(0, 3)
=> [9, 10, 4]

And they really work. But there is a simple way, using the “sample” method:

> list.sample(3)
=> [10, 5, 2]

Well, that’s the first post about the extensions that Rails defines to the Ruby built-in classes and that I am used to use. The next post will have lots of fun about the Date class.

This post is not about what is wrong or right. It’s about putting a light spot on extensions that Rails does to built-in Ruby classes. Maybe you disagree with me that using “first” or “last” is the best option, when you have a small and direct way of doing it using Array indexation. That’s OK for me and I can see your point. But maybe you were defining your own methods because you didn’t know that Rails had those extentions, so I would be glad to know you decided to start using them from now on.

0 notes &

Um ano na ThoughtWorks

Em 8 de Janeiro vai completar um ano que eu trabalho na ThoughtWorks. Para quem não conhece a empresa, a ThoughtWorks é consultoria em TI, referência no mundo por suas publicações e suas conhecidas práticas.

Me considero uma pessoa de sorte. Para você ter uma ideia, trabalhar na ThoughtWorks é como poder fazer parte do Cirque du Soleil para um artista, porque você sabe que lá dentro só tem gente incrível (shameless).

O que eu vivi neste primeiro ano de ThoughtWorks:

  • Práticas ágeis

    Muitas empresas se dizem ágeis (alias, hoje acredito que todas dizem isto), mas quantas você conhece que levam isto a sério? Testes, pair-programming, red-green-refactor e muito do que muitos dizem. Aqui na TW, nós realmente fazemos.
  • Ambiente de desenvolvimento

    Ser feliz por poder usar Ruby, Rails, Vim, Linux/Mac e uma máquina com 2 monitores enormes :)
  • Convivência com pessoas diferentes

    Neste primeiro ano de TW, eu tive a chance de conviver com Gaúchos, Bahianos, (muitos) Mineiros, Paulistas, Cariocas, Indianos, Americanos, Canadenses, Ingleses, Australianos, Bolivianos, Argentinos… Estive em contato com outras culturas, formas de pensar e diferentes experiências de vida.
  • Liberdade

    Não é apenas o fato de poder trabalhar de bermuda e chinelo, ou ficar jogando video-game quando se esta um pouco estressado. É muito difícil poder ter a liberdade de falar diretamente com todas as pessoas. Não existe hierarquia na empresa, você não precisa se reportar à alguém. Você tem apenas o compromisso e a responsabilidade de ser parte de um time que conta com você, e que você sabe que pode contar com.
  • Aprender, aprender e aprender

    Você já ficou entediado de estar em uma empresa e não conseguir usar ou aprender nada novo? Bom, na TW isto non-equiziste! Mesmo estando em um projeto por um determinado tempo, o time está sempre buscando o que há de melhor em tecnologia e metodologias.
  • Inglês

    Você está rodeado durante todo o tempo por pessoas não-brasileiras, frequentemente pareando ou almoçando com pessoas que não falam Português. Isto significa que você vai praticar o inglês durante todo o dia.
  • Mais

    Claro, esta lista está longe de ser completa, mas eu definitivamente não vou lembrar de tudo. Eu sei, que a vida poderia ser bem melhor e será, mas isto não impede que eu repita: escreve o teste, roda o rake e acredita.

0 notes &

Livros que eu li em 2011

Final do ano chegando, e vem com ele as lembranças das coisas que nós planejamos para fazer durante o ano. Uma das coisas que eu havia decidido para 2011, era ter tempo para ler sobre assuntos não relacionados diretamente com desenvolvimento de software. Neste post eu vou compartilhar esta lista de livros e também a minha opinião sobre eles.

Virando a própria mesa - Ricardo Semler

Publicado em 1988 logo se tornou um best seller no mundo dos negócios. Semler é uma pessoa que está completamente acima da média, e mostra como idéias inovadoras no gerenciamento de uma empresa e de pessoas podem trazer resultados positivos para todos. Mesmo se passando mais de 20 anos desde o lançamento deste livro, as idéias por trás dele são como ouro para quem procura ser um (melhor) empreendedor.

Purple Cow - Seth Godin

Este é o primeiro livro que eu leio do Seth Godin. Purple Cow é sobre fugir do comum, sobre conseguir atenção (seja em uma empresa ou na vida), e desta forma ganhar espaço no mercado. O livro trás uma série de casos, onde indivíduos ou empresas fugiram do comum e alcançaram o sucesso. Na minha opinião, este foi o livro menos interessante desta lista.

Rework - Jason Fried e David Heinemeier Hansson

Descrevendo a cultura da 37signals, os autores (e fundadores da empresa) mostram como você pode ser mais produtivo sem perder tempo com tarefas que não acrescentam valor. É uma leitura interessante para quem pretende montar uma empresa, mas sempre fica adiando isto com desculpas como “eu não tenho tempo” ou “eu não tenho dinheiro”. É uma leitura interessante, que trás muita das idéias contidas no livro do Semler (mostrado acima), mas como uma visão de uma empresa de desenvolvimento de software.

Delivering Happiness - Tony Hsieh

Quão importante é ser feliz no trabalho? Um salário alto é automaticamente traduzido em bons resultados? Este livro trás informações preciosas sobre empreendedorismo e como pequenos detalhes podem mudar o rumo/futuro de uma empresa. Nele, o autor mostra como foi construída a cultura da Zappos (http://www.zappos.com/) e como eles conseguiram levar uma empresa sem lucro a uma receita de US$ 1 bilhão. Mas na minha opinião, a parte mais interessante do livro é mostrar o dia-a-dia de uma startup, com todas as incertezas e medos.

Made to Stick: Why Some Ideas Survive and Others Die - Chip Heath and Dan Heath

Por que algumas idéias simplesmente ficam gravadas na nossa cabeça? Por que uma fofoca da a volta ao mundo em segundos? Por que você ainda lembra da aula de ciências do ensino fundamental? Bom, você entendeu. Este livro explica da uma forma muito agradável um estudo sobre as características que fazem uma idéia ser lembrada. Definitivamente este livro mudou a forma que eu penso.