Archive

Posts Tagged ‘rails’

Rails Note #15: Rails 3, Devise, Cucumber

February 9th, 2011 rupert Comments off

1. Installed rvm (Ruby Version Manager). See Episode 200. Rails3 Beta and RVM

rupert:tsa rupert$ rvm ruby-1.9.2-p0
rupert:tsa rupert$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.5.0]

To use ruby-1.9.2-p0 as default

rupert:rails3 rupert$ rvm ruby-1.9.2-p0 --default
rupert:rails3 rupert$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.5.0]

2. Install rails3

gem install rails

3. Create a rails app tsa (the sample app)

rails new tsa -d mysql

4. Start webrick. Yup, script/server is gone

rupert:tsa rupert$ rails server -e development
=> Booting WEBrick
=> Rails 3.0.3 application starting in production on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-12-06 20:47:27] INFO  WEBrick 1.3.1
[2010-12-06 20:47:27] INFO  ruby 1.9.2 (2010-08-18) [x86_64-darwin10.5.0]
[2010-12-06 20:47:27] INFO  WEBrick::HTTPServer#start: pid=1348 port=3000

Note: Upon checking http://127.0.0.1:3000/ I get a “Routing Error”

5. Update your GemFile with the necessary gems.
Let’s use devise as a login authentication system.

source 'http://rubygems.org'
 
gem 'rails', '3.0.3'
 
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
 
gem 'mysql2'
gem 'devise', :git => "git://github.com/plataformatec/devise.git", :branch => "master"

Then run bundle install. This will install devise gem.

rupert:tsa rupert$ bundle install
Fetching git://github.com/plataformatec/devise.git
remote: Counting objects: 10326, done.
remote: Compressing objects: 100% (3745/3745), done.
remote: Total 10326 (delta 6603), reused 9755 (delta 6163)
Receiving objects: 100% (10326/10326), 1.24 MiB | 314 KiB/s, done.
Resolving deltas: 100% (6603/6603), done.
Fetching source index for http://rubygems.org/

Where are the gems installed?

rupert:tsa rupert$ bundle show devise
/Users/rupert/.rvm/gems/ruby-1.9.2-p0/bundler/gems/devise-b50fd1a72e71

6. Create the necessary databases in mysql. See config/database.yml

CREATE DATABASE tsa_development;

7. Run devise generator.

rupert:tsa rupert$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
 
===============================================================================
 
Some setup you must do manually if you havent yet:
 
  1. Setup default url options for your specific environment. Here is an
     example of development environment:
 
       config.action_mailer.default_url_options = { :host => 'localhost:3000' }
 
     This is a required Rails configuration. In production it must be the
     actual host of your application
 
  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:
 
       root :to => "home#index"
 
  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:
 
       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>
 
===============================================================================

8. Generate a controller in Rails3.

rupert:tsa rupert$ rails generate controller main index
      create  app/controllers/main_controller.rb
       route  get "main/index"
      invoke  erb
      create    app/views/main
      create    app/views/main/index.html.erb
      invoke  test_unit
      create    test/functional/main_controller_test.rb
      invoke  helper
      create    app/helpers/main_helper.rb
      invoke    test_unit
      create      test/unit/helpers/main_helper_test.rb

Update routes.rb for the root_url

  root :to => "main#index"

9. Create a User model with devise.

rupert:tsa rupert$ rails generate devise User
      invoke  active_record
      create    app/models/user.rb
      invoke    test_unit
      create      test/unit/user_test.rb
      create      test/fixtures/users.yml
      create    db/migrate/20101206104321_devise_create_users.rb
      insert    app/models/user.rb
       route  devise_for :users
rupert:tsa rupert$

10. Run migration for User model

rupert:tsa rupert$ export RAILS_ENV=development
rupert:tsa rupert$ rake db:migrate
(in /Users/rupert/projects/rails3/tsa)
==  DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
   -> 0.0805s
-- add_index(:users, :email, {:unique=>true})
   -> 0.1368s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.1484s
==  DeviseCreateUsers: migrated (0.3662s) =====================================

11. Using cucumber

sudo port install libxml2 libxslt

12. Update Gemfile

group :test, :development do
  gem 'rspec'
  gem 'rspec-rails'
  gem 'cucumber'
  gem 'cucumber-rails'
  gem 'capybara'
  gem 'launchy'
end

13. Rspec

rupert:tsa rupert$ rails g rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  autotest
      create  autotest/discover.rb

14. Cucumber

rupert:tsa rupert$ rails g cucumber:install --rspec --capybara
      create  config/cucumber.yml
      create  script/cucumber
       chmod  script/cucumber
      create  features/step_definitions
      create  features/step_definitions/web_steps.rb
      create  features/support
      create  features/support/paths.rb
      create  features/support/env.rb
       exist  lib/tasks
      create  lib/tasks/cucumber.rake
        gsub  config/database.yml
        gsub  config/database.yml
       force  config/database.yml

15. Write your first feature

Feature: Home Page
  In order to make sure the home page works
  As a normal user
  I want to see the home page
 
Scenario: Show Main Sections
  When I go to the home page
  Then show me the page
  Then I should see "Login"

From Harold Jimenez:

“The Given step is where you set up the context of your scenario. Every scenario starts with a blank slate, so it is important to create a state in your application for example by creating data in the database, or by navigating to a specific page.

The When step is where you exercise the application in order to accomplish what needs testing. In the case of a web app like twiddr, this is usually where you fill in forms, press buttons, click links, or otherwise interact with the system in some way.

Finally, the Then step is where you verify the result, and it’s where we check that the correct pages are rendered, that we see a success or error message, or anything that could help us verify that the prior action was successful. As we move along with creating our own features, this will become much clearer.”

16. See it fail in cucumber

rake features  (or)
cucumber (or)
bundle exec cucumber features/home.feature
rupert:tsa rupert$ cucumber
Using the default profile...
F--
 
(::) failed steps (::)
 
Can't find mapping from "the home page" to a path.
Now, go and add a mapping in /Users/rupert/projects/rails3/tsa/tsa/features/support/paths.rb (RuntimeError)
./features/support/paths.rb:26:in `rescue in path_to'
./features/support/paths.rb:20:in `path_to'
./features/step_definitions/web_steps.rb:24:in `/^(?:|I )go to (.+)$/'
features/home.feature:7:in `When I go to the home page'
 
Failing Scenarios:
cucumber features/home.feature:6 # Scenario: Show Main Sections
 
1 scenario (1 failed)
3 steps (1 failed, 2 skipped)
0m0.062s

17. Defining “the home page” in the support/paths.rb

    when /the home page/
      root_path

and in the routes.rb

root :to => "home#index"

Other examples:

when /the profile page for "([^\"]+)"/
  user = User.find_by_twiddr_name!($1)
  user_path(user)

Note: When you see the error

undefined local variable or method `node' for #<Capybara::Driver::RackTest::Node:0x00000101151ad8> (NameError)"

You need to comment in features/support/env.rb

#require 'cucumber/rails/capybara_javascript_emulation'

For more info, read https://rspec.lighthouseapp.com/projects/16211-cucumber/tickets/674

18. Then show me the page will open up the browser

file://localhost/Users/rupert/projects/rails3/tsa/tsa/tmp/capybara/capybara-20101209222149.html

19. Automatic Testing with “autotest”. When you save a file, autotest automatically runs cucumber. To avoid autotest infinite loop with cucumber, make sure your IDE (i.e rubymine) does not save automatically in the file system. You can exclude files and directories from autotest with a “.autotest” file

Autotest.add_hook :initialize do |at|
  at.add_exception(%r{^\./\.git})
  at.add_exception(%r{^\./db})
  at.add_exception(%r{^\./log})
  at.add_exception(%r{^\./tmp})
  at.add_exception(%r{^\./.idea})
  at.add_exception(%r{^\./rerun\.txt})
  at.add_exception(%r{^\./Gemfile\.lock})
end

Now you can run, autotest from the terminal. Save a file and see autotest run.

autotest

20. If you have javascript AJAX calls included in cucumber scenarios, you need to append them with @javascript tag. Below is a sample which selects “Australia” from the “Country” and waits for the ajax request to finish before selecting the “State” drop down. More info on capybara github.

@javascript
Scenario: Creating a Fleet
  And I select "Australia" from "Country"
  And I wait for the ajax request to finish
  And I select "Victoria" from "State"

How does the step “I wait for the ajax request to finish” looks like? http://stackoverflow.com/questions/7286254/cucumber-wait-for-ajaxsuccess

When /^I wait for the ajax request to finish$/ do
  start_time = Time.now
  page.evaluate_script('jQuery.isReady&&jQuery.active==0').class.should_not eql(String) until page.evaluate_script('jQuery.isReady&&jQuery.active==0') or (start_time + 5.seconds) < Time.now
    sleep 1
  end
end
Categories: rails, ruby Tags: , ,

Rails3 Notes

December 19th, 2010 rupert Comments off

Controllers

Note: redirect_to

redirect_to admin_destinations_path( :country_id => @destination.country_id )

Note: Creating a controller under Admin namespace

$ rails generate model Country
$ rails g controller Admin::Countries
      create  app/controllers/admin/countries_controller.rb
      invoke  erb
      create    app/views/admin/countries
      invoke  rspec
      create    spec/controllers/admin/countries_controller_spec.rb
      invoke  helper
      create    app/helpers/admin/countries_helper.rb
      invoke    rspec
      create      spec/helpers/admin/countries_helper_spec.rb

Note: Change class Admin::CountriesController < ApplicationController to use

class Admin::CountriesController < Admin::ApplicationController
  def new
    @country = Country.new
  end
end
 
class Admin::ApplicationController < ApplicationController
  before_filter :authenticate_user!
 
  layout 'admin'  
end

Models

Note: Validation in Rails3

  #(rails2):
  #validates_presence_of :country_name
 
  #(rails3):
  validates :country_name, :presence => true

Note: My foreign key does not save?
When you have an association between models usually defined by foreign keys and sometimes it does not update, make sure you add the key in the model’s :attr_accessible

attr_accessible :destination_name, :description, :country_id, :destination_type_id

SEO Friendly URLS
http://www.seoonrails.com/to_param-for-better-looking-urls.html
http://nithinbekal.com/2010/03/01/rails-seo-friendly-urls-using-to_param/

class Poi < ActiveRecord::Base
  def to_param
    "#{id}-#{name.gsub(/[^a-z0-9]+/i, '-')}"
  end
end

In the view, its still the same:

<%= link_to poi.name, poi %>

Views

Note: Deleting a model from a view from a REST route

This is dependent on prototype or jquery.rails.js

<li><%= link_to "Destroy", admin_poi_path, :confirm => 'Are you sure?', :method => :delete %></li>

The “:delete” is a symbol of HTTP verb (POST, DELETE, PUT). :method => symbol of HTTP verb – This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. Useful for having links perform a POST operation in dangerous actions like deleting a record (which search bots can follow while spidering your site). Supported verbs are :post, :delete and :put. Note that if the user has JavaScript disabled, the request will fall back to using GET. If :href => ‘#’ is used and the user has JavaScript disabled clicking the link will have no effect. If you are relying on the POST behavior, you should check for it in your controller’s action by using the request object’s methods for post?, delete? or put?.

              admin_pois GET    /admin/pois(.:format)                  {:action=>"index", :controller=>"admin/pois"}
                         POST   /admin/pois(.:format)                  {:action=>"create", :controller=>"admin/pois"}
           new_admin_poi GET    /admin/pois/new(.:format)              {:action=>"new", :controller=>"admin/pois"}
          edit_admin_poi GET    /admin/pois/:id/edit(.:format)         {:action=>"edit", :controller=>"admin/pois"}
               admin_poi GET    /admin/pois/:id(.:format)              {:action=>"show", :controller=>"admin/pois"}
                         PUT    /admin/pois/:id(.:format)              {:action=>"update", :controller=>"admin/pois"}
                         DELETE /admin/pois/:id(.:format)              {:action=>"destroy", :controller=>"admin/pois"}

Note: Displaying in_groups_of vertical

http://railscasts.com/episodes/28-in-groups-of

<table cellpadding="2" cellspacing="2">
  <% @destinations.in_groups_of((@destinations.length/3).ceil).transpose.each do |destinations| %>
    <tr>
      <% destinations.each do |destination| %>
        <td>
            <%= render destination %>
        </td>
      <% end %>
    </tr>
  <% end %>  
</table>
 
<% @destinations.in_groups(5, false) do |group| %>
  <ul class="column_list">
    <%= render :partial => "destinations/destination", :collection => group %>
  </ul>
<% end %>

Others

Migrate a mysql to sqlite database

1. Install yaml_db.git from
http://www.kartar.net/2008/08/migrating-a-rails-database-from-sqlite3-to-mysql/

2. Have the mysql database ready. We will configure it on production.

3. config/database.yml

development:
  adapter: sqlite3
  database: db/mytp-1.0.4.db
  pool: 5
  timeout: 5000
 
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000
 
production:
  adapter: mysql
  database: tp_production
  username: rupert
  password: ******
  host: localhost

4. Dump the database from production with rake command below. We should have as output: data.yml
rake db:dump RAILS_ENV=production

5. Load data.yml to SQLite. Ensure you have given a database name for sqlite. We should have as output: mytp-1.0.4.db under db/
rake db:load RAILS_ENV=development

Adding ar_mailer to Rails

1. environment.rb:

  config.gem "adzap-ar_mailer", :lib => 'action_mailer/ar_mailer'
  config.action_mailer.delivery_method = :activerecord
#production mailing settings
ActionMailer::Base.smtp_settings = {
   :address => "127.0.0.1",
   :port => 25,
   :domain => "mytravelphilippines.com",
   :authentication => :login,
   :user_name => "info",
   :password => "******",
}
 
ActionMailer::Base.default_content_type = "text/plain"

2. Emailer.rb is still

class Emailer < ActionMailer::Base

3. Run

rupert@2rmobile:/opt/rails/tp/current$ ar_sendmail -ov
expired 0 emails from the queue
found 1 emails to send
sent email 00000000002 from info@mytravelphilippines.com to rupert@2rmobile.com: #<Net::SMTP::Response:0xb702279c @string="250 Message accepted.\n", @status="250">
Categories: rails Tags: ,

Rails Note #14: QuickStart Tutorial

February 7th, 2010 rupert Comments off

If you haven’t installed ruby, follow this post

Part 1: Installation and Configuration (Rails and Passenger)

1. Upgrade existing ruby gems

sudo gem list
sudo gem update --system

UPDATE: Took me 4 hours figuring this out. There was a problem when i run script/console that it will say the “gem” detected was 1.0.1 although the current gem version is 1.3.5 after gem update –system. Google didn’t helped out. But I was able to nail down the problem from this post:

https://wincent.com/wiki/Upgrading_to_RubyGems_1.0.1_on_Mac_OS_X_10.5.1
In the post above, notice that rubygems 1.0.1 was installed in /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin. I guess this gem was being referenced first before the actual /usr/local/bin/gem. So I deleted this directory /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr.

Possible sources of gem installations:

/Users/rupert/.gem/ruby/1.8/gems
/Library/Ruby/Gems/1.8/gems
rupert:1.8 rupert$ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.5
  - RUBY VERSION: 1.8.6 (2008-08-08 patchlevel 286) [i686-darwin9.5.0]
  - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/1.8
  - RUBY EXECUTABLE: /usr/local/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-darwin-9
  - GEM PATHS:
     - /usr/local/lib/ruby/gems/1.8
     - /Users/rupert/.gem/ruby/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://gems.rubyforge.org/

2. Install rails. Download from ruby-forge. Link?

gem install -V rails-2.3.3.gem
gem install -V mysql

3. Install and configure passenger for Apache2

gem install -V passenger
cd /Users/rupert/.gem/ruby/1.8/gems/passenger-2.2.5/bin
passenger-install-apache2-module
469 LoadModule passenger_module /Users/rupert/.gem/ruby/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
470 PassengerRoot /Users/rupert/.gem/ruby/1.8/gems/passenger-2.2.5
471 PassengerRuby /usr/local/bin/ruby
472 
473 <VirtualHost *:80>
474   RailsBaseURI /rails/travelsiteph
475 </VirtualHost>

4. Create a sample rails project (“travelsiteph”) in your project directory (“/Users/rupert/projects/rails”).

$ cd /Users/rupert/projects/rails
$ rails travelisteph
      create  
      create  app/controllers
      create  app/helpers
      create  app/models
      create  app/views/layouts
      create  config/environments
	.....
$ ls -la travelsiteph
drwxr-xr-x  15 rupert  admin    510  2 Sep 21:14 .
drwxr-xr-x   5 rupert  admin    170 30 Sep 16:31 ..
-rw-r--r--   1 rupert  admin  10011  2 Sep 21:14 README
-rw-r--r--   1 rupert  admin    307  2 Sep 21:14 Rakefile
drwxr-xr-x   6 rupert  admin    204  2 Sep 21:14 app
drwxr-xr-x   9 rupert  admin    306  2 Sep 21:14 config
drwxr-xr-x   4 rupert  admin    136  2 Sep 21:18 db
drwxr-xr-x   3 rupert  admin    102  2 Sep 21:14 doc
drwxr-xr-x   3 rupert  admin    102  2 Sep 21:14 lib
drwxr-xr-x   6 rupert  admin    204  2 Sep 21:14 log
drwxr-xr-x  11 rupert  admin    374  2 Sep 21:14 public
drwxr-xr-x  11 rupert  admin    374  2 Sep 21:14 script
drwxr-xr-x   8 rupert  admin    272  2 Sep 21:55 test
drwxr-xr-x   6 rupert  admin    204  2 Sep 22:07 tmp
drwxr-xr-x   3 rupert  admin    102  2 Sep 21:14 vendor

I have /wwwroot as my document WebRoot. Its running cf, php and mapserv (cgi-bin). Since I want to mix it with rails development, I’ll just make a rails subdirectory. Inside the rails subdirectory, I can create symbolic links to my rails applications located in my projects directory. This way, rails configuration is not exposed from Apache.

cd /wwwroot
mkdir rails
ln -s /Users/rupert/projects/rails/travelsiteph/public travelsiteph
 
$ ls -la
total 8
drwxr-xr-x   3 rupert  admin   102  2 Sep 14:09 .
drwxrwxr-x  60 root    admin  2040  2 Sep 14:08 ..
lrwxr-xr-x   1 rupert  admin    42  2 Sep 14:09 travelsiteph -> /Users/rupert/projects/rails/travelsiteph/public

5. Restart Apache to take the new configuration

sudo /Library/StartupItems/Apache2/Apache2 restart

6. Open http://127.0.0.1/rails/travelsiteph/

But for development purposes, it is better to use http://127.0.0.1:3000/ to see immediately any changes in code.

rails.png

Part 2: Rails Development
MySQL Prerequisites:

GRANT ALL PRIVILEGES ON *.* TO rupert@'%' IDENTIFIED BY '*************' WITH GRANT OPTION;
$ mysql -u rupert -p

1. Create three databases:

mysql> CREATE DATABASE travelsiteph_development;
Query OK, 1 row affected (0.00 sec)
 
mysql> CREATE DATABASE travelsiteph_test;
Query OK, 1 row affected (0.00 sec)
 
mysql> CREATE DATABASE travelsiteph_deployment;
Query OK, 1 row affected (0.00 sec)

2. Launch Textmate

cd /Users/rupert/projects/rails/travelsiteph
mate .

3. Edit database.yml

development:
  adapter: mysql
  database: travelsiteph_development
  username: root
  password: xxxxxxx
  host: localhost
 
test:
  adapter: mysql
  database: travelsiteph_test
  username: root
  password: xxxxxxx
  host: localhost
 
production:
  adapter: mysql
  database: travelsiteph_deployment
  username: root
  password: xxxxxxx
  host: localhost

4. Generate a Poi model. The model should be capitalized and singular.

$ ruby script/generate model Poi
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/poi.rb
      create  test/unit/poi_test.rb
      create  test/fixtures/pois.yml
      create  db/migrate
      create  db/migrate/20090902111538_create_pois.rb

5. Now let’s create the database table for Poi using migrations.

class Poi < ActiveRecord::Migration
  def self.up
    create_table :pois, :id => :poi_id do |t|
      t.column :name, :string
      t.column :full_address, :string
      t.column :location, :string
      t.column :get_there, :string
      t.column :short_description, :string
      t.column :full_description, :text
      t.column :other_info, :text
      t.column :tel_no, :string
      t.column :fax_no, :string
      t.column :mobile_no, :string
      t.column :email, :string
      t.column :website, :string
      t.column :other_contact_details, :text
      t.column :longitude, :decimal, :precision => 10, :scale => 7
      t.column :latitude, :decimal, :precision => 10, :scale => 7
      t.column :created_at, :timestamp
      t.column :updated_at, :timestamp
      t.timestamps
    end
  end
 
  def self.down
    drop_table :pois
  end
end
$ rake db:migrate
(in /Users/rupert/projects/rails/travelsiteph)
==  CreatePois: migrating =========================================
-- create_table(:point_of_interests, {:id=>:poi_id})
   -> 0.0353s
==  CreatePois: migrated (0.0362s) ================================

6. Generate a Poi controller.

$ script/generate controller Poi
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/poi
      create  test/functional/
      create  test/unit/helpers/
      create  app/controllers/poi_controller.rb
      create  test/functional/poi_controller_test.rb
      create  app/helpers/poi_helper.rb
      create  test/unit/helpers/poi_helper_test.rb

7. Add a list function to Poi Controller

class PoiController < ApplicationController
  def list
    @pois = Poi.find(:all)
  end
end

8. Lets test. Open a browser and point to http://127.0.0.1:3000/travelsiteph/poi/list

$ruby script/server

9. Now create the view list.rhtml in views/poi/

<% if @pois.blank? %>
 
	<p>There are currently no pois in the system. </p>
 
<% else %>
 
	<p>These are the pois in the system: </p>
 
	<ul>
		<% @pois.each do |poi| %>
			<li><%= link_to poi.name, {:action => 'show', :id => poi.id} -%></li>
		<% end %>
	</ul>
 
<% end %>

Part 3: Deploying
1. set RAILS_ENV to production

export RAILS_ENV=production

2. Make sure to populate the database in production mode, run rake db:migrate

3. Capistrano

set :port, 2210
set :application, "halalan2010"
#set :repository,  "svn+ssh://2rmobile.com/data/repos/web/rails/halalan2010/"
set :repository,  "http://2rmobile.com/repos/web/rails/halalan2010/"
 
set :scm, :subversion
set :scm_username, 'rupert'
set :scm_password, proc{Capistrano::CLI.password_prompt('SVN pass:')}
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`, `subversion` or `none`
 
role :web, "2rmobile.com" # IP Your HTTP server, Apache/etc
role :app, "2rmobile.com" # This may be the same as your `Web` server
role :db,  "2rmobile.com", :primary => true # This is where Rails migrations will run
#role :db,  "your slave db-server here"
 
set :user,  "rupert"
set :runner, "rupert"
set :deploy_to, "/opt/rails/#{application}"
 
# If you are using Passenger mod_rails uncomment this:
# if you're still using the script/reapear helper you will need
# these http://github.com/rails/irs_process_scripts
 
namespace :deploy do
  task :start do
    run "/etc/init.d/apache2 start"
  end
  task :stop do
    run "/etc/init.d/apache2 stop"
  end
  task :restart, :roles => :app, :except => { :no_release => true } do
     run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
  end
  task :production do
    run "export RAILS_ENV=production"
  end
end
 
namespace :db do
  task :seed do
    run "cd #{deploy_to}/current && RAILS_ENV=production rake db:seed"
  end
  task :populate do
    run "cd #{deploy_to}/current && RAILS_ENV=production rake db:populate"
  end
end

Capistrano commands I normally use:

#on local
#cap deploy:setup
 
#on remote and change owner and permissions of project
sudo chown -Rf rupert:root halalan2010
 
#on local
#cap deploy
#cap db:seed
#cap db:populate

Part 4: Miscellaneous

1. Get a description or rake commands

rake -D db

2. How to populate the database in production mode?

rupert:halalan2010 rupert$ export RAILS_ENV=production
rupert:halalan2010 rupert$ rake db:migrate
(in /Users/rupert/projects/rails/halalan2010)
==  CreateDatabase: migrating =================================================
-- create_table(:candidates)
   -> 0.0036s
-- create_table(:voters)
   -> 0.0031s
-- create_table(:votes)
   -> 0.0027s
==  CreateDatabase: migrated (0.0100s) ========================================

http://blog.airbladesoftware.com/2009/4/10/avoid-typing-rails_env-all-the-time

3. Uninstall specific gem version

gem uninstall activesupport -v 2.2.2

4 Add a source to gem

rupert:rails rupert$ sudo gem sources -a http://gems.github.com
http://gems.github.com added to sources

5. Adding a rails project in svn

#create a remote dir
svn mkdir http://www.2rmobile.com/repos/web/rails/virginmobilechecker
 
#checkout and copy all files
cd ~/projects/rails
mv virginmobilechecker virginmobilechecker_old
svn co "svn+ssh://2rmobile.com/data/repos/web/rails/virginmobilechecker" virginmobilechecker
mv virginmobilechecker_old/* virginmobilechecker/
cd virginmobilechecker
svn add *
 
#ignoring log files
svn revert log/*
svn propset svn:ignore "*.log" log
svn propset svn:ignore "*" tmp
svn propset svn:ignore "*" doc
 
#commit the files
svn commit -m "first commit" *
Categories: rails, ruby Tags: ,

TextMate CheatSheet (Updated)

August 2nd, 2009 rupert Comments off

Shortcuts

Ruby:
---------------------------------
:key => "value" - : + tab
 
Navigate:
---------------------------------
go to file - cmd - t
tab to file (left|right) - opt + cmd + (left arrow|right arrow)
select bundle item - ctrl + cmd + t
navigate (from controller to view) - opt + cmd + down arrow
show methods - shift + cmd + t
 
Views:
---------------------------------
create partial - ctrl + shift + H
render partial (object|collection|locals) - r + p + (o|c|l)
inserting an erb tag <%=  %> or <% %> - ctrl + shift + . (cycle)
code completion, <h3>foo</h3> - opt + cmd + .
 
2RMobile Snippets:
---------------------------------
<% objects.each do |object| %>		2rmloope
	<%= object. %>
<% end %>

* Make the project drawer appear on the left or right.

From the menubar select View, then Hide Project Drawer.

Move your TextMate editor window over to the left side of the screen so the project gutter won’t have enough room to open up on that side. (You can move the window all the way to the left if you want, but you don’t need to go that far.)

Select View, then Show Project Drawer, and the drawer will now open on the right side of your TextMate editor.

* Plugins directory is located at

1. /Applications/TextMate.app/Contents/PlugIns/
2. /Users/rupert/Library/Application Support/

http://manual.macromates.com/en/bundles#support_folder

* Installing a bundle.
RubyOnRails Bundle: https://github.com/drnic/ruby-on-rails-tmbundle
RSpec Bundle: https://github.com/rspec/rspec-tmbundle
Cucumber Bundle: https://github.com/aslakhellesoy/cucumber-tmbundle

mkdir -p ~/Library/Application\ Support/TextMate/Bundles
cd ~/Library/Application\ Support/TextMate/Bundles
git clone git://github.com/drnic/ruby-on-rails-tmbundle.git "Ruby on Rails.tmbundle"

Launch TextMate > Bundles > Bundle Editor > “Reload Bundles”

* Identify *.html.erb to open in HTML(Rails)
Read http://blog.macromates.com/2007/file-type-detection-rspec-rails/

rupert:blog rupert$ defaults read com.macromates.textmate OakLanguageFileBindings
(
        {
        fileTypes =         (
            txt
        );
        language = "17994EC8-6B1D-11D9-AC3A-000D93589AF6";
        name = HTML;
    },
        {
        fileTypes =         (
            builder,
            rb,
            erb
        );
        language = "54D6E91E-8F31-11D9-90C5-0011242E4184";
        name = "Ruby on Rails";
    }
)
rupert:blog rupert$ defaults delete com.macromates.textmate OakLanguageFileBindings

* Identify Gemfiles in TextMate for Ruby on Rails
Read http://efreedom.com/Question/1-3174451/Bundler-Gemfile-Syntax-Highlight-Text-Mate

Include the ‘Gemfile’ as a filetype

fileTypes = ( 'rb', 'rxml', 'builder', 'Gemfile' );

* Soft Tabs and Spaces in TextMate
To turn on soft tabs (bottom of the window, in the tab size selector). This will insert spaces instead of tabs, so there won’t be anything to convert when it’s time to save
Source: http://old.nabble.com/Convert-tabs-to-spaces-when-saving–td28891731.html

Categories: osx, rails, ruby Tags: , ,

Rails Note #13: RubyonRails + Oracle on Linux (i386 / x64)

December 11th, 2008 rupert Comments off

In summary, install Oracle Instant Client and try to run sqlplus. If sqlplus connects to the oracle sid then go ahead and install the rails adapters for oracle. What is important to note here, is to install the oracle-instantclient for the architecture of your machine.. I have tested this on Debian Lenny (i386) and CentOS5 (x64)

1. Download from http://www.oracle.com/technology/software/tech/oci/instantclient/

a. oracle-instantclient-basic-10.2.0.4-1.i386
b. oracle-instantclient-devel-10.2.0.4-1.i386
c. oracle-instantclient-sqlplus-10.2.0.4-1.i386

2. Unzip everything to /opt/oracle/instantclient . You should have something like the ff:

[root@csapp1 instantclient]# ls -la
total 102704
drwxr-xr-x 3 root root     4096 Dec 10 21:54 .
drwxr-xr-x 3 root root     4096 Dec 10 22:03 ..
-rw-r--r-- 1 root root      228 Dec 10 21:52 BASIC_README
-r--r--r-- 1 root root  1609607 Dec 10 21:52 classes12.jar
-rwxr-xr-x 1 root root    67542 Dec 10 21:52 genezi
-r--r--r-- 1 root root     1525 Dec 10 21:52 glogin.sql
lrwxrwxrwx 1 root root       17 Dec 10 21:54 libclntsh.so -> libclntsh.so.10.1
-rwxr-xr-x 1 root root 21038613 Dec 10 21:52 libclntsh.so.10.1
-r-xr-xr-x 1 root root  3796601 Dec 10 21:52 libnnz10.so
-rwxr-xr-x 1 root root  1664116 Dec 10 21:52 libocci.so.10.1
-rwxr-xr-x 1 root root 72674185 Dec 10 21:52 libociei.so
-r-xr-xr-x 1 root root   138033 Dec 10 21:52 libocijdbc10.so
-r-xr-xr-x 1 root root  1435561 Dec 10 21:52 libsqlplusic.so
-r-xr-xr-x 1 root root   997409 Dec 10 21:52 libsqlplus.so
-r--r--r-- 1 root root  1555682 Dec 10 21:52 ojdbc14.jar
drwxr-xr-x 4 root root     4096 Dec 10 21:52 sdk
-r-xr-xr-x 1 root root     7773 Dec 10 21:52 sqlplus
-rw-r--r-- 1 root root      232 Dec 10 21:52 SQLPLUS_README
-rw-r--r-- 1 root root      516 Dec 10 21:53 tnsnames.ora
[root@csapp1 instantclient]#

3. Make a symbolic link for libclntsh.so.10.1 as shown above.

4. Create the Oracle Environment variables

export ORACLE_HOME=/opt/oracle/instantclient
export TNS_ADMIN=$ORACLE_HOME
export LD_LIBRARY_PATH=$ORACLE_HOME:$LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=$ORACLE_HOME
export PATH=$PATH:$ORACLE_HOME

5. At this point, you should have oracle-instantclient properly installed. You can test by running sqlplus.

[root@csapp1 instantclient]# sqlplus
 
SQL*Plus: Release 10.2.0.4.0 - Production on Thu Dec 11 11:47:40 2008
 
Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.

NOTE: Sometimes you will get a SEGMENTATION FAULT. If so, try to open a new shell with the environment variables loaded and do an sqlplus in a directory which is not /opt/oracle/instantclient.

6. Install the oracle adapter for rails

7. gem install ruby-oci8

8. gem install oracle_enhanced-adapter –source=”http://gems.rubyonrails.org/”

activerecord-oracle-adapter (1.0.0.9250)
activerecord-oracle_enhanced-adapter (1.1.8)

NOTE: Try to look for the latest gems, the source above is at the time of this writing so it might change.

9. Test using irb

[root@csapp1 instantclient]# irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'oci8'
=> true
irb(main):003:0>
Categories: debian, linux, oracle, rails, ruby Tags: , , ,