Rails 3 Cheatsheet

Gregg Pollack von EnvyLabs hat ein Cheatsheet für Rails 3 Entwickler veröffentlicht. Es sollte ursprünglich früher erscheinen, aber die Arbeiten an seinen letzten Screencasts haben unerwartet mehr Zeit beansprucht. Auch wenn Rails 3 nun bereits seit einiger Zeit verfügbar ist, ist das Cheatsheet eine gute Quelle um das eine oder andere nachzuschlagen.

Es ist ein umfangreiches Cheatsheet geworden, dass sehr viele Bereiche abdeckt und somit auch für erfahrene Entwickler wertvoll/hilfreich sein wird.

Das PDF ist in sechs Haupt-Bereiche aufgeteilt und jeder Bereich ist in sich nochmal gegliedert:

  1. Routing:
    • Basic Routing
    • Optionale Parameter
    • Redirection
    • Named Routes
    • Rack Routing
    • Constraints
    • Legacy Route
    • Scope
  2. Bundler
    • Bundler Commands
    • Gemfile Syntax
    • Workflow
  3. ActiveRelation
    • Lazy Loading
    • CRUD Methods
    • Chain Methods
    • Chaining
    • (Named) Scopes
    • Deprecated
  4. XSS Protection & UJS
    • XSS Protection
    • Unobtrusive JavaScript
    • HTML5 Custom Data Attributes
    • Deprecated
    • Using JQuery
  5. ActionMailer & ActionController
    • Rails Mail Generator
    • Basic Mailer Syntax
    • Delivering Messages
    • Defaults and Attachements
    • Respond_To and Respond_With
  6. ActiveModel
    • Dirty
    • Validations
    • Serialization
    • Callbacks

Neben dem Umfang hat Gregg auch viel Wert auf das Layout gelegt.

Das Rails 3 Cheatsheet kann unter folgender URL runtergeladen werden: http://blog.envylabs.com/Rails_3_Cheat_Sheets.pdf

Der entsprechende Blogpost mit weiteren Details ist unter folgender Adresse erreichbar: http://blog.envylabs.com/2010/12/rails-3-cheat-sheets/

Dann bleibt uns nur noch übrig euch viel Spaß beim cheaten zu wünschen 🙂

The Rails 3 Way

Ruby on Rails strips complexity from the development process, enabling professional developers to focus on what matters most: delivering business value via clean and maintainable code. The Rails™ 3 Way is the only comprehensive, authoritative guide to delivering production-quality code with Rails 3. Pioneering Rails expert Obie Fernandez and a team of leading experts illuminate the entire Rails 3 API, along with the idioms, design approaches, and libraries that make developing applications with Rails so powerful. Drawing on their unsurpassed experience and track record, they address the real challenges development teams face, showing how to use Rails 3 to maximize your productivity.

Using numerous detailed code examples, the author systematically covers Rails 3 key capabilities and subsystems, making this book a reference that you will turn to again and again. He presents advanced Rails programming techniques that have been proven effective in day-to-day usage on dozens of production Rails systems and offers important insights into behavior-driven development and production considerations such as scalability. Dive deep into the Rails 3 codebase and discover why Rails is designed the way it is—and how to make it do what you want it to do.

This book will help you

  • Learn what’s new in Rails 3
  • Increase your productivity as a web application developer
  • Realize the overall joy in programming with Rails
  • Leverage Rails’ powerful capabilities for building REST-compliant APIs
  • Drive implementation and protect long-term maintainability using RSpec
  • Design and manipulate your domain layer using Active Record
  • Understand and program complex program flows using Action Controller
  • Master sophisticated URL routing concepts
  • Use Ajax techniques via Rails 3 support for unobtrusive JavaScript
  • Learn to extend Rails with popular gems and plugins, and how to write your own
  • Extend Rails with the best third-party plug-ins and write your own
  • Integrate email services into your applications with Action Mailer
  • Improve application responsiveness with background processing
  • Create your own non-Active Record domain classes using Active Model
  • Master Rails’ utility classes and extensions in Active Support
Praise for the Previous EditionThis encyclopedic book is not only a definitive Rails reference, but an indispensable guide to Software-as-a-Service coding techniques for serious craftspersons. I keep a copy in the lab, a copy at home, and a copy on each of my three e-book readers, and it’s on the short list of essential resources for my undergraduate software engineering course.

—Armando Fox, adjunct associate professor, University of California, Berkeley

Everyone interested in Rails, at some point, has to follow The Rails Way.

—Fabio Cevasco, senior technical writer, Siemens AG, and blogger at H3RALD.com

I can positively say that it’s the single best Rails book ever published to date. By a long shot.

—Antonio Cangiano, software engineer and technical evangelist at IBM

This book is a great crash course in Ruby on Rails! It doesn’t just document the features of Rails, it filters everything through the lens of an experienced Rails developer—so you come our a pro on the other side.

—Dirk Elmendorf, co-founder of Rackspace, and Rails developer since 2005

The key to The Rails Way is in the title. It literally covers the “way” to do almost everything with Rails. Writing a truly exhaustive reference to the most popular Web application framework used by thousands of developers is no mean feat. A thankful community of developers that has struggled to rely on scant documentation will embrace The Rails Way with open arms. A tour de force!

—Peter Cooper, editor, Ruby Inside

In the past year, dozens of Rails books have been rushed to publication. A handful are good. Most regurgitate rudimentary information easily found on the Web. Only this book provides both the broad and deep technicalities of Rails. Nascent and expert developers, I recommend you follow The Rails Way.

—Martin Streicher, chief technology officer, McLatchy Interactive; former editor-in-chief of Linux Magazine

Hal Fulton’s The RubyWay has always been by my side as a reference while programming Ruby. Many times I had wished there was a book that had the same depth and attention to detail, only focused on the Rails framework. That book is now here and hasn’t left my desk for the past month.

—Nate Klaiber, Ruby programmer

As noted in my contribution to the Afterword: “What Is the Rails Way (To You)?,” I knew soon after becoming involved with Rails that I had found something great. Now, with Obie’s book, I have been able to step into Ruby on Rails development coming from .NET and be productive right away. The applications I have created I believe to be a much better quality due to the techniques I learned using Obie’s knowledge.

—Robert Bazinet, InfoQ.com, .NET and Ruby community editor, and founding member of the Hartford, CT, Ruby Brigade

Extremely well written; it’s a resource that every Rails programmer should have. Yes, it’s that good.

—Reuven Lerner, Linux Journal columnist

The Rails™ 3 Way is a comprehensive resource that digs into the new features in Rails 3 and perhaps more importantly, the rationale behind them.
—Yehuda Katz, Rails Core

Screencast: Ajax Historie anpassen

Die neue pushState Funktion in JavaScript erlaubt es die gesamte URL mit Ajax zu verändern bzw. an den eigenen Bedarf anzupassen. Das bedeutet das auf einfache Weise eine Unterstützung für die Buttons „Zurück“, „Neu Laden“ und „Lesezeichen“ implementiert werden kann. Ryan zeigt in diesem Screencast wie dies in Kombination mit Rails eingesetzt werden kann.

 

Download:

Download(19.9 MB, 10:35)
Alternativer Download für iPod & Apple TV(18.9 MB, 10:35)

 

Resourcen:

 

Quellcode:

[javascript]
/* application.js */
if (history && history.pushState) {
$(function() {
$("#products th a, #products .pagination a").live("click", function() {
$.getScript(this.href);
history.pushState(null, document.title, this.href);
return false;
});
$("#products_search input").keyup(function() {
$.get($("#products_search").attr("action"), $("#products_search").serialize(), null, "script");
history.replaceState(null, document.title, $("#products_search").attr("action") + "?" + $("#products_search").serialize());
return false;
});
$(window).bind("popstate", function() {
$.getScript(location.href);
});
});
}

/* products/index.js.erb */
$("#products").html("<%= escape_javascript(render("products")) %>");
document.title = "<%= escape_javascript("#{params[:search].to_s.titleize} Products by #{(params[:sort] || ’name‘).titleize} – Page #{params[:page] || 1}") %>";
[/javascript]

Beginning Rails 3

Beginning Rails 3 is the practical starting point for anyone wanting to learn how to build dynamic web applications using the latest release of the Rails framework for Ruby. You’ll learn how all of the components of Rails fit together and how you can leverage them to create sophisticated web applications with less code and more joy. This book is particularly well suited to those with little or no experience with web application development, or who have some experience but are new to Rails.

Beginning Rails 3 assumes basic familiarity with web terms and technologies, but doesn’t require you to be an expert. Rather than delving into the arcane details of Rails, the focus is on the aspects of the framework that will become your pick, shovel, and axe. Part history lesson, part introduction to object-oriented programming, and part dissertation on open source software, this title doesn’t just explain how to do something in Rails, it explains why.
* Learn to create Rails web applications from scratch
* Includes a gentle introduction to the Ruby programming language
* Completely updated to include the new features of Rails 3What you’ll learn Rails 3 is a huge new release that includes the combined power of Rails and Merb. Beginning Rails 3 will get you started in learning this new technology and creating dynamic web applications in next to no time.
* Install Rails on a Mac, Windows, or Linux system
* Understand the Model-View-Controller architecture
* Learn the value of databases and how to set up MySQL in Rails
* Get instant feedback on your work by testing in the Rails Console
* Add Ajax and visual effects to create rich user interfaces
* Use and create your own Rails plug-insWho is this book for?
Web developers who want to harness the power of Rails 3 to quickly build dynamic Rich Internet Applications. Anyone who hasn’t used Rails before will be able to learn the basics from this book. About the Apress Beginning Series The Beginning series from Apress is the right choice to get the information you need to land that crucial entry-level job. These books will teach you a standard and important technology from the ground up because they are explicitly designed to take you from „novice to professional.“ You’ll start your journey by seeing what you need to know-but without needless theory and filler. You’ll build your skill set by learning how to put together real-world projects step by step. So whether your goal is your next career challenge or a new learning opportunity, the Beginning series from Apress will take you there-it is your trusted guide through unfamiliar territory!

Screencast: Ein Gem mit Bundler erstellen

Bundler kann nicht nur zur Installation von gems benutzt werden, es kann auch mit dem Befehl ‚bundle gem‘ ein gem generieren. Ryan zeigt wie das funktioniert und führt den Zuschauer durch die einzelnen Schritte.

 

Download:

Download(23.6 MB, 7:25)
Alternativer Download für iPod & Apple TV(19.4 MB, 7:25)

 

Resourcen:

 

Quellcode:

[bash]
bundle gem lorem
gem build lorem.gemspec
gem push lorem-0.0.1.gem
bundle
rake -T
rake build
rake install
rake release
[/bash]

[ruby]
# lorem.gemspec
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "lorem/version"

Gem::Specification.new do |s|
s.name = "lorem"
s.version = Lorem::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Ryan Bates"]
s.email = ["ryan@railscasts.com"]
s.homepage = ""
s.summary = %q{Lorem ipsum generator}
s.description = %q{Simply generates lorem ipsum text.}

s.add_development_dependency "rspec"

s.rubyforge_project = "lorem"

s.files = `git ls-files`.split("n")
s.test_files = `git ls-files — {test,spec,features}/*`.split("n")
s.executables = `git ls-files — bin/*`.split("n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end

# Gemfile
source "http://rubygems.org"

# Specify your gem’s dependencies in lorem.gemspec
gemspec

# Rakefile
require ‚bundler‘
Bundler::GemHelper.install_tasks

# lib/lorem.rb
module Lorem
def self.ipsum
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
end
end

# lib/lorem/version.rb
module Lorem
VERSION = "0.0.2"
end
[/ruby]

Rails AntiPatterns: Best Practice Ruby on Rails Refactoring

The Complete Guide to Avoiding and Fixing Common Rails 3 Code and Design Problems As developers worldwide have adopted the powerful Ruby on Rails web framework, many have fallen victim to common mistakes that reduce code quality, performance, reliability, stability, scalability, and maintainability. Railsa AntiPatterns identifies these widespread Rails code and design problems, explains why they’re bad and why they happen–and shows exactly what to do instead.

The book is organized into concise, modular chapters–each outlines a single common AntiPattern and offers detailed, cookbook-style code solutions that were previously difficult or impossible to find. Leading Rails developers Chad Pytel and Tammer Saleh also offer specific guidance for refactoring existing bad code or design to reflect sound object-oriented principles and established Rails best practices. With their help, developers, architects, and testers can dramatically improve new and existing applications, avoid future problems, and establish superior Rails coding standards throughout their organizations. This book will help you understand, avoid, and solve problems with.

  • Model layer code, from general object-oriented programming violations to complex SQL and excessive redundancy
  • Domain modeling, including schema and database issues such as normalization and serialization
  • View layer tools and conventions
  • Controller-layer code, including RESTful code
  • Service-related APIs, including timeouts, exceptions, backgrounding, and response codes
  • Third-party code, including plug-ins and gems
  • Testing, from test suites to test-driven development processes
  • Scaling and deployment
  • Database issues, including migrations and validations
  • System design for „graceful degradation“ in the real world.

Screencast: Gravatar

Gravatar ist ein Service, der Benutzern die Möglichkeit gibt öffentlich benutzbare Avartare zum Beispiel in ihren Social Networks zu verwenden. Ryan zeigt diese Woche wie einfach Gravatar in einer Rails-Applikation genutzt werden kann.

 

Download:

Download(13.2 MB, 5:36)
Alternativer Download für iPod & Apple TV(11.2 MB, 5:36)

 

Resourcen:

 

Quellcode:

[ruby]
# application_helper.rb
def avatar_url(user)
if user.avatar_url.present?
user.avatar_url
else
default_url = "#{root_url}images/guest.png"
gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
end
end
[/ruby]

[html]
<!– users/index.html.erb –>
<%= image_tag avatar_url(user) %>
[/html]

Screencast: Beanstalkd und Stalker

Beanstalkd ist ein einfacher, schneller und verteilt arbeitender Dienst zum Aufbau von Message Queues. Stalker ist ein Wrapper Interface um entsprechende Jobs in die Message Queue zu senden.

 

Download:

Download(13.6 MB, 9:16)
Alternativer Download für iPod & Apple TV(13.6 MB, 9:16)

 

Resourcen:

 

Quellcode:

[bash]
beanstalkd -d
killall beanstalkd
beanstalkd -d -b …
stalk ./config/jobs.rb
[/bash]

[ruby]
# Gemfile
gem ’stalker‘

# config/jobs.rb with Rails
require File.expand_path("../environment", __FILE__)

job "city.fetch_name" do |args|
City.find(args["id"]).fetch_name
end

# cities_controller.rb
Stalker.enqueue("city.fetch_name", :id => @city.id)

# config/jobs.rb without Rails
require "sqlite3"
require "json"
require "net/http"

RAILS_ENV = ENV["RAILS_ENV"] || "development"

db = SQLite3::Database.new(File.expand_path("../../db/#{RAILS_ENV}.sqlite3", __FILE__))

job "city.fetch_name" do |args|
zip = db.get_first_value("select zip_code from cities where id=?", args["id"])
url = "http://ws.geonames.org/postalCodeLookupJSON?postalcode=#{zip}&country=US"
json = Net::HTTP.get_response(URI.parse(url)).body
name = JSON.parse(json)["postalcodes"].first["placeName"]
db.execute("update cities set name=? where id=?", name, args["id"])
end

error do |exception|
# …
end

# config/god.rb
# run with: god -c config/god.rb
RAILS_ROOT = File.expand_path("../..", __FILE__)

God.watch do |w|
w.name = "anycity-worker"
w.interval = 30.seconds
w.env = {"RAILS_ENV" => "production"}
w.start = "/usr/bin/stalk #{RAILS_ROOT}/config/jobs.rb"
w.log = "#{RAILS_ROOT}/log/stalker.log"

w.start_if do |start|
start.condition(:process_running) do |c|
c.running = false
end
end

w.restart_if do |restart|
restart.condition(:memory_usage) do |c|
c.above = 50.megabytes
c.times = [3, 5] # 3 out of 5 intervals
end

restart.condition(:cpu_usage) do |c|
c.above = 50.percent
c.times = 5
end
end

w.lifecycle do |on|
on.condition(:flapping) do |c|
c.to_state = [:start, :restart]
c.times = 5
c.within = 5.minute
c.transition = :unmonitored
c.retry_in = 10.minutes
c.retry_times = 5
c.retry_within = 2.hours
end
end
end
[/ruby]