text
stringlengths
10
2.61M
require 'pry' count = 0 stopper = false while stopper == false count += 1 binding.pry end stopper = true binding.pry # puts "Ohhhh Baby" # count = 10 # minute = Time.new.strftime("%M").to_i # # while minute.even? # puts "The time is #{minute}" # minute = Time.new.strftime("%M").to_i # end # 5.times do |i| ...
class CreateFloorsJobs < ActiveRecord::Migration def change create_table :floors_jobs, :id => false do |t| t.references :floors t.references :jobs end add_index :floors_jobs, :floors_id add_index :floors_jobs, :jobs_id end end
class EsBrandsSyncJob < ActiveJob::Base queue_as :default def perform(overwrite_model="overwrite") EsBrandsSync.sync(overwrite_model) end end
require 'spec_helper' feature 'Commenting on challenge' do let!(:member) { new_member } let!(:organization) { new_organization } let!(:challenge) { FactoryBot.create(:challenge, organization: organization) } background do sign_in_user(member.user, password: 'password') end scenario "show 'Metodologia...
require 'minitest/autorun' require 'matilda-future' describe "Promise" do describe "#future" do it "returns a Future value that is set when the Promise is set" do promise = Promise.new future = promise.future assert_equal(future.ready?, false) promise.set("Done") assert_equal(futur...
class LikesController < ApplicationController before_action :set_item_search_query before_action :set_item, except: [:index] before_action :set_categories, only: [:index] before_action :move_show_item, except: [:index] def index like_ids = Like.users(params[:user_id]).pluck(:id) @items = Item.eager_...
require 'open-uri' class StockTrackerWorker include Sidekiq::Worker def perform if Time.now.during_business_hours? all_open_transactions = Transaction.all_open return if all_open_transactions.empty? all_open_stocks_string = all_open_transactions.map(&:stock).join(",") all_open_stocks_...
require 'test_helper' class Auth::Admin::UserTagsControllerTest < ActionDispatch::IntegrationTest setup do @user_tag = auth_user_tags(:one) end test 'index ok' do get url_for(controller: 'auth/admin/user_tags', action: 'index') assert_response :success end test 'new ok' do get url_for(cont...
class FavoritesController < ApplicationController def create palette_id = Palette.find_by(id: params[:palette_id]).id favorite = logged_in_user.favorites.build(palette_id: palette_id) if favorite.save render json: logged_in_user else render json: favor...
class Order < ActiveRecord::Base include AASM include NumberGenerator extend FriendlyId friendly_id :number, use: :slugged, slug_column: :number attr_accessor :refund_reason # -------------- SECTION FOR ASSOCIATIONS -------------------- # ------------------------------------------------------------- ...
class PlaylistsController < ApplicationController def new @playlist = current_user.playlists.build end def create @playlist = Playlist.new(playlist_params) if @playlist.save redirect_to @playlist else render :new end end def show @playlist = Playlist.find(params[:id]) ...
class TattooInformation < ApplicationRecord belongs_to :interaction has_many :reference_images end
class AddImageUrlandPageCountToBooks < ActiveRecord::Migration[5.2] def change add_column :books, :image_url, :string add_column :books, :page_count, :integer end end
namespace :npm do desc 'run deploy' task :production_deploy do on roles(:app) do within "#{current_path}" do execute :npm, "run deploy:prod" end end end task :staging_deploy do on roles(:app) do within "#{current_path}" do execute :npm, "run deploy:staging" e...
class Pitcher < ApplicationRecord validates :name, presence: true validates :birthdate, presence: true has_many :seasons has_many :pitch_events end
When /^I ask for the CSS weight$/ do @css_weight = PageWeight::PageWeight.of_css_for(@url) end Then /^the CSS weight is supplied$/ do @css_weight.should == 404 end When /^I ask for the number of CSS files for that url$/ do @css_files = PageWeight::PageWeight.css_files_count_for(@url) end Then /^the number of C...
# 1. is n divisible by x and y # 2. Create a function (or write a script in Shell) that takes an integer # as an argument and returns "Even" for even numbers or "Odd" for odd numbers. require './lib/methods' describe '#even_or_odd' do it "returns 'Even' for even numbers" do # require 'pry'; require 'pry-byebug'...
require 'selenium-webdriver' require 'mail' require 'nokogiri' require 'cgi' require 'json' class GoogleGroupDump attr_reader :driver attr_reader :topics attr_reader :messages attr_reader :google_group_url # set up variables from the env file def initialize(group_url) # set the local variables...
class FlickrController < ApplicationController def show @photos = flickr_search(params[:search]) end # def search # # query the API # # @images = photo_results(...) # # render 'index' # # @images = images_array.each { |image| Image.new(name: image[:name], url: image[:url])} # end priva...
class ClientSummarizer attr_reader :client_namespace, :fiscal_year def initialize(args) @client_namespace = args[:client_namespace] now = Time.zone.now @fiscal_year = (args[:fiscal_year] || FiscalYearFinder.new(now.year, now.month).run).to_i end def run @records ||= build_records @summary ...
class ShortMessage < ActiveRecord::Base belongs_to :sender, :class_name => 'User', :foreign_key => :sender_id belongs_to :receiver, :class_name => 'User', :foreign_key => :receiver_id validates :sender, :receiver, :content, ...
# Description: ChefVault::Compat module # Copyright 2013, Nordstrom, 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 b...
require 'mongoid' module SesProxy class RecipientsNumber include Mongoid::Document field :original, type: Integer field :filtered, type: Integer field :created_at, type: DateTime field :updated_at, type: DateTime end end
class CreateOfferings < ActiveRecord::Migration def change create_table :offerings do |t| t.integer :year t.string :term t.string :time t.float :median_grade t.string :specific_title t.string :wc t.text :specific_desc t.boolean :unconfirmed t.string :crn ...
require 'rails_helper' RSpec.describe Post, type: :model do describe "associations" do it { should belong_to(:user) } it { should have_many(:comments) } end describe "validation" do it { should validate_presence_of(:caption) } end end
require "rails_helper" require "models/concerns/ownable" require "models/concerns/assignable" require "models/concerns/assign_toable" require "models/concerns/purchasable" require "models/concerns/fieldable" require "models/concerns/serializable" RSpec.describe Item, type: :model do subject { create(:item) } desc...
# # Cookbook Name:: vim # Spec:: default # # Copyright (c) 2015 The Authors, All Rights Reserved. require 'spec_helper' describe 'vim::default' do context 'When all attributes are default, on an unspecified platform' do let(:chef_run) do runner = ChefSpec::ServerRunner.new do |node| node.set['curr...
# def ask question # goodAnswer = false # while (not goodAnswer) # puts question # reply = gets.chomp.downcase # if (reply == 'yes' or reply == 'no') # goodAnswer = true # if reply == 'yes' # answer = true # else # answer = false # end # else # puts 'Pl...
require 'spec_helper' describe RubricsController do describe 'GET index' do it 'should assign @rubric' do rubric = FactoryGirl.create :rubric get :index assign(:rubrics).all.should eq([rubric]) end end describe 'GET show' do it 'should assign @rubric' do rubric = FactoryGirl...
class Score < ActiveRecord::Base before_create :set_just_created scope :find_by_source, -> (paper) { where(:source => paper) } scope :express, -> { where(source:"express") } scope :guardian, -> { where(source:"guardian") } scope :independent, -> { where(source:"independent") } scope :mail, -> { where(source:"ma...
class AddColumnsToEvents < ActiveRecord::Migration[5.0] def change add_column :events, :description, :string add_column :events, :one_liner, :string add_column :events, :other_sellers, :boolean end end
class Category < ActiveRecord::Base has_many :movies, through: :movie_categories end
class Balance < ActiveRecord::Base belongs_to :account, dependent: :destroy scope :in_date_order, -> { order('created_at ASC') } scope :created_before, ->(date) do where('balances.created_at <= ?', date) end end
class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i record.errors[attribute] << (options[:message] || "is not an email") end end end class Producer < ActiveRecord::Base validates :email, pres...
#encoding: utf-8 require 'date' module VmstatCat module CreatedAt def created_at fill_0 = lambda{|val| format("%02d", val) } oclock = Time.now y = oclock.year.to_s m = fill_0.call(oclock.month) d = fill_0.call(oclock.day) h = fill_0.call(oclock.hou...
class PhotosController < ApplicationController before_action :authenticate_user! before_action :set_photo def show send_data @photo.content, :type => @photo.content_type,:disposition => 'inline' end def set_photo @photo = Photo.find params[:id] end end
# == Schema Information # # Table name: locations # # id :integer not null, primary key # name :string # external_id :string # secret_code :string # created_at :datetime not null # updated_at :datetime not null # class Location < ActiveRecord::Base has_and_belongs_to_...
# -*- encoding : utf-8 -*- class CreateEmails < ActiveRecord::Migration def change create_table :emails, id: :uuid do |t| t.string :address t.boolean :is_primary t.references :user, type: 'uuid', index: true t.timestamps null: false end add_foreign_key :emails, :users end end
# -*- coding: utf-8 -*- require 'test/unit' require 'date' require 'hcal' class TC_HolydayCalendar < Test::Unit::TestCase def test_isMonth_1 assert(HolydayCalendar.isMonth(1)) assert(HolydayCalendar.isMonth(12)) end def test_isMonth_2 assert_equal(false, HolydayCalendar.isMonth(-1)) assert_equa...
require 'bcrypt' class User < ActiveRecord::Base has_many :reviews has_many :comments has_many :businesses include BCrypt def password @password ||= Password.new(password_hash) end def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end ...
class StudentsController < ApplicationController def index @students = Student.all redirect_to student_profile_path end def new @student = Student.new end def create @student = Student.create(student_params) redirect_to student_profile_path end def show @enrolled_course = [] ...
class Student < ApplicationRecord has_many :assignments has_many :teachers, through: :assignments has_many :student_klasses has_many :teacher_klasses, through: :student_klasses has_secure_password validates :username, uniqueness: true def display_age Time.now.year - self.dob.slice(0...
module Vanity module Adapters class << self # Creates new connection to underlying datastore and returns suitable # adapter (adapter object extends AbstractAdapter and wraps the # connection). # # @since 1.4.0 def establish_connection(spec) begin require "vani...
class Picture < ActiveRecord::Base validates :artist, presence: true validates :url, presence: true validate :validate_title validate :validate_url private def validate_title if !(title.to_s.length >= 3 && 20 >= title.to_s.length) errors.add(:title, "Avast me hearty, thar is an error") end ...
SCHEDULER.every '60s' do send_event('installs', { current: 0 }) end
class UserPolicy < ApplicationPolicy permit :show def update? same_user end def change_password? update? end def change_avatar? update? end private def same_user @user.id == @scope.id end end
class ChemicalsController < ApplicationController before_filter :signed_in_user, :only => [:index, :edit, :update, :destroy, :show, :new, :create] before_filter :assignee_user, :only => [:edit, :update, :destroy, :new, :create] helper_method :sort_column, :sort_direction # GET /chemicals # GET /chemicals.j...
# Method: print_list # input: hash # steps: interpolate each key and value into a string for the UI # output: String def print_list(grocery_list) grocery_list.each do |x,y| puts "Item: #{x}-- ##{y}" end end # Method: make_grocery_list, print_list # input: string of items separated by spaces # steps: value groc...
class CreateChurchesPeople < ActiveRecord::Migration def change create_table :churches_people do |t| t.integer :church_id t.integer :person_id t.integer :start_date_year t.integer :start_date_month t.integer :start_date_day t.integer :end_date_year t.integer :end_date_mon...
class User < ActiveRecord::Base attr_accessor :remember_token has_secure_password validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create } validates :email, uniqueness: { case_sensitive: false } validates :username, length: { in: 2..15 } validates :password, length: ...
class StepFailer < Step def color '#ffC070' end def shape :box end def run(current_job, current_action) # Starting log "StepFailer.start" # Raise an unhandled exception raise Exceptions::UnhandledException, "failing as expected" # Finished log "StepFailer.end f...
class AddContactsPartnershipOrganisation < ActiveRecord::Migration def change add_column :dsc_contacts, :partnership_organisation_id, :integer end end
class Tag include Mongoid::Document field :name end
class AddMainColumnsToTypeAccounts < ActiveRecord::Migration def change change_table :type_accounts do |t| t.boolean :main end end end
require "rails_helper" describe Scheduler::ReconciledSchedule do before do @coach = create(:coach) end it "should be a hash" do reconciled_schedule = Scheduler::ReconciledSchedule.new(coach: @coach).to_hash expect(reconciled_schedule.class).to eq(Hash) end context "when availability" do it...
source 'https://rubygems.org' gem 'rails', '~> 5.0.0', '>= 5.0.0.1' gem 'puma', '~> 3.0' gem 'pg', '~> 0.19', group: [:development, :test] gem 'mysql2', '~> 0.4.4', group: :production gem 'slim-rails', '~> 3.1.0' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2' gem 'therubyracer', p...
class AddForeignToLookupTable < ActiveRecord::Migration[5.1] def change remove_column :accounts, :currency add_column :accounts, :currency_id, :integer add_foreign_key :accounts, :currencies add_column :accounts, :acc_type_id, :integer add_foreign_key :accounts, :acc_types remove_column :tran...
class AddIndexcours < ActiveRecord::Migration[5.2] def change add_reference :cours, :users, foreign_key: true end end
require 'spec_helper' require 'route_simulator' describe RouteSimulator do before do @route_simulator = RouteSimulator.new @route_simulator.init_map(5,5) @test_input = <<-eos 5 5 1 2 N LMLMLMLMM 3 3 E MMRMMRMRRM eos @test_output = <<-eos 1 3 N 5 1 E eos end it "should create a map" do ...
def nyc_pigeon_organizer(data) ret_hash = {} name_list = get_names(data).uniq name_list.each do |pigeon_name| ret_hash[pigeon_name]=build_pigeon(pigeon_name, data) end ret_hash end def get_names(data) # RETURN: all values in the arrays nested under two hashes {k,{k,[]}} name_list = [] data.each_...
require 'test_helper' class LocationControllerTest < ActionDispatch::IntegrationTest setup do @location = location(:one) end test "should get index" do get location_index_url assert_response :success end test "should get new" do get new_location_url assert_response :success end tes...
# rubocop:disable Metrics/BlockLength # rubocop:disable Layout/LineLength require 'rails_helper' RSpec.describe Friendship, type: :model do describe 'associations' do it 'belongs to one user' do friend = Friendship.reflect_on_association(:user) expect(friend.macro).to eql(:belongs_to) end it...
class CreateSocialMedias < ActiveRecord::Migration def self.up create_table :social_medias do |t| t.integer :person_id, :null => false t.string :linked_in_url t.string :facebook_url t.string :twitter_url t.string :flickr_url t.timestamps end end def self.down drop...
FactoryBot.define do factory :user do factory :admin_user do email { "admin_user@test.com" } first_name { "First Name"} last_name { "Last Name"} password { "123456" } password_confirmation { "123456" } end factory :tipic_user do email { "tipic_user@email.com" } p...
class SoftwareBinder::Software attr_accessor :name, :overall_rating, :reviews, :description, :page_slug attr_reader :category @@all = [] def initialize(category) @category = category self.save end def save @@all << self end def self.all @@all end def self.reset @@all.clear ...
class SendNotificationJob < ApplicationJob queue_as :default def perform(ticket) @ticket = ticket FirstNotificationMailer.first_notification_email(@ticket).deliver_later end end
require 'rails_helper' feature 'posts' do context 'no posts have been posted' do scenario 'should display a prompt to post a picture' do visit '/posts' expect(page).to have_content 'No posts yet' expect(page).to have_link 'Create a Post' end end context 'pictures have been added' do ...
class RenameColumnInAssignments < ActiveRecord::Migration def change rename_column :assignments, :difficulty, :level end end
class GuidesTags < ActiveRecord::Base belongs_to :guide belongs_to :tag end
class GameMobileController < ApplicationController before_action :check_game, except: [:welcome, :ended] before_action :check_user, only: [:game, :join, :choosen, :new_name, :repeat, :send_emoji] before_action :check_state, only: [:game] def welcome @game = Game.where(password: params[:password], active: tru...
# == Schema Information # # Table name: songs # # id :integer not null, primary key # title :string(255) # artist :string(255) # permalink :string(255) # description :text # num_stars :integer default(0) # created_at :datetime not null # updated_at :datetime ...
#Building Class require 'pry' class Building attr_accessor :name, :address, :apartments def initialize(name, address) @address = address @name = name @apartments = [] end def create_building(building_name, building_address) puts "-----------New Building-----------" puts "What is the buil...
#!/usr/bin/env ruby $VERSION = '0.1.1' require_relative 'lib/reversion' @usage = "Reversion #{$VERSION} Usage: rvn <command> [args] Commands: init: Create a new repository. add: Adds a file to the repo. checkout: Switch to a previous commit. all: List all currently tracke...
# 21章は Procクラス # 1. collectメソッドを自作する def my_collect(obj, &block) result = [] obj.each do |elem| result << block.call(elem) end result end ary = my_collect([1, 2, 3, 4, 5]) do |i| i * 2 end p ary # 2. 結果参照 to_class = :class.to_proc p to_class.call("test") # String p to_class.call(123) # Integer p to_cla...
class CreateClassrooms < ActiveRecord::Migration def change create_table :classrooms do |t| t.string :name t.integer :teacher_id, null: false t.string :courses_name t.timestamps null: false end add_index(:classrooms, :teacher_id) end end
require "shiv_includes" require "pp" cfg = Object::File.open("shiv.yml"){|x| YAML.load(x)} # So, once a upon a time it was possible to pass arguments to rackup configs via the comand line.. # then it stopped working, and life was bad. # meanwhile, this code switched to passing arguments via the --eval line.. if (log...
class DistributionDestroyService < DistributionService def initialize(distribution_id) @distribution_id = distribution_id end def call perform_distribution_service do distribution.destroy! distribution.storage_location.increase_inventory(distribution) end end end
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '商品出品登録' do context '商品登録がうまくいく時' do it '全ての項目の入力が存在すれば登録できる' do expect(@item).to be_valid end end context '商品登録がうまくいかない時' do it '商品画像が空だと登録できない' do ...
# == Schema Information # # Table name: service_providers # # id :integer not null, primary key # name :string(255) # address1 :string(255) # address2 :string(255) # city :string(255) # state :string(255) # zip :string(255) # email :string(255) # website :st...
require './test/test_helper' class ClientTest < Minitest::Test def test_get_weather_by_city configure_openweather2 stub_request(:get, "http://api.openweathermap.org/data/2.5/weather?q=London&APPID=dd7073d18e3085d0300b6678615d904d") response = Openweather2.get_weather(city:'london') assert_equal resp...
# rake task to import the tables from the kb3 Oracle db on bell. The task # takes as an argument either a model name or 'all' to load all models with # import_from_bell == true namespace :bell do desc "Reload a model (e.g. 'docs', default='all') from bell" # rake tasks with arguments: http://rake.rubyforge.org/fil...
class AddDetailsToTodoItems < ActiveRecord::Migration[6.0] def change add_column :todo_items, :due_date, :timestamp add_column :todo_items, :priority, :integer end end
ActiveAdmin.register User do permit_params :first_name, :last_name, :dob, :gender, :mobileno, :address, :email, :password, :password_confirmation, :is_admin, :anniversary, :status index do selectable_column column "Name" do |user| user.name end ...
# coding: utf-8 module Eturem module Base def self.warning_message(path, lineno, warning) script_lines = Eturem::Base.read_script(path) script = Eturem::Base.script(script_lines, [lineno], lineno) "#{path}:#{lineno}: warning: #{warning}\n" + script end end end
class Support::School::ChangeHeadteacherForm include ActiveModel::Model attr_accessor :email_address, :full_name, :id, :phone_number, :role, :school, :title def headteacher? role == 'headteacher' end def save updated_headteacher.errors.empty? || save_error end private def updated_headteacher ...
Rails.application.routes.draw do root to: 'main#index', as: 'home' resources :messages # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html messages GET /messages(.:format) messages#index # post /messages(.:format) ...
class Donor < ApplicationRecord has_many :contributions has_many :politicians, through: :contributions end
require "rails_helper" RSpec.describe Notifications, type: :mailer do describe "role_reset" do let(:user) { User.first } let(:mail) { Notifications.role_reset(User.first) } it "renders the headers" do expect(mail.subject).to eq("Статус Партнер") expect(mail.to).to eq([user.email]) expe...
module CitationHelper include BlacklightHelper include ActionView::Helpers::TextHelper # Creates a minimal BibTeX string in case the app can't find one # in the data from Solr. def create_bibtex(document) bibtex = '@book{resource, ' if document.has? 'author_display' bibtex.c...
class PassagesController < ApplicationController before_action :set_passage, only: [:show, :edit, :update, :destroy] # GET /passages # GET /passages.json def index @passages = Passage.all end # GET /passages/1 # GET /passages/1.json def show end # GET /passages/new def new @passage = Pa...
=begin 6. Сумма покупок. Пользователь вводит поочередно название товара, цену за единицу и кол-во купленного товара (может быть нецелым числом). Пользователь может ввести произвольное кол-во товаров до тех пор, пока не введет "стоп" в качестве названия товара. На основе введенных данных требуетеся: Заполнить и вывести...
require 'spec_helper' describe SimpleMoney::Currency, 'class methods' do subject { SimpleMoney::Currency } it "should be able to find AUD from symbol" do subject.find(:AUD).iso_code.should == 'AUD' end it "should be able to find AUD from string" do subject.find('AUD').iso_code.should == 'AUD' ...
require_relative 'journey' class JourneyLog attr_reader :journeys, :current_journey def initialize @journeys = [] end def start(entry_station) @current_journey = Journey.new(entry_station) end def finish(exit_station) @current_journey.update_exit_station(exit_station) @journeys << @curr...
class CreatePages < ActiveRecord::Migration def change create_table :pages do |t| t.text :html t.text :css t.text :js t.references :user, index: true t.references :template, index: true t.timestamps null: false end add_foreign_key :pages, :users add_foreign_key :pa...
# Address class CreateAddresses < ActiveRecord::Migration def self.up create_table :addresses do |t| t.references :client t.string :postcode t.timestamps null: false end add_index :addresses, [:client_id] add_index :addresses, [:postcode] end end
class User < ApplicationRecord has_one :invite, :dependent => :destroy before_create :create_invite def create_invite invite = build_invite(:header_title => "Bride & Groom", :wedding_date => "Bride & Groom", :primary_color => "#d1d1d1", ...
module MenuObjectHelper # defines and runs Main Menu # # calls the main menu def home main = Menu.new("What would you like to work on?") main.add_menu_item({key_user_returns: 1, user_message: "Work with movies.", do_if_chosen: "movie"}) main.add_menu_item({key_user_returns: 2,...
class Order < ActiveRecord::Base validates :order_time, presence: true belongs_to :user def self.of_user(user) all.where(user_id: user.id) end end
CarrierWave.configure do |config| config.storage = :grid_fs config.root = Rails.root.join('tmp') config.cache_dir = "uploads" config.grid_fs_access_url = "/images" if Rails.env.production? config.grid_fs_database = ENV['MONGOID_DATABASE'] || Mongoid.database.name config.grid_fs_host ...
class CheckPointStatus < ActiveRecord::Base belongs_to :report belongs_to :check_point attr_accessible :status attr_accessible :report_id, :check_point_id, :status acts_as_paranoid end