Posts Tagged ‘Ruby on Rails’

Ruby on Rails Paperclip com I18n

Postado em 18 nov 2009
Categoria(s) I18n, Ruby on Rails

O plugin paperclip não tem suporte para i18n por padrão.

Então vamos implementar isso no braço, talvez não seja a forma mais elegante do mundo, mas funciona.

No seu model:

class Ong < ActiveRecord::Base
  # Paperclip
  has_attached_file :logo, :styles => { :thumb => "100x100>" }
  validates_attachment_size :logo, :less_than => 50.kilobytes, :message => I18n.t('activerecord.errors.messages.attachment_size', :min => 0, :max => 50.kilobytes)
end

Agora você precisar criar a diretiva activerecord.errors.messages.attachment_size no seu config/locales/pt-BR.yml:

pt-BR:
  # Active Record
  activerecord:
    errors:
      template:
        header:
          one: "Não foi possível gravar: 1 erro"
          other: "Não foi possível gravar: {{count}} erros."
        body: "Por favor, verifique o(s) seguinte(s) campo(s):"
      messages:
        attachment_size: "tamanho do arquivo deve estar entre {{min}} e {{max}} bytes"

Pronto! Seja feliz!
Se o plugin não faz, a gente faz.

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

  • Share/Bookmark

Ruby on Rails Validação de Data

Postado em 05 nov 2009
Categoria(s) Ruby on Rails

Não existe no core do Ruby on Rails um validator para datas, mas existe um plugin que faz muito bem essa tarefa, o nome do plugin é validates_date_time.

Esse plugin está disponível no Github em: http://github.com/nickstenning/validates_date_time/.

Instalação

./script/plugin install git://github.com/nickstenning/validates_date_time.git

Configuração

class Investor < ActiveRecord::Base
  validates_date :date_of_birth
end

Esse validator aceita datas no formato: 2006-01-01 ou 1 Jan 06 ou 1 Jan 2006 ou 10/1/06 ou 1/1/2006, por padrão o plugin espera datas no formato dia/mês/ano, caso você queria datas no formato americano e necessário adicionar a seguinte linha no seu config/environment.rb:

ValidatesDateTime.us_date_format = true

Outro detalhe é que o validates_date por padrão considera que o campo de data é obrigatório, caso você queria que seu preenchimento seja opcional você pode adicionar o parâmetro :allow_nil => true da seguinte forma:

validates_date :date_of_birth, :allow_nil => true

I18n

Eu procurei na internet uma forma elegante para usar I18n no plugin, eu encontrei apenas uma (http://github.com/nickstenning/validates_date_time/blob/master/test/fixtures/en.yml), mas essa solução não contempla todas as mensagens de validações, existe a mensagem de validação de data inválida que eu não consegui traduzir da forma do link anterior, desta forma eu implementei manualmente o I18n para a mensagem de validação “is an invalid date” da seguinte forma:

No arquivo config/locales/pt-BR.yml adicionei o atributo invalid_date:

pt-BR:
  # Active Record
  activerecord:
    errors:
      messages:
        invalid_date: "é uma data inválida"

e no model eu configurei da seguinte forma:

class Investor < ActiveRecord::Base
  validates_date :date_of_birth, :message => I18n.t('activerecord.errors.messages.invalid_date')
end

O plugin também trabalha com validações time e date time, nos formatos: 1pm ou 10:11 ou 12:30pm ou 8am e 1 Jan 2006 2pm ou 31/1/06 8:30am.

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

  • Share/Bookmark

Rake listar todas as tasks

Postado em 29 set 2009
Categoria(s) Ruby on Rails

Eu sempre esqueço disso, para listar todas as tasks disponíveis em um projeto Rails digite:

rake -T

Resultado:

rake db:abort_if_pending_migrations          # Raises an error if there are pending migrations
rake db:charset                              # Retrieves the charset for the current environment's database
rake db:collation                            # Retrieves the collation for the current environment's database
rake db:create                               # Create the database defined in config/database.yml for the current RAILS_ENV
rake db:create:all                           # Create all the local databases defined in config/database.yml
rake db:drop                                 # Drops the database for the current RAILS_ENV
rake db:drop:all                             # Drops all the local databases defined in config/database.yml
rake db:fixtures:identify                    # Search for a fixture given a LABEL or ID.
rake db:fixtures:load                        # Load fixtures into the current environment's database.
rake db:migrate                              # Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false.
rake db:migrate:down                         # Runs the "down" for a given migration VERSION.
rake db:migrate:redo                         # Rollbacks the database one migration and re migrate up.
rake db:migrate:reset                        # Resets your database using your migrations for the current environment
rake db:migrate:up                           # Runs the "up" for a given migration VERSION.
rake db:reset                                # Drops and recreates the database from db/schema.rb for the current environment.
rake db:rollback                             # Rolls the schema back to the previous version.
rake db:schema:dump                          # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load                          # Load a schema.rb file into the database
rake db:sessions:clear                       # Clear the sessions table
rake db:sessions:create                      # Creates a sessions migration for use with ActiveRecord::SessionStore
rake db:structure:dump                       # Dump the database structure to a SQL file
rake db:test:clone                           # Recreate the test database from the current environment's database schema
rake db:test:clone_structure                 # Recreate the test databases from the development structure
rake db:test:load                            # Recreate the test database from the current schema.rb
rake db:test:prepare                         # Check for pending migrations and load the test schema
rake db:test:purge                           # Empty the test database
rake db:version                              # Retrieves the current schema version number
rake doc:app                                 # Build the RDOC HTML Files
rake doc:clobber_app                         # Remove rdoc products
rake doc:clobber_plugins                     # Remove plugin documentation
rake doc:clobber_rails                       # Remove rdoc products
rake doc:guides                              # Generate Rails guides
rake doc:plugins                             # Generate documentation for all installed plugins
rake doc:plugins:activerecord_i18n_defaults  # Generate documentation for the activerecord_i18n_defaults plugin
rake doc:plugins:i18n_label                  # Generate documentation for the i18n_label plugin
rake doc:plugins:jrails                      # Generate documentation for the jrails plugin
rake doc:plugins:paperclip                   # Generate documentation for the paperclip plugin
rake doc:plugins:rubyamf                     # Generate documentation for the rubyamf plugin
rake doc:rails                               # Build the RDOC HTML Files
rake doc:reapp                               # Force a rebuild of the RDOC files
rake doc:rerails                             # Force a rebuild of the RDOC files
rake gems                                    # List the gems that this rails application depends on
rake gems:build                              # Build any native extensions for unpacked gems
rake gems:build:force                        # Force the build of all gems
rake gems:install                            # Installs all required gems.
rake gems:refresh_specs                      # Regenerate gem specifications in correct format.
rake gems:unpack                             # Unpacks all required gems into vendor/gems.
rake gems:unpack:dependencies                # Unpacks all required gems and their dependencies into vendor/gems.
rake jrails:install:javascripts              # Installs the jQuery and jRails javascripts to public/javascripts
rake jrails:update:javascripts               # Copies the jQuery and jRails javascripts to public/javascripts
rake log:clear                               # Truncates all *.log files in log/ to zero bytes
rake middleware                              # Prints out your Rack middleware stack
rake notes                                   # Enumerate all annotations
rake notes:custom                            # Enumerate a custom annotation, specify with ANNOTATION=WTFHAX
rake notes:fixme                             # Enumerate all FIXME annotations
rake notes:optimize                          # Enumerate all OPTIMIZE annotations
rake notes:todo                              # Enumerate all TODO annotations
rake paperclip:clean                         # Cleans out invalid attachments.
rake paperclip:refresh                       # Refreshes both metadata and thumbnails.
rake paperclip:refresh:metadata              # Regenerates content_type/size metadata for a given CLASS (and optional ATTACHMENT).
rake paperclip:refresh:thumbnails            # Regenerates thumbnails for a given CLASS (and optional ATTACHMENT).
rake rails:freeze:edge                       # Lock to latest Edge Rails, for a specific release use RELEASE=1.2.0
rake rails:freeze:gems                       # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:template                          # Applies the template supplied by LOCATION=/path/to/template
rake rails:unfreeze                          # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update                            # Update both configs, scripts and public/javascripts from Rails
rake rails:update:application_controller     # Rename application.rb to application_controller.rb
rake rails:update:configs                    # Update config/boot.rb from your current rails install
rake rails:update:generate_dispatchers       # Generate dispatcher files in RAILS_ROOT/public
rake rails:update:javascripts                # Update your javascripts from your current rails install
rake rails:update:scripts                    # Add new scripts to the application script/ directory
rake routes                                  # Print out all defined routes in match order, with names.
rake secret                                  # Generate a crytographically secure secret key.
rake stats                                   # Report code statistics (KLOCs, etc) from the application
rake test                                    # Run all unit, functional and integration tests
rake test:benchmark                          # Run tests for benchmarkdb:test:prepare / Benchmark the performance tests
rake test:functionals                        # Run tests for functionalsdb:test:prepare / Run the functional tests in test/functional
rake test:integration                        # Run tests for integrationdb:test:prepare / Run the integration tests in test/integration
rake test:plugins                            # Run tests for pluginsenvironment / Run the plugin tests in vendor/plugins/*/**/test (or specify with PLUGIN=name)
rake test:profile                            # Run tests for profiledb:test:prepare / Profile the performance tests
rake test:recent                             # Run tests for recentdb:test:prepare / Test recent changes
rake test:uncommitted                        # Run tests for uncommitteddb:test:prepare / Test changes since last checkin (only Subversion and Git)
rake test:units                              # Run tests for unitsdb:test:prepare / Run the unit tests in test/unit
rake time:zones:all                          # Displays names of all time zones recognized by the Rails TimeZone class, grouped by offset.
rake time:zones:local                        # Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time
rake time:zones:us                           # Displays names of US time zones recognized by the Rails TimeZone class, grouped by offset.
rake tmp:cache:clear                         # Clears all files and directories in tmp/cache
rake tmp:clear                               # Clear session, cache, and socket files from tmp/
rake tmp:create                              # Creates tmp directories for sessions, cache, sockets, and pids
rake tmp:pids:clear                          # Clears all files in tmp/pids
rake tmp:sessions:clear                      # Clears all files in tmp/sessions
rake tmp:sockets:clear                       # Clears all files in tmp/sockets

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

  • Share/Bookmark

Ruby on Rails Authlogic com I18n para pt-BR

Postado em 01 set 2009
Categoria(s) Ruby on Rails

Para traduzir as mensagens, campos e modelos do Authlogic para pt-BR basta seguir os passos abaixo:

1) Define o default_locale para pt-BR

Abra o arquivo config/environment.rb, descomente a linha e define o idioma para pt-BR:

...
  # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
  # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
  config.i18n.default_locale = 'pt-BR'
end

2) Crie o arquivo pt-BR.yml

Dentro do diretório config/locales crie o arquivo pt-BR.yml, e adicione o seguinte conteúdo:

pt-BR:
  # Authlogic
  authlogic:
    error_messages:
      login_blank: "não pode ficar em branco"
      login_not_found: "não é válido"
      login_invalid: "deve usar somente letras, números, espaços e .-_@ por favor."
      consecutive_failed_logins_limit_exceeded: "Consecutivos logins que falharam limite excedido, a conta está desativada."
      email_invalid: "deve ser semelhante a um endereço de email."
      password_blank: "não pode ficar em branco"
      password_invalid: "não é válido"
      not_active: "Sua conta não está ativa"
      not_confirmed: "Sua conta não está confirmada"
      not_approved: "Sua conta não foi aprovada"
      no_authentication_details: "Você não forneceu nenhum detalhe para autenticação."
    models:
      user_session: "SessãoUsuário"
    attributes:
      user_session:
        login: "Usuário"
        email: "Email"
        password: "Senha"
        remember_me: "Lembrar me"

3) Reinicie a aplicação

Para garantir que todas as novas configurações sejam carregadas reinicie o servidor web.

4) Opcional: Instale o plugin para traduzir os labels dos formulários

./script/plugin install git://github.com/iain/i18n_label.git

Pronto!

Uma outra sugestão de leitura é: http://blog.patrickespake.com/2009/01/31/ruby-on-rails-22-como-usar-i18n-traduzir-as-mensagens-de-validacao-do-model-e-atributos-do-model/.

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

  • Share/Bookmark

Futuris.tk no ar!

Postado em 19 ago 2009
Categoria(s) Projetos, Ruby on Rails

Pessoal,

Tenho a imensa alegria de dizer que o projeto Futuris.tk está no ar para o público em geral.

Para realizar o seu cadastro visite www.futuris.me ou www.futuris.tk.

Essa aplicação foi construída utilizando Ruby on Rails e participou do TechCrunch50 2009. Ainda está em fase alpha, desta forma você poderá encontrar alguns bugs, caso isso ocorra favor notificar em: http://groups.google.com/group/futuris.

Com o Futuris.tk você pode enviar mensagens para o futuro, você pode enviar para daqui alguns dias, meses ou anos.

Também é possível enviar mensagens só depois que você morrer, você cria as mensagens e quando você morrer seus destinatários as recebem. Esse recurso dá um pouco de medo, mas está lá! o_O

Outro item bacana é o Future Blog, onde você pode tornar pública as suas mensagens recebidas no futuro.

Vou contar mais um item, para não tirar o sabor de você fuçar na aplicação. A Photo Timeline permite que você tire uma foto sua diária e depois veja as suas fotos em cada dia, meses e anos.

O Futuris.tk não está concluído, ainda há muito trabalho, durante os próximos meses vocês terão muitas novidades.

Futuramente vou escrever um post detalhando mais a tecnologia utilizada no projeto.

Por enquanto fico no aguardo das suas sugestões e críticas.

Obrigado pela atenção.
Não esqueça de fazer o seu cadastro no www.futuris.me.
Qualquer detalhe estou aqui.

  • Share/Bookmark