text
stringlengths
10
2.61M
class String def initialize (sentence) @sentence = sentence end def to_pirate if @sentence.downcase!.include?("are") @sentence.gsub! 'are', 'Yarr' # humanize before returning else return "=NO arr" end end end
require 'spec_helper' describe User do it "has a valid factory" do expect(FactoryGirl.create(:user)).to be_valid end it "is invalid without a email" do expect(FactoryGirl.build(:user, email: nil)).to be_invalid end it "is invalid without a password" do expect(FactoryGirl.build(:user, password: ...
ActiveAdmin.register Message do permit_params :user_id, :body, :subject, :unread, :id filter :subject filter :body filter :unread filter :user_id filter :updated_at filter :created_at actions :all, :except => [:edit] controller do def action_methods if current_user...
module AdminArea class RecommendationsMailer < ApplicationMailer def recommendations_ready(opts = {}) opts.symbolize_keys! @account = Account.find(opts.fetch(:account_id)) mail(to: @account.email, subject: "Action Needed: Card Recommendations Ready") end end end
class Product < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged paginates_per 18 # Scopes scope :available, -> { where(availability: true) } # Associations belongs_to :market, inverse_of: :products belongs_to :category, inverse_of: :products, optional: true has_many :price_hi...
module IqSMS class MaximumMessagesLimitExceededError < StandardError end end
## Generated from playlist4.proto for spotify.playlist4.proto require "beefcake" module SpotifyWeb module Schema module Playlist4 module ListAttributeKind LIST_UNKNOWN = 0 LIST_NAME = 1 LIST_DESCRIPTION = 2 LIST_PICTURE = 3 LIST_COLLABORATIVE = 4 LIST_PL3_VE...
require 'spec_helper' describe ProductReview do it 'has a valid factory' do expect(FactoryGirl.build(:product_review)).to be_valid end it 'is valid without a comment' do expect(FactoryGirl.build(:product_review, comment: nil)).to be_valid end end
class DifficultySerializer include FastJsonapi::ObjectSerializer has_many :puzzles attributes :name, :level end
class PaymentsController < ApplicationController layout 'authorize_net' helper :authorize_net protect_from_forgery :except => :relay_response NGROK = "http://5bc34b1d.ngrok.io" AIM_CAPTURE = AuthorizeNet::AIM::Transaction.new( AUTHORIZE_NET_CONFIG['api_login_id'], AUTHORIZE_NET_CONFIG['api_transactio...
require 'csv_row_model/concerns/dynamic_columns_base' require 'csv_row_model/concerns/export/attributes' require 'csv_row_model/internal/export/dynamic_column_attribute' module CsvRowModel module Export module DynamicColumns extend ActiveSupport::Concern include DynamicColumnsBase included do ...
require 'rails_helper' describe 'meta/formats/index' do let(:formats) { build_stubbed_list(:format, 5) } it 'shows all formats' do assign(:formats, formats) render formats.each do |format| expect(rendered).to include(format.name) end end end
class SitesController < ApplicationController include Tabulatable include Pagy::Backend load_and_authorize_resource before_action :set_site, only: [:show, :edit, :update, :destroy] # GET /sites # GET /sites.json def index @sites = Site.with_counts # filter unless site_params.blank? @...
class AddPhotoidToComments < ActiveRecord::Migration def change add_column :comments, :photoid, :integer end end
class SessionsController < ApplicationController # TODO What are the security implications of this? # See https://github.com/intridea/omniauth/wiki/Managing-Multiple-Providers/2174dce6c804f7c25b407859dacd75a9c0fe8ac8 # near the end #skip_before_filter :verify_authenticity_token, only: [:create, :failure] # NO...
# class Month # attr_reader :months # def initalize # @months = [01,02,03,04,05,06,07,08,09,10,11,12] # end # # def month_list(index) # months[index] # end # end
class CreateDeposits < ActiveRecord::Migration[5.1] def change create_table :deposits do |t| t.belongs_to :user, index: true t.belongs_to :worker, index: true t.decimal :income, precision: 10, scale: 2 t.timestamps end end end
class Menu def self.tag_name 'menu' end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Collection::View::ChangeStream do require_wired_tiger min_server_fcv '3.6' require_topology :replica_set max_example_run_time 7 let(:pipeline) do [] end let(:options) do {} end let(:view_options) do ...
class Project attr_reader :title def initialize(title) @title = title end def add_backer(backer) ProjectBacker.new(self, backer) end def backers (ProjectBacker.all.select{|projects|projects.project == self}).collect{|p| p.backer} end end
class CommissionInvoice < ApplicationRecord self.table_name = "gipi_comm_invoice" self.primary_key = "intrmdry_intm_no" alias_attribute :gross_commission, :commission_amt alias_attribute :w_tax, :wholding_tax belongs_to :policy, foreign_key: :policy_id has_one :intermediary, foreign_key: :intm_no def n...
# app/lib/brickset_service.rb require 'net/http' class BricksetService API_KEY = ENV['BRICKSET_API_KEY'] BASE_URL = "https://brickset.com/api/v2.asmx/" def self.get_sets_for_year year=2018 uri = URI.parse("#{BASE_URL}getSets?apiKey=#{API_KEY}&userHash=&query=&theme=&subtheme=&setNumber=&owned=&wanted=&order...
module Api::V1 class SessionsController < ApplicationController skip_before_action :authenticate # POST /sessions def create user = User.find_by( email: session_params[:email] ).try(:authenticate, session_params[:password]) if user.present? render json: user, status: :c...
$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + '/../lib') require 'spec_helper' require 'templates/html' require 'image' RSpec.describe Templates::Html, type: :aruba do before(:all) { setup_aruba Dir.chdir('tmp/aruba') } after(:all) { Dir.chdir('../..') } let(:attr_labels) { %w[directo...
module MazeCrosser # Class responsible for solving a maze, by using a given algorithm or a # cache. # # maze_solver = MazeSolver.new(maze, algorithm, cache_provider) # maze_solver.solve class MazeSolver def initialize(maze, algorithm, cache_provider) @algorithm = algorithm @cache_provider = ...
require 'rails_helper' RSpec.describe InvitationsController, :type => :controller do describe "GET accept" do context 'no params slug' do it 'redirects to root_path' do get :accept expect(response).to redirect_to root_path end end context 'params slug' do before do ...
require("spec_helper") describe(Brand) do it("validates presence of name") do brand = Brand.new({:name => ""}) expect(brand.save()).to(eq(false)) end it("assures that a brand name entry is unique in the database") do brand1 = Brand.create({:name => "addidas"}) brand2 = Brand.new({:name => "addid...
require 'nokogiri' require './lib/py2zy.rb' module PlecoAnki class Card attr_accessor :word_sc attr_accessor :word_tc attr_accessor :pron attr_accessor :pron_zh attr_accessor :pron_can attr_accessor :defn @@pinyinConverter = Pinyin2Zhuyin.new def initialize(card_node) card_nod...
class HomeController < ApplicationController before_action :authenticate_user! def index @reviews = Review.all render json: @reviews, status: 200 end def home # if user_signed_in? redirect_to search_search_path # end # @users = User.get_random end end
# == Schema Information # # Table name: roles # # id :bigint not null, primary key # name :string # description :text # head :boolean # division_id :bigint # department_id :bigint # created_at :datetime not null # updated_at :datetime not null # ...
FactoryGirl.define do factory :user do sequence(:nickname) { |i| "test_user#{i}" } sequence(:email) { |i| "email#{i}@example.com" } admin false password "password" password_confirmation "password" factory :admin do admin true end end end
class Diagnosis < ActiveRecord::Base has_many :visit_diagnoses has_many :visits, :through => :visit_diagnoses validates :characterization, :uniqueness => true end
class User < ActiveRecord::Base before_save { self.email = email.downcase } validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, ...
require "dumb_monitor/version" module DumbMonitor EMPTY_Hash = {}.freeze EMPTY_Array = [].freeze EMPTY_String = ''.freeze end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
class Message < ActiveRecord::Base attr_accessor :action belongs_to :user def after_initialize @action = 'Add' end def poster_name user ? user.nick_name : "未知" end def poster_img_url user ? user.photo_url : "" end end
class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.text :body # the t.references :question will generate an integer field that is called: question_id (rails convention) and also adds an index and a foreign key for us. t.references :question, index: true, fore...
FactoryBot.define do factory :league_roster_transfer, class: League::Roster::Transfer do user association :roster, factory: :league_roster is_joining { true } end end
require 'test_helper' class SectionsControllerTest < ActionDispatch::IntegrationTest setup do @section = sections(:one) end test "should get index" do get sections_url assert_response :success end test "should get new" do get new_section_url assert_response :success end test "shoul...
module Escpos class DimensionsMustBeMultipleOf8 < ArgumentError def message "Image width and height must be a multiple of 8 or the option \"extent\" must be set to true." end end class InputNotSupported < ArgumentError def message "Image must be a path or an instance of e.g. ChunkyPNG::I...
module Goby # A Player can interact with these on the Map. class Event # The default text for when the event doesn't do anything. DEFAULT_RUN_TEXT = "Nothing happens.\n\n" # @param [String] command the command to activate the event. # @param [Integer] mode convenient way for an event to have mult...
require File.dirname(__FILE__) + '/../../spec_helper.rb' describe "OracleEnhancedAdapter date type detection based on column names" do before(:all) do ActiveRecord::Base.establish_connection(CONNECTION_PARAMS) @conn = ActiveRecord::Base.connection @conn.execute <<-SQL CREATE TABLE test_employees ( ...
class CreateNotes < ActiveRecord::Migration def change create_table :notes do |t| t.string :name t.text :description t.text :note_from_author t.integer :comments_id t.integer :spam_count t.string :prereq t.string :file t.integer :list_count_id t.timestamps nu...
class LikesController < ApplicationController before_action :find_target before_action :find_like, only: %i[destroy] def create if already_liked? flash[:notice] = "You can't like more than once" else @target.likes.create(user_id: current_user.id) if params[:post_id] Notification....
Pod::Spec.new do |s| s.name = "AutoLayoutHelpers" s.version = "1.0.0" s.summary = "Helpers for auto layout." s.description = <<-DESC ##Before ``` NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.titleBar attribute:NS...
require 'yaml' module Verses # This class holds metadata about Bible book names, chapter counts, and verse counts class Metadata class << self # The metadata contents loaded from the yaml file. attr_reader :metadata # Access metadata for a specified book # # Examples: # ...
class DispositivosController < ApplicationController before_filter :authenticate_user!, :except => [:get_telebot_config] check_authorization load_and_authorize_resource rescue_from CanCan::AccessDenied do |exception| flash[:error] = exception.message redirect_to home_path end before_filter :get_d...
# @param {Integer} num # @return {Boolean} def is_power_of_four(num) if num == 0 false elsif num == 1 true else num % 4 == 0 && is_power_of_four(num / 4) end end
require 'spec_helper' describe Right do let(:robot){Robot.new} let(:position){CellPosition.new(0,0,'NORTH')} describe 'execute' do context 'robot is placed' do it 'turns robot 90 degrees right' do robot.position = position Right.new(robot).execute expect(robot.position.direction...
class EventsController < ApplicationController # include PgSearch::Model # pg_search_scope :search_by_title_and_category, # against: [ :title, :category ], # using: { # tsearch: { prefix: true } def filter @my_events = current_user.events @joined_events = current_user.joined_events @...
class Admin::HomesController < ApplicationController before_action :authenticate_admin! def top @orders = Order.order(updated_at: :desc).page(params[:page]).per(10) # @customer = Customer.find(params[:id]) end private def order_params params.require(:order).permit(:postcode, :address, :na...
FactoryGirl.define do factory :shipping_line do code "Free Shipping" price 0.00 source "shopify" after(:build) do |shipping_lines| shipping_lines.tax_lines << build(:tax_line) end end end
# frozen_string_literal: true require 'spec_helper' class AClass def self.call(argument, **_info) argument[:in_class_call] = true argument end def self.other(argument, **_info) argument[:in_class_other] = true argument end end class POROClass include RailwayOperation::Operator add_step ...
class GameBlueprint < Blueprinter::Base identifier :id fields :player1, :player2, :point1, :point2 end
################################################################################ class UserLoginData attr_reader :pick, :input, :home, :group, :status ################################################################################ def initialize(validator, dataarray, loginvalue, pick, input, home, group) #...
module Payment class Transfer < Base def perform purchase && orders && finish_purchase end def redirect_path [Rails.application.routes.url_helpers.checkout_transfer_path(purchase.invoice_id), flash: { notice: 'Aguardando confirmação' }] end private def payment_method 'tran...
class DocumentPagesController < ApplicationController before_action :set_document_page, only: [:show, :edit, :update, :destroy] # GET /document_pages def index @document_pages = DocumentPage.all end # GET /document_pages/1 def show end # GET /document_pages/new def new @document_page = Docu...
describe CoreExtensions::String::Harmonizer do describe '#harmonized' do context 'when the object is a String' do context 'when string is present' do subject { ' a test string ' } it 'is stripped' do expect(subject.harmonized).to eq('a test string') end it 'is f...
module Fog module Compute class Google class Mock def get_image_from_family(_family, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real # Returns the latest non-deprecated image that is part of ...
FactoryGirl.define do factory :user do username 'john_doe' name 'John Doe' email 'jdoe@example.com' end end
module IamI class Logger attr_accessor :connections alias connection_register_connections_initialize initialize def initialize(*args) connection_register_connections_initialize(*args) @connections = [] register_trigger 'connection_trigger' do |message, line, level| @connections....
# 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...
FactoryBot.define do factory :file_group do sequence(:title) {|n| "File Group #{n}"} type {'ExternalFileGroup'} external_file_location {'External File Location'} total_files {0} total_file_size {0} collection producer end factory :external_file_group, parent: :file_group, class: Exter...
class VotesController < ApplicationController def upvote if Vote.already_created(params[:id], session[:user_id]) flash[:error] = "Sorry, you already voted for this!" redirect_to root_path else vote = Vote.new vote[:work_id] = params[:id] vote[:user_id] = session[:user_id] ...
class CreateRequests < ActiveRecord::Migration def change create_table :requests do |t| t.integer :user_id t.string :title t.string :from_lat t.string :from_lng t.string :to_lat t.string :to_lng t.string :state t.integer :request_type, default:0 t.text :descri...
require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>, <%= type_metatag(:request) %> do context 'with <%= name.underscore.pluralize %>' do let!(:<%= class_name %>) { Fabricate(:<%= class_name %>) } describe 'GET /<%= name.underscore.pluralize %>' do it 'should return the...
class RecordqnntsController < ApplicationController before_action :set_recordqnnt, only: [:show, :edit, :update, :destroy] # GET /recordqnnts # GET /recordqnnts.json def index @recordqnnts = Recordqnnt.all end # GET /recordqnnts/1 # GET /recordqnnts/1.json def show end # GET /recordqnnts/new ...
class School < ActiveRecord::Base has_many :teachers has_many :students def self.find_or_create(school_name) school = School.find_by(name: school_name) while school == nil puts "We do not recognize this school. Would you like to add?" user_input = yes_or_no if user_input == "y" ...
require "application_system_test_case" class AdminBlackListsTest < ApplicationSystemTestCase setup do @admin_black_list = admin_black_lists(:one) end test "visiting the index" do visit admin_black_lists_url assert_selector "h1", text: "Admin Black Lists" end test "creating a Admin b...
class API::V1::UserSerializer < ActiveModel::Serializer attributes :id , :email , :name , :created_at def created_at object.created_at.strftime "%Y-%m-%d" end end
# PrefixStreamBuf is a utility class used my # MCollective::Application::Shell::Watcher. # PrefixStreambuf#display takes chunks of input, and on complete lines will # emit that line with the prefix. Incomplete lines are kept internally for # the next call to display, unless #flush is called to flush the buffer. modu...
class Privacy include Mongoid::Document field :name, :type => String, localize: true field :description, :type => String, localize: true field :css, :type => String validates :name, uniqueness: true validates :name, presence: true has_many :users has_many :offers end
class TabbedSearchResultsPresenter def initialize(search_response) @search_response = search_response end def spelling_suggestion if search_response["spelling_suggestions"] search_response["spelling_suggestions"].first end end def result_count search_response["streams"].values.sum { |...
module Chirper module Domain class Chirp attr_accessor :title, :body end end module UseCase class CreateChirp def initialize(chirp_gateway:) @chirp_gateway = chirp_gateway end def execute(*) chirp = Chirper::Domain::Chirp.new chirp.title = "Meow" ...
class CreateDrivers < ActiveRecord::Migration def change create_table :drivers do |t| t.string :name_driver t.string :address_driver t.string :telephone_driver t.string :status_driver t.string :placa_driver t.timestamps null: false end end end
class UserFriendship < ActiveRecord::Base belongs_to :user belongs_to :friend , class_name: 'User', foreign_key: 'friend_id' attr_accessible :user,:friend,:user_id,:friend_id state_machine :state, initial: :pending do event :accept do transition any => :accepted end end def send_request_email UserNoti...
require 'stringio' require_relative '../lib/tictactoe' describe TicTacToe do describe 'interface' do it 'can start' do expect(TicTacToe.new).to respond_to(:start_game) end end describe "status is" do context "started" do let(:fake_human) { FakeHuman.new } it "has a start and end" ...
class LearningTag < ApplicationRecord # Validations validates_presence_of :learning, :tag # Relations belongs_to :learning belongs_to :tag end
class AddResourceIdToReposts < ActiveRecord::Migration def change add_column :reposts, :resource_id, :string end end
class RailsToNgValidationTranslator attr_reader :validations def initialize @validations = {} end def self.translate(klass, attributes=klass._validators.keys) translator = RailsToNgValidationTranslator.new attributes.each do |attribute| klass._validators[attribute].each do |entry| ...
require 'spec_helper' require 'kindle-your-highlights' USERNAME = ENV["KINDLE_USERNAME"] PASSWORD = ENV["KINDLE_PASSWORD"] DUMP_FILE = "spec/data/out.dump" XML_FILE = "spec/data/out.xml" HTML_FILE = "spec/data/out.html" describe "KindleYourHighlights" do before(:all) do File.delete(DUMP_FILE) if File.exist?...
class AddForeignKeyToEquipment < ActiveRecord::Migration[5.2] def change add_foreign_key :equipment, :organizations end end
include WrappityWrap RSpec.describe WrappityWrap do it 'has a version number' do expect(WrappityWrap::VERSION).not_to be nil end it 'returns "" when given nil' do expect(WrappityWrap.wrap(nil, 4)).to eq("") end it 'returns "" when given empty string' do expect(WrappityWrap.wrap("", 4)).to eq("...
class RemoveOccurrenceDateFromLearnings < ActiveRecord::Migration def change remove_column :learnings, :occurrence_date, :string end end
class Ingredient < ApplicationRecord has_many :dose validates :name, uniqueness: true end
module DataMapper module Validate # A base class that all validators must be derived from. Child classes # must implement the abstract method call where the actual validation # occures # class GenericValidator attr_accessor :if_clause attr_accessor :unless_clause ...
class PingPong::TableControls def initialize(match) @match = match end def home_button player_button match.home_player end def away_button player_button match.away_player end def center_button rewind_match end private attr_reader :match def player_button(player) if match....
class CreateIndexes < ActiveRecord::Migration def change [:country_id, :city_id, :category_id, :sub_category_id, :description_type_id, :show_menu, :show_in_menu, :active].each do |i| add_index :pages, i end add_index :photos, :page_id add_index :sub_categories, :category_id add_index :sub_ca...
# frozen_string_literal: true class EventSpreadSerializer < BaseSerializer attributes :name, :course_name, :organization_name, :event_start_time, :event_start_time_local, :display_style, :split_header_data link(:self) { spread_api_v1_event_path(object.event) } has_many :effort_times_rows def event_start_time...
class PoliciesController < BaseController load_and_authorize_resource before_action :set_policy, only: [:show, :edit, :update, :destroy, :download] before_action :check_user_is_president, only: [:create, :update, :destroy] # GET /policies # GET /policies.json def index @policies = Policy.all @unre...
require_relative 'token' module Scheme class Scanner WHITESPACE_CHARS = [" ", "\n"] VALID_VARIABLE_REGEX = /[a-zA-Z_$!_\-\+\/\*]/ def initialize(string) @string = string end def read_next_char @string.slice!(0) end def get_next_token char = read_next_char ...
# frozen_string_literal: true module PgParty class ModelDecorator < SimpleDelegator def in_partition(child_table_name) PgParty.cache.fetch_model(cache_key, child_table_name) do Class.new(__getobj__) do self.table_name = child_table_name # to avoid argument errors when calling m...
class CreateBooksCourses < ActiveRecord::Migration[5.2] def change create_table :books_courses do |t| t.belongs_to :book, index: true t.belongs_to :course, index: true t.timestamps end end end
require 'sinatra' require 'data_mapper' require 'omniauth-bigcommerce' require 'json' require 'base64' require 'rest_client' require 'openssl' require 'bigcommerce' require 'logger' configure do set :run, true set :environment, :development # Actually need to disable frame protection because our app # lives ...
$:.unshift(File.join(File.dirname(__FILE__), 'lib')) require 'autoprotocol/version' spec = Gem::Specification.new do |s| s.name = 'autoprotocol' s.version = Autoprotocol::VERSION.dup s.summary = 'Ruby library for generating Autoprotocol' s.authors = ['Connor Warnock', 'Transon Nguyen'] s.email = ['connor@no...
class Vpcs < Formula desc "Virtual PC simulator for testing IP routing" homepage "https://vpcs.sourceforge.io/" url "https://downloads.sourceforge.net/project/vpcs/0.6/vpcs-0.6-src.tbz" sha256 "cc311b0dea9ea02ef95f26704d73e34d293caa503600a0acca202d577afd3ceb" bottle do cellar :any_skip_relocation sha...
require 'revent' require 'bunny' module Revent module Providers class RabbitMQ attr_reader :conn, :channel, :queue, :params def initialize @params = { hostname: Revent.config.host, username: Revent.config.username, password: Revent.config.password } ...
# Gem::Specification for Net-ssh-gateway-1.0.0 # Originally generated by Echoe Gem::Specification.new do |s| s.name = %q{net-ssh-gateway} s.version = "1.0.0" s.specification_version = 2 if s.respond_to? :specification_version= s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :requ...
class AddInfoToTrip < ActiveRecord::Migration def change add_column :trips, :distance, :integer add_column :trips, :checkpoint_num, :integer add_column :trips, :duration, :string end end
class RelatorioNaoformalController < ApplicationController def index @relatorios = Relatnaoformal.all if current_user.licenciatura == 'Ciências da Natureza' redirect_to action: "edit" end respond_to do |format| format.html format.pdf do @relatorio = Relatnaoformal.all i...