code
stringlengths
1
1.73M
language
stringclasses
1 value
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/destroy'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' $LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info" require 'commands/about'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/runner'
Ruby
#!/usr/bin/env ruby gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 ENV['RSPEC'] = 'true' # allows autotest to discover rspec ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux system((RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV) || $stderr.puts("Unable to find auto...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/runner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/generate'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/destroy'
Ruby
#!/usr/bin/env ruby gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 puts "Loading Rails environment" ENV["RAILS_ENV"] ||= 'test' require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT) require 'optparse' require 'spec/rails/spec_server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/plugin'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/console'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/dbconsole'
Ruby
#!/usr/bin/env ruby begin load File.expand_path(File.dirname(__FILE__) + "/../vendor/plugins/cucumber/bin/cucumber") rescue LoadError => e raise unless e.to_s =~ /cucumber/ require 'rubygems' require 'cucumber' load Cucumber::BINARY end
Ruby
#!/usr/bin/env ruby if ARGV.any? {|arg| %w[--drb -X --generate-options -G --help -h --version -v].include?(arg)} require 'rubygems' unless ENV['NO_RUBYGEMS'] else gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 ENV["RAILS_ENV"] ||= 'test' require File.expand_path(File.dirname(__FILE__) + "/../config/enviro...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' $LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info" require 'commands/about'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/dbconsole'
Ruby
#!/usr/bin/env ruby if ARGV.any? {|arg| %w[--drb -X --generate-options -G --help -h --version -v].include?(arg)} require 'rubygems' unless ENV['NO_RUBYGEMS'] else gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 ENV["RAILS_ENV"] ||= 'test' require File.expand_path(File.dirname(__FILE__) + "/../config/enviro...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/console'
Ruby
#!/usr/bin/env ruby begin load File.expand_path(File.dirname(__FILE__) + "/../vendor/plugins/cucumber/bin/cucumber") rescue LoadError => e raise unless e.to_s =~ /cucumber/ require 'rubygems' require 'cucumber' load Cucumber::BINARY end
Ruby
#!/usr/bin/env ruby gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 ENV['RSPEC'] = 'true' # allows autotest to discover rspec ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux system((RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV) || $stderr.puts("Unable to find auto...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/plugin'
Ruby
#!/usr/bin/env ruby gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 puts "Loading Rails environment" ENV["RAILS_ENV"] ||= 'test' require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT) require 'optparse' require 'spec/rails/spec_server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/generate'
Ruby
# This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' # Requires supporting files with custom matchers and...
Ruby
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end
Ruby
module MoviesHelper end
Ruby
module SessionsHelper end
Ruby
module ReviewsHelper end
Ruby
module UsersHelper # # Use this to wrap view elements that the user can't access. # !! Note: this is an *interface*, not *security* feature !! # You need to do all access control at the controller level. # # Example: # <%= if_authorized?(:index, User) do link_to('List all users', users_path) end %> ...
Ruby
module HomeHelper end
Ruby
class Movie < ActiveRecord::Base validates_presence_of :title, :description validates_uniqueness_of :title validates_length_of :description, :minimum => 10 validates_inclusion_of :rating, :in => %w{ G PG PG-13 R NC-17 } has_many :reviews, :dependent => :destroy def self.find_all_appropriate_for_...
Ruby
require 'digest/sha1' class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, ...
Ruby
class Review < ActiveRecord::Base belongs_to :user belongs_to :movie validates_inclusion_of :score, :in => 1..5 validates_uniqueness_of :user_id, :scope => :movie_id # validates_presence_of :user # validates_presence_of :movie end
Ruby
class MoviesController < ApplicationController before_filter :login_required, :except => [ :index, :show ] # GET /movies # GET /movies.xml def index @movies = Movie.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @movies } end end # GET /movies...
Ruby
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base include AuthenticatedSystem helper :all # include all helpers, all the time protect_from_forgery # See A...
Ruby
class ReviewsController < ApplicationController # GET /reviews # GET /reviews.xml def index @reviews = Review.find(:all, :conditions => {:movie_id => params[:movie_id]}) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @reviews } end end # GET /reviews...
Ruby
class HomeController < ApplicationController before_filter :login_required def dashboard @movies = Movie.find_all_appropriate_for_birthdate(current_user.birthdate) end end
Ruby
class UsersController < ApplicationController # render new.rhtml def new @user = User.new end def create logout_keeping_session! @user = User.new(params[:user]) success = @user && @user.save if success && @user.errors.empty? # Protects against session fixation attacks, causes request...
Ruby
# This controller handles the login/logout function of the site. class SessionsController < ApplicationController # render new.rhtml def new end def create logout_keeping_session! user = User.authenticate(params[:login], params[:password]) if user # Protects against session fixation attacks...
Ruby
# # What you should see when you get there # # # Destinations. Ex: # She should be at the new kids page # Tarkin should be at the destroy alderaan page # The visitor should be at the '/lolcats/download' form # The visitor should be redirected to '/hi/mom' # # It doesn't know anything about actual routes -- it...
Ruby
RE_User = %r{(?:(?:the )? *(\w+) *)} RE_User_TYPE = %r{(?: *(\w+)? *)} # # Setting # Given "an anonymous user" do log_out! end Given "$an $user_type user with $attributes" do |_, user_type, attributes| create_user! user_type, attributes.to_hash_from_story end Given "$an $user_type user named '$login'" do |...
Ruby
# The flexible code for resource testing came out of code from Ben Mabey # http://www.benmabey.com/2008/02/04/rspec-plain-text-stories-webrat-chunky-bacon/ # # Construct resources # # # Build a resource as described, store it as an @instance variable. Ex: # "Given a user with login: 'mojojojo'" # produces a User in...
Ruby
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) # Commonly used webrat steps # http://github.com/brynary/webrat Given /^I am on (.+)$/ do |page_name| visit path_to(page_name) end When /^I go to (.+)$/ do |page_name| visit path_to(page_name) end When /^I press "([^\"]*)"$/ d...
Ruby
# copy this file to features/step_definitions subdirectory # Givens Given /^I am logged in as "([^\"]*)"$/ do |username| user_params = { :login => username, :name => username, :password => 'dummy1', :password_confirmation => 'dummy1', :email => "#{username}@#{username}.com"} @user = User.create!(user_para...
Ruby
# If you have a global stories helper, move this line there: include AuthenticatedTestHelper # Most of the below came out of code from Ben Mabey # http://www.benmabey.com/2008/02/04/rspec-plain-text-stories-webrat-chunky-bacon/ # These allow exceptions to come through as opposed to being caught and having non-helpful...
Ruby
# # Where to go # # # GET # Go to a given page. When "$actor goes to $path" do |actor, path| case path when 'the home page' then get '/' else get path end end # POST -- Ex: # When she creates a book with ISBN: '0967539854' and comment: 'I love this book' and rating: '4' # When she cre...
Ruby
Before do Fixtures.reset_cache fixtures_folder = File.join(RAILS_ROOT, 'spec', 'fixtures') Fixtures.create_fixtures(fixtures_folder, "users") end # Make visible for testing ApplicationController.send(:public, :logged_in?, :current_user, :authorized?)
Ruby
# Be sure to overwrite features/support/paths.rb with this file. module NavigationHelpers # Maps a name to a path. Used by the # # When /^I go to (.+)$/ do |page_name| # # step definition in webrat_steps.rb # def path_to(page_name) case page_name when /the homepage/ '/' when /the...
Ruby
# Sets up the Rails environment for Cucumber ENV["RAILS_ENV"] ||= "cucumber" require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') require 'cucumber/rails/world' # Whether or not to run each scenario within a database transaction. # # If you leave this to true, you can turn off traqnsactions o...
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person',...
Ruby
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying do debug a probl...
Ruby
# A Site key gives additional protection against a dictionary attack if your # DB is ever compromised. With no site key, we store # DB_password = hash(user_password, DB_user_salt) # If your database were to be compromised you'd be vulnerable to a dictionary # attack on all your stupid users' passwords. With a site...
Ruby
# Be sure to restart your server when you modify this file. # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. if defined?(ActiveRecord) # Include Active Record class name as root for JSON serialized output. ActiveReco...
Ruby
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
Ruby
# Be sure to restart your server when you modify this file. # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Act...
Ruby
ActionController::Routing::Routes.draw do |map| #map.resources :reviews map.resources :movies do |movie| movie.resources :reviews end map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller ...
Ruby
# Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? ...
Ruby
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') ...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.action_controller.consider_all_reque...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.ca...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between...
Ruby
config.cache_classes = true # This must be true for Cucumber to operate correctly! # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching...
Ruby
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require(File.join(File.dirname(__FILE__), 'config', 'boot')) require 'rake' require 'rake/testtask' require 'rake/rdoctask' require 'tasks/rails'
Ruby
module AuthenticatedSystem protected # Returns true or false if the user is logged in. # Preloads @current_user with the user model if they're logged in. def logged_in? !!current_user end # Accesses the current user from the session. # Future calls avoid the database because nil is not ...
Ruby
module AuthenticatedTestHelper # Sets the current user in the session from the user fixtures. def login_as(user) @request.session[:user_id] = user ? (user.is_a?(User) ? user.id : users(user).id) : nil end def authorize_as(user) @request.env["HTTP_AUTHORIZATION"] = user ? ActionController::HttpAuthentic...
Ruby
$LOAD_PATH.unshift(RAILS_ROOT + '/vendor/plugins/cucumber/lib') if File.directory?(RAILS_ROOT + '/vendor/plugins/cucumber/lib') unless ARGV.any? {|a| a =~ /^gems/} begin require 'cucumber/rake/task' namespace :cucumber do Cucumber::Rake::Task.new({:ok => 'db:test:prepare'}, 'Run features that should pass') do...
Ruby
gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 rspec_gem_dir = nil Dir["#{RAILS_ROOT}/vendor/gems/*"].each do |subdir| rspec_gem_dir = subdir if subdir.gsub("#{RAILS_ROOT}/vendor/gems/","") =~ /^(\w+-)?rspec-(\d+)/ && File.exist?("#{subdir}/lib/spec/rake/spectask.rb") end rspec_plugin_dir = File.expand_path(Fil...
Ruby
### Iterators ### # 1 module Enumerable def each_even for n in self yield n if n % 2 == 0 end self end end # a bit of test code... x = (1..9) x.each_even { |n| puts n } # 2 module Enumerable def each_grouped_by_first_letter h = {} for item in self key = item...
Ruby
### Language extensions for convenience ### # 2 class String # 3: just wrap the definition with 'class String' def string_blank? # renamed to avoid conflicts with (4) below self.nil? || self.empty? end end # 4 # By defining blank? in the Object class, any object should respond # to it, since all Ruby o...
Ruby
require 'time' class Numeric def squared self * self end end class Movie include Comparable include Enumerable attr_reader :name attr_reader :showtime def initialize(name,showtime) @name = name if showtime.is_a?(Time) @showtime = showtime elsif showtime.is_...
Ruby
### Extending classes ### class IndifferentHash < Hash def []=(key, value) super(key.to_s, value) end def [](key) super(key.to_s) end end # a bit of test code... h = IndifferentHash.new h["foo"] = "bar" h[:foo] = "baz" h["foo"] # should be "baz" h[:foo] # should also be "baz"
Ruby
source 'movie.rb' module Enumerable def group_by h = {} for item in self key = yield item h[key] = [] unless h[key] h[key].push(item) end return h end end ### Higher-order functions ### # 1 a = %w(apple banana cherry alice bob carol alpha bravo charlie) a.group...
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # i...
Ruby
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Full error repor...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.ca...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between...
Ruby
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present # RAILS_GEM_VERSION = '2...
Ruby
# Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? ...
Ruby
ActionController::Routing::Routes.draw do |map| # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # ...
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # i...
Ruby
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Full error repor...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.ca...
Ruby
# Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between...
Ruby
# Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.0...
Ruby
# Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? ...
Ruby
ActionController::Routing::Routes.draw do |map| # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # ...
Ruby
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end
Ruby
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details...
Ruby
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require(File.join(File.dirname(__FILE__), 'config', 'boot')) require 'rake' require 'rake/testtask' require 'rake/rdoctask' require 'tasks/rails'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/console'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/runner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby