text
stringlengths
10
2.61M
class ChangeMalePost < ActiveRecord::Migration def change change_column :male_posts, :male_id, :integer, :null => false change_column :male_posts, :content, :string, :null => false end end
class AddJurosMultaBoletos < ActiveRecord::Migration def self.up add_column :boletos, :juros, :float add_column :boletos, :multa, :float end def self.down remove_column :boletos, :juros remove_column :boletos, :multa end end
describe Bike do context 'On creation' do it 'Bike is working' do expect(subject.working).to be_truthy end end context 'can be reported' do it 'as broken' do subject.break expect(subject.working).to be_falsey end end end
require 'rails_helper' RSpec.describe AnagramController, :type => :controller do describe "GET index" do it "returns http success" do get :index expect(response).to have_http_status(:success) end end describe 'GET search' do it 'should return http success' do get :search, :wordlist...
require "rails_helper" feature "authorization" do feature "registrations#new" do it "register with valid info" do visit root_path click_on "user-registration-action" fill_in :user_first_name, with: "John" fill_in :user_last_name, with: "Smith" fill_in :user_email, with: "g@g.com" ...
class CreateProblems < ActiveRecord::Migration[5.0] def change create_table :problems do |t| t.text :problem t.string :image_url t.string :answer t.string :dummy1 t.string :dummy2 t.string :dummy3 t.timestamps end end end
require "matrix" class Resource < Vector TYPES = %i[ore clay obsidian geode] def [](type) case type when :ore then super(0) when :clay then super(1) when :obsidian then super(2) when :geode then super(3) else super end end end class Blueprint BOTS = { ore: Vector[1, 0, 0, 0], ...
class TopicsController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource respond_to :html, :json def index @topics = Topic.all respond_with @topics end def show @topic = Topic.find(params[:id]) respond_with @topic end def new @topic = Topic.new ...
describe 'Add some valid text' do before(:all) { @text = 'This_a_test_from_user_GREY' } let(:get_text){ get "?text=#{@text}" } it 'Returned value should be a String' do get_text expect_json_types(result: :string) end it 'Introduced text should match on response' do get_text expect_json(resu...
class AddEvenMoreColumnsToTrial < ActiveRecord::Migration def change add_column :trials, :overall_contact_phone, :text add_column :trials, :overall_contact_email, :text add_column :trials, :location_countries, :text add_column :trials, :link_url, :text add_column :trials, :link_description, :text ...
# encoding: utf-8 class Piece DELTAS = [[1,0],[1,1],[0,1],[-1,1], [-1,0],[-1,-1],[0,-1],[1,-1]] def self.neighbor_locations(location) neighbors = {} DELTAS.each do |delta| neighbors[delta] = [location[0] + delta[0], location[1] + delta[1]] end neighbors end attr_accessor :co...
require 'rspec' require 'spec_helper' require 'crawler/vk_api' module Crawler describe VkApi do context "new" do it "sets Thread[:api] to self" do @client, @server = socket_pair @api=VkApi.new socket: @client Thread.current[:api].should == @api @client.close @server...
class Udipity::CommandBuilder class << self def from_datagram datagram = '' parts = datagram.split id = parts.shift cmd = parts.shift create_command cmd, id, data: parts.join(' ') end def create_command cmd, id, opts = {} klass_name = "Udipity::Command::#{cmd.capitalize}...
class Dog def name=(inputted_name) @name = inputted_name end def name return @name end def breed=(inputted_value) @breed = inputted_value end def breed return @breed end end snoopy = Dog.new snoopy.breed = "Beagle" puts("Here is the breed: " + snoopy.breed) puts("Instance variable:...
require 'test_helper' class CreateJoinTableUsersEquipsControllerTest < ActionDispatch::IntegrationTest setup do @create_join_table_users_equip = create_join_table_users_equips(:one) end test "should get index" do get create_join_table_users_equips_url, as: :json assert_response :success end tes...
FactoryBot.define do factory :order_form do token { 'tok_1234567890' } post_code { '098-6758' } prefecture_id { 1 } city { '稚内市' } address_line { '3' } building { '最北端' } phone_number { '09012345678' } user_id { 1 } item_id { 1 } end end
require_relative "fileserver" require_relative "app_logger" # Create upload ticket post "/tickets" do size = params[:size].to_i secure_id = Fileserver.get_upload_ticket(size) AppLogger.get.info("Created ticket #{secure_id}") secure_id end # Delete upload ticket delete "/tickets/*" do |secure_id| Fileserver...
require_relative '../engine/component' class Health < Component attr_accessor :current, :max, :min def initialize(name, max = 100) @current = max @max = max @min = 0 end def hurt(damage) @current -= damage end def heal(life) @current += life @current = @max if @current > @max e...
require 'json' require 'set' # # This class remembers the pieces of that that need to be remembered in order to avoid processing # twice notices received from Kubernetes watches. # # Current implementation stores the data in memory and there is no need to make it presistent # since we run full refresh every time we st...
require 'csv' desc "Import names from csv file" task import: :environment do file = "db/allnamesnew.csv" CSV.foreach(file, headers:true) do |row| Kidsname.create ({ :name => row[0], :gender => row[1], :rank => row[2], :score => row[3], :count => row[4] }) end end
require 'test_helper' class CurrencyHistoriesControllerTest < ActionDispatch::IntegrationTest setup do @currency_history = currency_histories(:one) end test "should get index" do get currency_histories_url, as: :json assert_response :success end test "should create currency_history" do asse...
require "rails_helper" describe "As a visitor" do describe "When I visit a hospital's show page" do it "I see the hospital's name, I see the number of doctors that work at this hospital, and I see a unique list of universities that this hospital's doctors attended" do hospital = Hospital.create!(name: "Gre...
class InvitationMailer < ApplicationMailer default from: 'notifications@example.com' def invitation_mailer(invitation) @invitation = invitation mail(to: @invitation.mail, subject: 'Invitation to the Astek planning') end end
class EmojisController < ApplicationController def index @emojis = Emoji.all end def show @emoji = Emoji.find(params[:id]) end def new end def create @emoji = Emoji.new(emoji_params) @emoji.save redirect_to @emoji end private def emoji_params params.require(:emoji).permit...
class AddProcessedToAssets < ActiveRecord::Migration def change add_column :assets, :processed, 'int unsigned', :null => false, :default => 0, :after => :state end end
class MortgagebotDocMagicPage < GenericBasePage include DataHelper #Loan number will be used to print loan number after it is created element(:altLenderCode) {|b| b.element(xpath: "/html/body/div/table/tbody/tr/td/table/tbody/tr/td/form/div/table/tbody/tr[5]/td/table/tbody/tr[6]/td/table/tbody/tr[4]/td[2]/input"...
class AddTotalPostsToBlog < ActiveRecord::Migration def self.up add_column :blogs, :total_posts, :integer, :null => false, :default => 0 end def self.down remove_column :blogs, :total_posts end end
class HomeController < ApplicationController respond_to :html, :xml, :json def index if current_user @lists = List.lists_by_user current_user.id end end end
class MyCar attr_accessor :color attr_reader :year def initialize(year, color, model) @year = year @color = color @model = model @current_speed = 0 end def change_color(color) self.color = color puts "Your car is now #{color}!" end def speed_up(number) @current_speed += numb...
# frozen_string_literal: true require 'test_helper' class WasapiFilesHelperTest < ActionView::TestCase def setup @wasapi_files_one = wasapi_files(:one) @wasapi_files_two = wasapi_files(:two) end test 'collection count helper' do assert_equal 2, collection_count(@wasapi_files_one.collection_id, ...
require 'spec_helper.rb' describe Compiler, "when given input" do before do @orig_stdin = $stdin $stdin = StringIO.new @orin_stdout = $stdout $stdout = StringIO.new @compiler = Compiler.new($stdin, $stdout) end def stdout $stdout.rewind $stdout.read end it "should do nothing wi...
# Class for handing Branches. class Branch < ActiveRecord::Base include Redis::Objects validates :name, presence: true validates :vendor, presence: true has_many :srpms has_many :changelogs, through: :srpms has_many :packages has_many :groups has_many :teams has_many :mirrors has_many :patches ...
module Phcmembers class Member::Profile < ApplicationRecord # Clean URL Initialize extend FriendlyId # Paper Trail Initialize has_paper_trail :class_name => 'Phcmembers::ProfileVersions' # Profile Gravatar include Gravtastic gravtastic :member_email # Relationships has_many :addr...
class ChordLeaderboardsController < ApplicationController def index chord_points = ChordLeaderboard.all render json: chord_points end def create chord_point = ChordLeaderboard.create(leaderboard_params) render json: chord_point end private def leaderboard_par...
require 'csv' require_relative 'order' module Grocery class OnlineOrder < Order attr_reader :customer_id, :status ## additional attributes (does that mean the arguments we pass in initialize?) #customer object #fulfillment status (SYMBOL) #pending, paid, shipped/complete #if no status, defaul...
class User < ActiveRecord::Base has_many :restaurants has_many :listings has_many :lists, :through => :listings has_many :bans has_many :banned_restaurants, :through => :bans, :class_name => 'Restaurant', :foreign_key => :restaurant_id has_many :grants def managed_restaurants grants.restaurants.manag...
class FacilitiesController < ApplicationController include MyUtility before_action :set_facility, only: [:show, :edit, :update, :destroy] # GET /facilities def index placeholder_set param_set @count = Facility.notnil().includes(:p_name, :holiday_name, :division_name, :detail_division_name).search(p...
# frozen_string_literal: true require 'spec_helper' require_relative '../../tasks/apply.rb' describe TerraformApply do describe "#apply" do let(:terraform_out) { "Terraform message" } let(:terraform_err) { "" } let(:terraform_code) { 0 } let(:terraform_response) { [terraform_out, terraform_err, terr...
require 'test_helper' class DocumentImportTest < ActiveSupport::TestCase setup do @khan_csv = File.new(File.join(fixture_path, 'document_import', 'khan_new_docs.csv')) @khan_repo = repositories(:khan) end test '#prepare_import creates doc import rows for the CSV rows' do doc_import = DocumentImport...
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.5.1' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.2.0' # Use Puma as the app server gem 'puma', '~> 3.11' # Use SCSS for stylesheets # gem 'sass-rails', '~> 5.0' gem 'sassc-rails...
require 'rails_helper' RSpec.describe Hole, type: :model do it { should belong_to(:course_hole) } it { should validate_presence_of(:course_hole) } it { should validate_presence_of(:score) } it { should validate_presence_of(:ipd) } it { should validate_presence_of(:gir) } end
# In development mode, Bullet logs suggestions on optimizing # your database queries to log/bullet.log if defined? Bullet and Rails.env.development? puts "Bullet is logging query suggestions" unless $rails_rake_task Bullet.enable = true Bullet.bullet_logger = true end
RSpec.describe 'GET /api/articles', type: :request do let!(:article_1) { create(:article, title: 'This is an awesome title') } let!(:article_2_3) { 2.times { create(:article) } } describe 'successfully gets the articles' do before do get '/api/articles' end it 'is expected to return a 200 res...
require File.dirname(__FILE__) + '/../spec_helper' describe APNS::Notification do it "should take a string as the message" do n = APNS::Notification.new('device_token', 'Hello') n.alert.should == 'Hello' end it "should take a hash as the message" do n = APNS::Notification.new('device_token', {:...
class SessionsController < ApplicationController def new end def create req = SwaggerClient::LoginRequest.new session_params data = @@api_auth.login req if data.status == "SUCCESS" session[:user_uuid] = data.uuid session[:username] = data.username session[:token] = "Bearer " + data...
class Runner < ActiveRecord::Base acts_as_content_block({:versioned => false}) attr_accessor :skip_callbacks has_many :orders attr_accessible :name, :phone, :address validates :name, :phone, :address, :username, :password, presence: true validates :username, uniqueness: true before_save :encode_passwo...
class Koite::Configurator class << self def configure configuration = Koite::Configuration.new yield configuration return configuration end end end
module Qualtrics::API class MailingListResource < ResourceKit::Resource include ErrorHandlingResourceable resources do action :all, "GET /API/v3/mailinglists" do handler(200) do |response| body = JSON.parse(response.body)["result"].to_json MailingListMapping.extract_collecti...
require 'delegate' require 'optparse' class NanoParser < DelegateClass(OptionParser) require 'nano-optparse/version' def initialize(**default_settings) @default_settings=default_settings @options = {} @used_short = [] @optionparser = OptionParser.new yield self if block_given? super(@optionparser) end ...
class GamesController < ApplicationController def index if params[:user_id] @user = User.find(params[:user_id]) @games = @user.games else @games = Game.all end end def new # Admin-only action @user = User.find(session[:user_id]) ...
#encoding:utf-8 #品牌管理 ActiveAdmin.register Brandsecondmenu do menu :parent => "商店管理", :priority => 3 permit_params Brandsecondmenu.permit_data index do column :menu_name column :brandmenu do |record| if record.brandmenu link_to record.brandmenu.menu_name,{:controller=>"#{ActiveAdmin.applicat...
# coding: utf-8 require 'spec_helper' feature 'gerenciar exame' do scenario 'incluir exame', :javascript => true do visit new_exame_path preencher_e_verificar_exame end scenario 'alterar exame' do #, :js => true do exame = FactoryGirl.create(:exame) visit edit_exame_path(exame) p...
class CreateDistricts < ActiveRecord::Migration def change create_table :districts, { :id => false } do |t| t.string :uuid, :limit => 36, :null => false t.string :constituency_uuid, :null => false t.string :member_uuid, :null => false t.string :name, :null => false t.integer :iterati...
FactoryGirl.define do factory :tournament do title '1st tournament of faculty of cybernetics' description 'This is the first tournament' sequence(:date) { |n| n.days.ago } end end
class SubOrganization < ActiveRecord::Base belongs_to :events_people has_many :organizations end
class PaymentsController < ApplicationController def create @project = Project.find(params[:project_id]) @payment = @project.payments.create(payment_params) #if @payment.save redirect_to project_path @project #end end def destroy @project = Project.find(params[:project_id]) @payment = @project.paym...
class AddSendToContactToEstimates < ActiveRecord::Migration def change add_column :estimates, :send_to_contact, :integer end end
require "rails_helper" describe "Edit author page", type: :feature do it "should render without an error" do @author = FactoryBot.create(:author) visit(edit_author_path(@author)) end it "should display the author's details" do @author = FactoryBot.create(:author) visit(edit_author_path(@author))...
# An RSpec matcher helper and spec. # # Author:: Nolan Eakins <nolan@eakins.net> # Copyright:: Public domain # License:: You are free to use and abuse this in anyway. # Makes defining RSpec matchers a simpler affair. You still have to provide # the typical set of methods: initialize, matches?, etc. The one thing you #...
require './bytecode.rb' class Compiler def compile(tree) case tree when Itl::Program compile_program tree when Itl::ExpressionList compile_expressionlist tree when Itl::Expression compile_expression tree when Itl::Block compile_block tree when Itl::EmptyExpressionList...
#!/usr/bin/env ruby # :title: Plan-R CLI Commands =begin rdoc (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end module PlanR module Cli # this should never be needed, but just in case... autoload :Command, 'plan-r/application/cli/command' =begin rdoc =end module Commands FILE_C...
Pod::Spec.new do |s| s.name = "RMImagePicker" s.version = "0.1.4" s.summary = "iOS image picker with single and multiple selection written in Swift using Apple PhotoKit." s.description = <<-DESC iOS image picker with single and multiple selection ...
require 'graphql' module Liql module GraphQL class Compiler Error = Class.new(StandardError) def initialize(ast, root: nil) @ast = ast @root = root end def compile query = ::GraphQL::Language::Nodes::Document.new( definitions: [ ::GraphQL::L...
module Omnimutant class FileIterator def initialize(files:) @files = files @index = 0 end def get_current_file if @files.size > 0 @files[@index] end end def move_next if ! is_beyond_end? @index += 1 end end def is_at_end? @inde...
class CreateAccounts < ActiveRecord::Migration def change create_table :accounts do |t| t.references :user t.string :payment_type, :account_number t.text :billing_address end end end
require 'detective.rb' require 'mediawiki_api.rb' require 'time' class AuthorDetective < Detective def table_name 'author' end #return a proc that defines the columns used by this detective #if using this as an example, you probably should copy the first two columns (the id and foreign key) def columns...
require 'test_helper' class MeasureTest < ActiveSupport::TestCase def setup @user = (:luiza) @measure = Measure.new(weight: '67', hight: '176', chest: '76', waist: '65', left_thigh: '65', right_thigh: '65', left_calf: '32', right_calf: '32', left_arm: '23'...
class AlbumsController < ApplicationController load_and_authorize_resource :user load_and_authorize_resource through: :user def new end def show @tags = @album.tags @photos = @album.photos end def edit end def update @album.tags = TagService.new(params[:album][:tags]).tags if @album.up...
class Video < ActiveRecord::Base belongs_to :gallery validates :gallery, :presence => true validates :video_link, :presence => true validates :name, :presence => true attr_accessible :gallery_id, :name, :video_link end
class Answer < ActiveRecord::Base belongs_to :participation belongs_to :choice end
module EasyPost class Report < Resource REPORT_TYPES = { shprep: 'shipment', plrep: 'payment_log', trkrep: 'tracker' } def self.create(params={}, api_key=nil) url = self.url wrapped_params = {} wrapped_params[class_name.to_sym] = params if REPORT_TYPES.values.include?(params[:type].t...
# == Schema Information # # Table name: carts # # id :integer(4) not null, primary key # user_id :integer(4) # complete :boolean(1) # created_at :datetime # updated_at :datetime # package_id :integer(4) # class Cart # < ActiveRecord::Base attr_accessor :items, :package_id, :package_name, :...
# 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...
#!/usr/bin/env ruby require 'pdf-reader' require 'oily_png' require_relative 'richter_parse' if ARGV == [] puts "Usage: richter_legible.rb [INPUT_FILES]" exit 0 # vielen Dank an David Herber für diesen großartigen Beitrag! end ARGV.each do | input_file | reader = PDF::Reader.new input_file png = ChunkyPNG::Image...
class AnimalVaccinationsController < ApplicationController before_action :set_animal, only: [:create, :destroy] before_action :set_animal_vaccination, only: [:destroy] before_filter :authenticate_user! authorize_resource def create vaccination = Vaccination.find(params[:animal_vaccination][:vaccination...
class AddTagsToLearningDynamic < ActiveRecord::Migration def change change_table :learning_dynamics do |t| t.string :tags, array: true end add_index :learning_dynamics, :tags, using: 'gin' end end
class UsersController < ApplicationController def show @questions = Question.where(user_id: current_user.id).order("created_at DESC").page(params[:page]).per(10) @answers = Answer.where(user_id: current_user.id).order("created_at DESC") end end
require 'rails_helper' RSpec.describe Sword::Endpoints::SpringerNatureEndpoint do ########################################## hierarchy describe 'hierarchy' do it 'inherits from Endpoint' do expect(described_class.superclass).to eq(Sword::Endpoints::MetsToHyacinthEndpoint) end end ###############...
require 'digest/sha1' class User < ActiveRecord::Base attr_accessible :login, :password, :password_confirmation validates_presence_of :login validates_confirmation_of :password attr_accessor :password before_save :encrypt_password def self.authenticated?(login, password) pwd = Digest::SHA1.hexdiges...
module Qualtrics::API class Distribution::Recipients < BaseModel attribute :mailing_list_id attribute :distribution_recipient_id attribute :contact_id ## # Make the model serializeable by ActiveModelSerializer # # @return [OpenStruct] # def self.model_name OpenStruct.new(nam...
json.array!(@chat_boxes) do |chat_box| json.extract! chat_box, :id, :open_time, :close_time, :flight_id, :comments json.url chat_box_url(chat_box, format: :json) end
require "test_helper" class CustomerTest < ActiveSupport::TestCase test "test save customer" do customer = Customer.new customer.first_name = "Yunus Erdem" customer.last_name = "Sıhhatlı" customer.email = "yunuserdemsihhatli@gmail.com" assert_equal true, customer.save end test "test not sa...
# input: pairs of (number of employees, level of those employees) # every employee has exactly 1 manager, who must be at least 1 rank higher # each employee cannot have more underlings than their level number # find the min level CEO that must be hired to cover all of these # employees = [[5, 0], [4, 1], [1, 5]...
# == Schema Information # # Table name: board_type_components # # id :integer not null, primary key # board_type_id :integer # component_id :integer # sequence :integer # created_at :datetime not null # updated_at :datetime not null # class BoardTypeComponent < Act...
class RenameTablePersonToPeople < ActiveRecord::Migration def change rename_table :person, :people rename_table :person_employment_status, :people_employment_statuses end end
class AddPhasesDatesToChallenges < ActiveRecord::Migration[5.0] def change add_column :challenges, :ideas_phase_due_on, :date add_column :challenges, :ideas_selection_phase_due_on, :date end end
class AddShowfilterToShowplace < ActiveRecord::Migration def change add_column :showplaces, :showfilter, :boolean, :default => true end end
class Service < ActiveRecord::Base mount_uploader :file_upload, FileUploader belongs_to :user has_many :assets geocoded_by :address_map after_validation :geocode validates :image , :presence => true end
require File.dirname(__FILE__) + "/../spec_helper" module GitRevisionNumbers describe CommitLibrarian do before :each do @repository = mock(Repository, :commits => nil) Repository.stub!(:new).and_return @repository end it "should initialize with a repository root" do Repository.should_...
source 'https://rubygems.org' ruby '2.4.0' gem 'rails', '5.0.1' # Use PostgreSQL both in development & production gem 'pg', '0.19.0' # Thin instead of WEBRick in development gem 'thin' # the default Rails gems gem 'sass-rails' gem 'uglifier', '>= 1.3.0' gem 'jquery-rails' gem 'turbolinks', "~> 5.0.0" # Bootstrap g...
class VideosController < ApplicationController def index @videos = Video.all render 'index' end def new #displaying a form render 'new' end def create @video = Video.new(video_params) if @video.save redirect_to('/') else render 'new' end end def edit @video = Video.find_by(id: pa...
class Team < ActiveRecord::Base attr_accessible :description, :logo, :name has_many :players has_many :home_games, class_name: 'Game', foreign_key: 'home_team_id' has_many :away_games, class_name: 'Game', foreign_key: 'away_team_id' end
require "json" require "mongo" class MongoService attr_reader :database_host, :database_port, :database_name, :album_table_name, :photograph_table_name, :page_size def initialize(args = {}) # set the defaults @database_name = "cliffy" ...
# module Flyable #模組 # def fly # puts "666666" # end # end # class Cat # include Flyable #Cat類別包含Flyable模組 # end # kitty = Cat.new # kitty.fly # class String #ruby相同名稱的類別,方法會合併 可以新增預設類別的方法 # def say_hi # puts "666666" # end # end # "aa".say_hi # "bb".say_hi class Dog def hello pu...
# == Schema Information # # Table name: coaches # # id :integer not null, primary key # user_id :integer # slug :string # description :string # created_at :datetime not null # updated_at :datetime not null # class CoachesController < ApplicationController before_a...
class AddIsCurrentToMenus < ActiveRecord::Migration def change add_column :menus, :is_current, :boolean end end
class CommentsController < ApplicationController def create #Each request for a comment has to keep track of the article to which the comment is attached, thus the initial call to the find method of the Article model to get the article in question. @article = Article.find(params[:article_id]) @comment = @article....
require './helper' require 'yaml' module Hangman class Game private attr_accessor :secret_word, :dictionary, :bad_letters, :hints, :line_count public def initialize @dictionary = "../5desk.txt" @line_count = File.foreach(dictionary).reduce(0){ |lines, _| lines + 1 } @secret_word = select_word ...
class Api::V1::LoansController < ApplicationController before_action :set_loan, only: [ :show, :update ] def index @loans = Loan.all render json: @loans end def show render json: @loan end def create @book = Book.find(loan_params[:book_id]) @user = User.find(loan_params[:user_id]) ...
class Reservation < ActiveRecord::Base belongs_to :table belongs_to :user validates :table_id, :presence => true validates :user_id, :presence => true validate :start_time_is_in_the_future, :end_time_after_start_time, :table_is_not_occupied def start_time_is_in_the_future errors.add(:start_...