text
stringlengths
10
2.61M
require 'spec_helper' describe Searchable do before(:all) do class MockModel include Indexable self.fetch_all_sort_by = 'foo' self.mappings = { name.typeize => { _timestamp: { enabled: true, store: true, }, properties: { ...
module Gsa18f class ProcurementFields def initialize(procurement = nil) @procurement = procurement end def relevant(recurring) fields = default if recurring fields += [:recurring, :recurring_interval, :recurring_length] end fields + [:is_tock_billable, :tock_projec...
module Towable def can_tow?(pounds) pounds < 2000 ? true : false end end class Vehicle attr_accessor :color attr_accessor :model, :year @@number_of_vehicles = 0 def self.number_of_vehicles puts "This program has created #{@@number_of_vehicles} vehicles" end def initialize(year, nodel, color) ...
#encoding: utf-8 Dado(/^que eu possua um msisdn válido e que não possua o "([^"]*)" "([^"]*)" assinado$/) do |produto, versao| @env = environment_config @product = generate_product produto, versao expect(@product.msisdn).not_to be_empty end Quando(/^eu enviar um sms com a keyword do produto$/) do send...
class User < ApplicationRecord validates :username, presence: true,uniqueness: true,length:{minimum:3,maximum:16} validates :email, presence: true,uniqueness: true validates :password, presence: true,length:{minimum:3,maximum:16},:confirmation => true end
json.categories do json.array!(@categories) do |category| json.id category.id json.name category.name end end json.photos do json.array!(@photos) do |photo| json.extract! photo, :id, :url, :thumb end end
ENV['RACK_ENV'] = 'test' require 'minitest/autorun' require 'sinatra/base' require 'ostruct' class MiniTest::Spec def settings @settings ||= OpenStruct.new end def engine @engine ||= OpenStruct.new end end
class GameTopic < ActiveRecord::Base belongs_to :topic belongs_to :game end
class TestsMailer < ApplicationMailer def completed_test(attempt) @user = attempt.user @test = attempt.test mail to: @user.email end end
# frozen_string_literal: true require 'Bank_account' describe 'BankAccount' do before(:each) do @account = BankAccount.new end describe '#initialize' do it 'instantiates the class ' do expect(@account).to be_an_instance_of BankAccount end it 'instantiates the class with a zero balance' do...
class Location < ApplicationRecord def full_address "#{city}, #{state}, #{country}" end # def state # "#{state}" # end # def country # "#{country}" # end has_many :groups has_many :events has_many :group_members has_many :rsvps geocoded_by :full_address reverse_geocoded_by :lat, ...
class JobsController < ApplicationController before_action :authenticate_user! #, except: [:index] respond_to :html, :json def index @jobs = Job.all end def show @job = Job.find(params[:id]) end def new @job = current_user.jobs.build end def edit @job = Job.find(params[:id]) end...
class Neuronio AT=0.5 attr_accessor :sigma, :sinapses, :v, :y, :e, :x_atual, :id def initialize sinapses = [] @sinapses = sinapses end def calcular_v vetor_x @x_atual = vetor_x @x_atual sum = 0 @x_atual.each_with_index do |x, i| sum += @sinapses[i] * x end @v = s...
class StudyMaterialController < ApplicationController def index @batches = Batch.active end def list_uploads_by_course @students = Student.find_all_by_batch_id(params[:batch_id], :order => 'first_name ASC') render(:update) { |page| page.replace_html 'students', :partial => 'uploads_by_course' } end end
class Shotcut < Cask url 'http://d1av856udzjaks.cloudfront.net/shotcut/shotcut-osx-x86_64-131218.dmg' homepage 'http://www.shotcut.org/' version '131218' sha1 '36f25eb022acc30f6210367246d07bcb75d7bc7a' link 'Shotcut.app' end
module Enjoy::Pages::Connectable extend ActiveSupport::Concern module ClassMethods def enjoy_connectable_field (name = :connected_pages, opts = {}) class_name = opts.delete(:class_name) class_name ||= "Enjoy::Pages::Page" routes_namespace = opts.delete(:routes_namespace) routes_namespac...
class AddColumnDistanceFromBaseRodToViaCaracteristic < ActiveRecord::Migration def change add_column :via_caracteristics, :distance, :float add_column :via_caracteristics, :km, :float end end
require 'rails_helper' describe Address do describe '#create' do #登録可 it "is valid with a user_id, postal_code, prefectures, city, address, building" do address = build(:address) address.valid? expect(address).to be_valid end #登録不可(user_idない) it "is invalid without a user_id" d...
class TalkInfoController < ApplicationController def create oembed = Oembed.new(params[:link]).open_presentation hash = if oembed { error: false, title: oembed.title, code: oembed.code, thumbnail: oembed.thumbnail, description: oembed.description } else { e...
class ReviewsController < ApplicationController before_action :require_user def new @business = Business.find(params[:business_id]) @review = Review.new end def create @business = Business.find(params[:business_id]) @review = @business.reviews.new(review_params) @review.user_id = current_u...
require 'rails' require 'rails/generators/active_record' require 'generators/coalla/cms/scaffold_helper' module Coalla module Cms class ScaffoldGenerator < ActiveRecord::Generators::Base argument :name, type: :string source_root File.expand_path("../templates", __FILE__) include Coalla::Cms::...
require 'ipaddr' # Validates that value is an IPv4 or IPv6 address. class IpFormatValidator < ActiveModel::EachValidator # Validates that `value` is an IPv4 or IPv4 address. Ranges in CIDR or netmask notation are not allowed. # # @param record [#errors, ApplicationRecord] ActiveModel or ActiveRecord # @param ...
module Moria # A constraint, created by a ConstraintBuilder. # A view constraint contains two view attribute (view, attribute) and a relation (>=, == or <=). class ViewConstraint attr_accessor :first_view_attribute attr_accessor :second_view_attribute attr_accessor :layout_priority attr_accessor ...
module Swaggard module Swagger class Response PRIMITIVE_TYPES = %w[number string integer float boolean] attr_reader :status_code def initialize(status_code, value) @status_code = status_code parse(value) end def to_doc { 'description' => '', ...
class WebScreen < PM::WebScreen title "网站" attr_accessor :url def content NSURL.URLWithString(@url) end end
# frozen_string_literal: true require "spec_helper" require "increase" require "double_crochet" require "repeat_instruction" RSpec.describe RepeatInstruction, type: :model do subject { described_class.new(3, [Increase.new([DoubleCrochet.new])]) } describe "#make" do it "returns dc inc dc inc dc inc" do ...
require_relative '../spec_helper' describe 'Basecamp Importer' do let(:client) {Basecamp.establish_connection!(BASECAMP_URL, BASECAMP_TOKEN, 'X', true); Basecamp } let(:project) { client::Project.first } describe Basecamp do use_vcr_cassette 'basecamp' it 'should be able to fetch ...
# frozen_string_literal: true module Sleet class Cli < Thor default_task :fetch desc 'fetch', 'Fetch and Aggregate RSpec Persistance Files from CircleCI' long_desc <<~LONGDESC `sleet fetch` will find build(s) in CircleCI for the current branch, and download the chosen Rspec Persistance Files...
require "spec_helper" describe Argyle::CallbackController do describe "plaid_access_token" do before do controller.params[:public_token] = 'myPublicToken' allow(controller).to receive(:plaid_exchange_token).and_return(Plaid::ExchangeTokenResponse.new({'access_token' => 'myToken'})) end it "...
# frozen_string_literal: true require "minitest/autorun" require "pty" require "expect" F2C = "0" C2F = "1" describe "main" do def run_cmd path = ENV.fetch("EXE_PATH") PTY.spawn(path) do |master, slave| yield(master, slave) end end def assert_output(io, pattern) refute_equal(nil, io.exp...
class FeatureUserDocument < ApplicationRecord belongs_to :document enum gender: {Male: "Male", Fermale: "Fermale"} enum status: {Student: "Student", Intern: "Intern", Junior: "Junior", Senior: "Senior", Profesional: "Profesional", Expert: "Expert"} enum generation: {Young: "Young", Middle: "Middle", Old: ...
class VideoPresenter < BasePresenter json( only: [ :id, :title, :description ] ) end
def da_boas_vindas puts "Bem vindo ao jogo da forca" puts "Qual é o seu nome?" nome = gets.strip puts "\n\n\n\n\n\n" puts "Começaremos o jogo para você, #{nome}" nome end def sorteia_palavra_secreta puts "Escolhendo uma palavra..." palavra_secreta = "programador" puts "Escolhida uma palavra com #{pal...
# (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...
class User < ActiveRecord::Base attr_accessible :email, :first_name, :last_name, :photo_blob, :password, :password_confirmation, :session_token has_secure_password has_many :travels has_many :requests, :foreign_key => :requester_id has_many :mulings, :class_name => "Request", :foreign_key => :mule_...
require 'tempfile' require 'fileutils' action :modify do updated = false @res.host.each do |host| @keys[host] = @res.key updated = true end if updated write_known_hosts(@res.filename) @res.updated_by_last_action(true) end end action :delete do updated = false @res.host.each do |hos...
# frozen_string_literal: true require 'common/models/base' module Preneeds class MilitaryRankDetail < Common::Base attribute :branch_of_service_code, String attribute :rank_code, String attribute :rank_descr, String def id branch_of_service_code + ':' + rank_code end end end
Rails.application.routes.draw do resources :students resources :lists # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'pages#home' get 'about', to: 'pages#about' get 'signup', to: 'students#new' end
class CreateReplies < ActiveRecord::Migration[5.1] def change create_table :replies do |t| t.integer :value t.text :note t.references :sendee, foreign_key: true t.references :sub_request, foreign_key: true t.timestamps end end end
class CreateLitters < ActiveRecord::Migration[5.2] def change create_table :litters do |t| t.date :date t.text :about t.text :main_image t.text :image_one t.text :image_two t.timestamps end end end
require "test_helper" class TestRoom < MiniTest::Unit::TestCase def setup @manager = Campfire::Manager.new(:subdomain => "foo", :token => "123") end def test_initialization room = Campfire::Room.new(@manager, "id" => "1", "name" => "bar") assert_equal "1", room.id assert_equal "bar", room.name ...
class Localization TRANSLATIONS = { :en_US => { # greetings :welcome => 'Welcome to Mission Control!', :bye => 'Bye bye! Hope you enjoyed it!', # responses :proceed => 'Y', :abort => 'n', # prompts :new_mission_prompt => 'Would you like to run another mission?', ...
require 'spec_helper' describe Xferslip do before do @xferslip = Xferslip.new(tostore: "SC1", fromstore: "SC2", user_id: 2) end subject { @xferslip } it { should respond_to(:tostore) } it { should respond_to(:tostore_number) } it { should respond_to(:tostore_company) } it { should respond_to(:from...
require 'sumac' # make sure it exists describe Sumac::Messages::Component::InternalException do # should be a subclass of Base example do expect(Sumac::Messages::Component::InternalException < Sumac::Messages::Base).to be(true) end # ::from_object, ::type_from_class, ::map, #properties # no message ...
class AddDeletedFlagToAlbumAndPhoto < ActiveRecord::Migration[5.0] def self.up add_column :partner_albums, :is_deleted, :boolean add_index :partner_albums, :is_deleted add_column :partner_photos, :is_deleted, :boolean add_index :partner_photos, :is_deleted end def self.down remove_column :pa...
class CardsController < ApplicationController before_action :set_card, only: [:destroy,:update] def create @card = current_user.cards.create!(card_params) json_response(@card, :created) end def update @card.update(card_params) json_response({message: "card succes...
require 'net/http' require 'uri' require 'json' class Cloudinary def self.list_folder(folder_name) cloud_name = ENV['CLOUDINARY_CLOUD_NAME']; api_secret = ENV['CLOUDINARY_API_SECRET']; api_key = ENV['CLOUDINARY_API_KEY']; if cloud_name.nil? || api_secret.nil? || api_key.nil? raise <<-HEREDOC ...
class VenuesController < ApplicationController def index @venues = Venue.all render json: @venues end end
class BrandsController < ApplicationController include ApplicationHelper before_action :get_brand, only: :show def show limit, offset = get_pagination uri = "/products?filter=eq(brand.id,#{@brand['id']})&include=main_image&page[limit]=#{limit}&page[offset]=#{offset}" products_resu...
desc 'Deploy current git branch to heroku' task :deploy do current_branch = `git branch | grep '* '`[2..-1].chomp `git checkout heroku; git merge #{current_branch} && git push heroku heroku:master; git checkout #{current_branch}` end
# encoding: utf-8 module PopulateMe module Mongo module BackendApiPlug # This module adds a layer between the backend API and the models. # It is legacy code and could probably be removed, # but in a way it makes it easier to plug something else than MongoDB. # I'll keep it and see. ...
module Admin class SellsController &lt; Fae::BaseController before_action :adjust_enum, only: [:create, :update] validates :client, presence: true def adjust_enum params[:sell][:status] = params[:sell][:status].to_i end end end
require 'logger' module IPay class Log < Logger def format_message(severity, timestamp, progname, msg) "#{timestamp} #{severity} -- #{msg}\n" end end class HttpDebug def initialize @buffer = '' end def <<(msg) @buffer << msg if @buffer.match "\n" IPa...
require_relative "test_helper" require_relative "../lib/rationalize" class TestRationalize < Test::Unit::TestCase def test_fixnum_slash assert_equal(0, 0 / 3) assert_equal(0, 1 / 3) assert_equal(1, 3 / 3) using Rationalize assert_equal(Rational(0, 3), 0 / 3) assert_equal(Rational(1, 3), 1 ...
class CreateHikes < ActiveRecord::Migration[5.1] def change create_table :hikes do |t| t.references :trip, foreign_key: true t.references :trails, foreign_key: true end end end
class CreatePlayerTransactions < ActiveRecord::Migration def change create_table :player_transactions do |t| t.integer :player_id t.integer :investment_type_id t.integer :investment_round_price_id t.float :amount_invested t.date :date_transacted t.date :expected_date_of_return ...
require 'generators/backbone/resource_helpers' module Backbone module Generators class RouterGenerator < Rails::Generators::NamedBase include Backbone::Generators::ResourceHelpers source_root File.expand_path("../templates", __FILE__) desc "This generator creates a backbone router with v...
# frozen_string_literal: true require "spec_helper" RSpec.describe Tikkie::Api::V1::Responses::PaymentRequests do subject { Tikkie::Api::V1::Responses::PaymentRequests.new(response) } let(:response) { instance_double("Net::HTTPResponse", body: body, code: response_code) } let(:body) { File.read("spec/fixtures/...
class FontSeoulNamsanCondensed < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/seoulnamsancondensed" desc "Seoul Namsan Condensed" homepage "http://english.seoul.go.kr/seoul-views/seoul-symbols/5-fonts/" def install (share/"fonts").i...
# coding: utf-8 describe SQLiterate::CommandParser do def should_parse(q) r = SQLiterate::CommandParser.new.parse q expect(r).not_to be_nil r end it "parses a single query" do should_parse "select a;" end it "parses multiple queries" do should_parse "select a; select b" end it "par...
class RenameUsernameName < ActiveRecord::Migration def up rename_column :users, :username, :name remove_index :users, :name => :index_users_on_username end def down rename_column :users, :name, :username add_index :users, :username, :unique => true end end
=begin Glassomium - web-based TUIO-enabled window manager http://www.glassomium.org Copyright 2012 The Glassomium Authors 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 h...
class BookChef class TreeMerger attr_reader :document, :version class LinkLevelOutOfReach < Exception; end def initialize(path, fn) @path = File.expand_path(path) @filename = fn @document = File.read("#@path/#@filename").gsub(/<%(.*?)%>/, '&lt;%\1%&gt;') @document = Nokogir...
require_relative 'bike_container' class Garage include BikeContainer def initialize(options = {}) self.capacity = options.fetch(:capacity, capacity) end def accept(van) van.broken_bikes.each do |bike| bike.fix! dock(bike) end van.broken_bikes.clear end end
class AddImageUrlToDeliveries < ActiveRecord::Migration def change add_column :deliveries, :image_url, :string end end
require "spec_helper" require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist feature "Commenting on an addresss" do background do address = Location.create!({ :address => "539 University Avenue, Missoula, MT 59801, USA", :latitude => 10, :longitude => 10, :apartment_n...
class ContactsController < ApplicationController def create @contact = Contact.new(create_params) if verify_recaptcha(:model => @contact) && @contact.save AdminNotifier.contact_report(@contact).deliver end end private def create_params params.require(:contact).permit(:name, :email, :ho...
require "rails_helper" RSpec.describe GovukDesignSystem::DateInputHelper, type: :helper do describe "#govukDateInput" do it "returns the correct HTML for the default example" do html = helper.govukDateInput({ id: "passport-issued", namePrefix: "passport-issued", fieldset: { ...
class GameResult def initialize @list = Array.new end def add(user, score) result = {:user => user, :score => score} @list << result end def winner winners = Array.new winning_score = highest_score @list.each do |result| if result[:score] == winning_score winners << result...
class CreateExperiences < ActiveRecord::Migration def change create_table :experiences do |t| t.belongs_to :student, index: true t.string :org_name t.string :job_title t.string :industry t.integer :yr_exp t.integer :salary t.string :city t.string :state t.stri...
# frozen_string_literal: true describe "API Versions API", functional: true do example "getting the API versions that are supported by the Kafka brokers" do produce_api = kafka.apis.find {|v| v.api_key == 0 } expect(produce_api.min_version).to eq 0 expect(produce_api.max_version).to be >= 2 end exa...
class Instant < Spell def initialize(owner=nil) super(owner) end def can_be_played owner.mana_pool.can_pay?(self.cost) end end
class AddAttributesToUser < ActiveRecord::Migration def change add_column :users, :year_of_birth, :integer add_column :users, :zip_code, :string # add_column :users, :accepted_consent_at, :timestamp # This is already in an earlier migration add_column :users, :first_name, :string add_column :users...
class School < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name has_many :registrations def self.names order('name asc').map(&:name) end end
require "faraday" require_relative "http_errors" module Kaseya::BMS class Connection < Kaseya::Connection ERROR_MIDDLEWARE = [Kaseya::BMS::HttpErrors] def initialize(host, token, expires) super(host, token) @expires = expires end def connection_options { headers: { ...
#!/usr/bin/env ruby # frozen_string_literal: true current_version = File.open('VERSION', &:readline).strip LATEST_RELEASE_HEADING_PATTERN = Regexp.new( "^## #{current_version} \\d{4}-\\d{2}-\\d{2}" ) PLACEHOLDER_HEADING_PATTERN = /^## (X.Y.Z|X.X.X)/i.freeze first_line = File.open('CHANGELOG.md', &:readline) unle...
Fabricator(:speech) do speech_type { Faker::Lorem.word } speaker { Faker::Lorem.word } end
require "rails_helper" RSpec.describe "Snack Show Page" do before :each do @owner_1 = Owner.create(name: "Owner 1") @machine_1 = Machine.create(location: "Denver", owner: @owner_1) @machine_2 = Machine.create(location: "Broomfield", owner: @owner_1) @snack_1 = Snack.create(name: "Kit-Kat", price: 1.25...
module Command class NewGameCommand def initialize(game, ui) @game = game @ui = ui end def execute(args) @game.reset end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # use ubuntu...
module Antlr4::Runtime class BlockEndState < ATNState attr_accessor :start_state def initialize super @start_state = nil end def state_type BLOCK_END end end end
module Vagrant module Butcher class Plugin < Vagrant.plugin('2') name "vagrant-butcher" description <<-DESC Delete node and client from the Chef server when destroying the VM. DESC class << self def provision(hook) # This should be at the end so that it can copy th...
Dado('que acesso o site inmrobo.tk') do @home_page = HomePage.new @home_page.load end Dado('acesso a tela de cadastro de usuário') do @home_page = HomePage.new @home_page.register_link.click end Quando('preencho os dados do usuário') do user = { email: Faker::Internet.email, password: '123mudar', password_c...
class User < ApplicationRecord has_many :orders # has_many :cartedproducts has_secure_password validates :email, uniqueness: true validates :first_name, presence: true validates :last_name, presence: true validates :password, presence: true end
module Daisy class Voice def self.sing ["Daisy, Daisy, give me your answer, do.", "I'm half crazy, all for the love of you."].join(" ") end end end
class UsersController < ApplicationController before_action :set_user, only: [:edit, :update, :show] before_action :authenticate_user! def index @users = User.all end def show end def edit unless current_user === @user || current_user.role === "administrator" redirect_to users_path, notic...
class User < ActiveRecord::Base has_many :agreements has_many :cars, through: :agreements def self.all_users # returns an array of all user instances in the database User.all.find do |user| user.id == self.user_id end end def specific_user # takes in a name (str...
require 'spec_helper' describe "Client pages" do subject {page} describe "index" do let(:client) { FactoryGirl.create(:client) } before(:all) { 30.times { FactoryGirl.create(:client) } } after(:all) { Client.delete_all } before(:each) do sign_in client visit clients_path end...
module ApplicationHelper def sortable(column, title) css_class = column == params[:sort_column] ? "sorted #{params[:sort_order]}" : '' sort_order = params[:sort_order] == 'asc' ? 'desc' : 'asc' search_params = { sort_column: column, sort_order: sort_order } if params[:player_name].present? sea...
module Noteshare module ErrorHandler # If the 'document' is nil, redirect the request # to an error page with information in the header # about the nature of the error def handle_nil_document(document, code) if document == nil redirect_to "/error/#{code}/?document_not_found" end ...
require 'minitest_helper' class TestQrserver < Minitest::Test def setup @object = Object.new @object.extend(Qrserver) # Query variables @query = { size: @size, format: @format, ecc: @ecc, data: 'string' } @merged_q = { query: @query } end def test_generate_qr_code assert_equal 'strin...
class AddColumnsToJournals < ActiveRecord::Migration def change add_column :journals, :txn_id, :string add_column :journals, :txn_number, :string add_column :journals, :qb_edit, :string add_column :journals, :txn_date, :date add_column :journals, :ref_number, :string add_column :journals, :currency_ref,...
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # All Vagrant configuration is done here. The most common configuration # options are documented and commen...
require 'rails_helper' RSpec.describe Link, type: :model do it { is_expected.to validate_presence_of :path } it { is_expected.to validate_presence_of :title } end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? protected # devise에 이름과 학번 추가 def conf...
module CDI module V1 class UserLearningTrackSerializer < SimpleLearningTrackSerializer has_one :learning_cycle, serializer: SimpleLearningCycleSerializer, embed: :ids, embed_in_root_key: :linked_data, embed_in_root: true has_one :user, ...
class Booking < ApplicationRecord belongs_to :availability belongs_to :club belongs_to :court belongs_to :client has_many :payments end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'devise/test_helpers' # to do. need to add fixture data to test approved/not approved q's. describe UsersController do include Devise::TestHelpers it "should use UsersController" do expect(controller).to be_an_instance_o...
class Auto::TestcasesController < ApplicationController include ActionView::Helpers::NumberHelper include Auto # act_as_extjs_direct # GET /testcases # GET /testcases.xml def index @testcases = Testcase.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @t...
class ChangePrioriryOnContextRules < ActiveRecord::Migration def self.up change_column :context_rules, :priority, :string end def self.down change_column :context_rules, :priority, :string end end