Skip to content

Instantly share code, notes, and snippets.

@danielres
Created January 9, 2011 23:32
Show Gist options
  • Save danielres/772145 to your computer and use it in GitHub Desktop.
Save danielres/772145 to your computer and use it in GitHub Desktop.
random personal notes and reminders related to my funny adventures with Rails
# inheritance in yml files:
development: &defaults
adapter: mysql
encoding: utf8
database: acme_development
username: root
test:
<<: *defaults
database: acme_test
cucumber:
<<: *defaults
database: acme_cucumber
# based on: http://handyrailstips.com/tips/14-drying-up-your-ruby-code-with-modules
# in model User:
class User < ActiveRecord::Base
include SpaceStripper
end
# in model Comment:
class Comment < ActiveRecord::Base
include SpaceStripper
end
# in lib/space_stripper.rb:
module SpaceStripper
before_save :strip_spaces_from_name
def strip_spaces_from_name
name = self.name.strip
end
end

DRY with block helpers:

source: github.com/markevans/block_helpers article: blog.new-bamboo.co.uk/2009/8/14/block-helpers

In Gemfile

gem "block_helpers"

In application_helper.rb

class MyBlockHelper < BlockHelpers::Base
  def hello(name)
    "<div style='background: gray'><i>Hi there #{name}!</i></div>" 
  end

  def to_s
  end

  def display(body)
    raw %(
      <div class="tl">
        <div class="tr">
          <div class="bl">
            <div class="br">
              #{body}
            </div>
          </div>
        </div>
      </div>
    )
  end    

end

In view.html.haml

=my_block_helper do |h|
  Here goes
  = h.hello('Marmaduke')
  hooray!

Result

<div class="tl">
  <div class="tr">
    <div class="bl">
      <div class="br">
        Here goes
          <div style="background: gray"><i>Hi there Marmaduke!</i></div>
        hooray!
      </div>
    </div>
  </div>
</div>
# run this script in the rails project folder, and all erb files will be converted to haml
# erb files are not removed, you'll have to delete the manually
class ToHaml
def initialize(path)
@path = path
end
def convert!
Dir["#{@path}/**/*.erb"].each do |file|
`html2haml -rx #{file} #{file.gsub(/\.erb$/, '.haml')}`
end
end
end
path = File.join(File.dirname(__FILE__), 'app', 'views')
ToHaml.new(path).convert!
# In config/routes.rb :
scope ':locale', :locale => /en|fr|es|nl/ do
resources :movies
end
# In app/controllers/application_controller.rb :
before_filter :set_locale
def set_locale
I18n.locale = params[:locale]
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{ :locale => I18n.locale }
end
class Product < ActiveRecord::Base
validates :title, :description, :image_url, :presence => true
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
validates :image_url, :format => {
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG or PNG image.'
}
end
# usage:
# curl https://gist.github.com/raw/772145/railsapp_generator.sh | bash -s {APPNAME}
APP=$1
mkdir $APP
cd $APP
gem install rails --no-rdoc --no-ri
rails new . -T # note: -T switch removes the Test::Unit stuff
rvm gemset create $APP
echo "rvm ruby-1.9.2-p0@$APP" > .rvmrc
echo "export rvm_pretty_print_flag=1" >> .rvmrc
rvm use 1.9.2-p0@$APP
gem install bundler --no-rdoc --no-ri
echo "
#views -------------
gem 'haml-rails'
gem "jquery-rails"
#gem 'compass'
gem 'formtastic'
gem 'will_paginate'
gem 'block_helpers'
#sys ---------------
gem 'capistrano'
gem 'mysql2'
gem 'thin'
#auth --------------
gem 'devise'
gem 'hpricot' # required by devise
gem 'ruby_parser' # required by devise
#admin -------------
# gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'
#dev ---------------
group :development, :test do
gem 'rspec-rails'
gem 'autotest-rails' # see: https://gist.github.com/365816
gem 'autotest'
gem 'cucumber-rails'
gem 'database_cleaner'
gem 'webrat'
gem 'selenium-client'
# using test_notifier: https://github.com/fnando/test_notifier
end
" >> Gemfile
"
Autotest.add_hook :initialize do |autotest|
%w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|
autotest.add_exception(exception)
end
end
" >> .autotest
git init .
echo "bundle in 5 seconds"; sleep 1s
echo "bundle in 4 seconds"; sleep 1s
echo "bundle in 3 seconds"; sleep 1s
echo "bundle in 2 seconds"; sleep 1s
echo "bundle in 1 second"; sleep 1s
bundle install
echo "
next steps:
-----------
rails g rspec:install
rails g cucumber:install
rails g formtastic:install
rails g jquery:install
"
# source: http://groups.google.com/group/refinery-cms/browse_thread/thread/35f962b53b5bed74#
# The plans for Refinery? You can either install the refinery gem and ask it to generate you an application using:
# $ refinerycms /path/to/my/app
# or you can plug it into an existing Rails application by putting this in your Gemfile:
gem 'refinerycms', :git => 'git://github.com/resolve/refinerycms.git', :branch => 'master'
# Then run:
# $ bundle install
# $ rails generate refinerycms
# $ rake db:migrate
# $ rake db:seed # (optional)
# usage: rake db:seed
#---
# Excerpted from "Agile Web Development with Rails, 4rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
# encoding: utf-8
Product.delete_all
Product.create(:title => 'Web Design for Developers',
:description =>
%{<p>
<em>Web Design for Developers</em> will show you how to make your
web-based application look professionally designed. We'll help you
learn how to pick the right colors and fonts, avoid costly interface
and accessibility mistakes -- your application will really come alive.
We'll also walk you through some common Photoshop and CSS techniques
and work through a web site redesign, taking a new design from concept
all the way to implementation.
</p>},
:image_url => '/images/wd4d.jpg',
:price => 42.95)
# . . .
Product.create(:title => 'Programming Ruby 1.9',
:description =>
%{<p>
Ruby is the fastest growing and most exciting dynamic language
out there. If you need to get working programs delivered fast,
you should add Ruby to your toolbox.
</p>},
:image_url => '/images/ruby.jpg',
:price => 49.50)
# . . .
Product.create(:title => 'Rails Test Prescriptions',
:description =>
%{<p>
<em>Rails Test Prescriptions</em> is a comprehensive guide to testing
Rails applications, covering Test-Driven Development from both a
theoretical perspective (why to test) and from a practical perspective
(how to test effectively). It covers the core Rails testing tools and
procedures for Rails 2 and Rails 3, and introduces popular add-ons,
including Cucumber, Shoulda, Machinist, Mocha, and Rcov.
</p>},
:image_url => '/images/rtp.jpg',
:price => 43.75)

Advanced find_or_create

It does not work for protected attributes, but you can pass those in a block, eg.

user = User.find_or_create_by_screen_name( 
  :screen_name => "atog", 
  :name => "Koen Van der Auwera"
) {|u| u.admin = true }

.gitconfig:

# in home directory:

user

name = {FIRSTNAME LASTNAME} email = {EMAIL}

in Capfile:

set :keep_releases, 3

in .rvmrc:

rvm ruby-1.9.2-p0@ubuapp
export rvm_pretty_print_flag=1

Notes to self inside code

# TODO = Things you still need to do.
# OPTIMIZE = Code you need to clean-up, refactor etc.
# FIXME = Mark a bug or method that needs to be fixed.

then, use:

$ rake notes

Writing migrations quicker

rails generate migration add_quantity_to_line_item quantity:integer

The two patterns that Rails matches on is add_XXX_to_TABLE and remove_XXX_from_TABLE where the value of XXX is ignored: what matters is the list of column names and types that appear after the migration name.

The only thing Rails can’t tell is what a reasonable default is for this column. In many cases a null value would do, but let’s make it the value one for existing carts by modifying the migration before we apply it: media.pragprog.com/titles/rails4/code/depot_g/db/migrate/20100301000004_add_quantity_to_line_item.rb

Testing

the standard set of Test::Unit assertions:

assert(boolean, message=nil)
assert_block(message="assert_block failed.") do ... end
assert_equal(expected, actual, message=nil)
assert_in_delta(expected_float, actual_float, delta, message="")
assert_instance_of(klass, object, message="")
assert_kind_of(klass, object, message="")
assert_match(pattern, string, message="")
assert_nil(object, message="")
assert_no_match(regexp, string, message="")
assert_not_equal(expected, actual, message="")
assert_not_nil(object, message="")
assert_not_same(expected, actual, message="")
assert_nothing_raised(*args) do ... end
assert_nothing_thrown(message="") do ... end
assert_operator(object1, operator, object2, message="")
assert_raise(expected_exception_klass, message="") do ... end
assert_respond_to(object, method, message="")
assert_same(expected, actual, message="")
assert_send(send_array, message="")
assert_throws(expected_symbol, message="") do ... end

running 1 test:

$ ruby -Itest test/unit/article_test.rb

Example

gist.github.com/358401

Cheat sheet

nubyonrails.com/articles/ruby-rails-test-rails-cheat-sheet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment