Archive

Archive for the ‘ruby’ Category

Invalid gemspec on what?!

September 14th, 2011 rupert No comments

This belongs to a royal PITA moment, thus needs a worthy post. I’m trying to do a

bundle install

with my Gemfile as follows:

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

At the time of writing this, these are the errors that I encountered. Since you are reading this, then I guess something is still wrong here.

Installing cucumber (1.0.6) 
Installing cucumber-rails (1.0.4) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]
 
Installing database_cleaner (0.6.7) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]
 
Installing orm_adapter (0.0.5) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]
 
Installing warden (1.0.5) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]
 
Installing devise (1.4.5) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]
 
Installing meta_programming (0.2.2) Invalid gemspec in [/Users/rupert/.rvm/gems/ruby-1.9.2-p180@cws/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000104b82a40> 0.7.2"]

Ok, avoid the PITA moment by reading this. And make the changes to the Gemfile like this:

group :development, :test do
  gem 'capybara'
  gem 'cucumber', "1.0.6"
  gem 'cucumber-rails', :git => "https://github.com/cucumber/cucumber-rails.git"
  gem 'database_cleaner'
  gem 'rspec-rails'
  gem 'autotest'
  gem 'spork'
  gem 'launchy'
end

Now, I understand why the commit message is like this: I EAT YAML AND RUBYGEMS FOR toot…

Categories: rails, ruby Tags: , ,

Rails Note #16: rails3, devise, paperclip, uploadify, formtastic

February 10th, 2011 rupert No comments

Setup

dev:rails3 rupert$ rails new photogallery
dev:rails3 rupert$ cd photogallery
dev:photogallery rupert$ rm public/index.html
dev:photogallery rupert$ vim Gemfile 
  1 source 'http://rubygems.org'
  2 
  3 gem 'rails', '3.0.3'
  4 
  5 # Bundle edge Rails instead:
  6 # gem 'rails', :git => 'git://github.com/rails/rails.git'
  7 
  8 gem 'sqlite3-ruby', :require => 'sqlite3'
  9 gem 'devise', :git => "git://github.com/plataformatec/devise.git", :branch => "master"
 10 gem 'formtastic', '~> 1.1.0'
 11 gem 'paperclip'
 12 gem 'mime-types', :require => 'mime/types'

Paperclip needs imagemagick to work. No need to install by source

sudo apt-get install imagemagick
dev:photogallery rupert$ bundle install
Updating git://github.com/plataformatec/devise.git
Fetching source index for http://rubygems.org/
Using rake (0.8.7) 
Using abstract (1.0.0) 
Using activesupport (3.0.3) 
Using builder (2.1.2) 
Using i18n (0.5.0) 
Using activemodel (3.0.3) 
Using erubis (2.6.6) 
Using rack (1.2.1) 
Using rack-mount (0.6.13) 
Using rack-test (0.5.7) 
Using tzinfo (0.3.23) 
Using actionpack (3.0.3) 
Using mime-types (1.16) 
Using polyglot (0.3.1) 
Using treetop (1.4.9) 
Using mail (2.2.14) 
Using actionmailer (3.0.3) 
Using arel (2.0.6) 
Using activerecord (3.0.3) 
Using activeresource (3.0.3) 
Using bcrypt-ruby (2.1.4) 
Using bundler (1.0.7) 
Using orm_adapter (0.0.4) 
Using warden (1.0.3) 
Using devise (1.2.rc) from git://github.com/plataformatec/devise.git (at master) 
Using formtastic (1.1.0) 
Using paperclip (2.3.8) 
Using thor (0.14.6) 
Using railties (3.0.3) 
Using rails (3.0.3) 
Using sqlite3-ruby (1.3.2) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

Devise

dev:photogallery rupert$ rails g devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
 
===============================================================================
 
Some setup you must do manually if you haven't 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>
 
===============================================================================
dev:photogallery rupert$
dev:photogallery rupert$ rails g 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/20110210032416_devise_create_users.rb
      insert    app/models/user.rb
       route  devise_for :users
  1 class User < ActiveRecord::Base
  2   # Include default devise modules. Others available are:
  3   # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  4   devise :database_authenticatable, :registerable,
  5          :recoverable, :rememberable, :trackable, :validatable
  6 
  7   # Setup accessible (or protected) attributes for your model
  8   attr_accessible :email, :password, :password_confirmation, :remember_me
  9 
 10   has_many :pictures
 11 end
dev:photogallery rupert$ vim app/controllers/home_controller.rb
  1 class HomeController < ApplicationController
  2   def index
  3   end
  4 end
dev:photogallery rupert$ mkdir -p app/views/home
dev:photogallery rupert$ vim app/views/home/index.html.erb
  1 <h1>Welcome to Photo Gallery</h1>
  2 <%= render :partial => 'shared/header' %>
dev:photogallery rupert$ mkdir -p app/views/shared
  1 <ul>
  2   <% if user_signed_in? %>
  3     <li><%= link_to "Log Out", destroy_user_session_path %></li>
  4     <li><%= link_to "My Pictures", pictures_path(:user_id => current_user.id) %></li>
  5   <% else %>
  6     <li><%= link_to "Log In", new_user_session_path %></li>
  7     <li><%= link_to "Sign Up", new_user_registration_path %></li>
  8   <% end %>
  9 </ul>
dev:photogallery rupert$ vim config/routes.rb
  1 Photogallery::Application.routes.draw do
  2   devise_for :users
  3 
  4   resources :pictures
  5 
  6   root :to => "home#index"
  7 
  8 end

Paperclip

dev:photogallery rupert$ vim config/environments/development.rb
  1 # Be sure to restart your server when you modify this file.
  1 Photogallery::Application.configure do
  2   # Settings specified here will take precedence over those in config/application.rb
  3 
  4   # In the development environment your application's code is reloaded on
  5   # every request.  This slows down response time but is perfect for development
  6   # since you don't have to restart the webserver when you make code changes.
  7   config.cache_classes = false
  8 
  9   # Log error messages when you accidentally call methods on nil.
 10   config.whiny_nils = true
 11 
 12   # Show full error reports and disable caching
 13   config.consider_all_requests_local       = true
 14   config.action_view.debug_rjs             = true
 15   config.action_controller.perform_caching = false
 16 
 17   # Don't care if the mailer can't send
 18   config.action_mailer.raise_delivery_errors = false
 19 
 20   # Print deprecation notices to the Rails logger
 21   config.active_support.deprecation = :log
 22 
 23   # Only use best-standards-support built into browsers
 24   config.action_dispatch.best_standards_support = :builtin
 25 
 26   Paperclip.options[:command_path] = "/usr/local/ImageMagick/bin"
 27   Paperclip.options[:swallow_stderr] = false
 28 end
 29
dev:photogallery rupert$ rails g model Picture
      invoke  active_record
      create    db/migrate/20110210032526_create_pictures.rb
      create    app/models/picture.rb
      invoke    test_unit
      create      test/unit/picture_test.rb
      create      test/fixtures/pictures.yml
dev:photogallery rupert$ vim db/migrate/20110210032526_create_pictures.rb
  1 class CreatePictures < ActiveRecord::Migration
  2   def self.up
  3     create_table :pictures do |t|
  4       t.string :caption_title
  5       t.text :caption_description
  6       
  7       t.references :user
  8       
  9       t.timestamps
 10     end
 11   end
 12   
 13   def self.down
 14     drop_table :pictures
 15   end
 16 end
dev:photogallery rupert$ rails g migration AddPaperclipToPictures
      invoke  active_record
      create    db/migrate/20110210032654_add_paperclip_to_pictures.rb
dev:photogallery rupert$ vim db/migrate/20110210032654_add_paperclip_to_pictures.rb
  1 class AddPaperclipToPictures < ActiveRecord::Migration
  2   def self.up
  3     add_column :pictures, :image_file_name, :string
  4     add_column :pictures, :image_content_type, :string
  5     add_column :pictures, :image_file_size, :integer
  6     add_column :pictures, :image_updated_at, :datetime
  7   end
  8 
  9   def self.down
 10     remove_column :pictures, :image_file_name
 11     remove_column :pictures, :image_content_type
 12     remove_column :pictures, :image_file_size
 13     remove_column :pictures, :image_updated_at
 14   end
 15 end
dev:photogallery rupert$ vim app/models/picture.rb
  1 class Picture < ActiveRecord::Base
  2   belongs_to :user
  3 
  4   has_attached_file :image,
  5                     :styles => {
  6                       :thumb => ["100x100>", :jpg],
  7                       :pagesize => ["500x400>", :jpg],
  8                     },
  9                     :default_style => :pagesize,
 10                     :url => "/images/photogallery/:id/:style/:basename.:extension",
 11                     :path => "/wwwroot/images/photogallery/:id/:style/:basename.:extension"
 12 
 13   validates_attachment_presence :image
 14   validates_attachment_size :image, :less_than => 10.megabytes
 15 end
dev:images rupert$ mkdir -p /wwwroot/images/photogallery
dev:images rupert$ ln -s /wwwroot/images/photogallery photogallery
dev:photogallery rupert$ rake db:migrate
(in /Volumes/rupert/projects/rails3/photogallery)
==  DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
   -> 0.0084s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0679s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0007s
==  DeviseCreateUsers: migrated (0.0772s) =====================================
 
==  CreatePictures: migrating =================================================
-- create_table(:pictures)
   -> 0.0007s
==  CreatePictures: migrated (0.0008s) ========================================
 
==  AddPaperclipToPictures: migrating =========================================
-- add_column(:pictures, :image_file_name, :string)
   -> 0.0005s
-- add_column(:pictures, :image_content_type, :string)
   -> 0.0003s
-- add_column(:pictures, :image_file_size, :integer)
   -> 0.0003s
-- add_column(:pictures, :image_updated_at, :datetime)
   -> 0.0003s
==  AddPaperclipToPictures: migrated (0.0016s) ================================
dev:photogallery rupert$ rails g controller pictures
      create  app/controllers/pictures_controller.rb
      invoke  erb
      create    app/views/pictures
      invoke  helper
      create    app/helpers/pictures_helper.rb
dev:photogallery rupert$ vim app/controllers/pictures_controller.rb 
  1 class PicturesController < ApplicationController
  2   def index
  3     @user = User.find(params[:user_id])
  4     @pictures = @user.pictures
  5   end
  6 
  7   def create
  8     #You can specify a sleep here to mimic a long response
  9     #sleep 5
 10     newparams = coerce(params)
 11 
 12     current_pictures = Picture.where(:user_id => params[:user_id]).all
 13 
 14     @picture = Picture.new(newparams[:picture])
 15     @picture.user_id = current_user.id
 16 
 17     if @picture.save
 18       flash[:notice] = "Picture was successfully created"
 19 
 20       respond_to do |format|
 21         format.html {redirect_to pictures_path(:user_id => @picture.user_id)}
 22         format.json {render :json => { :result => 'success', :picture => picture_path(@picture) } }
 23       end
 24     else
 25       flash[:alert] = "There is an error in saving the picture."
 26       respond_to do |format|
 27         format.html {redirect_to pictures_path(:user_id => @picture.user_id)}
 28         format.json {render :json => { :result => 'error', :error => flash[:alert] } }
 29       end
 30     end
 31   end
 32   
 33   def show
 34     @picture = Picture.find(params[:id], :include => :user)
 35     @total_pictures = Picture.find(:all, :conditions => { :user_id => @picture.user.id})
 36     render :template => 'pictures/show'
 37   end
 38   
 39   def destroy
 40     picture = Picture.find(params[:id])
 41     user_id = picture.user_id
 42     picture.destroy
 43     flash[:notice] = "Picture was successfully deleted"
 44     redirect_to pictures_path(:user_id => user_id)
 45   end
 46     
 47   private
 48     def coerce(params)
 49       if params[:picture].nil?
 50         h = Hash.new 
 51         h[:picture] = Hash.new
 52         h[:picture][:user_id] = params[:user_id]
 53         h[:picture][:image] = params[:Filedata]
 54         h[:picture][:image].content_type = MIME::Types.type_for(h[:picture] [:image].original_filename).to_s
 55         h
 56       else
 57         params
 58       end 
 59     end
 60 end

Uploadify

dev:photogallery rupert$ vim config/initializers/session_store.rb
  1 # Be sure to restart your server when you modify this file.
  2 
  3 Photogallery::Application.config.session_store :cookie_store, :key => '_photogallery_session'
  4 
  5 # Use the database for sessions instead of the cookie-based default,
  6 # which shouldn't be used to store highly confidential information
  7 # (create the session table with "rails generate session_migration")
  8 # Photogallery::Application.config.session_store :active_record_store
  9 Rails.application.config.middleware.insert_before(
 10   ActionDispatch::Session::CookieStore,
 11   FlashSessionCookieMiddleware,
 12   Rails.application.config.session_options[:key]
 13 )
dev:photogallery rupert$ mkdir app/middleware
dev:photogallery rupert$ vim app/middleware/flash_session_cookie_middleware.rb
  1 require 'rack/utils'
  2  
  3 class FlashSessionCookieMiddleware
  4   def initialize(app, session_key = '_session_id')
  5     @app = app
  6     @session_key = session_key
  7   end
  8  
  9   def call(env)
 10     if env['HTTP_USER_AGENT'] =~ /^(Adobe|Shockwave) Flash/
 11       req = Rack::Request.new(env)
 12       env['HTTP_COOKIE'] = [ @session_key,
 13                              req.params[@session_key] ].join('=').freeze unless req.params[@session_key].nil?
 14       env['HTTP_ACCEPT'] = "#{req.params['_http_accept']}".freeze unless req.params['_http_accept'].nil?
 15     end
 16  
 17     @app.call(env)
 18   end
 19 end
dev:photogallery rupert$ rm -rf public/javascripts/*
dev:photogallery rupert$ cd doc/
dev:doc rupert$ wget http://www.uploadify.com/wp-content/uploads/Uploadify-v2.1.4.zip
--2011-02-10 14:58:26--  http://www.uploadify.com/wp-content/uploads/Uploadify-v2.1.4.zip
Resolving www.uploadify.com... 67.205.57.45
Connecting to www.uploadify.com|67.205.57.45|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 237327 (232K) [application/zip]
Saving to: `Uploadify-v2.1.4.zip'
 
100%[===========================================================================================================================================>] 237,327     88.9K/s   in 2.6s    
 
2011-02-10 14:58:29 (88.9 KB/s) - `Uploadify-v2.1.4.zip' saved [237327/237327]
dev:doc rupert$ unzip Uploadify-v2.1.4.zip
dev:doc rupert$ cd jquery.uploadify-v2.1.4/
 
dev:jquery.uploadify-v2.1.4 rupert$ mkdir -p ../../public/javascripts/uploadify
dev:jquery.uploadify-v2.1.4 rupert$ mkdir -p ../../public/uploadify
 
dev:jquery.uploadify-v2.1.4 rupert$ cp uploadify.css ../../public/stylesheets/
 
dev:jquery.uploadify-v2.1.4 rupert$ cp jquery.uploadify.v2.1.4.js ../../public/javascripts/uploadify/
dev:jquery.uploadify-v2.1.4 rupert$ cp swfobject.js ../../public/javascripts/uploadify/
 
dev:jquery.uploadify-v2.1.4 rupert$ cp -Rf uploadify.swf ../../public/uploadify/
dev:jquery.uploadify-v2.1.4 rupert$ cp -Rf cancel.png ../../public/uploadify/
 
dev:photogallery rupert$ cd ../../public/javascripts/
wget https://github.com/rails/jquery-ujs/raw/master/src/rails.js --no-check-certificate
dev:photogallery rupert$ vim app/views/layouts/pictures.html.erb
  1 <!DOCTYPE html>
  2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3 <head>
  4   <title>Photo Gallery</title>
  5   
  6   <%= stylesheet_link_tag 'formtastic/formtastic' %>
  7   <%= stylesheet_link_tag 'formtastic/formtastic_changes' %>
  8 
  9   <%= stylesheet_link_tag 'uploadify' %>
 10 
 11   <%= javascript_include_tag 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' %>
 12   
 13   <!-- 
 14     Taken from https://github.com/rails/jquery-ujs/raw/master/src/rails.js
 15     Do not remove jquery.rails.js as the delete links will not work 
 16   -->
 17   <%= javascript_include_tag "jquery.rails.js" %>
 18   
 19   <%= csrf_meta_tag %>
 20 </head>
 21 <body>
 22 <div class="container">
 23   <% flash.each do |name, msg| %>
 24     <hr/>
 25     <%= content_tag :div, msg, :class => "flash_#{name}" %>
 26   <% end %>
 27 
 28   <%= render :partial => 'shared/header' %>
 29 
 30   <hr/>
 31 
 32   <%= yield %>
 33 
 34 </div>
 35 
 36 </body>
 37 </html>
dev:photogallery rupert$ vim app/views/pictures/index.html.erb
  1 <h1><%= "Manage #{pluralize(@user.pictures.size, 'Picture')}" %></h1>
  2 
  3   <div class="upload_form">
  4     <%= form_for Picture.new(:user_id => @user.id), :html => {:multipart => true } do |f| %>
  5       <h2>Step 1: Choose your images</h2>
  6       <%= f.file_field :image %>
  7 
  8       <%= f.hidden_field :user_id, "value" => @user.id %>
  9 
 10       <h2>Step 2: Upload</h2>
 11       <%= f.submit 'Upload' %>
 12     <% end %>
 13 
 14     <% if simple_upload_form? %>
 15 
 16       <span class="simple_upload_link">
 17         If you want to see the Browse flash button above, click on the
 18         <%= link_to "Flash Upload", pictures_path(:user_id => @user.id) %>
 19       </span>
 20 
 21     <% else %>
 22 
 23       <!-- Important: Please see uploadify. It contains javascript functions to provide the BROWSE button, submit to a user with content_type json, and process the response. See     more details in uploadify -->
 24       <%= render :partial => "uploadify" %>
 25 
 26       <span class="simple_upload_link">
 27         If you cannot see the Browse flash button above, click on the
 28         <%= link_to "Simple Upload", pictures_path(:user_id => @user.id, :simple => 1) %>
 29       </span>
 30 
 31     <% end %>
 32   </div>
 33 
 34 <div class="clear"></div>
 35 
 36 <hr/>
 37 
 38 <div class="picture_container">
 39   <ul class="thumbs noscript">
 40     <%= render @pictures %>
 41   </ul>
 42 </div>
dev:photogallery rupert$ vim app/views/pictures/_uploadify.html.erb 
  1 <%= javascript_include_tag "uploadify/swfobject.js", "uploadify/jquery.uploadify.v2.1.4.js" %>
  2 
  3 <script type="text/javascript" charset="utf-8">
  4 <%- session_key = Rails.application.config.session_options[:key] -%> 
  5 $(document).ready(function() {
  6   
  7   $('#picture_image').click(function(event){ 
  8     event.preventDefault();
  9   }); 
 10   
 11   $('#picture_image').uploadify({
 12     buttonText: 'Browse',
 13     width: 110,
 14     uploader : '/images/uploadify/uploadify.swf',
 15     cancelImg : '/images/uploadify/cancel.png',
 16     multi : true,
 17     auto : true,
 18     script : 'pictures',
 19     //Function 'onComplete' below will process response from pictures_controller 'create'
 20     //format.json {render :json => { :result => 'success', :picture => admin_picture_path(@picture) } }
 21     onComplete : function(event, queueID, fileObj, response, data) { 
 22       var data = eval('(' + response + ')');
 23       if(data.result == 'success'){
 24         $.getScript(data.picture);
 25       }
 26       else{
 27         alert(data.error);
 28         //We can have a <hr/> before alert or notice using jquery
 29         $('#alert').html(data.error)
 30       }
 31     },
 32     scriptData : {
 33           '_http_accept': 'application/javascript',
 34           'format' : 'json',
 35           '_method': 'post',
 36           '<%= session_key %>' : encodeURIComponent('<%= u cookies[session_key] %>'),
 37           'authenticity_token': encodeURIComponent('<%= u form_authenticity_token %>'),
 38           'user_id' : '<%= @user.id %>'
 39         }
 40   });
 41   
 42   $('#picture_submit').click(function(event){ 
 43       event.preventDefault(); 
 44       $('#upload_photo').uploadifyUpload(); 
 45     });
 46     
 47 }); 
 48 </script>
dev:photogallery rupert$ vim app/helpers/pictures_helper.rb
  1 module PicturesHelper
  2   def simple_upload_form?
  3     if params[:simple] == nil
  4       return false
  5     else
  6       return true
  7     end
  8   end
  9 
 10   def link_to_picture(picture)
 11     link_to(
 12       image_tag( picture.image.url(:thumb), :size => '80x80', :border => 0 ),
 13       picture.image.url(:pagesize),
 14       {
 15         :class => "thumb",
 16         :title => "#{picture.image_file_name}",
 17         :name => "#{picture.image_file_name}",
 18         :rel => "nofollow"
 19       }
 20     )
 21   end
 22 
 23   def link_to_web_photo(photo)
 24     link_to(
 25       image_tag( photo.thumb_path, :size => '80x80', :border => 0 ),
 26       photo.full_path,
 27       {
 28         :class => "thumb",
 29         :title => "#{photo.thumb_path}",
 30         :name => "#{photo.thumb_path}",
 31         :rel => "nofollow"
 32       }
 33     )
 34   end
 35 end
dev:photogallery rupert$ vim app/views/pictures/_picture.html.erb
  1 <li>
  2   <p>
  3     <%= link_to_picture(picture)%><br/>
  4     <%= picture.caption_title %>
  5   </p>
  6   <%= link_to "Delete Picture", picture_path(picture), :confirm => "Are you sure?", :method => :delete %>
  7 </li>
dev:photogallery rupert$ vim app/views/pictures/show.js.erb
  1 $('h1').html('Manage <%= pluralize(@total_pictures.count, "Picture") %>');
  2 $('ul.thumbs').append('<%= escape_javascript(render @picture) %>');
dev:photogallery rupert$ vim app/views/pictures/edit.html.erb
  1 <% title 'Edit Caption' %>
  2 
  3 <%= render "shared/error_messages", :target => @picture %>
  4 
  5 <p style="text-align:center"><%= image_tag @picture.image.url(:pagesize) %></p>
  6 
  7 <%= semantic_form_for @picture do |f| %>
  8   <%= f.inputs do %>
  9     <%= f.input :caption_title %>
 10     <%= f.input :caption_description %>
 11   <% end %>
 12   
 13   <%= f.buttons do %>
 14     <%= f.commit_button %>
 15     <%= f.cancel_button pictures_path(:page_id => @picture.page.id) %>
 16   <% end %>
 17   
 18 <% end %>

Download photogallery.tar.gz

Rails Note #15: Rails 3, Devise, Cucumber

February 9th, 2011 rupert No comments

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: , ,

Rails Note #14: QuickStart Tutorial

February 7th, 2010 rupert No comments

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: , ,