Arquivo

Arquivo da Categoria ‘Ruby’

Generate PDF with prawn and Google charts

29, dezembro, 2011 Sem comentários

Hey guys,

It’s a quickly post about how to generate pdf with prawn and google charts. Prawn is a awesome lib in ruby for generating PDF documents and google charts is a API to generate charts.

I like to create a class responsible to generate my pdf documents. Here is my implementation:

# encoding: UTF-8
require 'open-uri'
class GenderReportPdf < Prawn::Document

  def initialize(mens, womans)
    super(top_margin: 70)
    add_title
    @mens = mens
    @womans = womans
    add_count
    add_image
  end

  def add_title
    text "Report by Gender", size: 28, style: :bold, position: :center
  end

  def add_count
    move_down 20
    text "Mens #{@h_count}"
    text "Womans #{@m_count}"
  end

  def add_image
    move_down 20
    image get_external_image, :position => :center
  end

  def get_external_image
    img = URI.parse(URI.encode("https://chart.googleapis.com/chart?cht=p3&chd=t:#{@mens},#{@womans}&chs=250x100&chl=Mens|Womans")).to_s
    img = open(img)
  end

end

It’s a simple ruby code, very easy to understand (I guess). In the next post I will show you how to send this report to client using Rails.

Categories: API, Gems, Ruby Tags: , , ,

OmniAuth strategy for authenticating to Podio

22, dezembro, 2011 Sem comentários

Hello fellows,

Now that I finished my bachelor’s degree, I have free time to devote to open source projects that I like and a project that I really like is OmniAuth.

OmniAuth is a libary that standardizes multi-provider authentication for web applications. It’s very flexible and nice!

In my current job, we are using a lot a web application called Podio. It’s a very cool app.
So yesterday I started to develop a OmniAuth strategy for authenticating to Podio and today I finished it.

You can see the code here

Fell free to contribute and use it.

Thanks,

Categories: API, Gems, Rails, Ruby Tags:

Validates password strength in Rails app

13, dezembro, 2011 Sem comentários

Hello guys,

In the last weekend I finished a rubygem to validate the password strength. It’s a very simple gem, the code are available at github

To install:

gem install password_strong

It’s very simple to use, just add verify_strong in the attribute.

Example:

class User < ActiveRecord::Base

  verify_strong :password

end

In the future I gonna work in client side validation. Feel free to contribute.

Categories: Rails, Ruby Tags: , , ,

Creating custom middlewares with Rack

12, dezembro, 2011 Sem comentários

To kick off, What is Rack?

A Rack applications is a object that has a methods named ‘call’ and that method receive the enviroment as a argument and return a array with exactly three values: status, header and body.

The following is a simple example:


class App
  def call(env)
    [200, {"Content-Type" => "text/plain"},["LucasAllan.com"]]
  end
end

Rack is the base of a lot of web frameworks written in Ruby, like Ruby On Rails, Sinatra, Camping and others…

What is a Rack Middleware?

Rack middleware is a kind of filter to requests in a Rack application. It behaves like a rack application and needs the same things that a simple rack application. It’s like a rack application inside another rack application.

I created a file named cache_control.rb with the follow code:

require 'rack/utils'

module Rack

  class CacheControl
    include Rack::Utils

    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, body = @app.call(env)
      headers = Utils::HeaderHash.new(headers)
      headers['Cache-Control'] = "no-cache"
      [status, headers, body]
    end
  end
end

In that code, I get the enviroment (with headers, content and http code) and I can manipulate it. In that case I just added a new header.

Now in my Rack Application I will load that middleware and use it.

require 'rack'
require 'cache_control'

class App
  def call(env)
    [200, {"Content-Type" => "text/plain"},["LucasAllan.com"]]
  end
end

use Rack::CacheControl
run MyApp.new

I used the word ‘use’ to call my middleware.

You can run this app using the Thin server, for this you must have the Thin installed: gem install thin

And use the follow command:
You the file name of your application is config.ru (Rack standard), use it:

thin -R config.ru start

If don’t, replace config.ru for the right filename.

You can try to access the application using your browser or curl:

curl -i localhost:3000

HTTP/1.1 200 OK
Content-Type: text/plain
Cache-Control: no-cache
Connection: close
Server: thin 1.3.1 codename Triple Espresso

LucasAllan.com

Categories: Rack, Ruby Tags: ,

Integrations tests and Devise Login

27, outubro, 2011 Sem comentários

Yesterday I started doing a new project using devise gem to manage login features. When I started to do integration tests using rspec, I found a problem: devise test helpers doesn’t work with rspec integration test.
So this is a quick solution to fix this.

require 'spec_helper'
include Warden::Test::Helpers

describe "UserDashboards" do

  before(:each) do
    @user = Factory.create(:user)
    login_as @user, :scope => :user
  end

  it "should access dashboard" do
    visit users_dashboard_path
    page.should have_content("dashboard")
  end
end

At top of spec file, after require ‘spec_helper’ include Warden::Test::Helpers. And in the before(:each) block I just used a warden helper to do login.

Short tips to create a great API

21, outubro, 2011 1 comentário

The last projects that I have worked had a API for external client access, I learned a lot with those projects and here I gonna share with you what I learned.

  • HTTP You must to understand how HTTP protocol works. This is the first and more important thing.
  • Use HTTP verbs – Your api must be able to understand what we expect that it does if for example a request with put verb is received. It’s terrifying to use just get and post to everything or to use get to modify data.
  • Everything needs a ID - Every resource needs to have a identification. That way you can provide a way for your users can access that resource.
  • Hypermedia Support – Link resources together. This is hard to explain, lets see a example:
<order self='http://example.com/customers/4332' >

<amount>53</amount>

<product ref='http://example.com/products/45654' />

<customer ref='http://example.com/customers/2332' />

</order>

In this example, we have a resource representation named ‘order’. That resource has a attribute named amount and a link to two another resource. That way, my client doesn’t need to know how to access resources connected with that resource, It just follow the links. If any time I change the url of products resources, the clients will not break.

  • Use multiple representations - Not just XML and JSON, you can create your own representation format to give more power to your API.
  • Etag and Cache-Control – Your client must know what to do when it found headers like “If-Modified-Since”, “If-None-Match”, “Last Modified” . Your Api must send back informations like  etag and cache-control and your client needs to respect this.

Take time to know restfulie. It’s a great lib that can help you with this things.

Categories: API, Dicas, Ferramentas, Ruby Tags: , ,

Singleton Classes on Ruby

5, setembro, 2011 2 comentários

First, this post is not about Singleton Pattern.

Every object on Ruby belongs to two classes. The class that  instantiated it and one anonymous class. This anonymous class is named Singleton Class. We can access the Singleton class using something like that:

class << my_class
end

In that example, my_class is the Singleton Class that I want.
So we can add a new method using something like that:

class City
  class << self        
    def size       
      @size ||= 0     
    end   
  end 
end 

Every time that we add method in a object, is added like a singleton method and it’s added only in the specific object that it was defined. For example:

city = "Vancouver"
another_city = "Montreal" 

def city.province
  "British Columbia"
end 

city.province
#=> "British Columbia"

another_city.respond_to?(:province)
#=> false

This is a simple example of the power of Ruby. In the next post I will show you some other cool things that you can do with Ruby.

Categories: hacking, Ruby Tags:

will_paginate with Rails3 and Caching

26, janeiro, 2011 2 comentários

This is a quick solution to use will_paginate gem with Rails3 and Caching.
If you have a Rails application with cache and you are using will_paginate gem, maybe you have a problem with your routes.
A simple solution for this, is add a route in your routes.rb file.

For example, if you have a model named ‘post’ and you need add paginate in your index page. You have a problem, because for default your url with paginate is ‘/posts?page=number’ and this doesn’t work because your cache ignore the page parameter when it saves.
So the solution is change the routes for use some like this ‘/posts/page/number’.

In your routes.rb add:

  resources :posts, :except => :index
  get "posts(/pages/:page)" => "posts#index", :as => :posts

Just it! Now your application will work with page caching and paginate.

Categories: Rails, Ruby Tags:

Rails 2.3.10 on App Engine

26, dezembro, 2010 Sem comentários

Durante esse feriado de natal, estive testando o suporte a JRuby no Google App Engine. Conseguir rodar tanto uma aplicação feita com Sinatra quanto uma feita em Rails 2.3.10. Infelizmente a gem google-appengine ainda não suporta o Rails 3, mas esse suporte já está sendo desenvolvido.

Então pesquisando no Github achei um gist mostrando como gerar uma aplicação com Rails 2.3.10 e DataMapper, infelizmente não funcionou como deveria. Mas ao analisar percebi que o problema era não está incluindo o DataMapper::Resource no model, então fiz um fork do gist e modifiquei, testei e agora tudo está funcionando. Para acessar o gist clique aqui e divirta-se.

Categories: Gae, Java, JRuby, Rails, Ruby Tags: , , , , ,

De volta ao blog

6, novembro, 2010 Sem comentários

Olá pessoa, sei que o blog anda meio parado. Os últimos 3 meses foram de muita correria, fui promovido no trabalho, assumindo o cargo de gerente do setor de desenvolvimento, o que tomou grande parte do meu tempo.

Oxente Rails

Fazendo um resumo dos últimos meses, em agosto estive em natal, no OxenteRails. Um evento de muita qualidade, recomendo a todos, em 2011 estarei lá novamente. Agradecimento ao meu grande amigo Karlisson que ofereceu hospedagem.

Software Freedom Day 2010

Em Setembro, estive em Campina Grande (cidade maravilhosa que espero ter o prazer de conhecer melhor) para palestrar no Software Freedom Day 2010 sobre Ruby On Rails e Desenvolvimento Ágil. Em breve estarei postando os slides da palestra aqui. Infelizmente estava um pouco doente e não conseguir ficar até o final do evento (minha voz acabou no momento que terminei minha palestra). Espero está lá novamente em 2011.

Atualmente

Estou no momento mexendo um pouco com aplicativos de Web Mapping com Ruby On Rails, já havia mexido com Java e agora como tenho dedicado meu tempo somente a Rails, achei interessante começar a fuçar.

Para quem tem interesse, existe uma excelente Gem chamada Spatial_Adapter, que auxilia o ActiveRecord a tratar os dados geográficos. Atualmente os Bancos suportados são:
PostgreSQL (com sua extensão espacial Postgis)
e o MySQL.
E para quem quer utilizar o Google Maps para exibição dos mapas no seu aplicativo, também já existe uma Gem para isso, a google_maps.

Resumindo é isso, tentarei postar pelo menos mensalmente no blog.

Happy Hack ;-)