Monday, June 4, 2012

PostgreSQL setup for Rails development in Ubuntu 12.04

Rails comes with SQLite and it works out of the box with no configuration. That's great! but... its not suitable for a production environment so we need another database if your app is to see the light of day.

You could use SQLite in your development environment and switch it up for production, however, it makes far more sense to use the same database in development and production.

My personal preference is to use PostrgreSQL, its open source and gaining traction in the Rails world due to stability and rather nifty features. Heroku also uses PostgreSQL so its a good option if you plan on using their services.

See the excellent PostgreSQL Documentation for more information.

1. Install postgresql and admin tools through the package manager


sudo apt-get install postgresql libpq-dev phppgadmin pgadmin3

Change the postgresql configuration to solve this error
FATAL: Peer authentication failed for user

sudo nano /etc/postgresql/9.1/main/pg_hba.conf

Replace local peer with local md5 in the file. Then reload postgresql to apply the change.

sudo /etc/init.d/postgresql reload


2. Setup your databases from the command line


a) Login to postgresql prompt as the postgres user

sudo su postgres -c psql

b) Create a postgresql user for your project

create user username with password 'password';

TIP: If you are running tests, then to ease permission issues setup your postgres user with the same name and password as your Ubuntu user and make him a postgres superuser ( \du lists users with permissions).

alter user username superuser;


c) Create the development and test databases

create database projectname_development;
create database projectname_test;

d) Give permissions to the user on the databases

grant all privileges on database projectname_development to username;
grant all privileges on database projectname_test to username;

e) Finish your postgresql session

\q

Other useful commands in a postgresql session


Update password

alter user username with password ‘new password’;

Destroy database

drop database projectname;

Connect to specific database

\c databasename

Common MySQL commands with postgresql shortcut

MySQL Postresql
SHOW DATABASES \l
SHOW TABLES \d
SHOW COLUMNS \d table



3. Place a database configuration file in your rails project


Save the code below as app/config/database.yml and rake db:migrate your project

development:
  adapter: postgresql
  encoding: unicode
  database: projectname_development
  pool: 5
  username: username
  password: password

test:
  adapter: postgresql
  encoding: unicode
  database: projectname_test
  pool: 5
  username: username
  password: password




4. Misc Errors encountered


If you are importing data (or using a seed file) then you may run across this error.
PG::Error: ERROR: duplicate key value violates unique constraint "table_name_pkey"

Your import didn’t use the sequence so we need to reset it to be in sync again.

Note when replacing table_name use a plural.

sudo su postgres -c psql
\c database_name
select setval('table_name_id_seq', (select max(id) + 1 from table_name));


Tuesday, May 15, 2012

How to install Rvm, Ruby, and Rails in Ubuntu 12.04

A concise guide to get Rails running locally.

1. Install package dependencies

sudo apt-get install zlib1g zlib1g-dev build-essential
sqlite3 libsqlite3-dev openssl libssl-dev curl git
libmagick++-dev libmagick++4

2. Install rvm from Github source

bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)

3. Reload terminal shell

source /home/ben/.rvm/scripts/rvm

4. Add rvm to bash

echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile

5. Add any additional requirements specified by rvm

rvm requirements
copy / paste any Additional Dependencies: specified in the terminal output into sudo apt-get

6. Install ruby version to rvm

rvm install 1.9.3-p194

*Update rvm and Ruby version (useful to know)
rvm get stable
rvm list known

Troubleshooting
RVM is not a function, selecting rubies with 'rvm use ...' will not work.
Open your Terminal  and select Edit > Preferences > Run command as login shell (make sure it is selected)

7. Setup default ruby version in rvm

rvm use 1.9.3-p194 --default

8. Install rails

gem install rails

9. Install RSpec

gem install rspec

10. Install Bundler

gem install bundler

If you see ERROR: Gem bundler is not installed, run `gem install bundler` first. when running bundle change https://rubygems.org to http://rubygems.org in your Gemfile.

Saturday, May 12, 2012

Sublime Text 2 Setup for Rails

NB: Please see this post for Sublime Text 2 installation

After installing Sublime Text 2 these are the settings I use and packages I install to assist with Ruby on Rails development. Use all or some of these to suit your own needs.

Remove the Minimap 

View > Hide Minimap

Install Package Manager

View > Show console

Copy code below / paste / enter


import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())); open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read()); print 'Please restart Sublime Text to finish installation'

 

Install Ruby / Rails related Packages 

Preferences > Package Control > Package Control:Install Package
  • ERB Insert and Toggle Commands 
  • Rails Related Files 
  • RubyTest 
  • Rspec 
  • Guard 
  • Haml 
  • Sass 
  • Coffeescript 

 

User Settings

Preferences > Settings - User

Copy code below / paste / save

{
"color_scheme": "Packages/Color Scheme - Default/railscasts.tmTheme",
"font_face": "Droid Sans Mono",
"font_size": 12,
"scroll_past_end": false,
"detect_indentation": false,
"tab_size": 2,
"translate_tabs_to_spaces": true,
"trim_trailing_white_space_on_save": true,
"word_wrap": true
}

 

Create a plugin to Open file in browser

Tools > New plugin...

Copy code below / paste / save as OpenBrowser.py

# OpenBrowser.py
import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self,edit):
      url = self.view.file_name()
      webbrowser.open_new(url)

 

Add Keybindings to Open file in new browser and to insert ERB

Tools > Command Palette > "User Key bindings"

Copy code below / paste / save

[
{ "keys": ["ctrl+shift+b"], "command": "open_browser" },
{ "keys": ["ctrl+shift+."], "command": "erb" }
]

 

Monday, May 7, 2012

Sublime Text 2 - Linux Textmate Alternative

There are plenty of editors and IDE's out there for Linux Rubyists and my search was based on an editor that was modern, fast, and a viable alternative to the popular Mac only editor Textmate.

Sublime Text 2 came out on top, as my editor of choice, for its features, speed, and ability to use Textmate themes. Its not perfect or free (price) yet... while its in beta status you are free to use it (with minor nagware). To get started see below or download directly (more detailed setup instructions in my next blog post).

Ubuntu install via the webupd8 maintained repo

sudo add-apt-repository ppa:webupd8team/sublime-text-2
sudo apt-get update
sudo apt-get install sublime-text-2-dev
or
sudo apt-get install sublime-text-2-beta

Install Railscasts theme


Copy
https://raw.github.com/ryanb/textmate-themes/master/railscasts.tmTheme

Place it here
.config/sublime-text-2/Packages/Color Scheme - Default

Select it
Preferences > Color Scheme > railscasts