Posts Tagged ‘lib’

Ruby on Rails enviando e-mails usando o Google Apps

Postado em 31 jul 2009
Categoria(s) Ruby on Rails

Depois de algumas horas quebrando a cabeça, consegui fazer funcionar o envio de e-mails usando o Google Apps.

Vou explicar como configurar. ;-)
Vamos lá!

Configure o config/environment.rb

Configure o seu environment.rb com a sua conta de e-mail do Google Apps, ou conta do Gmail, os e-mails serão enviados via smtp.

1
2
3
4
5
6
7
8
9
10
11
12
...
Rails::Initializer.run do |config|
...
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => 587,
    :authentication => :plain,
    :user_name => "seu-usuario@seudominio.com",
    :password => "sua senha"
  }
end

Mas só fazendo isso não vai funcionar, o Google Apps utiliza TLS (Transport Layer Security), ou seja, Protocolo de Camada de Sockets Segura.

Para funcionar é necessário adicionar a lib smtp_tls.rb responsável pela camada TLS, você encontra ela no seguinte endereço: http://github.com/patrickespake/SMTP-TLS/tree/master.

smtp_tls.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require "openssl"
require "net/smtp"
 
Net::SMTP.class_eval do
  private
  def do_start(helodomain, user, secret, authtype)
    raise IOError, 'SMTP session already started' if @started
    #check_auth_args user, secret, authtype if user or secret
    check_auth_args user, secret
 
    sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
    @socket = Net::InternetMessageIO.new(sock)
    @socket.read_timeout = 60 #@read_timeout
 
    check_response(critical { recv_response() })
    do_helo(helodomain)
 
    if starttls
      raise 'openssl library not installed' unless defined?(OpenSSL)
      ssl = OpenSSL::SSL::SSLSocket.new(sock)
      ssl.sync_close = true
      ssl.connect
      @socket = Net::InternetMessageIO.new(ssl)
      @socket.read_timeout = 60 #@read_timeout
      do_helo(helodomain)
    end
 
    authenticate user, secret, authtype if user
    @started = true
  ensure
    unless @started
      # authentication failed, cancel connection.
      @socket.close if not @started and @socket and not @socket.closed?
      @socket = nil
    end
  end
 
  def do_helo(helodomain)
    begin
      if @esmtp
        ehlo helodomain
      else
        helo helodomain
      end
    rescue Net::ProtocolError
      if @esmtp
        @esmtp = false
        @error_occured = false
        retry
      end
      raise
    end
  end
 
  def starttls
    getok('STARTTLS') rescue return false
    return true
  end
 
  def quit
    begin
      getok('QUIT')
    rescue EOFError
    end
  end
end

Copie o arquivo smtp_tls.rb para o diretório lib do seu projeto Ruby on Rails.

Carregando a lib smtp_tls.rb no environment.rb

Volte para o environment.rb e adicione para carregar a lib smtp_tls.rb:

1
2
3
4
5
...
require 'smtp_tls'
 
Rails::Initializer.run do |config|
...

Pronto! Fazendo isso você irá conseguir enviar e-mails usando o Google Apps ou Gmail.

Existe um detalhe a ser considerado na lib smtp_tls.rb, se você olhar o código vai encontrar as linhas abaixo:

7
8
9
10
...
    #check_auth_args user, secret, authtype if user or secret
    check_auth_args user, secret
...

O código por padrão tinha a linha check_auth_args user, secret, authtype if user or secret, mas quando essa linha está habilitado os e-mails não são enviados, você pode entender melhor o por que lendo aqui: http://blog.inspired.no/smtp-error-while-using-gmail-in-rails-271. Desta forma eu deixei apenas check_auth_args user, secret.

Se você precisa entender o básico de como criar um e-mail e enviar leia aqui: http://guides.rubyonrails.org/action_mailer_basics.html.

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ruby on Rails usando strip_tags nos controllers, models e libs

Postado em 15 jun 2009
Categoria(s) Ruby on Rails

O Ruby on Rails possui o métogo strip_tags para remover tags html. Esse método está apenas disponível na camada de view, uma vez que faz parte ActionView::Helpers::SanitizeHelper.

Eu não concordo com essa implementação do Rails, acho que deveria ser disponível também na camada de controller e model, onde são os lugares que esse método é mais útil.

Para implementar o strip_tags nos controllers, models e libs, nós podemos adicionar esse método na classe String, desta forma estará disponível em qualquer lugar.

Abra o arquivo config/initializers/new_rails_defaults.rb:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Be sure to restart your server when you modify this file.
 
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
 
if defined?(ActiveRecord)
  # Include Active Record class name as root for JSON serialized output.
  ActiveRecord::Base.include_root_in_json = true
 
  # Store the full class name (including module namespace) in STI type column.
  ActiveRecord::Base.store_full_sti_class = true
end
 
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
 
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false

Adicione no final do arquivo as linhas:

1
2
3
4
5
class String
  def strip_tags
    ActionController::Base.helpers.strip_tags(self)
  end
end

As linhas acima criam o método strip_tags na classe String.

Ficando o arquivo completo assim:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Be sure to restart your server when you modify this file.
 
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
 
if defined?(ActiveRecord)
  # Include Active Record class name as root for JSON serialized output.
  ActiveRecord::Base.include_root_in_json = true
 
  # Store the full class name (including module namespace) in STI type column.
  ActiveRecord::Base.store_full_sti_class = true
end
 
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
 
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false
 
class String
  def strip_tags
    ActionController::Base.helpers.strip_tags(self)
  end
end

Agora reinicie o seu servidor web para pegar essas novas configurações na inicialização da aplicação.

Agora quando você precisar do strip_tags pode usar assim, exemplos:

params['title'] = params['title'].strip_tags
 
ou
 
>> '<b>meu texto</b>'.strip_tags
=> "meu texto"

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Ruby on Rails estendendo as migrações com helpers

Postado em 24 mar 2009
Categoria(s) Ruby on Rails

É muito comum termos nas migrações instruções sql para criar chaves estrangeiras e o rails não tem métodos para criar-las.

Por exemplo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class CreateGameTeams < ActiveRecord::Migration
  def self.up
    create_table :game_teams do |t|
      t.references :team, :null => false
      t.references :game, :null => false
      t.timestamps
    end
 
    execute "ALTER TABLE game_teams ADD CONSTRAINT fk_game_team_teams FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE CASCADE ON UPDATE
 CASCADE"
    execute "ALTER TABLE game_teams ADD CONSTRAINT fk_game_team_games FOREIGN KEY (game_id) REFERENCES games (id) ON DELETE CASCADE ON UPDATE
 CASCADE"
  end
 
  def self.down
    drop_table :game_teams
  end
end

Para simplificar mais as coisas, é possível criar helpers e estender as funcionalidades das migrações, é isso que será feito para criar um método que gera as chaves estrangeiras (foreign key).

Faça o seguinte:

No diretório lib do projeto crie o arquivo migration_helpers.rb com o conteúdo abaixo:

1
2
3
4
5
6
7
8
9
module MigrationHelpers
 
  def foreign_key(from_table, from_column, to_table)
    constraint_name = "fk_#{from_table}_#{from_column}"
 
    execute %{alter table #{from_table} add constraint #{constraint_name} foreign key (#{from_column}) references #{to_table}(id)}
  end
 
end

Agora é possível adicionar esse método a qualquer migração acrescentando as linhas a seguir no início do arquivo de migração:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require "migration_helpers"
 
class CreateGameTeams < ActiveRecord::Migration
 
  extend MigrationHelpers
 
  def self.up
    create_table :game_teams do |t|
      t.references :team, :null => false
      t.references :game, :null => false
      t.timestamps
    end
 
    foreign_key(:game_teams, :team_id, :teams)
    foreign_key(:game_teams, :game_id, :games)
  end
 
  def self.down
    drop_table :game_teams
  end
end

A linha require coloca a definição do módulo no código de migração e a linha extend adiciona os métodos do módulo MigrationHelpers à migração como métodos de classe.

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark

Como instalar a gem rmagick no Ubuntu

Postado em 01 fev 2009
Categoria(s) Ruby on Rails, Ubuntu

Para instalar a gem rmagick no Ubuntu faça o seguinte:

Instale o imagemagick:

1
sudo apt-get install imagemagick

Instale a lib dev do imagemagick:

1
sudo apt-get install libmagick9-dev

Finalmente instale a gem rmagick:

1
sudo gem install rmagick

Se você gostou desse texto e acha que ajudou você, me recomende: Recommend Me.

  • Share/Bookmark