Rupeal
RSSLinkedInTwitterFacebook

Arquivo para a categoria ‘Software Development’

RUPEAL development setup

Na RUPEAL temos a convicção de que a productividade dos colaboradores depende directamente da qualidade do material com que trabalham.

Como são actualmente estações de trabalho na RUPEAL?

photo

Hardware:

  • Imac’s dual core de 20″ com 4GB de ram / MacBook de 13.3″ com 2Gb;
  • 2º ecrã de 22″ (1680×1050);

Software:

  • OS X Snow Leopard;
  • Textmate – O nosso “pau para toda a obra” O Textmate é o editor de texto por excelência, usado por developers e designers para fazer todo o código subjacente aos nossos trabalhos, possuí um muito bom suporte a macros, é extensível através de bundles e plugins e tem syntax highlighters para a maioria das linguagens de programação;
  • Safari / Firefox – O Safari é o browser de eleição, superando o Firefox sobretudo pelo uso de menos recursos, memória principalmente. O que se torna importante quanto o número de tabuladores abertos é constantemente superior a 20. O firefox vale sobretudo pela extensibilidade fornecida através dos inúmeros plugins disponíveis, dos quais destacamos o “grande” firebug, a ferramenta por excelência para fazer debug em HTML, CSS e Javascript;
  • SequelPro – O nosso navegador de BD’s MySQL, sendo uma ferramenta grátis, o SequelPro, principalmente desde o último update, apresenta-se como um eficiente navegador para BD’s MySQL, sendo rápido e funcional;
  • Versions – Versions é o nosso cliente de SVN, usamo-lo para tudo o que é controlo de versões na RUPEAL como cliente para o nosso repositório online, o Beanstalk. É funcional e apresenta uma interface muito bem conseguida, apesar de não suportar completamente as funcionalidaes mais avançadas, como é o caso do “merge”.
  • DropBox – O Dropbox é usado para sincronizar entre os vários postos de trabalho pastas com recursos especificos, de forma a que todos disponham desses mesmos recursos de forma rápida e eficiente;
  • Transmit – O nosso client de sftp,  usado sobretudo para aceder a alguns dos alojamentos com que trabalhamos, quando há necessidade de fazer upload ou download dos mesmos.

Menções honrosas: Adium, Itunes, Tweetie.

Quais são as vossas soluções?

Rui Alves on November 10th, 2009

People, Software Development

2
 

Pagar online – Vencer o medo em pt

Ao oferecer um serviço exclusivamente online em Portugal (www.invoicexpress.com) enfrentamos uma série de barreiras associadas ao medo da mudança / adopção de novas tecnologias.

O maior desses medos é o de fornecer dados bancários para efectuar o pagamento. Mesmo com o MBNET e o PAYPAL ainda há muita gente que prefere os meios mais tradicionais.

A forma que encontrá-mos para contornar este problema foi oferecer um meio de pagamento exclusivo para Portugal, suportando os nossos bem conhecidos MultiBancos.
Após analisar algumas alternativas escolhemos como parceiro para este serviço a Hi-Media e o seu Serviço Compra Fácil.

Este serviço desponibiliza um webservice através do qual podemos pedir a geração de referências multibanco notificando-nos quando estas são pagas.

De uma perspectiva mais técnica como decorre o processo e como o integramos na nossa aplicação Rails?

  1. O utilizador, cliente do invoic€xpress escolhe o plano desejado, selecciona a opção de pagamento com multibanco e selecciona a opção gerar referência.
  2. O invoic€xpress gera um token único para a referência
    token = Digest::SHA1.hexdigest([Time.now, rand].join)
  3. Constroi o url para onde pretende ser notificado do pagamento, incluindo este token único
    url = "https://www.invoicexpress.net/references/payed/#{@mbreference.token}"
  4. Coloca esse URL e os restantes parametros necessários no pedido para o webservice compra fácil e efectua o pedido.
    factory = SOAP::WSDLDriverFactory.new("http://hm.comprafacil.pt/SIBSClick/webservice/clicksmsV4.asmx?WSDL")
    soap = factory.create_rpc_driver
    soapResponse = soap.SaveCompraToBDValor1(:origem=>url, :IDCliente=>"cliente_teste",
     :password=>"teste_password", :valor=> value , :informacao=>"teste", :IDUserBackoffice=>"-1")
  5. Guarda a referência multibanco gerada na BD
    @mbreference.reference = soapResponse.referencia
  6. O cliente desloca-se ao MB e efectua o pagamento
  7. O sistema compra-fácil notifica o invoic€xpress usando URL que indicámos no pedido (passo 3)
  8. O invoic€xpress recebe a notificação, e procura a referência através do token único, activando assim a subscrição paga pelo cliente.
    mbreference = Mbreference.find_by_token(params[:reference_token])
    mbreference.state = "payed"
    mbreference.save

Para os mais distraidos foram menos de 20 linhas de código…

O código é apresentada numa versão simplificada apenas para efeitos demonstrativos.

Não poderá ser descurado o facto de estarmos a trabalhar com dinheiro e com dados de clientes, é sempre necessário garantir o máximo de segurança possível usando HTTPS.

Apesar de ser uma solução especifica para Portugal, é de simples implementação e é uma forte ajuda para quebrar uma barreira à adopção deste tipo de aplicações web.

Rui Alves on July 14th, 2009

Software Development

1
 

One user – Multiple accounts

One of the new features we have for the next release of InvoicExpress is to allow a user to be a member of multiple accounts.

The advantage of this model is that you only need one login credential to use all the accounts that you have access to.

In this post we show you a glimpse of our development process while developing this feature.

Our starting data model was (simplified here for clarity), a user belongs to an account, an account has many users, a user has many roles, nothing fancy.

class Account < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :account
  has_and_belongs_to_many :roles
end

class Roles < ActiveRecord
  has_and_belongs_to_many :users
end

Users, Accounts and Memberships

The most obvious change is that the relation between user and account evolves from a one-to-many to many-to-many.

This change means user roles now have to be scoped by account. This isn’t easy with a regular many-to-many association.

In plain english we say “a user is a member of an account”. Member? We don’t have that in our data model. The relation between a user and its account is called Membership. Naming this showed us the missing link between a user and its accounts.

So we add a Membership model to map the relation between a user and it’s account.

User roles are now associated to an account through a membership.

class Account < ActiveRecord::Base
  belongs_to :o wner, :class_name => "User",
                     :foreign_key => "owner_id" 

  has_many :memberships, :dependent => :destroy
  has_many :users,:through => :memberships

end

class User<; ActiveRecord::Base
  has_many :memberships
  has_many :accounts, :through => :memberships,
                      :uniq => true
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :account

  has_and_belongs_to_many :roles
end

class Roles < ActiveRecord::Base
end

Keeping track

With multiple accounts per user we need know the currently used account. Our choice was to do it at the database level, because it would imply the least changes to our code base.

Knowing the current account means we also know the current membership. User roles can now be scoped to the current membership.

class User < ActiveRecord::Base

  has_many :memberships
  has_many :accounts, :through => :memberships,
                                   :uniq => true

  belongs_to :current_account, :class_name => "Account"
  has_one :current_membership,
          :class_name => "Membership",
          :foreign_key => "user_id",
          :conditions => 'current_account_id = #{self.current_account.id}'

  def roles
    self.current_membership.roles unless current_membership.blank?
  end
end

And that’s it for the data model changes

Changing accounts

Having multiple accounts, the user needs to know which one he is currently working on, as well as, be able to easily select another account.

For this double duty, we chose to use a always visible combo box located on the header of InvoicExpress.

The following code samples are simplified for readability.

Here we create a select input on our header partial and wire the onChange event to an ajax call to the users_controller.

# _header.html.erb
...
<%if current_user.accounts.count > 1 -%>;
  <%= select "change",:account, current_user.accounts.map{|a| [a.name, a.id]},
                                {:selected => current_user.account.id},
                                :o nchange => change_account
  %>
<% end -%>
...
# application_helper.rb
...
def change_account
  remote_function(:url => change_current_account_path, :method => :post,
                  :with =>"$('change_account').serialize()"
                 )
end

The change_current_account action fetches the selected account from the accounts the user is a member of.

If none is found the save will fail and we return a 412 – Precondition Failed error. On a successful save the user is now scoped the selected account, and we just have to redirect to the selected account account home screen.

# user_controller.rb
...
def change_current_account
  current_user.current_account = current_user.accounts.find(params[:change][:account])

  respond_to do |format|
    if current_user.save
      flash[:notice] = "You are now using account: #{account.name}"
      format.js do
        render :update do |page|
           page.redirect_to home_url
        end
      end
    else
        format.js{render :text => "change account error", :status =>; 412}
    end
  end
end

Wrapping up

Some say that every programming problem can be solved by another layer of indirection.
Others say that naming things is the hardest part of programming, and in this case both were true.

After we acknowledged and named the relation between a user and its accounts as a membership, all issues found almost resolved themselves. We were following a clear path. We were on rails after all.

Ps: In case you’re wondering the plugins we’re using for authentication and authorization are:

both available on github

Bruno Coelho on July 3rd, 2009

Software Development

0
 

“butt ugly” perfect design…

Pois é, nem sempre o que é bonito é bom design, ou melhor ainda, nem sempre o que é feio é mau design.

Ora leiam lá este artigo do Jason Fried, um dos artistas da 37signals.

Rui Alves on November 19th, 2008

Software Development

0
 

Good Unix Habits

Here’s a nice article on good unix habits! DeveloperWorks has been one of the good many sources for reading about new technologies, specially on the Java Department

Rui Alves on August 25th, 2008

Software Development

0
 

Ruby on Rails Scaling

Just came across with this article about RoR scaling issues. 

Some quotes:

“When it comes to handling massive HTTP traffic, you can scale a Rails application horizontally just like any other by replicating your front-end web servers behind a load balancer. There’s nothing about Rails that makes this more difficult than with any other technology.”

So if you don’t know how to scale with Java, C# or whatever you’re using… it’s useless to point your finger to RoR.

“There’s a lot of different things that can slow down a web application. Rails makes it easy to get your application running without worrying about any of the performance issues, and that’s a good thing. If you ignore everything about performance tuning, you’ll still have a working application, and from there you can tune. There’s little point in tuning for performance before you have something that is successful for a small group of people. And if you focus on building an optimally scalable site and end up late to market as a result, you’ll have achieved nothing.”

Bottom line: Build traffic first, worry about performance later. Comments?

Rui Alves on May 4th, 2008

Software Development

0
 

Better Web Application Framework

 A collegue just passed me a screencast of Sean Kelly who describes the different available frameworks for developing web applications. The chosen technologies include Java (JEE), Ruby on Rails, Django, TurboGears and Zope, I believe.

Although I find the first examples on Java a little bit “tendencious” since he doesn’t use any IDE or help tool for writting the XML files, writes an Hello World in a Servlet (which nobody uses this days) I find the conclusions very interesting!

Enjoy

Rui Alves on December 1st, 2007

Software Development

1
 

Java and Web 2.0 Applications

This article explains all my toughts about how JEE is not fit for developing Web 2.0 based applications and why we need to use auxiliar frameworks that are not Java standard (Like Spring, Hibernate, etc.)!

“Web 2.0 applications developed using standard Java™ Platform, Enterprise Edition 5 (Java EE)-based approaches face serious performance and scalability problems. The reason is that many principles that underlie the Java EE platform’s design — especially, the use of synchronous APIs — don’t apply to the requirements of Web 2.0 solutions.”

“In a Web 2.0 context, mash-up applications frequently use services and feeds exposed through an SOA’s service APIs Java EE meets SOA. These applications need to consume services in a B2C context.”

For me, this also explains how frameworks like Ruby on Rails that were built with considerations of this new trend of applications, have a huge success on the development of Web 2.0 applications!

Enjoy: http://www.ibm.com/developerworks/java/library/wa-aj-web2jee/index.html?ca=drs-

Rui Alves on November 28th, 2007

Software Development

0
 

JPA and Rollbacks…

David Van Couvering has a nice article on JPA and Transaction Rollbacks

I haven’t got to the point where I’ll have this kind of problems, but I guess this post is a good reminder that someone else have the solution to a problem that I don’t have yet

Rui Alves on April 30th, 2007

Software Development

0
 

Are JSP really Dead?

Just came across this article about how JSP are dead and asked myself if the author as a good point or not.

One thing is for sure, most of JEE technologies (EJB, JSF, etc.) are sure like cannons to kill flies, and makes me wonder if JSP is on that package and I have’nt noticed since I’m so used to using them…

Guess I have to give a try to Freemarker

Rui Alves on April 20th, 2007

Software Development

0