code
stringlengths
1
1.73M
language
stringclasses
1 value
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.string :profile_id t.string :email t.string :refresh_token end add_index :users, :profile_id end def down drop_table :users end end
Ruby
# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Ruby
source :gemcutter gem 'sinatra', :require => 'sinatra/base' gem 'thin', '~> 1.3' gem 'pg' gem 'sinatra-activerecord' gem 'google-api-client', '>= 0.4.4', :require => 'google/api_client' group :development do gem 'rake' gem 'sqlite3-ruby' end
Ruby
require 'sinatra.rb' # Sinatra defines #set at the top level as a way to set application configuration set :run, false set :env, (ENV['RACK_ENV'] ? ENV['RACK_ENV'].to_sym : :development) require './main' run Sinatra::Application
Ruby
require 'sinatra/activerecord/rake' require './main'
Ruby
class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.string :title t.text :description t.string :image_url t.timestamps end end def self.down drop_table :products end end
Ruby
ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'test_help' class Test::Unit::TestCase # Transactional fixtures accelerate your tests by wrapping each test method # in a transaction that's rolled back on completion. This ensures that the # test datab...
Ruby
#!/usr/bin/ruby1.8 #!/usr/local/bin/ruby require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) # If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like: # "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performan...
Ruby
#!/usr/bin/ruby1.8 #!/usr/local/bin/ruby # # You may specify the path to the FastCGI crash log (a log of unhandled # exceptions which forced the FastCGI instance to exit, great for debugging) # and the number of requests to process before running garbage collection. # # By default, the FastCGI crash log is RAILS_ROOT/...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/destroy'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/about'
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/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 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/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/console'
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/process/spawner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/spawner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/inspector'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/reaper'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/reaper'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/inspector'
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/request'
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/performance/request'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/generate'
Ruby
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end
Ruby
module StoreHelper end
Ruby
module ProductsHelper end
Ruby
class Product < ActiveRecord::Base validates_presence_of :title, :description, :image_url validates_uniqueness_of :title validates_numericality_of :price validate :price_must_be_at_least_a_cent validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i, :message => 'must be a url for GIF,JPG or PN...
Ruby
class Cart attr_reader :items def initialize @items = [] end def add_product(product) current_item = @items.find {|item| item.product == product} if current_item current_item.increment_quantity else @items << CartItem.new(product) end end end
Ruby
class CartItem attr_reader :product, :quantity def initialize(product) @product = product @quantity = 1 end def increment_quantity @quantity += 1 end def title @product.title end def price @product.price * @quantity end end
Ruby
class StoreController < ApplicationController def index @products = Product.get_products_for_sale end def add_to_cart @cart = find_cart product = Product.find(params[:id]) @cart.add_product(product) end private def find_cart unless session[:cart] session[:cart] = Cart.new ...
Ruby
class ProductsController < ApplicationController # GET /products # GET /products.xml def index @products = Product.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @products } end end # GET /products/1 # GET /products/1.xml def show ...
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 session :session_key => '_depot_session_id' helper :all # include all helpers, all the time # See ActionC...
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
ActionController::Routing::Routes.draw do |map| map.resources :products # 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 :c...
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 # 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
# 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
# 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
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.string :profile_id t.string :email t.string :refresh_token end add_index :users, :profile_id end def down drop_table :users end end
Ruby
# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Ruby
source :gemcutter gem 'sinatra', :require => 'sinatra/base' gem 'thin', '~> 1.3' gem 'pg' gem 'sinatra-activerecord' gem 'google-api-client', '>= 0.4.4', :require => 'google/api_client' group :development do gem 'rake' gem 'sqlite3-ruby' end
Ruby
require 'sinatra.rb' # Sinatra defines #set at the top level as a way to set application configuration set :run, false set :env, (ENV['RACK_ENV'] ? ENV['RACK_ENV'].to_sym : :development) require './main' run Sinatra::Application
Ruby
require 'sinatra/activerecord/rake' require './main'
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflec...
Ruby
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
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 is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to diction...
Ruby
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters f...
Ruby
# Be sure to restart your server when you modify this file. BookerApp::Application.config.session_store :cookie_store, key: '_booker-app_session'
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 to debug a probl...
Ruby
BookerApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web se...
Ruby
BookerApp::Application.configure do # Settings specified here will take precedence over those in config/application.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 web...
Ruby
BookerApp::Application.configure do # Settings specified here will take precedence over those in config/application.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...
Ruby
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. BookerApp::Application.initialize!
Ruby
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
Ruby
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module BookerApp class Application < Rails::Application # Settings in config/environments/* ta...
Ruby
BookerApp::Application.routes.draw do #root 'books#index' root :to => redirect('/books') get '/help', to: 'static_pages#help' get '/signup', to: 'users#new' get '/signin', to: 'sessions#new' delete '/signout', to: 'sessions#destroy' resources :books get '/author_books/:author_id'...
Ruby
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title) base_title = I18n.t(:main_app_title) if page_title.empty? base_title else "#{base_title} | #{page_title}" end end def titleize(str) str.split(" ").map(&:capitalize).join(" ") en...
Ruby
module FormHelper ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| html = %(<div class="has-error">#{html_tag}</div>).html_safe end end
Ruby
require 'pp' module UsersHelper # Before filters def signed_in_user store_location redirect_to signin_url, notice: I18n.t(:please_sign_in) unless signed_in? end def admin_user redirect_to(root_url) unless current_user != nil && current_user.admin? end end
Ruby
module SessionsHelper def sign_in(user) remember_token = User.new_remember_token cookies.permanent[:remember_token] = remember_token user.update_attribute(:remember_token, User.encrypt(remember_token)) self.current_user = user end def signed_in? !current_user.nil? end def current_use...
Ruby
class Book < ActiveRecord::Base belongs_to :author has_and_belongs_to_many :book_categories validates :author_id, presence: true validates :isbn, presence: true, format: /[\-0-9]+/ validates :title, presence: true validates :quantity, numericality: {greater_than: 0}, unless: Proc.new {|book| book.quantity....
Ruby
class User < ActiveRecord::Base before_save {self.email = email.downcase} before_create :create_remember_token has_secure_password VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i validates :name, presence: true, length: {maximum: 50} validates :surname, length: {maximum: 50} val...
Ruby
class Author < ActiveRecord::Base has_many :books, dependent: :restrict_with_exception validates :name, presence: true, length: {maximum: 50} validates :surname, presence: true, length: {maximum: 50} def name_and_surname "#{name} #{surname}" end def surname_and_name "#...
Ruby
class BookCategory < ActiveRecord::Base has_and_belongs_to_many :books validates :category_name, presence: true end
Ruby
class BookCategoriesController < ApplicationController before_action :set_book_category, only: [:destroy] before_action :signed_in_user, only: [:create, :destroy, :index] before_action :admin_user, only: [:create, :destroy] # GET /book_categories def index @book_categories = BookCategory.all.order(:cat...
Ruby
class StaticPagesController < ApplicationController def help end end
Ruby
class SessionsController < ApplicationController def new end def create user = User.find_by(email: downcase_email) if user && user.authenticate(params[:session][:password]) sign_in user redirect_back_or_default else flash.now[:error] = I18n.t(:invalid_email_pass_combination) ...
Ruby
class AuthorsController < ApplicationController before_action :set_author, only: [:edit, :update, :destroy] before_action :signed_in_user, only: [:new, :create, :edit, :update, :destroy, :index] before_action :admin_user, only: [:new, :create, :edit, :update, :destroy] # GET /authors # GET /authors.json de...
Ruby
class BooksController < ApplicationController before_action :set_book, only: [:show, :edit, :update, :destroy] before_action :signed_in_user, only: [:new, :create, :edit, :update, :destroy, :index, :show] before_action :admin_user, only: [:new, :create, :edit, :update, :destroy] # GET /books # GET /books.jso...
Ruby
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper include UsersHelper end
Ruby
require 'pp' class UsersController < ApplicationController before_action :admin_user, only: [:index, :destroy] before_action :correct_user, only: [:edit, :update, :show, :destroy] before_action :set_user_to_edit_by_admin, only: [:edit, :update] # GET /users # GET /users.json def index @users...
Ruby
# encoding: utf-8 class PictureUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded f...
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.expand_path('../config/application', __FILE__) BookerApp::Application.load_tasks
Ruby
source 'https://rubygems.org' #ruby '1.9.3' #ruby-gemset=railstutorial_rails_4_0 gem 'rails', '4.0.0' gem 'bootstrap-sass', '3.0.3.0' gem 'bcrypt-ruby', '3.0.1' gem 'faker', '1.1.2' gem 'will_paginate', '3.0.5' gem 'bootstrap-will_paginate', '0.0.10' gem 'carrierwave' group :development, :test do gem 'sqlite3', '1....
Ruby
class CreateBookCategoriesBooksJoin < ActiveRecord::Migration def change create_table :book_categories_books, :id => false do |t| t.column 'book_id', :integer t.column 'book_category_id', :integer end end end
Ruby
class AddIndexToUsersEmail < ActiveRecord::Migration def change add_index :users, :email, unique: true end end
Ruby
class AddAdminToUsers < ActiveRecord::Migration def change add_column :users, :admin, :boolean, default: false end end
Ruby
class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :isbn t.string :title t.integer :author_id t.string :language t.string :description t.string :photo t.integer :quantity t.string :place t.date :release_date t.inte...
Ruby
class AddRememberTokenToUsers < ActiveRecord::Migration def change add_column :users, :remember_token, :string add_index :users, :remember_token end end
Ruby
class AddPasswordDigestToUsers < ActiveRecord::Migration def change add_column :users, :password_digest, :string end end
Ruby
class CreateAuthors < ActiveRecord::Migration def change create_table :authors do |t| t.string :name t.string :surname t.timestamps end end end
Ruby
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.string :surname t.string :email t.timestamps end end end
Ruby
class CreateBookCategories < ActiveRecord::Migration def change create_table :book_categories do |t| t.string :category_name t.timestamps end end end
Ruby
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
Ruby