code
stringlengths
1
1.73M
language
stringclasses
1 value
class AddIsGiftToOrder < ActiveRecord::Migration def change add_column :orders, :is_gift, :boolean, :default => 0 end end
Ruby
class CombineItemsInCart < ActiveRecord::Migration def up Cart.all.each do |cart| sums = cart.line_items.group(:product_id).sum(:quantity) sums.each do |product_id, quantity| if quantity >1 cart.line_items.where(product_id: product_id).delete_all ...
Ruby
class CreateCarts < ActiveRecord::Migration def change create_table :carts do |t| t.timestamps end end end
Ruby
class CreateLineItems < ActiveRecord::Migration def change create_table :line_items do |t| t.integer :product_id t.integer :cart_id t.timestamps end end end
Ruby
class AddOrderIdToLineItem < ActiveRecord::Migration def change add_column :line_items, :order_id, :integer end end
Ruby
class CreateCheckouts < ActiveRecord::Migration def change create_table :checkouts do |t| t.string :name t.text :address t.string :email t.string :pay_type t.string :shipping_type t.boolean :is_gift t.timestamps end end end
Ruby
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integrati...
Ruby
#!/usr/bin/env rake # 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__) Webshop::Application.load_tasks
Ruby
source 'https://rubygems.org' gem 'rails', '3.2.5' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3' # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3...
Ruby
#!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands'
Ruby
#!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands'
Ruby
Order.transaction do (1..100).each do |i| Order.create(:name => "Customer #{i}", :address => "Anystreet #{i}", :email => "customer-#{i}@example.com", :pay_type => "Check", :shipping_type => "Post", :is_gift => false) end end
Ruby
atom_feed do |feed| feed.title "Products of Students Bookshop" @products.each do |product| feed.entry(product) do |entry| entry.title "#{product.title}" entry.summary "#{product.description}" end end end
Ruby
class ProductPdf < Prawn::Document def initialize(product, view) super() @product = product @view = view text "Produkt #{@product.id}" draw_text "#{@product.title}", :at => [220, 575], size: 22 logopath = "#{Rails.root}/app#{@product.image_url.gsub("/assets/","/assets/images/")}" image...
Ruby
class InvoicePdf < Prawn::Document def initialize(order, view) super() @order = order @view = view text "Students Book Shop - Invoice" move_down 30 text "Students Book Shop AG" text "Studentengasse 3" text "3011 Bern" text "+41 79 123 456" move_down 5 text @ord...
Ruby
module LineItemsHelper end
Ruby
module ApplicationHelper def hidden_div_if(condition, attributes = {}, &block) if condition attributes["style"] = "display: none" end content_tag("div", attributes, &block) end end
Ruby
module CartsHelper end
Ruby
module StoreHelper end
Ruby
module OrdersHelper end
Ruby
module SessionsHelper end
Ruby
module AccountHelper end
Ruby
module CheckoutHelper end
Ruby
module UsersHelper end
Ruby
module ProductsHelper end
Ruby
module AdminHelper end
Ruby
module CategoriesHelper end
Ruby
module HomeHelper end
Ruby
class LineItem < ActiveRecord::Base attr_accessible :product, :product_id, :id, :cart_id belongs_to :order belongs_to :product belongs_to :cart def total_price product.price * quantity end end
Ruby
require 'httparty' class CurrencyWebservice include HTTParty def get() response = HTTParty.get('http://webservices.bermilabs.com/exchange/eur/chf') if response.success? response else raise response.response end end end
Ruby
class Product < ActiveRecord::Base attr_accessible :product_id, :description, :image_url, :price, :title, :category_id, :line_item_id, :promote validates :title, :description, :price, presence: true has_one :category has_many :line_items has_and_belongs_to_many :addons, :class_name => "Product", ...
Ruby
class Cart < ActiveRecord::Base # attr_accessible :title, :body has_many :line_items, dependent: :destroy def add_product(product_id) current_item = line_items.find_by_product_id(product_id) if current_item current_item.quantity += 1 else current_item = line_items.build(:product...
Ruby
class User < ActiveRecord::Base attr_accessible :name, :password_digest, :password, :password_confirmation validates :name, presence: true, uniqueness: true has_secure_password end
Ruby
class Category < ActiveRecord::Base attr_accessible :description, :name has_many :product end
Ruby
class Checkout < ActiveRecord::Base attr_accessible :address, :email, :is_gift, :name, :pay_type, :shipping_type, :status validates :name, :address, :email, presence: true, if: :on_order_person_step? validates_format_of :email, :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\...
Ruby
class Order < ActiveRecord::Base PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order"] SHIPPING_TYPES = [ "Post"] has_many :line_items, dependent: :destroy attr_accessible :address, :email, :name, :pay_type, :shipping_type, :is_gift validates :name, :address, :email, presence: true validates :pa...
Ruby
class StoreController < ApplicationController layout "sidebar" # Main page of the store, shows promoted products def index @categories = Category.order("name") @cart = current_cart @products = Product.order("RANDOM()").find(:all, :conditions => [ "promote = ?", true], :limit => 5) end ...
Ruby
class ProductsController < ApplicationController before_filter :authorize, except: [:list] # Shows all products # GET /products # GET /products.json def index @products = Product.all respond_to do |format| format.html # index.html.erb format.json { render json: @products } end ...
Ruby
class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_i18n_locale_from_params before_filter :set_controller_and_action_names private # adds the name of the current controller and the current action to the view def set_controller_and_action_names @curre...
Ruby
class CartsController < ApplicationController before_filter :authorize, except: [:show, :new, :create, :destroy] # Lists all carts # GET /carts # GET /carts.json def index @carts = Cart.all respond_to do |format| format.html # index.html.erb format.json { render json: @carts } ...
Ruby
class AccountController < ApplicationController before_filter :authorize def index end end
Ruby
class CategoriesController < ApplicationController before_filter :authorize # Lists all categories # GET /categories # GET /categories.json def index @categories = Category.all respond_to do |format| format.html # index.html.erb format.json { render json: @categories } end en...
Ruby
class LineItemsController < ApplicationController # Shows all line items # GET /line_items # GET /line_items.json def index @line_items = LineItem.all respond_to do |format| format.html # index.html.erb format.json { render json: @line_items } end end # Shows a specific line it...
Ruby
class HomeController < ApplicationController # Index page that sets locale if necessary def index if params[:set_locale] redirect_to home_index_path(locale: params[:set_locale]) end end end
Ruby
class UsersController < ApplicationController before_filter :authorize # Lists all users # GET /users # GET /users.json def index @users = User.order(:name) respond_to do |format| format.html # index.html.erb format.json { render json: @users } end end # Shows a single user ...
Ruby
class OrdersController < ApplicationController layout "sidebar" before_filter :authorize, except: [:create, :invoice] # Lists all orders # GET /orders # GET /orders.json def index @orders = Order.paginate page: params[:page], order: 'created_at desc', per_page: 10 respond_to do |format| ...
Ruby
class CheckoutController < ApplicationController include Wicked::Wizard require 'mail' layout "sidebar" # order of the wizard steps :order_person, :order_options, :order_summary, :order_invoice # Shows the current cart def show @cart = current_cart @checkout = current_checkout c...
Ruby
class AdminController < ApplicationController before_filter :authorize # Lists all orders on the page def index @total_orders = Order.count end end
Ruby
class SessionsController < ApplicationController # does nothing ;) def new end # saves a new session def create user = User.find_by_name(params[:name]) if user and user.authenticate(params[:password]) session[:user_id] = user.id redirect_to admin_url else redirect_to login_u...
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 to debug a probl...
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 ...
Ruby
# Be sure to restart your server when you modify this file. # Your secret key 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 dictionary attac...
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 Mime::Type.register "application/pdf", :pdf
Ruby
#encoding utf-8 I18n.default_locale = :en LANGUAGES = [ ['English','en'], ['Deutsch','de'] ]
Ruby
# Be sure to restart your server when you modify this file. Webshop::Application.config.session_store :cookie_store, key: '_webshop_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails g...
Ruby
Webshop::Application.routes.draw do get 'admin' => 'admin#index' controller :sessions do get 'login' => :new post 'login' => :create delete 'logout' => :destroy end scope '(:locale)' do resources :users resources :orders resources :line_items resources :carts resources...
Ruby
require 'rubygems' # 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' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.requi...
Ruby
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Webshop::Application.initialize!
Ruby
Webshop::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 # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action...
Ruby
Webshop::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 s...
Ruby
Webshop::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 su...
Ruby
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run Webshop::Application
Ruby
#!/usr/bin/env rake # 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__) Webshop::Application.load_tasks
Ruby
# # A sample ruby script, which performs something impossible in java: extending Array functionalities. # class Array # If +number+ is greater than the size of the array, the method # will simply return the array itself sorted randomly def randomly_pick(number) sort_by{ rand }.slice(0...number) end end l...
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. # 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
# 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
# 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
# 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.5' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') ...
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| map.resources :budgets # The priority is based upon order of creation: first created -> highest priority. map.resource :session map.resources :users, :has_many => :budgets # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :...
Ruby
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end
Ruby
module UsersHelper end
Ruby
module SessionsHelper end
Ruby
module BudgetsHelper end
Ruby
class User < ActiveRecord::Base has_many :budgets end
Ruby
class Budget < ActiveRecord::Base belongs_to :user validates_presence_of :budget_name, :budget_amount BUDGET_TYPE = ['Household', 'Bills', 'Entertainment', 'Hobbies', 'Misc'] end
Ruby
class BudgetsController < ApplicationController before_filter :login_required, :only => [ :new, :create, :index, :show ] def new @budget = Budget.new end def index @my_total = 0 @bills_total = 0 @budgets = Budget.find(:all, :conditions => ["user_id = ?", @current_user.id]).each do |budg...
Ruby
class SessionsController < ApplicationController def new end def create @current_user = User.find_by_login_and_password(params[:login], params[:password]) if @current_user session[:user_id] = @current_user.id if session[:return_to] redirect_to session[:return_to] session[:retu...
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 protect_from_forgery # See ActionController::RequestForgeryPr...
Ruby
class UsersController < ApplicationController before_filter :login_required, :only => [ :new, :create ] def index end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:notice] = "User creation succeeded" redirect_to users_path ...
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.expand_path('../../config/boot', __FILE__) require 'commands/dbconsole'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/console'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/runner'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../../config/boot', __FILE__) require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../../config/boot', __FILE__) require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../../config/boot', __FILE__) require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../../config/boot', __FILE__) require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/plugin'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/destroy'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) $LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info" require 'commands/about'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/dbconsole'
Ruby
#!/usr/bin/env ruby require File.expand_path('../../config/boot', __FILE__) require 'commands/runner'
Ruby