text
stringlengths
10
2.61M
# $Id$ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/../timeline_event_spec_helper') describe MedicalCondition do include UserSpecHelper before(:all) do @member = make_member end describe "on create" do it "should belong to ...
class Item < ActiveRecord::Base actable belongs_to :stock belongs_to :material def item_id self.id end def material_type self.material ? self.material.actable_type : self.actable_type.split("Item").second end def full_description "#{self.material.name_with_description} - #{self.descripti...
require 'rspec' require 'dessert' =begin Instructions: implement all of the pending specs (the `it` statements without blocks)! Be sure to look over the solutions when you're done. =end describe Dessert do let(:chef) { double("chef", name: "Ramsay") } subject(:pie) do Dessert.new('pie', 2, chef) end des...
class AddPaymentOrganisationToUserTransactions < ActiveRecord::Migration[6.1] def change add_column :user_transactions, :payment_organisation_id, :integer end end
require_relative '../lib/rules' RSpec.describe Rules do describe '#first_line' do it 'returns an array of error messages' do first_line = 'json file test' expect(Rules.new(first_line, 0).check_for_errors).to include(["'{' expected at the beginning of the line", 1]) # p Rules.new(first_line, 0)....
class HotelsController < ApplicationController before_action :set_hotel, only: [:show, :edit, :update, :destroy, :update_picture] # GET /hotels # GET /hotels.json def index @hotels = Hotel.all end # GET /hotels/1 # GET /hotels/1.json def show end # GET /hotels/new def new @hotel = Hotel...
require( 'minitest/autorun' ) require( 'minitest/rg') require_relative( '../models/card' ) class TestCard < MiniTest::Test def setup @card1 = Card.new("hearts", 2) end def test_get_value assert_equal(2,@card1.value) end def test_get_suit assert_equal("Hearts",@card1.suit) end end
class DropUpdatedAtFromTmpgImpressions < ActiveRecord::Migration def change remove_column :tmpg_impressions, :updated_at, :date end end
require 'test_helper' class RequestControllerTest < ActionController::TestCase # test "the truth" do # assert true # end describe "GET #index" do it "loads index view" do get :index response.should render_template :index end end describe "GET #show" do it "assigns the requested conta...
require_relative "test_helper" class TestCustomer < Minitest::Test def test_customer_has_id customer = Customer.new(1, "Joey", "Ondricka", "2012-03-27 14:54:09 UTC", "2012-03-27 14:54:09 UTC") asse...
INTEGRATIONS = %w(sentry-rails sentry-sidekiq sentry-delayed_job sentry-resque sentry-opentelemetry) GEMS = %w(sentry-ruby) + INTEGRATIONS def get_version_file_name(gem_name) case gem_name when "sentry-ruby" "lib/sentry/version.rb" else integration_name = gem_name.sub("sentry-", "") "lib/sentry/#{int...
class VideosController < ApplicationController respond_to :html def index @user = User.find_by(:id => params[:user_id]) end def show @video = Video.find(params[:id]) end def new @video = Video.new end def edit @video = Video.find(params[:id]) end def create @video = Video.create(video_params) ...
require 'rails_helper' RSpec.describe CardAccount::Edit do let(:account) { create_account } let(:op) { described_class } let(:card_account) { create_card_account(person: account.owner) } describe 'prepopulation' do it 'sets "closed" correctly' do contract = op.({ id: card_account.id }, 'current_acco...
class CreateEventProducts < ActiveRecord::Migration def change create_table :event_products do |t| t.string :name t.integer :price t.integer :event_id t.timestamps end add_index :event_products, [:event_id] end end
class RenameColumnComponentsIdFromCertificates < ActiveRecord::Migration def change rename_column :certificates, :componetns_id, :other_work_id end end
require_relative 'application_record' class Question < ApplicationRecord belongs_to :session validates :name, presence: true validates :start_time, presence: true validates :duration, presence: true end
class CreateNeeds < ActiveRecord::Migration[5.2] def change create_table :needs do |t| t.text :description t.boolean :is_taken t.integer :duration t.datetime :datetime_range_start t.datetime :datetime_range_end t.text :categories t.timestamps end end end
class RemoveCommentAndApprovedAndSupervisorHourFromWorkhour < ActiveRecord::Migration def up remove_column :workhours, :comment remove_column :workhours, :approved remove_column :workhours, :supervisor_hour end def down end end
class AddColumnDeleteColumnProjects < ActiveRecord::Migration def up add_column :projects, :delete_flag, :boolean, :default => false remove_column :projects, :available end def down add_column :projects, :available, :boolean, :default => true end end
require 'util/win32/nt_util' require 'binary_struct' module NTFS # # STANDARD_INFORMATION - Attribute: Standard information (0x10). # # NOTE: Always resident. # NOTE: Present in all base file records on a volume. # NOTE: There is conflicting information about the meaning of each of the time # fields bu...
class ApiSearchLogger attr_reader :user_input, :model_class attr_accessor :last_search def initialize(model_class, user_input) @model_class = model_class @user_input = user_input @last_search ||= model_class.includes(:versions).find_by(user_input: user_input) end def log_search! return last_s...
# == Schema Information # # Table name: ad_campaigns # # id :integer not null, primary key # description :text # shop_id :integer # created_at :datetime not null # updated_at :datetime not null # class AdCampaign < ActiveRecord::Base belongs_to :shop has_many :advertise...
class Array def split mid = size / 2 left = slice(0, mid) right = slice(mid, (size - mid)) return left, right end end class MergeSort def self.perform(array) return array if array.size < 2 left, right = array.split merge(perform(left), perform(right)) end def self.merge(a1, a2) ...
require 'test_helper' class BrochuresControllerTest < ActionDispatch::IntegrationTest setup do @brochure = brochures(:one) end test "should get index" do get brochures_url assert_response :success end test "should get new" do get new_brochure_url assert_response :success end test "...
class ActionPoint < ApplicationRecord belongs_to :action_quality validates :point, presence: true scope :fav, -> { find(1) } scope :retweet, -> { find(2) } scope :quote, -> { find(3) } scope :reply, -> { find(4) } scope :xs_tweet, -> { find(5) } scope :s_tweet, -> { find(6) } scope :l_tweet, -> { fi...
Pod::Spec.new do |s| s.name = "TwitterKitLegacy" s.version = "3.5.0" s.summary = "Increase user engagement and app growth." s.homepage = "https://github.com/twitter/twitter-kit-ios" s.documentation_url = "https://github.com/twitter/twitter-kit-ios/wiki" s.social_media_url = "https://twitter.com/TwitterDev" ...
module Scalablepress class RequestParams attr_accessor :klass, :params, :collection def initialize(args={}) @klass = args.fetch(:klass) @params = args.fetch(:params) { {} } @collection = args.fetch(:collection) { true } end def resource_name @resource_name ||= collection ? co...
require 'rails_helper' RSpec.describe Vendor, type: :model do describe 'db structure' do it { is_expected.to have_db_column(:first_name).of_type(:string) } it { is_expected.to have_db_column(:last_name).of_type(:string) } it { is_expected.to have_db_column(:phone).of_type(:string) } it { is_expected....
class AddProductsToProducts < ActiveRecord::Migration[6.1] def change add_column :products, :puissance, :decimal add_column :products, :vitesse_max, :decimal add_column :products, :Acceleration, :decimal end end
require 'sphinx_helper' describe 'User can search', " In order to search some information As an authenticate user I'd like to be able to use search " do let!(:user) { create(:user) } let!(:community) { create(:community, creator: user) } before do sign_in(user) visit root_path end it 'search ...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
class Repo def initialize(storage) @storage = storage end end
ENV["RAILS_ENV"] ||= "test" require_relative "../config/environment" require "rails/test_help" class ActiveSupport::TestCase # Run tests in parallel with specified workers #parallelize(workers: :number_of_processors, with: :threads) # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order...
class ClinicAssociate::ClinicAssociatesController < ApplicationController layout "patient_layout" # before_filter :require_clinic_associate_signin, except: [:new, :create,:confirm_email] def dashboard end def privacy_policy end def new @clinic_associate = ClinicAssociate.new render :layout => "...
#encoding: utf-8 gem 'myerror' module Ogem class Player attr_accessor :name, :r def initialize name="Player", m=1000, c=1000, d=0 if !name.is_a?String Error.call "Ogem::Player::new : invalid name", Error::ERR_MEDIUM name = "Player" end @name = name @r = {m: m.to_i, ...
require 'test_helper' class PostsControllerTest < ActionController::TestCase test 'should render table' do get :index, template: :render assert_select 'table#the-id.the-class' do assert_select 'thead' do assert_select 'tr' do assert_select 'th' end end assert_sel...
class Forest < Formula version '0.3.0' desc "For the forest on your computer." homepage "https://github.com/robinmitra/forest" url "https://github.com/robinmitra/forest/archive/v#{version}.tar.gz" sha256 "c4cedb0e32fc8534f183dab5f9a363f71daac162b2eee546ae231f9339324ac0" depends_on "go" => :build def ins...
class Pokemon #bonus version attr_accessor :name, :type, :db, :hp attr_reader :id def initialize(name:, type:, db:, id: nil, hp: nil) @id = id @name = name @type = type @db = db @hp = hp end def self.save(name, type, db) sql = <<-SQL INSERT INTO pokemon (name, type) VA...
require 'spec_helper' describe AuthenticatedService do subject { AuthenticatedService.new mock_action_controller } def mock_action_controller @mock_action_controller ||= mock(ActionController) end describe "delegates methods to the controller instance" do it "should delegate :current_user to the ...
require File.expand_path('../lib/delayed_worker/version', __FILE__) Gem::Specification.new do |s| s.name = 'delayed_worker' s.version = DelayedWorker::VERSION s.date = Time.now.strftime('%F') s.required_ruby_version = '>= 2.2.2' s.author...
module Chronic class Keyword < Tag # Scan an Array of Token objects and apply any necessary Keyword # tags to each token. # # tokens - An Array of tokens to scan. # options - The Hash of options specified in Chronic::parse. # # Returns an Array of tokens. def self.scan(tokens, options...
module Authenticable extend ActiveSupport::Concern included do before_action :authenticate, if: -> { request.path.start_with?('/api') } protect_from_forgery with: :exception skip_before_action :verify_authenticity_token, if: -> { request.path.start_with?('/api') } end private def authenticate ...
module OMS # kaveesh: These error codes are from the base OMS Agent for linux and for consistency I'm keeping them as is because the numbers don't really make a difference to us. # https://github.com/microsoft/OMS-Agent-for-Linux/blob/824c40889ba0c0a819a97184846c4abef30f474c/source/code/plugins/agent_common.rb#...
# frozen_string_literal: true class LegacyCourseUserImporter def self.add_users(data, role, course) data.map do |user_data| add_user(user_data, role, course) end end def self.add_user(user_data, role, course) user = User.find_or_create_by(id: user_data['id']) user.username = user_data['user...
require 'spec_helper' describe MacWiki2MD do it 'has a version number' do expect(`bundle exec exe/macwiki2md --version`).to include MacWiki2MD::VERSION end end
Rails.application.routes.draw do mount Ckeditor::Engine => '/ckeditor' namespace :admin do resources :users, except: [:show] end namespace :teacher do resources :questions, except: [:show] get 'student_exam_results/:student_id', to: 'students#exam_results', as: 'student_exam_results' resources...
class EventsController < ApplicationController before_action :find_event, only: [:show, :edit, :update, :dashboard, :join, :withdraw, :destroy] def index @page = params[:page] ||= "1" @events = Event.includes(:groups, :location, :category).all @events.search(params[:search]) if par...
require './lib/user' require './lib/joke' require 'pry' class OpenMic attr_reader :location, :date, :performers def initialize(info) @location = info[:location] @date = info[:date] @performers = [] end def welcome(performer) @performers << performer end def re...
module Jwshinroma module Physical module Body def skin 'fur' end def has_fins false end end end end
# frozen_string_literal: true # typed: strict require 'sorbet-runtime' require 'active_support/core_ext/object' require_relative 'keyword' require_relative 'token' require_relative 'expression' module MonkeyLang # The Parser for the Monkey language. # The goal of a parser is to turn a list of tokens # into an a...
class PhotoSet < ActiveRecord::Base has_many :photos def self.options find(:all).map {|i| [i.name, i.id] } end end
class ProjectsController < ApplicationController before_filter :find_project before_filter :require_user, :except => [:show, :index] def create @project = Project.new(params[:project]) if @project.name && @project.url == '' @project.url = "http://github.com/#{current_user.login}/#{@project.name}" ...
class Api::V1::ProjectsController < ApplicationController skip_before_action :verify_authenticity_token swagger_controller :projects, 'Projects Management' swagger_api :index do summary 'Returns project details' param :query, :id, :integer, :required, 'Project Id' end def index...
class ConvertUserIntoCharacterInMonthlyGoal < ActiveRecord::Migration def change rename_column :monthly_goals, :user_id, :character_id MonthlyGoal.find_each do |goal| goal.update character_id: User.find(goal.character_id).last_used_character end end end
class Plan # not subclassing off active record base because there will be no plans table PLANS = [:free, :premium] def self.options PLANS.map { |plan| [plan.capitalize, plan] } end # map modifies all elements in an array taht you pas # this modifies all plans to be capitalized ...
describe "Job" do it "calculates running time of a job" do job = Job.first job.calculated_running_time.should_not be_nil if job end end
configatron.product_name = "test product" require_relative './lib/paypalhttp/version' # Custom validations def get_package_version VERSION end def validate_version_match package_version = get_package_version if package_version != @current_release.version Printer.fail("package version #{package_version} does no...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Score', type: :model do let(:unit) { create(:unit) } let(:opponent_unit) { create(:unit) } let(:game) { create(:game, record_user_id: user.id) } let(:user) { create(:user) } let(:opponent_user) { create(:user) } let(:score) do Score....
class AppointmentsController < ApplicationController include AppointmentsHelper def index if !logged_in? redirect_to root_path else @phase = params[:phase] @user = User.find_by(id: session[:user_id]) @next_appointment = User.find_by(id: session[:user_id]).next_booked_appointment ...
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are 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-...
require 'station' describe Station do station = Station.new("here", 4) it "stores station name when it initializes" do expect(station.name).to eq("here") end it "stores the zone when it initializes" do expect(station.zone).to eq(4) end end
class Recipe @@all = [] def initialize(type) @type = type @@all << self end def self.all @@all end def users arr = [] RecipeCard.all.each do |recipe_card| if recipe_card.recipe == self arr << recipe_card.user end...
# frozen_string_literal: true FactoryGirl.define do factory :response, class: Hash do skip_create ok true user { build(:response_user) } initialize_with { attributes.stringify_keys } end factory :response_user, class: Hash do skip_create id 'SLACKUSERID' initialize_with { attributes.s...
Gem::Specification.new do |s| s.name = 'array_range_extensions' s.version = '0.0.1' s.date = '2016-02-28' s.summary = "array_range_extensions" s.description = "check duplicates in an array of ranges" s.authors = ["Dinesh Theetla"] s.email = "dinesh.t2707@gmail.com" s.file...
class ProtoFile attr_reader :path def initialize(options) if !options[:path].nil? and !options[:id].nil? raise ArgumentError, 'ProtoFile cannot be specified with both a path and an id' elsif options[:path] @path = Pathname.new options[:path] elsif options[:id] id = options...
# # Cookbook Name:: cubrid # Attributes:: web_manager # # Copyright 2012, Esen Sagynov <kadishmal@gmail.com> # # Distributed under MIT license # # latest build numbers for each CUBRID version in the form of 'version'=>'build_number' build_numbers = {'9.1.0' => '0001', '9.0.0' => '0004', '8.4.3' => '0009', '8.4.1' => '...
class PublicationsController < ApplicationController def index if params[:user_id] @user = User.find(params[:user_id]) @publications = @user.publications else @publications = Publication.all end end def new @user = User.find(session[:user_id]) @publication = @user.publicati...
class ChangeColumnTypeOfComeAndGo < ActiveRecord::Migration def change change_column :contacts, :come, :date change_column :contacts, :go, :date end end
#rules, takes on integer argument (valid), returns true if the number's absolute value is odd # input: integer # output: return boolean def is_odd?(number) number % 2 == 1 end puts is_odd?(2) # => false puts is_odd?(5) # => true puts is_odd?(-17) # => true puts is_odd?(-8) # => false puts is_odd?(0) # =>...
class ContactRequestsController < ApplicationController def create @contact_request = ContactRequest.new(contact_params) if @contact_request.save ContactMailer.contact_request(@contact_request).deliver_later! render json: @contact_request, status: :created else render json: @contact_requ...
require "rvm/capistrano" # For RVM require 'bundler/capistrano' # for bundler support require 'whenever/capistrano' # for whenever support set :whenever_command, "bundle exec whenever" set :application, "handraise" set :repository, "git@github.com:flatiron-school/handraise-redux.git" set :user, 'handraise' set :dep...
class AddStartAmountToModuleInstance < ActiveRecord::Migration def change add_column :module_instances, :amount, :float end end
class Api::V1::AlbumsController < ApplicationController def index albums = Album.all render json: albums, except: [:created_at, :updated_at] # render json: users, only: [:name, :id], include: :tweets end def create album = Album.create(album_params) render json: album, except: [:created_at, :...
class CreateUsers < ActiveRecord::Migration[4.2] def change create_table :users, id: false do |t| t.string :first_name t.string :last_name t.string :status t.string :email t.string :is_student t.string :is_teacher t.string :is_management t.string :is_admin t....
module KPM module SystemProxy module DiskSpaceInformation class << self def fetch disk_space_info = nil if OS.windows? disk_space_info = fetch_windows elsif OS.linux? disk_space_info = fetch_linux_mac(5) elsif OS.mac? disk_...
#!/usr/bin/env ruby require 'json' require 'mailgun' require 'open-uri' require 'rake/thread_pool' MAX_ADS = 100 MAILGUN_API_KEY = ''.freeze MAILGUN_DOMAIN = ''.freeze NOTIFICATION_EMAIL = ''.freeze STDOUT.sync = true flag_allow_new_traders = ARGV.include?('--allow-new-traders') def send_email(subject, txt, reci...
class Doc < ActiveRecord::Base scopify def document_file=( document_data ) self.filename = document_data.original_filename self.content_type = document_data.content_type.chomp self.binary_content = document_data.read end end
class ConnectCallToConference def initialize(call:, sids:, adapter: TwilioAdapter.new) @connecting_call = call @sids = sids @adapter = adapter end def call connected_sids = sids.map { |sid| if connect_to_conference(sid) sid end }.compact if connected_sids === sids ...
class ImportReportMailer < ActionMailer::Base include ActionView::Helpers::TextHelper include ActionView::Helpers::NumberHelper default :from => "no-reply@zenmaid.com" def customers_import_report(num_saved, num_error, failed_customers) @saved_customer = num_saved @not_saved_customer = num_error ...
# frozen_string_literal: true require 'system_spec_helper' require 'net/scp' RSpec.describe '#work with dump' do context 'check if can remove db' do it 'should be possible to drop database' do @project_name = 'magento_1_9' @database = { host: CONFIG['database']['host'], user: CONFIG...
class AddPasswordToSubcontractor < ActiveRecord::Migration def change add_column :subcontractors, :password, :string end end
class CarSerializer < ActiveModel::Serializer attributes :id, :year, :make, :model, :km, :tran, :fuel_type, :weekday_price,:weekend_price, :plate_num, :color, :description has_many :car_photos end
class Widgets::Index < Mustache::Rails def new_path new_widget_path() end def listing widgets.collect do |record| { :title => record.title, :description => record.description, :show_path => widget_path(record) } end end end
class Locations2 < ActiveRecord::Migration[5.0] def up rename_column :locations, :country, :city rename_column :locations, :language, :weather end def down rename_column :locations, :city, :country rename_column :locations, :weather, :language end end
class OrderItem < ApplicationRecord validates_presence_of :delivery_order_id, :meal_id, :quantity, :unit_price belongs_to :delivery_order belongs_to :meal has_many :feedbacks, as: :ratable end
# frozen_string_literal: true require 'rails_helper' require_relative '../../support/shared_examples_for_activeadmin' RSpec.describe Admin::DataTablesController, type: :controller do include ActionDispatch::TestProcess it_behaves_like 'an activeadmin resource' do let(:resource_name) { :data_table } let(:c...
class Product attr_reader :name, :units # available getters # attr_writer :price # available setters attr_accessor :price # setter + getter # constructor def initialize(name, price, units = 0) @name = name @price = price @units = units end def available() ...
class Fond < ActiveRecord::Base has_many :really_fonds FIELDS = { :amount => 1, :firstname =>2, :lastname => 3, :sex => 4, :email => 5, :street => 6, :number => 7, :city => 8, :psc =>9, :professi...
When(/^I select the Capital One logo$/) do on(StatementsPage) do |page| page.wait_for_logo_to_load page.logo @page_data = page.data_for(:header_footer_account) end end Then(/^I should be redirected to the Account Summary Page$/) do expect(on(AccountSummaryPage).customername_element.text).to eq @page_data['s...
class MobileNotifier attr_accessor :user NOTIFICATION_DELAYS = [5.minutes, 10.minutes, 20.minutes, 30.minutes, 1.hour, 2.hours, 4.hours, 8.hours, 24.hours] # approximate 2^n exponential backoff # Frequency is in minutes # Frequency of -1 means don't send any digests - send notifications for every story STORI...
require 'pry' def find_item_by_name_in_collection(name, collection) # Implement me first! # # Consult README for inputs and outputs collection.each do |hash| if hash[:item] == name return hash end end return nil end def consolidate_cart(cart) # Consult README for inputs and outputs # #...
require "rails_helper" module Archangel RSpec.describe PostsController, type: :controller do describe "GET #show" do it "uses correct layout" do post = create(:post) archangel_get :show, params: { year: post.published_at.year, month: "%02d" % post.published_at.month, ...
module KindlePras class Processor DEFAULT_PATH = 'data/My Clippings.txt' #DEFAULT_PATH = 'data/My Clippings.txt.sample' REGEXP_CHUNK_DELIMITER = '==========' REGEXP_TITLE_AUTHOR_LINE = /^(?<title>.*).*\((?<author>.*?)\)$/ REGEXP_NOTE_CHUNK = /Your Note on Location/ REGEXP_BOOKMARK_CHUNK = /...
class StacheCategory < ActiveRecord::Base belongs_to :stache belongs_to :category end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you ...
class Rol < ActiveRecord::Base belongs_to :user has_and_belongs_to_many :menu_options has_many :functions end
arr = [1,2,3,4,5,6,7,8,9,10] # print out each value arr.each do |e| puts e end puts # print out values greater than 5 arr.each do |e| puts e if e > 5 end puts # extract odd numbers in the array puts arr.select {|num| num.odd?} puts # Append "11" to the end of the array and prepend "0" to the beginning puts ...
class LocationValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if valid_location?(value) record.errors[attribute] << "The #{attribute} is not a valid location" end private def valid_location?(location) location.is_a?(DistanceMatrix::Location) && location.v...
module TicTacToeRZ module Core module Rules def self.all_marks_same?(marks) marks.all? { |m| m == marks[0] } end def self.winning_marks?(marks) marks[0] if all_marks_same?(marks) && !(marks[0].blank?) end def self.who_won?(board) board.attack_sets.map { |ma...
require 'rails_helper' describe "Remove user from team", type: :feature, js: true do it "removes the user from team" do owner = create(:user) invited = create(:user) team = create(:team, user: owner, users: [invited]) login_as owner visit team_chat_path(team.slug) find("#channel_users").clic...