text
stringlengths
10
2.61M
describe Models::User, type: :model do it { is_expected.to have_many(:sounds) } it { is_expected.to have_many(:keyboards) } end
class CreateDictionaries < ActiveRecord::Migration[5.0] def change create_table :dictionaries do |t| t.references :user, foreign_key: true t.string :chinese t.string :english t.string :pinyin t.string :part_of_speech t.integer :times_tested t.integer :times_correct ...
class AwsCertificatesController < ApplicationController before_action :set_aws_certificate, only: [:show, :edit, :update, :destroy] # GET /aws_certificates # GET /aws_certificates.json def index @aws_certificates = AwsCertificate.all end # GET /aws_certificates/1 # GET /aws_certificates/1.json def...
class RemoveCdiCodeFromUsers < ActiveRecord::Migration def change # this code must be in instituitions remove_column :users, :cdi_code end end
class Task < ActiveRecord::Base belongs_to :user def complete? !complete_at.blank? end end
require 'spec_helper' describe "add presence", type: :request, js: true do let(:user) { create(:user, :paul) } let(:billy) { create(:user, :billy) } let(:event) { create(:event, :tasafoconf, owner: billy, start_date: Date.today, end_date: Date.today) } before do login_as(user) end context "when user ...
class Conversation include Mongoid::Document field :author, :type => String field :members, :type => Array #Will contain author and recipients field :subject, :type => String field :unread, :type => Hash #{"id" => "count"} def unread_messages(id) return self.get_messages[(self.get_messages.size - unread[id])...
require 'rails_helper' require 'swagger_helper' RSpec.describe Movie, type: :model do describe 'relation' do it { should have_many(:ratings) } it { should have_many(:movie_catalogs) } end end
# TODO: To consider to be replace module Inventory class HarvestPackageSerializer include FastJsonapi::ObjectSerializer attributes :package_tag, :quantity, :uom, :other_harvest_batch, :drawdown_quantity, :drawdown_uom, :cost_per_unit, :breakdowns attributes :id ...
require 'init_game' describe Game do let(:game) { Game.new } describe '#initialize' do context 'when initialized without arguments' do it 'does not raise an error' do expect { Game.new }.to_not raise_error end end end describe '#game' do context 'when initialized' do it ...
reg = %r(Ruby) str = <<EOS Ruby is object-oriented programming language. EOS str[reg] ="Ruby1.8" p str
# frozen_string_literal: true require 'rails/generators' require 'rails/generators/named_base' require_relative 'core' module Graphql module Generators # TODO: What other options should be supported? # # @example Generate a `GraphQL::Schema::RelayClassicMutation` by name # rails g graphql:mutatio...
class Product < ApplicationRecord belongs_to :category validates :price, presence: true end
# desc "Explaining what the task does" # task :keppler_poll do # # Task goes here # end require File.expand_path('../../keppler_poll/tasks/install', __FILE__) namespace :poll do desc "Copiar vistas al proyecto" task :copy_views do KepplerPoll::Tasks::Install.copy_view_files end end
shared_examples 'a successful search request' do specify { expect(subject.status).to eq(200) } specify { expect(subject.content_type).to eq(:json) } end
json.array! @items do |item| json.(item, :id, :name, :product_id) end
RSpec.describe Trundle::TextBundle do let(:text_bundle) { described_class.new(text_bundle_path) } describe 'Reading a TextBundle' do let(:text_bundle_path) { 'spec/samples/offical-v2.textbundle' } it 'exists' do expect(text_bundle).to exist end it 'has a path' do expect(text_bundle.pa...
class ApplicationController < ActionController::Base before_action :authenticate_user! before_action :set_stripe_urls protect_from_forgery with: :null_session def set_stripe_urls @stripe_url_path = Rails.env == "production" ? "http://www.boomslangfitness.com" : "http://localhost:3000" end end
class Timecard < ActiveRecord::Base COMING_TITLE = '登校時刻'.freeze OUT_TITLE = '下校時刻'.freeze belongs_to :user validates :title, inclusion: { in: [COMING_TITLE, OUT_TITLE] } def coming? title == COMING_TITLE end def out? title == OUT_TITLE end end
class CommentsController < ApplicationController before_action :find_task def create @comment = @task.comments.new(comment_params) respond_to do |format| format.json do if @comment.save #ActionCable.server.broadcast 'activity_channel', :task => @task render :json => @task...
# encoding: utf-8 dep 'ufw ssh and http only' do requires 'ufw.managed' setup { unmeetable! "This dep has to be run as root." unless shell('whoami') == 'root' } met? { status = shell("ufw status") status.match /Status: active/ and status.match /80\/tcp\s+ALLOW/ and status.match /443\/tcp\...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
=begin #qTest Manager API Version 8.6 - 9.1 #qTest Manager API Version 8.6 - 9.1 OpenAPI spec version: 8.6 - 9.1 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require "uri" module SwaggerClient class UserprofileApi attr_accessor :api_client def initialize(api_cl...
class AddLanguageToInvestees < ActiveRecord::Migration def self.up change_table :investees do |t| t.string :lang, default: "zh" end end def self.down change_table :investees do |t| t.remove :lang end end end
require 'digest/md5' class BloomFilter def initialize(set, max_bits, num_hashes) @max_size = max_bits @num_hashes = num_hashes @dataset = set init_bitarray(max_bits) # initialize the bit array @hashes = Array.new(num_hashes) { |i| BloomMd5Hash.new(i, @max_size -1) } # create an array with the specified n...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Ladders', type: :request do let!(:ladders) { create_list(:ladder, 5) } let(:ladder_id) { ladders.first.id } describe 'requires auth token' do before do get '/api/ladders' end it 'returns status code 401' do expect(res...
class IngredientSerializer include FastJsonapi::ObjectSerializer attributes :name, :cost, :cost_size, :cost_unit, :updated_at has_many :recipe_ingredients has_many :recipes, through: :recipe_ingredients end
require 'terminal-table' require_relative './constants.rb' require_relative './team_scraper.rb' require_relative './player_scraper.rb' require_relative './file_handler.rb' class InterfaceDataControl attr_accessor :league def initialize; end def league_data_options(user_input) case user_input when 1 ...
class Post < ApplicationRecord default_scope -> { order(created_at: :desc) } mount_uploader :thumbnail, ThumbnailUploader validates :title, presence: true validates :desc, length: { maximum: 250 } belongs_to :user end
# Time complexity: O(n + m), where n is the length of array1 and m is the length of array2 # Space complexity: O(n), where n is the smaller of the two arrays def intersection(array1, array2) common_elements = [] if array1 == nil || array2 == nil return common_elements end if array1.length < array2.length ...
class ChangeRightsToPermissionsOnMemberships < ActiveRecord::Migration[5.0] def change rename_column :memberships, :rights, :permissions end end
# frozen_string_literal: true require 'test_helper' require 'helpers/base_helper' module Dealersocket module Client class ActivityTest < Minitest::Test include BaseHelper def setup use_default_configuration @model = Activity.new(id: 1, customer_id: 1, event_id: 1, dealer_number_id: ...
require 'time' require 'faraday' require 'faraday_middleware' module HellNo BASE_URL = "https://getamen.com/" FEED_PATH = "/amen.json" USER_PATH = "/users/%d.json" USER_FEED_PATH = "/users/%d/amen.json" AMEN_PATH = "/amen/%d.json" #USER_AGENT = "Hell No/#{HellNo::VERSION}" USER_AGENT = "Amen/1.5.2 (iPh...
desc "Test Puppetfile URLs" task :puppetfile do # Use anonymous `git://` URLs because they don't require authentication or # distributing the host key. $stderr.puts "---> Checking Puppetfile URLs" %w{Puppetfile Puppetfile.lock}.each do |file_name| File.readlines(file_name).each do |file_line| if file...
class AddUserIdToUsertests < ActiveRecord::Migration def change add_column :usertests, :user_id, :integer end end
class AppConfig # ACTION RELATED ACTION_TOTAL_AP = 10; ACTION_COST_USE = 2 ACTION_COST_KILL = 5 ACTION_COST_REPAIR = 2 ACTION_COST_MOVE = 1 ACTION_COST_INITVOTE = 2 ACTION_COST_VOTE = 5 ACTION_COST_STATUS = 2 # WATER RELATED WATER_CONSUMED_PER_PERSON = 50 WATER_UNIT...
class AddFlavorIdToProducts < ActiveRecord::Migration def change add_reference :products, :flavor, index: true, foreign_key: true end end
class Task < ApplicationRecord def self.retrieve_tasks(overdue, today, tomorrow, completed) if completed return self.where({completed: true}) end if overdue overdue_tasks = self.where("due_date < ? AND completed = ?", Date.today, false) end if today or tomorrow date...
class FixChildrenInBirminghamSchoolName < ActiveRecord::Migration def change rename_column :members, :children_in_school, :children_in_birmingham_school end end
class App include PushapiHelper include AppHelper attr_accessor :_id, :appId, :name ENDPOINT = "apps" def save PushapiHelper.api_post(ENDPOINT, ActiveSupport::JSON.encode(self)) end class << self def get apps = Array.new resp = PushapiHelper.api_get(ENDPOINT) resp.each do |r...
class UserBadge < ActiveRecord::Base belongs_to :user filterrific( default_filter_params: { sort_badge: 'created_at_asc' }, available_filters: [ :sort_badge, :with_badge_search, :with_badge_type, ], ) scope :with_badge_search, lambda { |query| return nil if query.blank? terms...
#!/usr/bin/env ruby puts "airstream example parses the imgur-funny rss feed and streams images to an airplay device. requires: gem feedzirra (https://github.com/pauldix/feedzirra) gem nokogiri (https://github.com/sparklemotion/nokogiri) note: this script will never stop ;) " require 'feedzirra' require 'nokogiri' ...
require File.dirname(__FILE__) + "/../spec_helper" require 'dns_mock' describe Comment do before(:each) do CachedModel.cache_reset end def test_permalink_url c = feedback(:old_comment) assert_equal "http://myblog.net/2004/05/01/inactive-article#comment-#{c.id}", c.permalink_url end def test_ed...
require "json" require_relative "transcoder" require_relative "app_logger" get "/mediuminfo/*" do |id| info = Transcoder.get_medium_info(id) content_type :json info.to_json end post "/transcodings" do source_id = params[:source_id] begin jobs = JSON.parse(params[:jobs] || "", symbolize_names: true) r...
require 'pry' class Song attr_accessor :name, :artist @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def artist_name self.artist ? self.artist.name : nil end end class Artist attr_accessor :name @@all = []...
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
class PurchaseOrder < ActiveRecord::Base include ModelParanoia belongs_to :supplier, class_name: "Company", foreign_key: "supplier_id" has_many :purchase_order_items, dependent: :destroy belongs_to :warehouse, class_name: "Address", foreign_key: "warehouse_id" validates :supplier_id, presence: true valida...
# Cookbook Name:: rs_utils # Recipe:: setup_ssh # # Copyright (c) 2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the...
json.array!(@distributes) do |distribute| json.extract! distribute, :id, :name, :path json.url distribute_url(distribute, format: :json) end
# encoding: UTF-8 require 'spec_helper' describe Ad do let(:ad) { Ad.sham!(:build) } describe "Validations" do specify { ad.should be_valid } it "not creates a new instane given a invalid attribute" do ad = Ad.new ad.should_not be_valid end [:title, :category_id, :email, :ad_content...
class RailwayStation < ActiveRecord::Base validates :title, presence: true, uniqueness: true has_many :trains has_many :railway_stations_routes has_many :routes, through: :railway_stations_routes end
module Dev class Env < Thor::Group include Thor::Actions argument :project_root, :type => :string, :default => File.expand_path( File.dirname( __FILE__ ) ) class_option :vagrant_mount_file, :type => :string, :aliases => [ '-V' ], :default => 'config.json' class_option :output_file, :type => :string, ...
require 'rails_helper' RSpec.describe Invitation, type: :model do describe 'associations' do it { should belong_to(:attendee).with_foreign_key(:attendee_id).class_name('User') } it { should belong_to(:attended_event).with_foreign_key(:attended_event_id).class_name('Event') } end end
class CreateEventVolunteers < ActiveRecord::Migration def change create_table :event_volunteers do |t| t.integer :event_id t.integer :volunteer_id t.string :rights t.timestamps null: false end end end
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # 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 by applicabl...
require 'rails_helper' RSpec.describe Tympanogram, :type => :model do context "valid data の場合" do it "保存できること" do tympanogram = FactoryGirl.build(:tympanogram) expect(tympanogram.save).to be true end end context "examdate がない場合" do it "保存できないこと" do tympanogram = FactoryGirl.build(:...
# Copyright (C) 2014 Jan Rusnacko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of the # MIT license. require 'spec_helper' require 'ruby_util/hash_with_method_access_shared' require 'tempfile' require 'fileutils' requir...
require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/../../../shared_examples/server_examples' describe 'Fog::Slicehost::Compute::Server' do if Fog.mocking? it "needs to have mocks implemented" else it_should_behave_like "Server" end # flavor 1 = 256, image 49 =...
class ApplicationController < ActionController::Base protect_from_forgery before_filter :authenticate, :except => [:index, :show] def authenticate authenticate_or_request_with_http_basic do |u, p| u == Settings.admin.name && p == Settings.admin.password end end end
require 'sinatra' require 'sinatra/activerecord' before do end ###################### ##### Routes ######### ###################### # Homepage get '/' do "This is the RiffRaff homepage!" erb :home end # About get '/about' do erb :about end # Logging in/out get '/signup' do ...
class ApplicationController < ActionController::Base before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_friend_requests # def after_sign_in_path_for(resource) # activities_path || welcome_path # end protected def set_friend_re...
class CreateGoals < ActiveRecord::Migration[5.0] def change create_table :goals do |t| t.string :name, :null => false t.integer :exercise_type, :null => false t.integer :goal_number, :null => false t.integer :current_value, :null => false t.belongs...
require 'net/http' include ActiveSupport::Benchmarkable class Nlp::Package # Used to disable nlp sync if necessary via # Nlp::Package.sync_active = false class_attribute :sync_active self.sync_active = true VERSION = 4 # Used to invalidate cache JSON_HEADERS = {"Content-Type" => "application/json", "Acce...
require 'fileutils' class Refactorer include FileUtils FILE_EXTENSIONS = %{ .java .groovy .xml .properties } def initialize source_pkg, dest_pkg, work_dir = Dir.pwd @source_pkg, @dest_pkg, @work_dir = source_pkg, dest_pkg, work_dir end def refactor source_subpath = pkg_to_subpath @source_pkg s...
class Game < ActiveRecord::Base has_many :throws, -> {order(:frame_number, :player_number, :throw_number)} validates :player_count, numericality: {greater_than_or_equal_to: 1, less_than_or_equal_to: 8} def register_throw(pins) throw = Throw.new throw.pins_down = pins throw.p...
# frozen_string_literal: false # The base class for questions, should never actually be used by itself. class ExamQuestion < ApplicationRecord belongs_to :exam_section validates_presence_of :title end
module Catlady class Config require 'yaml' def self.yml_file @yml_file ||= fetch_yml_file end def self.fetch_yml_file filename = ENV["CATLADY_YML"] || "catlady.yml" if File.exist?(filename) YAML.load_file(filename) else raise CatldayYMLError end end ...
require 'rails_helper' RSpec.describe FamilyUser do describe 'factories' do it { expect(FactoryGirl.create(:family_user)).to be_instance_of(FamilyUser) } end describe 'associations' do # belongs_to +Family+ it { should belong_to(:family) } end describe 'validations' do subject { FactoryGirl.b...
# frozen_string_literal: true require 'spec_helper' require 'rails_helper' require 'capybara' RSpec.feature 'Sign up', type: :feature do @controller = CalculationsController.new before :each do user = FactoryGirl.create(:user) login_as(user, scope: :user) calculate end describe 'Spec for Sign Up'...
require_relative "../lib/game" describe Game do before do allow($stdout).to receive(:write) end game = Game.new describe "#.format" do it 'returns an array for a valid input' do expect(game.send(:format, "a4")).to eql([4,0]) end it 'asks again for an inval...
require_relative '../Utilities/Pos' require_relative '../game' class Building def initialize(position,size,health,buildTime,symbol,color,isZombie,cost) include ClassLevelInheritableAttributes inheritable_attributes :pos, :health, :buildingSize, :isProducing, :productionProgress, :isReady, :productionQueue, :...
################################################ # Options Hash def optional(one, two, opts = {}) puts one puts two puts opts end # only requires two parameters - the final parameter is optional. if left empty, it will return an empty hash, but if there are multiple parameters it will automatically add them int...
class DoctorsController < ApplicationController def index @doctors = Doctor.all @markers = @doctors.map {|d| {:latlng => [d.latitude,d.longitude]}} end def new @doctor = Doctor.new end def create @doctor = Doctor.new(permit_params) if @doctor.save redirect_to '/' else ren...
require 'Matrix' class Minesweeper def initialize(sequence) @seq = sequence.split("\r\n") @matrix = Matrix[] @array_count_mines=[] @cols=0 @rows=0 end def generate_minesweeper generate_matrix convert_matrix_in_count_mines_matrix print_count_mines end private def generate...
class Site < ApplicationRecord belongs_to :user has_one :sitemap_file, dependent: :destroy validates :domain, presence: true, uniqueness: { case_sensitive: false } validates :user, presence: true after_create :parse_sitemap_job def sitemap sparser = SitemapParser.new(domain) create_sitemap_file(p...
class Category < ActiveRecord::Base include TheSortableTree::Scopes has_many :children, class_name: 'Category', :foreign_key => 'parent_id' belongs_to :parent_category, class_name: 'Category', :foreign_key => "parent_id" attr_accessible :title validates :title, presence: true acts_as_nested_set end
# frozen_string_literal: true require_relative './transaction' require_relative './statement' class Account attr_reader :balance, :transactions def initialize(statement = Statement.new, transaction = Transaction) @balance = 0 @transactions = [] @statement = statement @transaction = transaction ...
require_dependency "noodle/application_controller" # @see https://blog.codeship.com/the-json-api-spec/ # @see http://ieftimov.com/sprinkle-some-hateoas-on-rails-apis # @see http://stackoverflow.com/questions/30158710/how-to-write-a-spec-to-check-if-a-record-is-saved-in-the-database-using-rspec-wi module Noodle class ...
# Method to print a list and make it look pretty # input: list # steps: # IF empty # print empty message # ELSE # FOR each key-value pair in list # print in format: "item: quantity" # output: hil def print_list(list) puts "Your grocery list:" if list.empty? puts "Your list is empty." else ...
class Product < ApplicationRecord belongs_to :store, :validate => true has_and_belongs_to_many :order,optional: true validates :Name, presence: true, length: {maximum: 50} validates :price, presence: true,numericality: {greater_than: 0} validates :store_id, presence: true validates :descript...
#.to all(matchers) -> will run for every element through the matcher RSpec.describe "all matcher" do it 'allows for aggregate checks' do expect([1,3,5]).to all(be_odd) expect([1,3,5]).to all(be < 6) end end
class ChangeLogsController < ApplicationController def index @change_logs = ChangeLog.order(created_at: :desc) end end
class Player attr_reader :name, :position, :salary def initialize(info) @name = info[:name] @position = info[:position] @salary = info[:salary] end end
module TariffRate class Consolidated include Searchable self.model_classes = [TariffRate::Australia, TariffRate::Bahrain, TariffRate::Chile, TariffRate::Colombia, TariffRate::CostaRica, ...
Pod::Spec.new do |s| # 1 s.platform = :ios s.ios.deployment_target = '9.0' s.name = "SachemPod" s.summary = "SachemPod" s.requires_arc = true # 2 s.version = "0.1.0" # 3 s.license = { :type => "MIT", :file => "LICENSE" } # 4 s.author = { "Mark Yankovsky" => "[yankovsky.mark@gmail.com]" } # 5 s.homepage = "https://...
# == Schema Information # # Table name: accounts # # id :integer not null, primary key # name :string(255) not null # type :string(255) not null # profile_id :integer # status :string(255) # balance_id :integer # email :string(255) not null # created_at :date...
# 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: # Restaurant.destroy_all restaurant_examples = [ { name: 'Dishoom', address...
class Structura; module Containable # @group Basic def initialize(*values) @db, @locks = {}, {} replace_values(*values) end # see self.class.*args delegate_class_methods( :members, :keys, :names, :has_member?, :member?, :has_key?, :key?, :length, :size ) # @return [Boolean] de...
require 'spec_helper_acceptance' describe 'homes defintion', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do context 'valid user parameter' do it 'should work with no errors' do pp = <<-EOS $myuser = { 'testuser' => { 'shell' => '/bin/bash' } } homes { 'tes...
def select_even_nums(arr) arr.select {|nums| nums.even?} end def reject_puppies(arr) arr.reject {|dog| dog["age"] <= 2} end def count_positive_subarrays(arr) arr.count {|sub| sub.sum > 0} end def aba_translate(word) vowels = "aeiou" new_str = "" word.each_char do |char| if vowels.incl...
class UpdateForeignKey < ActiveRecord::Migration[5.0] def change remove_foreign_key :listings, :users add_foreign_key :listings, :users, on_delete: :cascade end end
xml.instruct! xml.Response do xml.Say "Record your message." xml.Record :maxLength => "30", :action => "/record", :method => "get" xml.Say "Press any other key to start over." end end
class RemoveColumnMaxItemsNDecBoxType < ActiveRecord::Migration def self.up remove_column :decs_box_type, :max_items_n end def self.down add_column :decs_box_type, :max_items_n, :integer end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :wikis, dependent: :destroy has_many :collaborators has_many :wiki_collaborations, through: :collaborators, source: :wiki after_initialize { self.role ||...
feature 'form used to take player names' do scenario 'displays names' do sign_in_and_play expect(page).to have_content 'Ed' && 'Alex' end end
class Section < ActiveRecord::Base belongs_to :page, inverse_of: :sections validates_presence_of :header, :page end
# == Schema Information # # Table name: promotions # # id :bigint not null, primary key # discount_flat :integer # discount_percent :decimal(, ) # promo_code :string(8) # service_type :string # title :string # created_at :datetime not null # updated_...
# class GoodDog # def initialize # puts "This obj was initialized!" # end # end # sparky = GoodDog.new class GoodDog # acts similarly to a getter and setter attr_accessor :name, :height, :weight def initialize(n, h, w) @name = n @height = h @weight = w end # def get_name # @name ...
ActiveAdmin.register Movie do menu priority: 2, label: Movie.model_name.human(count: :many) permit_params :name, :category_id index download_links: false do selectable_column id_column column :name do |movie| link_to movie.name, admin_movie_path(movie) end column :category do |movie| ...