text
stringlengths
10
2.61M
require 'rspec/autorun' # We are going to build a system to help track the contents of a trailer (think 18 wheeler) and calculate the weight of the trailer over time. # - Trailers can hold pallets. # - A pallet has a weight, and a unique pallet ID. # - Pallets can be loaded and unloaded from trailers. # Part 1 # Crea...
class ApplicationController < ActionController::Base # Devise config protect_from_forgery with: :exception devise_group :member, contains: [:student, :user] # authenticate for either a user or a student before_action :authenticate! def authenticate! :authenticate_user! || :authenticate_student! ...
class Waiter < ActiveRecord::Base attr_accessible :name, :surname validates :name, length: { maximum: 40, minimum: 1 }, presence: true validates :surname, length: { maximum: 40, minimum: 1 }, presence: true has_many :tables end
class AddFieldsToProjects < ActiveRecord::Migration[5.1] def change add_column :projects, :title, :string add_column :projects, :subtitle, :string add_column :projects, :start_date, :date add_column :projects, :end_date, :date add_column :projects, :show, :boolean, default: false, null: false ...
module RailsJwtAuth module Spec module Helpers require 'rails_jwt_auth/spec/not_authorized' require 'rails_jwt_auth/jwt/manager' def sign_out request.env['warden'] = RailsJwtAuth::Strategies::Jwt.new request.env allow(request.env['warden']).to receive(:authenticate!).and_raise(R...
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'memoized_on_frozen/version' Gem::Specification.new do |spec| spec.name = 'memoized_on_frozen' spec.version = MemoizedOnFrozen::VERSION spec.authors = ['Ilya...
class GroupsController < ApplicationController before_filter :authenticate_user!, only: [:index, :create, :new, :edit, :show, :update, :destroy] def index @groups = Group.paginate(page: params[:page]) end def create @group = Group.new(params[:group]) if @group.save flash[:success] = 'Group c...
class RemoveScores < ActiveRecord::Migration def up remove_column :exercises, :score end def down add_column :exercises, :score, :decimal, :precision => 12, :scale => 7 end end
class AwardsController < ApplicationController load_and_authorize_resource def index @awards = Award.order("created_at desc") end def new @award = Award.new end def create @award = Award.new(params[:award]) if @award.save! flash[:success] = "Dodano" redirect_t...
# config valid only for current version of Capistrano lock '3.4.0' set :application, 'CurrentApp' set :repo_url, 'git@github.com:mazikwyry/current.git' set :deploy_via, :remote_cache set :branch, 'production' # Default deploy_to directory is /var/www/my_app_name # set :deploy_to, '/var/www/my_app_name' # Default val...
# # Cookbook Name:: AllegroGraph # Recipe:: default # # Copyright 2015, Gannett, Inc. # # All rights reserved - Do Not Redistribute # remote_file '/tmp/' + node['allegrograph']['agraph_package_name'] + '.rpm' do source node['allegrograph']['rpm_url'] checksum node['allegrograph']['agraph_rpm_checksum'] end rpm_pac...
class PrototypesController < ApplicationController before_action :set_prototype, only: [:edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] def index @prototypes = Prototype.eager_load(:user, :main_image).order("prototypes.created_at DESC").page(params[:page]) end def ne...
module Fog module Parsers module Bluebox class GetFlavor < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'cost' @response[name] = @value.to_f when 'description', 'id' @response[n...
require 'sinatra/json' module Routes class Base < Sinatra::Base helpers Sinatra::JSON configure do set :views, File.join(ENV['RACK_ROOT'], 'app/views') end error Sinatra::NotFound do halt 404 end error ActiveRecord::RecordNotFound do halt(404, { error: 'Not Found' }.to_js...
class CreateQuestionResultDetails < ActiveRecord::Migration def self.up create_table :question_result_details do |t| t.integer :question_detail_id t.integer :question_result_id t.integer :answer_id t.timestamps end end def self.down drop_table :question_result_details end en...
module ET3 module Test class PersonasRepository PERSONAS_FILE = File.absolute_path('../fixtures/personas.yml', __FILE__) def initialize self.registry = {} end # Fetch a persona # @param [String] name The name of the persona to fetch # @return [OpenStruct] An open struc...
class AddAnimalTypeIdToMedicalDiagnoses < ActiveRecord::Migration def change add_column :medical_diagnoses, :animal_type_id, :integer end end
require 'rails_helper' require "cancan/matchers" describe Ability, :type => :model do describe "abilities" do context "Admin user can manage all" do let(:user) { FactoryGirl.create(:admin) } subject(:ability) { Ability.new(user) } it { is_expected.to be_able_to(:manage, User) } end c...
# Copyright (C) 2014 Jan Rusnacko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of the # MIT license. require 'spec_helper' # require 'ruby_util/hash_with_method_access_shared' describe Xenuti::Config do let(:hash) do...
class AddInviteCodeToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :incoming_invite_code, :string add_column :users, :outgoing_invite_code, :string end end
module Pretentious # Deconstructor - decompose an object into its parts class Deconstructor # Represents an unresolved class class UnResolved attr_accessor :target_object def initialize(object) @target_object = object end end # Represents a reference class Reference ...
module Representable Pipeline.class_eval do # FIXME: this doesn't define Function in Pipeline. module Function class Insert def call(arr, func, options) arr = arr.dup delete!(arr, func) if options[:delete] replace!(arr, options[:replace], func) if options[:replace] ...
class UsersController < ApplicationController before_action :authenticate_user! load_and_authorize_resource rescue_from CanCan::AccessDenied do |exception| redirect_to(root_path, flash: { error: exception.message }) end expose(:user) expose(:reviews) expose_decorated(:user) expose_decorated(:revie...
# encoding: utf-8 class VoluntariosController < ApplicationController # GET /voluntarios # GET /voluntarios.xml def index if params[:centro].blank? @voluntarios = Voluntario.all else @voluntarios = Voluntario.find_all_by_centro_id params[:centro] end respond_to do |format| forma...
require 'spec_helper' describe Place do let(:group) { FactoryGirl.create(:group) } before { @place = group.places.build(name: "Example Place") } subject { @place } it { should respond_to(:name) } it { should respond_to(:group_id) } its(:group) { should == group } describe "when name is not present" do...
class Resume < ActiveRecord::Base has_many :resume_educations has_many :resume_positions has_many :resume_projects end
require 'test_helper' class CardigansControllerTest < ActionDispatch::IntegrationTest setup do @cardigan = cardigans(:one) end test "should get index" do get cardigans_url assert_response :success end test "should get new" do get new_cardigan_url assert_response :success end test "...
FactoryBot.define do factory :diver do first_name { "MyString" } last_name { "MyString" } email { "MyString" } contact { "MyString" } address { "MyString" } secondary_contact { "MyString" } end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :omniauthable # Setup accessible (or p...
RSpec.describe Timewizard do it 'should have a VERSION constant' do expect(Timewizard::VERSION).to_not be_nil end end
# Problem 306: Paper-strip Game # http://projecteuler.net/problem=306 # The following game is a classic example of Combinatorial Game Theory: # # Two players start with a strip of n white squares and they take alternate turns. # On each turn, a player picks two contiguous white squares and paints them black. # The fi...
# typed: true class CreateBanalDocuments < ActiveRecord::Migration[6.0] def change create_table :banal_documents do |t| t.text :global_path t.references :banal_metadata, null: false, foreign_key: true t.references :banal_related_object, null: false, foreign_key: true t.timestamps end ...
# frozen_string_literal: true # == Schema Information # # Table name: events # # id :bigint not null, primary key # capacity :integer default(1) # description :text # location :string # name :string # price :decimal(, ) # slug :string # starts_at :datetim...
# frozen_string_literal: true require 'pry' class SecretFolder class SecretErrors def initialize(app) @app = app end def call(env) status, header, body = @app.call(env) if [404, 500].include?(status) env['PATH_INFO'] = "/public/#{status}.html" header['Content-Type'] = ...
class Player < ApplicationRecord has_many :lost_matches, foreign_key: :loser_id, class_name "Match" has_many :won_matches, foreign_key: :winner_id, class_name "Match" end
class Appointment < ApplicationRecord belongs_to :interaction belongs_to :artist belongs_to :client end
class BlakstarLikeMigration < ActiveRecord::Migration def self.up create_table :likes do |t| t.references :user t.integer :likeable_id t.string :likeable_type, :limit => 32 t.integer :value t.timestamps end add_index :likes, :user_id add_index :likes, :likeable_id...
require 'bundler/setup' require 'simplecov' require 'webmock/rspec' require 'get_address' require 'pry' Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |file| require file } RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.r...
#This is to recreate the deleted onetime payment for DealFish class ShardMigration < ActiveRecord::Migration shard :all def self.up add_column :emails, :sharded_column, :integer end def self.down remove_column :emails, :sharded_column end end
require 'rails_helper' RSpec.describe "enterprise_messages/index", type: :view do before(:each) do assign(:enterprise_messages, [ EnterpriseMessage.create!( :number => "Number", :customer => "Customer", :message => "Message", :status => "Status", :invoice_no => "Invo...
class InitialMigration < ActiveRecord::Migration[6.0] def change create_table :problems do |t| t.integer :m, null: false t.integer :n, null: false t.string :matrix, null: false t.string :b, null: false t.timestamps end create_table :solutions do |t| t.references :probl...
class CreateFlatsResidents < ActiveRecord::Migration def change create_table :flats_residents do |t| t.integer :resident_id t.integer :flat_id t.boolean :active t.date :from t.date :to t.boolean :family_head t.boolean :owner t.timestamps null: false end end e...
module JobsHelper require 'pundit' def user_is_authorized_for_edit?(job) current_user == job.user || is_an_admin? end def is_an_admin? true if current_user && current_user.admin? end def user_is_authorized_for_delete?(job) current_user == job.user || is_an_admin...
class CreateAnalyses < ActiveRecord::Migration def change create_table :analyses do |t| t.boolean :total_breakdown t.string :title t.text :symptom t.references :environment, index: true, foreign_key: true t.references :target, index: true, foreign_key: true t.datetime :when ...
require 'spec_helper' describe User do before :each do User.destroy_all DataFile.destroy_all load_roles end def admin_user User.find_by_name('admin') || FactoryGirl.create(:admin_user) end it 'name should exists' do user = FactoryGirl.create(:user) user.name = '' user.should_not...
require "vworkapp_ruby" describe VW::Base do before(:all) do end describe "#New" do it "Creates a base object from a given hash" do t = B1.new( :a => "a", :b => "b", :c => { :one => "one", :two => "two" } ) t.a.should == "a" t.b....
$LOAD_PATH.unshift 'lib' Gem::Specification.new do |s| s.name = 'prophet' s.date = Time.now.strftime('%F') s.version = open('VERSION').read().strip s.homepage = 'http://github.com/b4mboo/prophet' s.email = 'bamboo@suse.com' s.authors = ['Dominik Bamberger', 'Thomas Schmidt', 'Jordi Massaguer ...
module Bibliovore # Parent class for all Collectnik errors class BibliovoreError < StandardError end # Indicates a invalid page has been requested from a result set class ApiError < BibliovoreError end # Indicates that the response couldn't be interpreted as a BiblioCommons API # object or a proper er...
module Fog class Slicehost class Real # Get list of slices # ==== Parameters # * flavor_id<~Integer> - Id of flavor to create slice with # * image_id<~Integer> - Id of image to create slice with # * name<~String> - Name of slice # # ==== Returns # * response<~Excon...
class Admins::AdminReviewsController < ApplicationController before_action :authenticate_admins_admin_user! def edit @review = Review.find(params[:id]) end def update review = Review.find(params[:id]) review.update(review_params) redirect_to tops_index end def destroy review = Review.find(params[...
# Proc # - allow the use of blocks with multiple arguments # - allow saving blocks for later to use as a callback
class PublicationsMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.publications_mailer.publication_create.subject # def publication_create @greeting = "Hello!!" mail( to: "v25093735@gmail.com", subject: "Felicidade...
# 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class AddDrinkColumnsWithoutQuestionMarkToQuery < ActiveRecord::Migration def change add_column :queries, :beer, :boolean add_column :queries, :wine, :boolean add_column :queries, :cocktail, :boolean end end
class AddNameToUsers < ActiveRecord::Migration def change add_column :users, :first_n, :string, limit: 30 add_column :users, :last_n, :string, limit: 30 add_column :users, :company, :string, limit: 40 add_column :users, :country, :string, limit: 20 add_column :users, :city, :string, limit: 30 ...
feature 'User sign up' do scenario 'User can sign up and enter their details to create a new account' do expect{ sign_up }.to change(User, :count).by(1) expect(page).to have_content "Welcome, Bob" expect(User.first.email).to eq "bob@gmail.com" end scenario 'User cannot sign up with a mismatching pass...
class Product < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged belongs_to :brand belongs_to :category has_many :product_images, dependent: :destroy has_many :variants, dependent: :destroy accepts_nested_attributes_for :product_images, allow_destroy: true validates_presence_of :n...
module PdfTempura module Render class Table include OptionAccess include FieldBounds def initialize(table, values, options = {}) @table = table @options = options @values = values || [] unless @values.respond_to?(:each) raise ArgumentError.new("Expecte...
class Player @@players = [] def Player.players @@players end def Player.clear @@players = [] end attr_accessor :name def initialize(name) @name = name @@players << self end end
# Source: "Curve P-256" from http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.doc module ECDSA class Group Nistp521 = new( name: 'nistp521', p: 68647976601306097149819007990813932172694353_00143305409394463459185543183397656052122559_64066145455497729631139148085803712198799971_66438125...
# frozen_string_literal: true RSpec.describe 'Email confirmation' do resource 'Confirm email' do route '/api/v1/confirm_email', 'Confirm user email' do post 'Confirm email' do with_options scope: %i[data attributes] do parameter :token, required: true end let(:token) { Se...
class AddPageToBlocks < ActiveRecord::Migration[5.0] def change add_reference :blocks, :page, foreign_key: true Website.all.each do |website| if !website.pages.where(is_homepage: true).present? new_homepage = website.pages.create( is_homepage: true, website_id: website.id, ...
require "leadcreator/version" require 'restforce' module Leadcreator def self.initialize(instance_url, client_id, client_secret, oauth_token) credential = {:instance_url => instance_url, :client_id => client_id, :client_secret => client_secret, :oauth_token ...
class EndedNotice < UIView attr_accessor :alert def initWithFrame(frame) super self.frame = frame self.backgroundColor = UIColor.colorWithRed(50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 0.95) self.layer.cornerRadius = 5.0 self.sizeToFit self end def alert=...
require 'spec_helper' describe Hutch::Consumer do around(:each) do |example| isolate_constants do example.run end end let(:simple_consumer) do unless defined? SimpleConsumer class SimpleConsumer include Hutch::Consumer consume 'hutch.test1' end end SimpleCon...
require_relative('../../lib/installer') Uninstaller = Class.new unless Kernel.const_defined?('Uninstaller') ConfigFile = Module.new { def self.add_cluster_name(arg1, arg2);end; } unless Kernel.const_defined?('ConfigFile') shared_examples_for 'a successful installation' do context "when the tmp directory exists" do ...
class Vigil class Log def initialize @log = [] end def <<(item) @log << item end def serialize @log.map {|i| i.serialize} end end end
#!/usr/bin/ruby #part 8 ## Worked with Luke Woodruff class Class def attr_accessor_with_history(attrName) attr_name = attrName.to_s attr_reader attr_name attr_writer attr_name attr_reader attr_name + "_history" class_eval %Q( def #{attr_name}=(attr_name) ...
require 'pp' require 'fileutils' include FileUtils require_relative '../lib/ciphermyurl/meta' require 'minitest/autorun' def cd_to_tests case File.basename(Dir.pwd) when CipherMyUrl::Meta::NAME.downcase # test probably is executed from the Rakefile Dir.chdir('test') $stderr.puts('*** chdir to ' + Dir....
require 'pry' class Say def initialize number @number = number end def in_english words = { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten" } end end binding.pry
class ChatsController < ApplicationController before_action :ensure_admin!, only: [:new, :create, :index, :update, :destroy] before_action :authenticate_user!, only: :show before_action :set_chat, only: [:show, :destroy] respond_to :html def index @chats = Chat.all respond_with(@chats) end def s...
class NdkStack < Utility desc "A ndk-stack utility" name 'ndk-stack' homepage "" release version: '1', crystax_version: 3 def prepare_source_code(release, dir, src_name, log_prefix) end def build_for_platform(platform, release, options, _host_dep_dirs, _target_dep_dirs) src_dir = File.join(Build::...
class Bank < ApplicationRecord has_many :accounts validates :code, uniqueness: true end
# Perhaps this is not a good implementaiton of a LRUCache because if we added # multiples of the same line, then we would expect it to be the last element # that we see in the array. We could improve its efficiency by creating a hash # and for every object that is recieved, we set the amount of times we recieved # this...
module GitRevisionNumbers class MasterCommitLibrarian < CommitLibrarian def initialize(init_directory=".") super @commits = @repository.commits(:master) end end end
class Reporter def create_payload(action_group) values = action_group.values.flatten card_name = values.first[:data]['card']['name'] card_link = "[#{card_name}](https://trello.com/c/#{values.first[:data]['card']['shortLink']})" completed = values.map{ |x| x[:completed] }.inject{|m, o| m or o} ac...
module DynamodbOrm module AllowsSoftDeletion def acts_as_soft_deletable(opts = {}) include SoftDeletion.new(opts) end end class SoftDeletion < Module def initialize(opts = {}) @deleted_at_key = opts.fetch(:field, :deleted_at) end def included(base) base.send :extend, ClassM...
# Demo player: Allows a human to enter the guess per turn. Please note that the class name ends with the word "Player" to enable loading. class HumanDemoPlayer # Returns this players name. def name "Human Demo Player" end # Prepares for a new game (no action required for this player). def new_game(dict...
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' root 'static_pages#home' #localhost:3000でHomeページを開く #本来はlocalhost:3000/static_pages/helpで開くhelpページを #localhost:3000/helpで開くようにした get '/help', to: 'static_pages#help' # helpのURLを有効化 get '/about', to: 'static_pag...
class Course < ApplicationRecord has_many :activities has_many :people, through: :activities validates :description, :weekdays, :times, :status, presence: true end
class Supervise < ActiveRecord::Base belongs_to :user belongs_to :goal state_machine initial: :normal do state :accepted state :refused state :changed_user # 接受督促 event :accept do transition :normal => :accepted end # 拒绝督促 event :refuse do transition :norma...
require 'spec_helper' describe Task do describe 'state switching' do describe 'to finished' do it 'fill finished_at with current time' do Timecop.freeze do task = create :task expect{ task.finish task.reload }.to change{task.finished_at.to_i}.to...
require 'spec_helper' describe SessionsController do context 'GET :create' do before { request.env['omniauth.auth'] = TWITTER_AUTH_HASH } it 'renders the :index template' do get :create, params: { provider: :twitter } expect(controller.send(:signed_in?)).to be_truthy expect(response).to re...
class Comment < ApplicationRecord belongs_to :user belongs_to :review validates :content, presence: true delegate :strip_tags, to: 'ApplicationController.helpers' end
class Video < ActiveRecord::Base belongs_to :user has_many :comments end # == Schema Information # # Table name: videos # # id :integer not null, primary key # user_id :integer # video_number :integer default(1) # filename :string(255) # thumbnail :str...
module Bowline module Desktop # The Dock module gives you a few methods to control # the Mac OSX dock. It's platform specific, and on platforms # other than OSX calling the methods won't do anything. module Dock # Set the badge number. This is the little numbered red star above # the App...
class ReviewsController < ApplicationController def new @restaurant = Restaurant.find_by_location_name(params[:restaurant_id]) @review = Review.new end def create @restaurant = Restaurant.find_by_location_name(params[:restaurant_id]) @review = @restaurant.reviews.new(params[:review].permit(:rating, :commen...
require 'journey' describe Journey do let(:start_station) { double :station, name: "Waterloo", zone: 1 } let(:end_station) { double :station, name: "Kings Cross", zone: 2 } describe '#start_journey' do it 'should set entry_station to station' do subject.start_journey(start_station) expect(s...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable mount_uploader :profile_picture, Profi...
class Cnsift < ActiveRecord::Base self.table_name = "cnsift" self.primary_key = "cnsiftid" has_many :cnstyps end
# 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 rails db:seed command (or create!d alongside the database with db:setup). # # Examples: # # movies = Movie.create!([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
class Forecasting::DonationsController < Forecasting::BaseController def index @series = series('Donation') @title = 'Monthly Donations' end end
require_relative "../config/environment.rb" class Student attr_accessor :name, :grade, :id def initialize(name, grade, id = nil) @id = id @name = name @grade = grade end def self.create_table sql = <<-SQL CREATE TABLE students ( id INTEGER PRIMARY KEY, name TEXT, grade TEXT ) SQL DB[:conn].execute(sql) ...
module StartCommand def start!(*) if registered? respond_with :message, text: t('user.already_registered') else save_context :name respond_with :message, text: t('user.start') end end def name(name) save_context :email session[:name] = name respond_with :message, text: t...
class SegmentSubscriptionsController < InheritedResources::Base skip_before_action :verify_authenticity_token, only: [:create] belongs_to :user respond_to :json def create begin user = User.find(params[:user_id]) user.update_mailchimp_subscription Gibbon::API.lists.static_segment_members...
require 'spec_helper' describe 'loop_message_five_times' do it 'takes in a message and outputs it five times' do message = "Hello World." expect { loop_message_five_times(message) }.to output(/Hello World.\n/).to_stdout expect { loop_message_five_times(message) }.to output(/Hello World.\nHello World.\...
namespace :dev do task :fetch_city => :environment do puts "Fetch city data..." response = RestClient.get "http://v.juhe.cn/weather/citys", :params => { :key => JUHE_CONFIG["api_key"] } data = JSON.parse(response.body) data["result"].each do |c| existing_city = City.find_by_juhe_id( c["id"] ) ...
class CallbacksController < Devise::OmniauthCallbacksController # from : http://www.munocreative.com/nerd-notes/winvoice # @user = current_user didn't work in the past, may work if we login for prior to stripe OAuth def stripe_connect @user = current_user if @user.update_attributes({ provid...
require './producer.rb' class Wagon include Producer attr_reader :type def initialize(producer_name, type) self.producer_name = producer_name self.type = type validate! end def valid? validate! rescue false end private def validate! raise 'Имя производителя не может быть п...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :favorites,dependent: :destroy has_many :c...