text
stringlengths
10
2.61M
class Blurb < ActiveRecord::Base belongs_to :day # attr_accessible :text has_many :tag_types, as: :taggable has_many :tags, through: :tag_types end
class AddIndexToKindAndTitleOfStory < ActiveRecord::Migration[5.1] def change add_index :stories, %i(kind title), unique: true end end
module Parse def parse(score_line) rolls = score_line.chars.map {|char| Roll.new(char)} rolls.each_cons(2) do |roll, next_roll| next_roll.previous = roll roll.next = next_roll end frames = [] until rolls.empty? frames << pop_frame(rolls, frames.size == 9) end frames en...
class Author attr_accessor :name @@authors = [] def initialize(name) @name = name @post_list = [] @@authors << self end def posts @post_list end def add_post(posting) posting.author = self posts << posting end def add_post_by_title(post_name) posting = Post.n...
class RemoveEntryStatusFromLectureStudent < ActiveRecord::Migration def change remove_column :lecture_students, :entry_status, :string end end
require File.dirname(__FILE__) + '/../spec_helper' describe ChartsTimelineController do include Redmine::I18n before do Time.set_current_date = Time.mktime(2010,3,12) Setting.default_language = 'en' @controller = ChartsTimelineController.new @request = ActionController::TestRequest.n...
class ASIAttachment < ActiveRecord::Base attr_accessible :filename, :description, :s3_path, :asi_id belongs_to :asi, class_name: "ASI", foreign_key: "asi_id" validates :filename, :s3_path, :asi_id, presence: true end
class AddSentMoneyAndReceiptMoneyToUsers < ActiveRecord::Migration def change add_column :users, :sent_money, :decimal,precision: 16, scale: 2, default: 0.00 add_column :users, :receipt_money, :decimal, precision: 16, scale: 2, default: 0.00 remove_column :users, :income end end
# frozen_string_literal: true module Admin # MetaTagController class MetaTagsController < AdminController before_action :set_meta_tag, only: %i[show edit update destroy] before_action :show_history, only: %i[index] before_action :authorization, except: %i[reload] include ObjectQuery # GET /met...
require 'test/unit' require_relative '../crm_contact' class TestContact < Test::Unit::TestCase def test_initialize_with_valid_params_works contact = Contact.new(5, "Will", "Richman", "will@bitmakerlabs.com", "") # Assert that the variables passed in are retrievable and therefore saved correctly # As...
class Oniguruma < Formula homepage "http://www.geocities.jp/kosako3/oniguruma/" url "http://www.geocities.jp/kosako3/oniguruma/archive/onig-5.9.6.tar.gz" sha1 "08d2d7b64b15cbd024b089f0924037f329bc7246" bottle do cellar :any sha1 "12f394ce6f8694efa03d1a7ce2d18fc9a069a75c" => :yosemite sha1 "5243422d...
class TimeSlot < ActiveRecord::Base has_many :positions validates "time_slots.starts_at", "time_slots.ends_at", :overlap => { :query_options => {:includes => :positions}, :scope => {"positions.user_id" => proc{|time_slot| time_slot.positions.map(&:user_id)} } } end
class PasswordsController < DeviseTokenAuth::PasswordsController def update if @resource @resource.allow_password_change = true end super end end
class Matches < ROM::Relation[:sql] schema(:matches, infer: true) do associations do belongs_to :teams, as: :home_team, foreign_key: :home_team_id belongs_to :teams, as: :away_team, foreign_key: :away_team_id end end def by_id(id) where(id: id) end def all order(:kick_off) end ...
require 'spec_helper' describe Robot do let(:robot){Robot.new} let(:position){CellPosition.new(0,0,'N')} let(:table){TableTop.new(5,5)} describe 'is_placed?' do it 'should return false when robot is not placed' do expect(robot.is_placed?).to be false end it 'should return true when robot is ...
Trunk::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...
require 'spec_helper' describe "acls/index.html.erb" do before(:each) do @org = assign(:org, stub_model(Org, :display_name => 'VMWare')) @project = stub_model(Project, :org => @org, :display_name => 'Cloud Foundry') @user = stub_model(User, :first_name => 'Monica', :last_name => 'Wilkinson', :display_nam...
module Outputs module MessageMediaType include Types::BaseInterface include Types::ActiveRecord field :url, String, null: false field :location, String, null: false, deprecation_reason: "Renamed to url" field :content_type, String, null: false field :type, String, null: false, deprecation_rea...
class ChangeDeadOfEvents < ActiveRecord::Migration[5.0] def change change_column :events, :dead, :date end end
module Recliner module Conversions extend self class ConversionError < TypeError end def clear! conversions.clear end def convert(from, to, options={}) return nil if from.nil? return from if to.is_a?(Class) && from.kind_of?(to) source = options[:so...
class Board attr_accessor :cells def initialize @cells = [" "," "," "," "," "," "," "," "," "] end def reset! @cells = [" "," "," "," "," "," "," "," "," "] end def display puts " #{cells[0]} | #{cells[1]} | #{cells[2]} " puts "-----------" puts " #{cells[3]} | #{cells[4]} | #{cells[...
class Api::Users::SignInOp class << self def execute(login, password) Auth.authenticate(login, password) end def allowed?(*) true end end end
class BookingsController < ApplicationController def new #pass it the parameters from submitting the last form @booking = Booking.new @flight = Flight.find(params[:flightChoice]) @passenger = Passenger.new end def create @booking = Booking.new(booking_params) ...
module RailsParam module ErrorMessages class MustBeAStringMessage < RailsParam::ErrorMessages::BaseMessage def to_s "Parameter #{param_name} must be a string if using the format validation" end end end end
module Yard2steep class Type class TypeBase def to_s raise "Must be implemented in child class" end end class AnyType < TypeBase # @return [String] def to_s 'any' end end class NormalType < TypeBase # @param [String] type def initialize(t...
require 'httparty' class TogglReport include HTTParty base_uri "https://toggl.com/reports/api/v2" def details(*args) params = { basic_auth: {username: config["toggl_api_key"], password: "api_token"}, query: { user_agent: "toggl_to_harvest Ruby gem", workspace_id: config["toggl_w...
class FixTypeColumnNameInStatus < ActiveRecord::Migration def self.up rename_column :facebook_statuses, :type, :feed_type end def self.down rename_column :facebook_statuses, :feed_type, :type end end
module TicTacToe class Game attr_reader :board attr_reader :type HUMAN_VS_HUMAN = :hvh HUMAN_VS_COMPUTER = :hvc COMPUTER_VS_COMPUTER = :cvc COMPUTER_VS_HUMAN = :cvh def initialize(game_type = :hvh, board = TicTacToe::Board.empty_board) @type = game_type @board = board en...
# frozen_string_literal: true class ImagesDownloadService def initialize(file_path, batch_size) @file_path = file_path @batch_size = batch_size @target_folder = File.join(File.dirname(file_path), 'images') end def call @failed_downloads = [] File.foreach(file_path).each_slice(batch_size) do...
class CoursesController < ApplicationController # you need to be able to pick a course to be authorized for it skip_before_action :authorize_user_for_course, only: [ :index, :new, :create ] # if there's no course, there are no persistent announcements for that course skip_before_action :update_persistent_announ...
require 'spec_helper' describe StripBuilder do subject { described_class.new } describe :exists? do it 'should return true when exists a strip with this number' do create :strip, number: 1 subject.exists?(1).should be_true end it 'should return false when do not exists a strip with this n...
class ChangePriceToBeFloatInProducts < ActiveRecord::Migration[5.2] def change change_column :products, :price, :float end # rollback def down change_column :products, :price, :integer end end
class Word @@words =[] attr_reader(:name, :definitions, :id) def initialize attributes @name = attributes[:name] @definitions = [] @id = @@words.length + 1 end def add_definition definition @definitions<<definition end def save @@words<<self end def self.all @@words e...
class AddRoundToCompetitionMatches < ActiveRecord::Migration[4.2] def change add_column :competition_matches, :round, :integer, null: true, default: nil end end
require_relative 'snack.rb' class Pack attr_accessor :pack_size, :items PACK_SIZE = 5 def initialize @pack_size = PACK_SIZE @items = [] end def add_item(item) @items.push(item) end def remove_item(item) @items.delete(item) end def list_items @items.each do | item | it...
class UserMailer < ActionMailer::Base FEEDBACK_EMAIL = "dorotawnuk11@o2.pl" def feedback_email(feedback) @feedback = feedback mail(:from => feedback.username, :to => FEEDBACK_EMAIL, :subject => "Skauting Jurajski - Wiadomość z serwisu") end end
# frozen_string_literal: true class CreateBasketItems < ActiveRecord::Migration[5.2] def change create_table :basket_items do |table| table.belongs_to :basket, index: true table.integer :count table.belongs_to :product_item, index: true table.belongs_to :product, index: true table....
def caesar_cipher(str, factor) result = '' #puts "\nString: #{str} Factor: #{factor}" str.each_char do |c| char_num = c.ord if char_num < 66 || char_num > 122 # Special character #printf "#{c}" result << c next end if (65..90).include?(char_num) # Upper case lete...
# == Schema Information # # Table name: votes # # id :integer not null, primary key # user_id :integer # match_id :integer # yes :boolean # created_at :datetime not null # updated_at :datetime not null # class VotesController < ApplicationController include Applicat...
require File.join( File.dirname( __FILE__ ), "..", "spec_helper" ) class Configurator describe Client do context "guessing SCM" do before :each do @basedir = Client::REPOSITORY_BASE_DIRECTORY @ip = "192.168.0.1" @node = mock( "node" ) @node.stub!( :name ).and_return( "NODE...
# frozen_string_literal: true class Product < ApplicationRecord belongs_to :provider has_many :purchases end
class Song attr_accessor :name, :artist def initialize(name) @name = name end def self.new_by_filename(file) temp=file.split(" - ") temp[1] = temp[1].split(".")[0] new_song = Artist.find_or_create_by_name(temp[0]).add_song(temp[1]) new_song end end
# # Cookbook Name:: aet # Recipe:: activemq # # AET Cookbook # # Copyright (C) 2016 Cognifide Limited # # 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/L...
class User < ActiveRecord::Base has_many :adventurers has_many :items, through: :adventurers has_many :battles, through: :adventurers has_many :enemies, through: :adventurers @@prompt = TTY::Prompt.new def self.main_menu_sign_in puts "Sign in or create new account below: " username_input = @@prompt...
require 'test_helper' class BlockFieldBlockPartsControllerTest < ActionDispatch::IntegrationTest setup do @block_field_block_part = block_field_block_parts(:one) end test "should get index" do get block_field_block_parts_url assert_response :success end test "should get new" do get new_bloc...
require 'minitest/autorun' require './lib/task_store' class TestTaskStore < Minitest::Test def setup sleep 0.2 @my_store = TaskStore.new @my_own_store = TaskStore.new(101) end def test_initialize assert_match(/\/tmp\//, @my_store.path) # a /tmp/ path has been called assert_equa...
require 'rails_helper' feature 'user can add new clinician' do background do visit new_clinician_path end scenario "user adds new clinician with valid information" do expect(page).to have_content("New Clinician Information") fill_in "clinician_first_name", with: "David" fill_in "clinician_las...
WIN_COMBINATIONS = [ [0,1,2], #top row [3,4,5], #middle row [6,7,8], #bottom row [0,3,6], #first column [1,4,7], #second column [2,5,8], #third column [0,4,8], #diagonal from left top down [6,4,2] #diagonal from right top down ] def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]...
require "rails_helper" RSpec.describe BulkApiImport::Importer do before { FactoryBot.create(:facility) } # needed for our bot import user describe "#import" do let(:organization) { FactoryBot.build_stubbed(:organization) } let(:facility) { Facility.first } let(:facility_identifier) do create(:fa...
class CreateDrawOnAssets < ActiveRecord::Migration def change create_table :draw_on_assets do |t| t.string :draw_on_asset_file_name t.string :draw_on_asset_content_type t.integer :draw_on_asset_file_size t.datetime :draw_on_asset_updated_at t.integer :si_draw_on_id t.timestamp...
begin load_script 'rubyctest.so' rescue Exception => e report_exception(e) flag_error(e) end
require 'spec_helper' describe "User confirmation requests" do # Request a new confirmation token describe "POST /users/confirmation" do let(:user) { create :user, :unconfirmed } subject{ post user_confirmation_url, email: user.unconfirmed_email, format: :json } context 'if successfully sent' do ...
require_relative '../helpers/dependency_graph' module OpenBEL module ConfigurePlugins def check_configuration(plugins, config) sorted_plugin_config_ids = build_dependency_graph(config) all_errors = [] valid_plugins = {} sorted_plugin_config_ids.each do |plugin_config_id| # valid...
class Store class EmployeeLockersController < StoreController load_and_authorize_resource def create @employee_locker = EmployeeLocker.new(employee_locker_params) @employee_locker.products = @employee_locker.locker.products @employee_locker.save @employee_locker.locker.update_columns(sta...
require "net/http" require "tasks/scripts/refresh_bsnl_sms_jwt" require "tasks/scripts/get_bsnl_template_details" require "tasks/scripts/get_bsnl_account_balance" # Usage instructions at: doc/howto/bsnl/sms_reminders.md namespace :bsnl do desc "Fetch a fresh JWT for BSNL Bulk SMS and overwrite the old token" task ...
#encoding: utf-8 class SpecimenTypeVersion < ActiveRecord::Base # Constants # Put here constants for SpecimenTypeVersion # Relations belongs_to :specimen_type # Callbacks # Put here custom callback methods for SpecimenTypeVersion # Validations # validates :specimen_type, <validations> # validates ...
require 'rails_helper' RSpec.describe 'team creation' do # As a user # When I visit a competition's show page # Then I see a link to register a new team # When I click this link # Then I am taken to a new page where I see a form # When I fill in this form with a team's hometown and nickname # And I click submit # Th...
class RemoveUserIdFromDishes < ActiveRecord::Migration[5.0] def change remove_column :dishes, :user_id, :integer end end
class Article < ApplicationRecord validates :title, presence: true, length: { in: 2..100 } validates :text, presence: true, length: { in: 2..1000 } scope :order_by_most_recent, -> { order(updated_at: :desc) } belongs_to :author, class_name: 'User' has_many :votes has_and_belongs_to_many :categories end
class Game SUITS = ["Clubs", "Spades", "Hearts", "Diamonds"] NUMBERS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"] attr_reader :deck, :player, :dealer def initialize @deck = [] end def create_deck SUITS.each do |suit| NUMBERS.each do |num| @deck << Card.new(suit, num) end...
require "rubygems/cli/filtered" module Gem module CLI class List < Gem::CLI::Filtered def self.active? true end def self.args %w([pattern]) end def self.description "List gems in the repo." end def self.verbs %w(list ls) end ...
FactoryGirl.define do factory :url do name 'http://test.com' end end
class MessagesController < ApplicationController before_action :authenticate_user!, except: [:index] before_action :search_message, only: [:index, :search] def index @q = Message.ransack(params[:q]) @messages = Message.includes(:user).order("created_at DESC") end def new @message_tag = MessageTa...
Given(/^"([^"]*)" has navigated to Google Page$/) do |customer| visit(Google_Page) on(Google_Page).loaded?.should be true @user=customer end When(/^he searches for "([^"]*)"$/) do |query| on(Google_Page).enter_query(query) on(Google_Page).submit end Then(/^System should display "([^"]*)" as result$/) do |ti...
class Consult < ApplicationRecord has_many :comments belongs_to :user enum question_type: [ :法律咨询, :立案咨询, :司法确认, :案件流程查询, :举报投诉, :信访申诉 ] mount_uploader :attachment, AttachmentUploader end
class PayrollOtherPayment::EmploymentSubsidy include Mongoid::Document include Mongoid::Timestamps field :subsidy_caused, type: Money field :subsidy_paid, type: Money belongs_to :payroll_other_payment end
class WorkoutsController < ApplicationController before_action :authorize def index @workouts = Workout.all flash[:alert] = "HI" end def new @workout = Workout.new end def create @workout = Workout.create(workout_params) @hopper = Hopper.new(style: @workout.style, number_of_movements...
namespace :generate do desc 'generate error files' task :errors do on roles(:web) do |_| %w(404 422 500).each do |code| obj = OpenStruct.new code: code template 'error.html.erb', "#{release_path}/public/#{code}.html", obj.instance_eval { binding } end end end end def template...
class AddDoneToBetMatch < ActiveRecord::Migration def change add_column :bet_matches, :done, :boolean,:default => false add_column :bet_fixtures, :result, :string end end
class StudentPaymentDecorator < Draper::Decorator delegate_all def charge_value h.number_to_currency(object.charge_value / 100.00) end def month_name object.payment_deadline.strftime("%B") end def payment_deadline object.payment_deadline.strftime("%d %B %Y") end def payment_date obj...
=begin #BombBomb #We make it easy to build relationships using simple videos. OpenAPI spec version: 2.0.831 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.3.1 =end require "uri" module BombBomb class SocialsApi attr_accessor :api_client def initialize(api_cl...
class ListingsController < ApplicationController before_action :authenticate_user! def index @listings = Listing.all end def new @listing = Listing.new end def create @listing = Listing.new listing_params.merge(user_id: current_user.id) if @listing.save == true flash[:notice] ...
require_relative "../helpers/validator" require_relative "../helpers/display" require_relative "../helpers/utility" require "pry" class Character include Validator include Display # TODO: Move to Hero class instead. Not sure monsters need this? include Procs include Utility attr_accessor :attack, :defense, :...
class Ticket < ActiveRecord::Base belongs_to :project validates :title, :description, presence: true, length: {minimum: 10} end
#!/usr/bin/env ruby # encoding: UTF-8 # # Copyright © 2012-2017 Cask Data, 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 r...
class List < ApplicationRecord validates :title, presence: true has_many :list_words, dependent: :destroy has_many :words, through: :list_words, source: :word has_many :definitions, through: :words, source: :definitions has_many :examples, thr...
class Computer < Player def move(board) if !board.taken?('5')#If middle isn't taken '5'#take middle (cell[5-1]) else best_move(board) + 1 #select the best move #Add 1 to offset index value returned by best_move(board) end end def best_move(board) win(board) || block(board) || co...
class PeopleMailingAddress < ActiveRecord::Base belongs_to :people belongs_to :mailing_address end
Gem::Specification.new do |s| s.name = %q{rollcall-xmpp} s.version = "0.0.1" s.authors = ["Matt Zukowski"] s.date = %q{2012-05-17} s.summary = %q{Rollcall plugin for automatically creating XMPP accounts via in-band registration} s.email = %q{matt dot zukowski at utoronto dot ca} s.files = `git ls-files`.s...
require 'rails_helper' describe Activity, type: :model do it 'is valid with a name' do activity = Activity.new(name: "runjumping") expect(activity).to be_valid end it 'is invalid without a name' do activity = Activity.new activity.valid? expect(activity.errors[:name]).to include("can't be bl...
# frozen_string_literal: true class RemoveFieldsFromAttendanceAndAddOthers < ActiveRecord::Migration[4.2] def change remove_column :attendances, :address, :string remove_column :attendances, :neighbourhood, :string remove_column :attendances, :twitter_user, :string remove_column :attendances, :zipcod...
# -*- encoding: utf-8 -*- module SendGrid4r::REST # # SendGrid Web API v3 Mail # module Mail Personalization = Struct.new( :to, :subject, :cc, :bcc, :headers, :substitutions, :custom_args, :send_at ) do def to=(to) tap { |s| s[:to] = to.map(&:to_h) } end def cc=(c...
# == Schema Information # # Table name: discussions # # id :integer not null, primary key # title :string # description :text # created_at :datetime not null # updated_at :datetime not null # class Discussion < ActiveRecord::Base belongs_to :user belongs_to :project ...
require "application_system_test_case" class ClassPeriodsTest < ApplicationSystemTestCase setup do @class_period = class_periods(:one) end test "visiting the index" do visit class_periods_url assert_selector "h1", text: "Class Periods" end test "creating a Class period" do visit class_perio...
require 'rails_helper' describe Item, type: :model do describe "validations" do it { should validate_presence_of :name } it { should validate_presence_of :description } it { should validate_presence_of :price } it { should validate_presence_of :image } it { should validate_presence_of :inventory ...
# == Schema Information # # Table name: questions # # id :integer not null, primary key # text :string # isactive :boolean # isspam :boolean # image_url :string # created_at :datetime # updated_at :datetime # user_id :integer # topic_id :integer # class Question < ActiveReco...
class ReservationMailer < ApplicationMailer default from: "libapp517@gmail.com" def reservation_mail(member) @member = member mail(to: @member.email, subject: 'Reservation') end def release_mail(member) @member = member mail(to: @member.email, subject: 'Release room') end end
class AddRoleToTeamUsers < ActiveRecord::Migration def change add_column :team_users, :role, :string end end
class RemoveSequenceFromContact < ActiveRecord::Migration[5.0] def change remove_column :contacts, :sequence, :integer remove_column :contacts, :is_primary, :boolean remove_column :contacts, :is_visible, :boolean end end
describe do attr :published, Date.new(2013, 2, 1) # 1 Feb. 2013 attr :title, "Introduction" attr :is_article, true content file('article/1-introduction.md') end
class AddImageToEventPost < ActiveRecord::Migration[5.1] def change add_column :event_posts, :image_filename, :string end end
class GithubApi PROTOCOL = "https" HOST = "api.github.com" attr_reader :github_user def initialize github_user @github_user = github_user end def self.get github_user, path GithubApi.new(github_user).get(path) end def get path uri = (path =~ /^http(s)?/) ? path : "#{PROTOCOL}://#{HOST}#{...
# Write your code here require 'net/http' require 'open-uri' require 'json' class GetRequester attr_accessor :url def initialize(url_address) self.url = url_address end def get_response_body uri = URI.parse(self.url) response = Net::HTTP.get_response(uri) response.body end def parse_json JSON.parse(self....
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require "Countdown" describe "Countdown" do it "should calculate seconds until expiration" do now = Time.now end_time = now + 100 countdown = Countdown.new(end_time) countdown.seconds_until_expiration(now).should == 100 end it "s...
module Binged class Synonyms include Enumerable attr_reader :client, :query BASE_URI = 'https://api.datamarket.azure.com/Bing/Synonyms/GetSynonyms' # @param [Binged::Client] client # @param [String] query The search term to be sent to Bing def initialize(client, query=nil) @cli...
class User < ApplicationRecord has_many :tweets has_many :group_users has_many :groups, through: :group_users end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Search results displays field', type: :system, clean: true do before do solr = Blacklight.default_index.connection solr.add([dog]) solr.commit end let(:dog) do { id: '111', title_tesim: 'Jack or Dan the Bulldog', ...
require 'prawn_charts/layers/layer' module PrawnCharts module Layers # Provides a generic way for stacking graphs. This may or may not # do what you'd expect under every situation, but it at least kills # a couple birds with one stone (stacked bar graphs and stacked area # graphs work fine). c...
module HashSyntax Token = Struct.new(:type, :body, :line, :col) do # Unpacks the token from Ripper and breaks it into its separate components. # # @param [Array<Array<Integer, Integer>, Symbol, String>] token the token # from Ripper that we're wrapping def initialize(token) (self.line, s...
class ChangeInstockFromProduceOrderItems < ActiveRecord::Migration def change change_column :produce_order_items, :instock, :string change_column :produce_order_items, :quantity, :string end end