Posts Tagged ‘bash’

Instalação do PostgreSQL

Postado em 09 nov 2009
Categoria(s) PostgreSQL

Instalação

Para instalar o PostgreSQL no Ubuntu digite o comando:

sudo apt-get install postgresql-common postgresql-8.3 postgresql-client-8.3

Mudando a senha do usuário postgres

sudo su postgres psql

No console do psql

ALTER USER postgres WITH PASSWORD 'postgres';
\q

Configurando o postgresql.conf

sudo vi /etc/postgresql/8.3/main/postgresql.conf

Localizar a linha:

listen_addresses = 'localhost'

e mudar para:

listen_addresses = '*'

remova o carácter de comentário (#) da linha.

A opção listen_addresses permite definir qual host pode se conectar no servidor, exemplo: localhost somente para conexões locais, * para qualquer host ou um ip específico como: 192.168.1.236.

Configurando pg_hba.conf

sudo vi /etc/postgresql/8.3/main/pg_hba.conf

Adicionar no fim do arquivo a linha:

host all all 192.168.1.0/24 md5

Essa configuração específica na ordem:

  • host: Define regras para o protocolo TCP/IP, essa opção pode ser host, local ou hostssl;
  • all: Define qual banco de dados que essa regra se aplica, se definindo all será para todos;
  • all: Define qual usuário tem permissão para usar essa regra, se definido all será para todos;
  • 192.168.1.0/24: Padrão CIDR, define qual faixa de ip’s podem ser conectar no servidor através do padrão CIDR;
  • md5: Método de autenticação, md5 padrão, trust para aceitar, reject para negar e mais algumas outras opções.

Reiniciar o PostgreSQL

sudo /etc/init.d/postgresql-8.3 restart

Usuários de banco de dados

Criar um novo usuário. Para pode criar um novo usuário é necessário estar logado com o usuário postgres.

sudo su postgres

Existem duas formas de criar e deletar um usuário, uma através do shell e outra através do cliente postgre.

Via Shell

createuser patrick

Via cliente postgres

psql
CREATE USER patrick;

As duas opções criam patrick como superusuário.

Exemplos:

Definindo password

CREATE USER patrick PASSWORD '123';

Definindo privilégios de superusuário, permissão para criar databases e roles:

CREATE USER patrick SUPERUSER INHERIT CREATEDB CREATEROLE;

Mais informações: http://pgdocptbr.sourceforge.net/pg80/sql-createuser.html.

Deletar usuário

Via Shell:

dropuser patrick

Via cliente postgres:

psql
DROP USER patrick;

Alterar usuário:

ALTER USER patrick PASSWORD ‘teste123′;

Mais detalhes: http://pgdocptbr.sourceforge.net/pg80/sql-alteruser.html.

  • 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

Ubuntu resolvendo problema de locale: perl: warning: Please check that your locale settings

Postado em 25 set 2009
Categoria(s) Ubuntu

Para resolver o problema:

perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
        LANGUAGE = (unset),
        LC_ALL = (unset),
        LANG = "pt_BR.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory

Siga os passos abaixo:

No terminal digite:

sudo apt-get install --reinstall language-pack-en
sudo apt-get install --reinstall language-pack-pt
sudo locale-gen
sudo dpkg-reconfigure locales

Pra mim resolveu! :)

  • Share/Bookmark

Ruby on Rails plugin tableless_model

Postado em 11 ago 2009
Categoria(s) Plugins, Ruby on Rails

tableless_model

Ruby on Rails model sem banco de dados, com todo o poder do ActiveRecord e validações.

A principal utilidade é usar em formulários que não precisam de banco de dados, mas precisam das validações do ActiveRecord, form_for e rotas RESTful. Por exemplo formulário de contato.

Instalação

./script/plugin install git://github.com/patrickespake/tableless_model.git

Geradores

Gerador tableless_model

Cria o esboço de um novo tableless model. Passe o nome do tableless model, em CamelCased ou under_scored, e uma lista de pares de atributos opcionais como argumentos.

Os atributos pares opcionais são column_name:sql_type como argumentos, especificando os atributos do tableless model.

Você não tem que pensar em cada atributos lá na frente, mas ajuda a esboçar um pouco para que você possa começar a trabalhar com o tableless model imediatamente.

Isto gera uma classe tableless model em app/models, um teste de unidade em test/unit e uma fixture em test/fixtures/singular_name.yml

Exemplos:

./script/generate tableless_model contact

Cria o tableless model Contact, test e fixture:

  • Model: app/models/contact.rb
  • Test: test/unit/contact_test.rb
  • Fixtures: test/fixtures/contacts.yml
./script/generate tableless_model invite name:string body:text email:string

Cria o tableless model Invite com a string name, text body e string email.

Gerador tableless_scaffold

Tableless scaffolds é composto por vários recursos, a partir do model, controller e views, juntamente com um conjunto completo de testes. O recurso está pronto para ser usado como um ponto de partida, sendo RESTful, orientado para o pedido.

Passe o nome do tableless model (na forma singular), em CamelCased ou under_scored, como primeiro argumento, e uma lista de pares de atributos opcionais.

Os pares de atributos opcionais são column_name:sql_type, especificando os atributos do modelo.

Você não tem que pensar em cada atributo lá na frente, mas ajuda esboçar um pouco para que você possa começar a trabalhar com os recursos imediatamente.

Por exemplo ‘tableless_scaffold contact name:string telephone:string firm:string email:string message:text’ dá-lhe um tableless model com cinco atributos, um controlador para lidar com a criação, formulário para criar os contatos e routas declaradas em config/routes.rb.

Se você quiser remover todos os arquivos gerados, execute:

script/destroy scaffold ModelName

Exemplos:

./script/generate tableless_scaffold invite
./script/generate tableless_scaffold contact name:string telephone:string firm:string email:string message:text

Tipos de colunas disponíveis nos tableless_models

1
2
3
4
5
6
7
class ModelName < TablelessModel
  column :column_name1, :column_type
  column :column_name2, :column_type
  column :column_name3, :column_type
  column :column_nameN, :column_type
  ...
end

Tipos de colunas (column_type) disponíveis:

  • :string
  • :text
  • :integer
  • :float
  • :decimal
  • :datetime
  • :timestamp
  • :time
  • :date
  • :binary
  • :boolean

Validações do ActiveRecord funcionam perfeitamente

1
2
3
4
5
6
7
8
9
10
11
class Contact < TablelessModel
  column :name, :string
  column :telephone, :string
  column :firm, :string
  column :email, :string
  column :message, :text
 
  validates_presence_of :name, :email, :message
  validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  validates_length_of :message, :minimum => 3
end

Exemplo completo usando tableless_scaffold gerador

Criar o tableless scaffold

./script/generate tableless_scaffold contact name:string telephone:string firm:string email:string message:text

Adicionar as validações no model

Abra o arquivo app/models/contact.rb e adicione as validações:

1
2
3
4
5
6
7
8
9
10
11
12
class Contact < TablelessModel
  column :name, :string
  column :telephone, :string
  column :firm, :string
  column :email, :string
  column :message, :text
 
  # Validations
  validates_presence_of :name, :email, :message
  validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  validates_length_of :message, :minimum => 3
end

Execute

./script/server

Abra o seu navegador em: http://localhost:3000/contacts/new

Exemplo completo usando tableless_model gerador

Criar tableless model

./script/generate tableless_model contact name:string telephone:string firm:string email:string message:text

Adicionar as validações no model

Abra o arquivo app/models/contact.rb e adicione as validações:

1
2
3
4
5
6
7
8
9
10
11
12
class Contact < TablelessModel
  column :name, :string
  column :telephone, :string
  column :firm, :string
  column :email, :string
  column :message, :text
 
  # Validations
  validates_presence_of :name, :email, :message
  validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  validates_length_of :message, :minimum => 3
end

Criar o controlador

./script/generate controller contacts new create

Adicionar os códigos das actions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ContactController < ApplicationController
  def new
    @contact = Contact.new
  end
 
  def create
    @contact = Contact.new(params[:contact])
 
    if @contact.save # or @contact.valid?
      flash[:notice] = "Contact email sent successfully."
 
      # Send contact email
      #MyMailer.deliver_contact(@contact)
 
      redirect_to new_contact_path
    else
      render :action => "new"
    end
  end
end

Criar as routas para os contacts

Abra o arquivo config/routes.rb e adicione a linha:

1
2
3
4
ActionController::Routing::Routes.draw do |map|
  map.resources :contacts, :only => [:new, :create]
  ...
end

Criar o formulário de contato

Abra o arquivo app/views/contacts/new.html.erb e adicione o conteúdo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<% form_for(@contact) do |f| %>
  <%= f.error_messages %>
 
  <%= f.label :name %>
  <%= f.text_field :name %>
 
  <%= f.label :telephone %>
  <%= f.text_field :telephone %>
 
  <%= f.label :firm %>
  <%= f.text_field :firm %>
 
  <%= f.label :email %>
  <%= f.text_field :email %>
 
  <%= f.label :message %>
  <%= f.text_area :message %>
 
  <%= f.submit "Send" %>
<% end %>

Apague o arquivo app/views/contacts/create.html.erb.

Execute

./script/server

Abra o seu navegador em: http://localhost:3000/contacts/new

Documentação

http://lab.patrickespake.com/tableless_model

Código fonte

http://github.com/patrickespake/tableless_model

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

  • Share/Bookmark