text
stringlengths
10
2.61M
=begin Write a method that takes two strings as arguments, determines the longest of the two strings, and then returns the result of concatenating the shorter string, the longer string, and the shorter string once again. You may assume that the strings are of different lengths. Examples: short_long_short('abc...
class Member < ActiveRecord::Base validates :name, presence: true has_many :member_projects has_many :projects, through: :member_projects end
class IngredientsController < ApplicationController def index @ingredients = Ingredient.all render json: @ingredients end # GET /mods/1 def show set_ingredient render json: @ingredient end private # Use callbacks to share co...
class Grid < ApplicationRecord belongs_to :session # belongs_to :user, through: :sessions has_many :spaces end
class IterationsController < ApplicationController before_action :set_iteration, only: [:show, :edit, :update, :destroy] # GET /iterations # GET /iterations.json def index @iterations = Iteration.all end # GET /iterations/1 # GET /iterations/1.json def show @project = Project.find_by_id(params...
require 'features/features_spec_helper' feature "User successfully deletes book from cart" do let!(:book){FactoryGirl.create(:book)} let(:user){FactoryGirl.create(:user, :as_customer)} before do visit new_user_session_path within '#new_user' do fill_in 'Email', with: user.email fill_in 'Pas...
class Partner class ListServiceSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :services def services ActiveModelSerializers::SerializableResource.new(object[:services], each_serializer: ServiceSerializer) end end end
# Source: https://github.com/gutomotta/aws_lambda_trello_archiver.rb require 'time' require 'json' def main(event:, context:) api_key = ENV.fetch('TRELLO_API_KEY') api_token = ENV.fetch('TRELLO_API_TOKEN') board_id = ENV.fetch('TRELLO_BOARD_ID') list_name = ENV.fetch('TRELLO_LIST_NAME') old_cards_threshold ...
class AddKarmaToStories < ActiveRecord::Migration def change add_column :stories, :karma, :integer, default: 1 end end
# frozen_string_literal: true module Pulfalight class DeliveryNote attr_reader :location_code def initialize(location_code) @location_code = location_code end def brief_note return unless delivery_warning_locations.include?(location_code) "This item is stored offsite. Please allow ...
class RequisitometrologicosController < ApplicationController before_action :set_requisitometrologico, only: [:show, :edit, :update, :destroy] before_action :signed_in_user, only: [:index, :edit, :update, :destroy, :new, :show, :create] # GET /requisitometrologicos # GET /requisitometrologicos....
class AddAdmissionPriceToAmusementParks < ActiveRecord::Migration[5.1] def change add_column :amusement_parks, :admission_price, :integer end end
require 'spec_helper' describe Category, :focus do let(:category_hash) { { bag: { en: 'bagen', ro: 'bagro' }, port: { en: 'porten' } } } before(:each) { Category.should_receive(:category_collection).with.at_least(:once).and_return category_hash } describe '.labels' do it 'returns the Category keys' do ...
# frozen_string_literal: true module Vedeu module Output # Directly write to the terminal. # # @example # Vedeu.write(output, options) # # @api private # class Write include Vedeu::Presentation include Vedeu::Presentation::Colour include Vedeu::Presentation::Pos...
require 'rails_helper' feature 'Manage songs', js: true do let!(:artist1) {create :artist} scenario 'add a new song' do # Point your browser towards the todo path visit artist_path # visit artist_path(artist1) # Enter description in the text field fill_in 'song_title', with: 'Be Batman' ...
require "spec_helper" describe Audio::ProgramAudio do describe "callbacks" do describe "#set_description_to_episode_headline" do let(:content) { create :show_episode, headline: "Cool Episode, Bro", show: create(:kpcc_program, audio_dir: "coolshow") } it "sets description to content's headline before...
=begin Custom Equipment Slots Script by Fomar0153 Version 1.2 ---------------------- Notes ---------------------- No requirements Allows you to customise what equipment characters can equip e.g. add new slots or increase the number of accessories. ---------------------- Instructions ---------------------- You will need...
# + plus # - minus # / slash # * asterisk # % percent # < less-than # > greather-than # <= less-than-equal # >= greater-than-equal puts "I will now count my chickens:" # A string printed regaring chickens to be counted puts "Hens #{25 + 30 / 6}" # This is how may hens are available puts "Roosters #{100 - 25 * 3 % 4}...
# +++++ Talk about class inheritance # When a class is said to inherit from another class it means that the subclass is given access to attributes # and methods in the superclass # This is useful when classes have a hierarchichal relationship so when a class inherits behaviours from # another class we can expand fun...
class CreateBrandings < ActiveRecord::Migration def self.up create_table :brandings do |t| t.text :name t.integer :studio_id t.string :logo_file_name, :string t.string :logo_content_type, :string t.integer :logo_file_size, :integer t.datetime :logo_updated_at, :datetime ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable before_save :set_defaults private def set_defaul...
require('rspec') require('pry') require('title_case') describe('String#title_case') do # "string".title_case should return "String" it("will title_case a lower case word") do expect('word'.title_case).to(eq('Word')) end # "multiple word string".title_case should return "Multiple Word String" it("will ti...
# CGI version to play with: http://rubyquiz.com/cgi-bin/madlib.cgi class Madlibs attr_reader :questions, :madlib attr_writer :answers def initialize(filepath) @madlib = File.read(filepath) @words = @madlib.scan(/\(\([^(\)\))]+\)\)/).map { |m| m[2..-3] } @words_repeated = @words.select { |s| s =~ /...
#!/usr/bin/env ruby require File.expand_path("../../helper", __FILE__) require "series_calc/term" class SeriesCalc::TermTest < Test::Unit::TestCase Term = SeriesCalc::Term class Count < Term def calculate_value value = 1 children.each do |child| value += child.value end value ...
# encoding: UTF-8 require_relative '../test_helper' describe ReqCommand do let(:id) {'id'} let(:title) {'title'} let(:content_id) {"# [id] id\n"} let(:content_id_title) {"# [id] title\n"} let(:file_name) { "#{Settings.src}/#{id}.md"} it 'must create file by id' do inside_sandbox do ...
module StatsdServer module Readers class Redis attr_reader :redis def initialize(redis) @redis = redis end def fetch(metric, datatype, opts) redis.zrangebyscore("#{datatype}:#{metric}", *opts[:range]).map do |val| split = val.split("\x01R") [ split.fi...
require File.dirname(__FILE__) + '/../spec_helper' describe 'UserExtension' do before(:each) do @radu = User.make end describe 'is_subscribed_to_notification_type?(notification_type) method' do it 'should return false if the user is not subscribed to any notifications' do @radu.is_subscribed_to_...
class Facility < ApplicationRecord validates :name, presence: true attachment :image geocoded_by :address after_validation :geocode, if: :address_changed? is_impressionable counter_cache: true end
class Termnote < ActiveRecord::Base validates :termcapmodel, uniqueness: true end
require_relative '../exceptions/smart_log_parser_exception' require_relative '../helpers/interface_helper' module SmartLogParser class SmartLogGrouper include SmartLogParser::InterfaceHelper def initialize(reader) raise SmartLogParser::SmartLogParserException.new 'Reader must exist!' if reader.nil? ...
class AddMoreColumnsToUser < ActiveRecord::Migration[6.1] def change add_column :users, :account_set_up_at, :string add_column :users, :current_cursor_value, :string add_column :users, :reserved_points, :integer add_column :users, :total_points, :integer end end
#Basic Damage Popup v1.3b #----------# #Features: What the title says, very simple damage popup # #Usage: Plug and play, customize as needed # #----------# #-- Script by: V.M of D.T # #- Questions or comments can be: # given by email: sumptuaryspade@live.ca # provided on facebook: http://www.facebook.com/Daimo...
require "rails_helper" feature "Task notifications", js: true do scenario "Identity sees that they have no Tasks" do given_i_have_no_tasks when_i_visit_the_home_page then_i_should_see_that_i_have_no_tasks end scenario "Identity sees that they have one assigned Task" do given_i_have_one_task ...
#hangman ruby script #jacob & kuhfß 2013 load 'hangman.rb' load 'file_reader.rb' load 'gallows.rb' #init file_reader reader = File_Reader.new("words.txt") #init hangman hangman = Hangman.new() hangman.max_mistakes = 6 hangman.set_word(reader.get_random_word) puts("\nWelcome to Hangman! \n\n") puts(h...
class UserSerializer < ActiveModel::Serializer has_many :events has_many :user_events attributes :id, :name end
# Write a method that takes a string, and returns a new string in which every # consonant character is doubled. Vowels (a,e,i,o,u), digits, punctuation, and # whitespace should not be doubled. def double_consonants(string) doubled_string = '' string.chars.each do |char| doubled_string << char doubled_stri...
=begin #Scubawhere API Documentation #This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API OpenAPI spec version: 1.0.0 Contact: bryan@scubawhere.co...
require('pry') class NumberWords def initialize(number) @num = number end def numbers_to_words(num) ones_hash = { 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'four...
class ShippersController < ApplicationController def index shipper = Shipper.all render json: shipper, include: :loads end def show shipper = Shipper.find_by(shipper_params[:id]) render json: shipper, include: :loads end def create shipper = Shipper.create!...
require_relative 'instance_counter' require_relative 'validation' require_relative 'accessors' class Route include InstanceCounter include Validation include Acсessors attr_reader :stations validate :stations, :kind, Station def initialize(from, to) @stations = [from, to] validate! register_i...
require 'faker' namespace :db do desc "Fill database with sample data" task :populate => :environment do Rake::Task['db:reset'].invoke make_users make_colors make_swatches end end def make_users admin = User.create!(:username => "meleyal", :email => "william.meleyal@gmail.com...
class TaskItem < ActiveRecord::Base belongs_to :task validates_presence_of :task has_many :links, inverse_of: :task_item validates_presence_of :name accepts_nested_attributes_for :links end
module Tubular class Buffer attr_reader :data def initialize(data = "") @data = data end def get_u8 get(1).unpack('C')[0] end def put_u8(v) @data << [v].pack('C') end def get_u32 get(4).unpack('N')[0] end def put_u32(v) @data << [v].pack('N') ...
require 'rails_helper' RSpec.describe AlmostStory, type: :model do context "almost story doesn't exist, story should be created" do it "should return the story" do AlmostStory.process(hn_id: 10, href: "dummy href", description: "description") expect(AlmostStory.first.hn_id).to eq 10 expect(Almo...
# frozen_string_literal: true RSpec.describe 'Character Extra Build Request', type: :request do include_context 'with branch location' include_context 'with user token' include_context 'with json response' before do allow(Rails.logger).to receive(:warn) end describe '#index' do subject(:index!) {...
class Category < ApplicationRecord has_many :game_genre, dependent: :delete_all has_many :items, through: :game_genre end
class ValidacaoPage < SitePrism::Page #Esse comando esta setando a url que sera utilizada na automação set_url 'https://automacaocombatista.herokuapp.com/treinamento/home' #Esse comadno esta setando os elementos que sera utilizado na automação #Esses comando esta sendo utilizado no teste ct07...
class RentalItem < ActiveRecord::Base validates :name_ja, presence: true, uniqueness: true validates :name_en, presence: true, uniqueness: true def to_s # aciveAdmin, simple_formで表示名を指定する self.name_ja end def self.permitted(group_id) # 許可された貸出物品を返す category = Group.find(group_id).group_category # 団...
require 'honor_codes/core' class License OPEN_CHORUS = 'openchorus' def initialize path = (File.exists?(license_path) ? license_path : default_license_path) @license = HonorCodes.interpret(path)[:license].symbolize_keys end def self.instance @instance ||= License.new end def [](key) @lic...
require "./spec/spec_helper" require "json" describe 'The Word Counting App' do def app Sinatra::Application end test_string_1 = "Hello there! Hello there again...!?" test_string_2 = "foo FOO fOo!!! foO?" it "counts words correctly" do word_counter = WordCounter.new(test_string_1, true) expect(...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? def after_sign_up_path_for(resource) flash[:notice] = "Welcome! You have signed up successfully" user_path(@user.id) @user = User.find(curr...
require 'rails_helper' RSpec.describe ApplicationHelper, type: :helper do describe '#full_title' do context '引数に文字列が与えられなかった時' do it '地元メシ!という文字列のみを返す' do expect(full_title('')).to eq '地元メシ!' end end context '引数に文字列が与えられた時' do it "'地元メシ!'という文字列の前に与えられた文字列を追加したものを返す" do ...
#encoding: utf-8 class Board COLORS = {:white => :red, :black => :black} attr_accessor :board, :king_positions def initialize(with_pieces = true) @board = Array.new(8) { Array.new(8, nil) } @king_positions = [nil,nil] #make 8 x 8 empty board if with_pieces @king_positions = [[7, 4], [0, 4]] ...
module Linter class JavaScript < Base DEFAULT_CONFIG_FILENAME = 'javascript.json' FILE_REGEXP = /.+\.js\z/ def file_review(commit_file) FileReview.create!(filename: commit_file.filename) do |file_review| Jshintrb.lint( commit_file.content, linter_config ).compact...
Pod::Spec.new do |s| s.name = 'mobpex-iOS' s.version = '0.1.3' s.summary = 'test of mobpex-iOS.' s.license = 'MIT' s.authors = {"junwen.deng"=>"junwen.deng@yeepay.com"} s.homepage = 'http://www.yeepay.com' s.description = 'It is a marquee view used on iOS, which implement by Objective-C.' s.requires_arc...
require 'rails_helper' RSpec.describe "paragraphs/new", type: :view do before(:each) do assign(:paragraph, Paragraph.new( :name => "MyString", :working_article => nil, :order => 1, :para_text => "MyText", :tokens => "MyText" )) end it "renders new paragraph form" do ren...
class Level < ActiveRecord::Base has_many :challenges # Validations validates :name, presence: true end
class GameTable < ActiveRecord::Migration def change create_table :games do |t| t.integer :cards_correct, :cards_shown # t.references :user, :deck t.integer :user_id, :deck_id t.timestamps end end end
class CreateUserBadgesTestsJoinTable < ActiveRecord::Migration[5.2] def change create_table :user_badge_tests do |t| t.integer :user_badge_id, null: false t.integer :test_id, null: false t.timestamps end end end
# #= 閲覧管理コントローラ # class Susanoo::VisitorsController < ApplicationController include Concerns::Susanoo::VisitorsController before_action :set_consult_attach_file, only: %i(attach_file) private # #=== 広告画像を返す # def set_consult_attach_file path = request.path dir = File.dirname(path) ...
require 'spec_helper' describe "Account Communication Creation" do describe "self.gen_statement(params)", :vcr do it "Generates a statement based on an invoice that has not been inluded in a statement" do response = api.gen_statement({"acct_no" => 1}) response.should have_key("error_code") res...
module Users class MerchantUser < Users::User has_one :store, class_name: "Merchant::MerchantStore" end end
class NotesController < ApplicationController def index if user_signed_in? @notes = Note.all else redirect_to new_user_session_path end end def new if user_signed_in? @note = Note.new else redirect_to new_user_session_path end end def create @note = Note....
class CreateReleasePlanningReasons < ActiveRecord::Migration def change create_table :release_planning_reasons do |t| t.integer :release_planning_id t.text :date_reason t.text :hour_reason t.integer :created_by t.timestamps null: false end end end
# frozen_string_literal: true class Room < ApplicationRecord has_many :bookings, dependent: :destroy validates :name, presence: true, length: { maximum: 255 } validates :description, :seats, presence: true def self.available_rooms(params) @date = params[:date] @start_time = params[:start_time] @s...
class Tag < ApplicationRecord belongs_to :category belongs_to :tweet end
class Character < ApplicationRecord has_many :party_characters end
# frozen_string_literal: true # a tutorial model that has many videos and accepts tags class Tutorial < ApplicationRecord has_many :videos, -> { order(position: :ASC) }, dependent: :destroy acts_as_taggable_on :tags, :tag_list accepts_nested_attributes_for :videos validates_presence_of :title def self.non_c...
#encoding: utf-8 class DataImporter @queue = :high DNA_PATH = File.join(Settings.data_dir, 'pdb', 'dna') RNA_PATH = File.join(Settings.data_dir, 'pdb', 'rna') def self.perform Dir.foreach(DNA_PATH) do |f| next if File.directory? File.join(DNA_PATH, f) entry_id = f.downcase.chomp('.pdb') ...
#!/usr/bin/ruby require_relative 'githubapi' class GithubClient RESULT_MESSAGES = { success: 'succeeded', failure: 'failed', error: 'has an error', pending: 'is pending', } def initialize(conf = {}) @config = conf end def organization @config[:organization] end def repositor...
# frozen_string_literal: true module StatisticCalcs module Helpers class GarciaEquation def self.calc!(a) (2.0 / 9 * (a + ((a**2 + 1)**0.5))**2).ceil end end end end
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/files' require 'bolt_spec/pal' require 'bolt_spec/config' require 'bolt/pal' require 'bolt/inventory/inventory' require 'bolt/plugin' describe 'set_features function' do include BoltSpec::Files include BoltSpec::PAL include BoltSpec::Config ...
class CreateEvaluations < ActiveRecord::Migration def self.up create_table :evaluations do |t| t.column :interview_id, :integer t.column :question, :text t.column :question_type, :text t.column :boolean_answer, :boolean t.column :note_answer, :inte...
class Launch::Component::Card::Body::Footer < Launch::Component def html return "" unless content.present? content_tag :footer, role: "contentinfo", class: css_class do nested_content end end private def css_classes ["card--footer"] end end
require 'test_helper' class PhotoTest < ActiveSupport::TestCase test "search works" do photo = photos(:one) photo.title = "nice title" photo.save search_results = Photo.search_for "nice title" search_result_ids = search_results.map {|search_result| search_result.id } assert search_result_i...
class RenameAdvertisingToBreeze < ActiveRecord::Migration def self.up rename_table :advertisings, :breezes end def self.down rename_table :breezes, :advertisings end end
require 'spec_helper' describe Typhoeus::Header do let(:options) { {} } let(:header) { described_class.new(options) } let(:variations) { [ 'Content-Type', 'content-type', 'cOnTent-TYPE', 'Content-Type', 'Content-Type', 'content-type', :content_type ] } describe ".new" do let(:options) { ...
class ApplicationController < ActionController::Base include Pundit before_action :configure_permitted_parameters, if: :devise_controller? # after_action :verify_authorized # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :ex...
require 'rubygems' require 'thor/group' module Bookshop module Generators # Thor based generator for creating new projects based upon a template project which # is copied into the name_of_book project-folder when 'build new name_of_book' is issued class AppGenerator < Thor::Group include Thor::Acti...
class MultiFeeDiscount < ActiveRecord::Base belongs_to :receiver, :polymorphic => true belongs_to :master_receiver, :polymorphic => true belongs_to :fee, :polymorphic => true has_many :fee_discounts, :dependent => :destroy attr_accessor :finance_fee_ids attr_accessor :collections attr_accessor :p...
require_relative '../../test_helper' module Events module Board class DeletedTest < Minitest::Test def deleted @deleted ||= Deleted.new(id:) end def id @id ||= 1 end def test_id assert_equal(id, deleted.id) end end end end
control "M-3.5" do title "3.5 Ensure that /etc/docker directory ownership is set to root:root(Scored)" desc " Verify that the /etc/docker directory ownership and group-ownership is correctly set to root. /etc/docker directory contains certificates and keys in addition to various sensitive files. He...
module CreditCard::Serializers CREDIT_CARD_ATTRIBUTES = %i{ id cc_number month year cvv zipcode card_holder_name } def serialize_credit_card credit_card CREDIT_CARD_ATTRIBUTES.inject({}){ |a,m| a.update m => credit_card.send(m) } end def serialize_credit_card_as_list_item cr...
module NavigationHelpers def path_to(page_name) case page_name when 'the list of brigades' # '/brigades' brigades_path else raise "Can't find routes for \"#{page_name}\"." end end end World(NavigationHelpers)
describe User do let!(:user) do User.create(name: 'Jack Bauer', user_name: 'Jack24', email: 'jbauer@ctu.com', password: 'damn_it!', password_confirmation: 'damn_it!') end it 'authenticates when given a valid email address and password' do a...
require 'chef/log' module Opscode class CookbookVersionsHandler < Chef::Handler def report cookbooks = run_context.cookbook_collection Chef::Log.info("Cookbooks and versions run: #{cookbooks.keys.map {|x| cookbooks[x].name.to_s + " " + cookbooks[x].version} }") end end end
module UnlockGateway class Setting attr_accessor :key, :title, :description def initialize(key, title, description) self.key = key self.title = title self.description = description end end end
# frozen_string_literal: true describe Zafira::Operations::Run::Finish do let(:client) { build(:zafira_client, :with_environment, :with_run, :rspec) } let(:env) { client.environment } let(:finisher) { Zafira::Operations::Run::Finish.new(client) } before do logger_mock = double('starter.logger').as_null_o...
class Kakeibo < ApplicationRecord belongs_to :user has_many :gachakakeibos, dependent: :destroy has_many :otherkakeibos, dependent: :destroy validates :name, presence: true validates :is_kakeibo_status, inclusion: { in: [true, false] } end
class AddWipColumnToBot < ActiveRecord::Migration[5.1] def change add_column :bots, :wip_enabled, :boolean, default: true end end
class AffiliateLinkCategory < ActiveRecord::Base belongs_to :user has_many :affiliate_links attr_accessible :name validates :name, presence: true end
class CreateMobileZoneRefs < ActiveRecord::Migration def change create_table :mobile_zone_ref, id: false do |t| t.integer :mobile_zone t.integer :zone_parent t.integer :is_default t.integer :is_internal end end end
# encoding: utf-8 # copyright: 2018, Franklin Webber class Git < Inspec.resource(1) name 'git' def initialize(path) @path = path end def branches inspec.command("git --git-dir #{@path} branch").stdout end def current_branch branch_name = inspec.command("git --git-dir #{@path} branch").stdout...
# frozen_string_literal: true module Darlingtonia ## # @example Building an importer with the factory # record = InputRecord.from({some: :metadata}, mapper: MyMapper.new) # record.some # => :metadata # class InputRecord ## # @!attribute [rw] mapper # @return [#map_fields] attr_accesso...
require 'rails_helper' RSpec.describe PostsController, type: :controller do let(:post) { FactoryGirl.create(:post) } let(:valid_post) { FactoryGirl.attributes_for(:post) } let(:invalid_attributes) { attributes_for(:invalid_post) } describe "GET index" do before do get :index end it "populat...
class WholesalerInvoice < ActiveRecord::Base belongs_to :wholesaler has_many :sales has_many :wholesaler_payments, :conditions => { :charged => true } has_many :all_payments, :class_name => 'WholesalerPayment' has_many :orders, :through => :sales def total sum = 0 sales.each {|s| sum = sum + s.to...
require 'sinatra/base' require 'openssl' require 'webrick' require 'webrick/https' require 'logger' require 'mongo' require 'mongo_mapper' require './api/services/configuration_service' class ApiApp < Sinatra::Base configure do config = ConfigurationService.new.get_config # set the public folder set ...
FactoryBot.define do factory :category do name event_id { create(:event).id } end end
module Talk def display print 'Hello ' end end class CommunicateUser include Talk attr_reader :name def initialize(name) @name = name end end # Creating object object = CommunicateUser.new('Ruby') # Calling object object.display puts object.name
=begin Create a Program to keep a record of successes that one could reference when needed. Each record will store a date, category of the challenge, brief description of the success, and whether you'd like to mark it as an exceptional success. Users can create and retrieve data. They can also reclassify successe...