text
stringlengths
10
2.61M
require "active_flags/engine" require_relative 'active_flags/handler/flag_mapper' require_relative 'active_flags/handler/flag_builder' require_relative 'utils/value_stringifier' module ActiveFlags extend ActiveSupport::Concern ACTIVE_FLAGS_PREFIX = 'flagged_as_' class_methods do def has_flags(*authorized_f...
class CreateSalesDays < ActiveRecord::Migration[5.2] def change create_table :sales_days do |t| t.date :sales_date t.integer :amount_spent t.integer :amount_sold t.references :market, foreign_key: true t.timestamps end end end
require 'openssl' require 'json' module Oshpark class Client attr_accessor :token, :connection # Create an new Client object. # # @param connection: # pass in a subclass of connection which implements the `request` method # with whichever HTTP client library you prefer. Default is Net::HTTP...
namespace :db do desc 'Loading data from Faker' task :populate => :environment do require 'faker' User.destroy_all 40.times do |n| name = Faker::Name.name email = Faker::Internet.email phone = Faker::PhoneNumber.phone_number state = Faker::Address.city company = F...
class Goreleaserpoc < Formula desc "A simple Go app to test out GoReleaser (POC)" homepage "https://github.com/Ilyes512/goreleaserpoc" url "https://github.com/Ilyes512/goreleaserpoc/releases/download/0.2.4/goreleaserpoc_0.2.4_macOS_64-bit.tar.gz" version "0.2.4" sha256 "3263d0a130d7188b4208623dbc8a3d168448ec1...
class AddOrderDeadlineToGroupManagerCommonOptions < ActiveRecord::Migration[5.2] def change add_column :group_manager_common_options, :order_deadline, :string end end
# frozen_string_literal: true require 'bolt_command_helper' test_name "Install modules" do extend Acceptance::BoltCommandHelper # Install modules to the `modules` dir in bolt gem path to replicate # where modules will be with system packages. find_bolt_gem = bolt_command_on(bolt, "gem which bolt") bolt_gem...
# frozen_string_literal: true # Copyright (c) 2017-present, BigCommerce Pty. Ltd. All rights reserved # # 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 l...
# frozen_string_literal: true module Kafka module Protocol class CreateTopicsRequest def initialize(topics:, timeout:) @topics, @timeout = topics, timeout end def api_key CREATE_TOPICS_API end def api_version 0 end def response_class P...
class JoinRequirement < ActiveRecord::Base has_many :requirements has_many :requirement_values has_many :users, through: :requirement_values has_and_belongs_to_many :locations validates :title, presence: true end
# frozen_string_literal: true RSpec.shared_examples 'a model with ohsu core metadata' do subject(:model) { described_class.new } it { is_expected.to have_editable_property(:date, RDF::Vocab::DC11.date) } it { is_expected.to have_editable_property(:date_label, RDF::Vocab::DWC.verbatimEventDate) } it { i...
# -*- Mode: RSpec; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- require 'spec_helper' require "occurrence_summer" describe OccurrenceSummer do it "should sum occurrences based on the to_s method" do s = OccurrenceSummer.new(:to_s) s.sum %w(one two three two one) s.occurrences.should == { ...
class AddThumbnailToEmoticons < ActiveRecord::Migration def change add_column :emoticons, :thumb_id, :uuid end end
class Game < ActiveRecord::Base LEGAL_SHOTS = {1 => [3], 2 => [2,3], 3 => [1,2,3] } attr_accessible :phase, :result, :queue, :winner_id, :loser_id has_many :players, dependent: :destroy, order: "id ASC" has_many :users, through: :players has_many :cards, dependent: :destroy has_many :damage_tokens, depend...
module Url attr_reader :url, :params def set_url(url = "") @url = url end def set_params(params = {}) @params = params end def full_url "#{@url}?#{params_string}" end private def params_string @params.inject([]) do |result, pair| key, value = pair value.present? ? resul...
# frozen_string_literal: true # Seed data for the application # # The command `bin/hanami db seed` executes these seeds require 'faker' authors = Main::Container[ 'repositories.authors' ] authors.create(first_name: 'Seb', last_name: 'Wilgosz') authors.create(first_name: 'Hanami', last_name: 'Master') authors.crea...
class Centre < ActiveRecord::Base # AR classes are singular and capitalized by convention # attr_accessible :avatar belongs_to :user has_and_belongs_to_many :courses mount_uploader :avatar, AvatarUploader validates :contact_no, numericality: { only_integer: true, message: ": %{value} should only...
class Facility < ActiveRecord::Base attr_accessible :name validates_presence_of :name end
require_relative "../../shared_ruby/euler.rb" class ConcatenationSolver attr_reader :answer def initialize(num_elements) @num_elements = num_elements @min_size_found = 30_000 @answer = nil end def concatenates?(i, array) num = Primes[i] array.each do |j| orig = Prime...
require 'test_helper' class CartTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "test adding unique products to cart" do cart = Cart.create pone = products(:prodone) ptwo = products(:prodtwo) cart.add_product(pone.id).save! cart.add_product(ptwo.id).save! ...
class MailsController < ApplicationController include MailsHelper include ActionController::Live def upload uploaded_files = params[:templates] uploaded_files.each do |file| process_template(file) end respond_to do |format| format.js {render inline: "location.reload();" } end ...
# frozen_string_literal: true class CreateClauses < ActiveRecord::Migration[5.2] def change create_table :clauses do |t| t.integer :section_id t.decimal :number t.text :body t.timestamps end end end
class Team < ApplicationRecord has_many :team_members validates :name, :slug, presence: true end
class Brand < ApplicationRecord has_many :models, dependent: :destroy has_many :equipment, dependent: :destroy has_and_belongs_to_many :categories has_one :stock, as: :item, dependent: :destroy before_destroy :create_log before_save :format_data after_save :create_stock validates :name, presence: true,...
class User < ActiveRecord::Base has_many :posts has_many :likes, dependent: :destroy has_many :posts_liked, through: :likes, source: :post has_secure_password EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :name, :alias, :email, :password, :password_confirmation, presence: true validate...
# # Cookbook Name:: frog # Recipe:: _mysql.rb # # Copyright (C) 2014 Nick Downs # # 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 right...
# SPECIFIC TIMES EVERY DAY # every "16:00" # every "8:10:00 pm" # every 12pm, 4pm, 8pm # every midnight # SPECIFIC DAYS OF THE WEEK # every monday at 4pm # every weekend at 10:00 # every weekday at 7:00am, 5pm # every monday, wednesday, friday at 2:00 # SPECIFIC DAYS OF THE MONTH # every 1st of the month at noon # e...
require 'rails_helper' RSpec.describe Search, type: :model do it { should have_many(:products) } it { should validate_presence_of(:query) } it 'has a valid factory' do expect(create(:search)).to be_valid end describe '.fetch_products' do it 'expects crawler with crawler settings' do allow(Set...
class PrefectureCode < ActiveHash::Base self.data = [ {id: 1, prefecturecode: '北海道'}, {id: 2, prefecturecode: '青森県'}, {id: 3, prefecturecode: '岩手県'}, {id: 7, prefecturecode: '福島県'}, {id: 8, prefecturecode: '茨城県'}, {id: 9, prefecturecode: '栃木県'}, {id: 10, prefecturecode: '群馬県'}, {id: 11, prefecturecode: '埼...
class String def palindrome? return true if length < 2 return false if self[0] != self[-1] self[1...-1].palindrome? end end ans = (1..1_000_000).inject(0){|s, n| n.to_s.palindrome? && n.to_s(2).palindrome? ? s + n : s } puts ans
require 'json' def check_required_keys(required_keys, format) required_keys.each do |required_key| required_key = required_key.to_sym raise ArgumentError, "format missing '#{required_key}'" unless format.key? required_key end end def create_app_sequence(format, count) format = format.symbolize_keys ch...
describe SearchController do login_user describe "#index" do it "searches for the term in body" do FactoryGirl.create :recipe, body: "cream cheese" post :index, search: "cheese" expect(assigns[:recipes].size).to eq(1) end it "searches for the term in name" do FactoryGirl.create...
class ChangedContestAnsSheetsAddedSkips < ActiveRecord::Migration def self.up add_column :contest_ans_sheets, :skips, :integer end def self.down remove_column :contest_ans_sheets, :skips end end
# coding: utf-8 require 'rails_helper' RSpec.describe Bookmark, type: :model do let!(:user) {FactoryBot.build(:user)} let!(:post) {FactoryBot.build(:post)} it "正常系" do expect(FactoryBot.create(:bookmark, post: post, user: user)).to be_valid end # Assosiation it {should belong_to(:user)} it {should ...
class Slither class Definition attr_reader :sections, :templates, :options, :columns, :length RESERVED_NAMES = [:spacer] def initialize(options = {}) @sections = [] @templates = {} @options = { :align => :right, :by_bytes => true, :sectionless => fal...
class ChangeAuthorizations < ActiveRecord::Migration def self.up change_table :authorizations do |t| t.remove :user_id t.integer :account_id end end def self.down change_table :authorizations do |t| t.remove :account_id t.string :user_id end end end
describe Blorgh::Article do it "can be created from a factory" do expect(create(:blorgh_article)).to be_persisted end it "gets cleaned properly" do expect(described_class.count).to eq(0) end end
class Comment < ActiveRecord::Base belongs_to :article validates_presence_of :name, :email, :body validates :body, length: { maximum: 250} end
require "securerandom" require_relative "user" class ShortenedURL < ApplicationRecord def self.random_code shorturl = nil until !shorturl.nil? && !self.exists?(short_url: shorturl) shorturl = SecureRandom.base64(16) end shorturl end validates :short_url, presence: true, uniqueness: true ...
class CityType < ActiveRecord::Base has_many :cities validates_presence_of :full_name end
# encoding : utf-8 MoneyRails.configure do |config| # Register a custom currency # # Example: config.register_currency = { :priority => 1, :iso_code => "VMK", :name => "Venthian Mark", :symbol => "¥", :symbol_first => false, :sub...
unless Rails.env.production? require 'rspec/core/rake_task' require 'rubocop/rake_task' require 'active_fedora/rake_support' namespace :donut do RSpec::Core::RakeTask.new(:rspec) do |t| t.rspec_opts = ['--color', '--backtrace'] end desc 'Load test config' task :load_test_config do ...
# == Schema Information # # Table name: players # # id :integer not null, primary key # summonerid :string # created_at :datetime not null # updated_at :datetime not null # name :string # tier :string # topchampionid :string # class Player < Applica...
require 'spec_helper' describe EmployeesController do render_views before(:each) do @attr = { :first_name => "Test", :last_name => "Employee", :address1 => "Address", :address2 => "", :city => "Macon", :state => "GA", :zip => "99999", :birthday => '1990-1-1', :hire_date => '2004-1-1', :company_c...
class Playlist < Sequel::Model many_to_one :curator, :class => Speaker many_to_many :talks, :join_table => :playlists_talks, :left_key => :playlist_id, :right_key => :talk_id, :class => Talk many_to_many :talks_with_conference_and_speakers, clone: :talks, :eager => [:...
class Api::V1::MessagesController < ApiController def index if current_user.nil? head 403 else render json: Message.limit(50) .where(lobby_id: params['lobby_id']) .order("id desc") .reverse, # Renders oldest to newest root: "messages" end end end
require File.dirname(__FILE__) + '/../test_helper' class UserControllerTest < ActionController::TestCase fixtures :users # The user creation page loads def test_user_create_view get :new assert_response :success assert_select "html:root", :count => 1 do assert_select "head", :count => 1...
class ErrorsController < ActionController::Base skip_forgery_protection def not_found @title = "404 - viky.ai" @message = t('errors.not_found.comment') render status: 404 end def internal_error exception = request.env['action_dispatch.exception'] @message = exception.message @applicat...
class MakeAllSlugsUnique < ActiveRecord::Migration def change add_index :areas, :slug, unique: true add_index :coaches, :slug, unique: true add_index :stadiums, :slug, unique: true add_index :static_pages, :slug, unique: true end end
class Admins::BrandingsController < ApplicationController before_filter :authenticate_admin! layout "admins" def index @brandings = Branding.all respond_to do |format| format.html end end def new @branding = Branding.new @branding.photos.build respond_to do |format| format.html end end ...
class JobRequest < ApplicationRecord acts_as_paranoid # has_many :design_requests # has_many :designs, through: :design_requests has_many :quotation_lines has_many :add_ons has_many :attachments, as: :attachable, dependent: :destroy belongs_to :deal has_many :print_details, dependent: :destroy has_man...
class Api::V1::SalesProductsController < Api::V1::BaseApiController def setup_harvest_package command = Inventory::SetupHarvestPackage.call(current_user, params[:sales_product].to_unsafe_h) if command.success? render json: Inventory::HarvestPackageSerializer.new(command.result).serialized_json else ...
Rails.application.routes.draw do mount Launch::Engine => "/launch" end
class Person < ApplicationRecord #commented to a more flexible user registration belongs_to :person_type belongs_to :ic_type has_and_belongs_to_many :addresses accepts_nested_attributes_for :addresses, allow_destroy: false end
# This tests the Prime class' generation speed. # # Ruby 1.8 MRI has an extremely poor/naive implementation of Prime # therefore it is expected to timeout on most machines for all but # n = 3_000. The higher parameters are still useful to test Ruby 1.9 # and other implementations. # # Ruby 1.9 generates a warning abou...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :definition do term "MyTerm" definiens "A definiens for my term" end end
class Ability include CanCan::Ability def initialize(user) if user if user.kind == 'salesman' can :access, :rails_admin can :dashboard can :manage, Client, user_id: user.id # vendedor pode gerenciar seus clientes can :manage, Sale, user_id: user.id # vendedor pode gerencia...
class PlayersController < ApplicationController def index @players = Player.all.sort_by(&:rating).reverse end def show @player = Player.find(params[:id]) @stats = PlayerStatistician.new(@player) @games = @player.games.page(params[:games_page]).per(10) @tournaments = @player.tournaments.page(p...
class SessionsController < ApplicationController skip_before_action :verified_user, only: [:new, :create] def new @user = User.new render :login end def create o_user = user_by_omni p_user = user_by_params if (p_user && p_user.authenticate(params[:password])) || o_user #good logi...
class Projet < ActiveRecord::Base validates_uniqueness_of :description end
# frozen_string_literal: false require_relative "rss-testcase" require "rss/maker" module RSS class TestMakerITunes < TestCase def test_author assert_maker_itunes_author(%w(channel)) assert_maker_itunes_author(%w(items last)) end def test_block assert_maker_itunes_block(%w(channel)) ...
#!/usr/bin/env ruby require 'json' require_relative '../spec_helper' LINK_PREFIX = test_object_prefix.freeze class LinkTests < CommandTest def setup @props = { name: "#{LINK_PREFIX} link name", description: "#{LINK_PREFIX} link description", template: "https://#{LINK_PRE...
require_relative "heap" class Array def heap_sort! prc = Proc.new { |el1, el2| el2 <=> el1 } len = self.length (1...len).each do |i| BinaryMinHeap.heapify_up(self, i, &prc) end (1...len).each do |i| self[0], self[self.length - i] = self[self.length - i], self[0] BinaryMinHeap.he...
class Vampire @@coven = [] def initialize(name, age) @name = name @age = age @in_coffin = true @drank_blood_today = false end def self.coven_status @@coven end def in_coffin @in_coffin end def drank_blood_today @drank_blood_today end def in_coffin=(in_coffin) @in...
# ================================================================ # Created: 2015/03/25 # Author: Thomas Nguyen - thomas_ejob@hotmail.com # Purpose: Generic time related methods # ================================================================ class MyClock def self.get_date #self = static method in Ruby ret...
# Bundler require 'bundler/setup' # STDLib & Gems require 'yaml' require 'sqlite3' require 'sequel' module GoogleNGrams module Processor AUTHORS = ["Nicholas Brochu"] VERSION = ["0.1.0"] @config = { :log_level => "minimal", :raw_data_path => "./data/raw", ...
class AddUserToProductArrangement < ActiveRecord::Migration def change add_column :product_arrangements, :user_id, :integer add_column :product_arrangements, :acceptance, :boolean end end
# encoding: utf-8 class Api::UsersController < ApplicationController before_filter :authenticate_user!, :except => [:name] before_filter :get_user, :except => [:name] def names @users = User.active_user.where("username like ? and id != ? ", "%#{params[:term]}%", current_user.id).order("updated_at desc").lim...
class CreateValidations < ActiveRecord::Migration def change create_table :validations do |t| t.references :sample, index: true t.boolean :confirmation t.string :reference_build t.string :chr t.string :pos t.string :ref t.string :alt t.string :hgvs_c t.string ...
class Rockpaperscissors attr_reader :beaten_by def initialize @beaten_by = {rock: [:paper, :spock], scissors: [:rock, :spock], paper: [:scissors, :lizard], lizard: [:scissors, :rock], spock: [:lizard, :paper]} end def winner(name1, c...
control "M-5.22" do title "5.22 Ensure docker exec commands are not used with privileged option(Scored)" desc " Do not docker exec with --privileged option. Using --privileged option in docker exec gives extended Linux capabilities to the command. This could potentially be insecure and unsafe to do esp...
class AddColumnCategory < ActiveRecord::Migration def change add_column :recipes, :category_id ,:integer ,references: :categories end end
class Address < ApplicationRecord belongs_to :addressable, polymorphic: true validates :addressable_id, presence: true validates :addressable_type, presence: true with_options if: :need_be_specific do |specific| specific.validates :street_address, presence: true specific.validates :city,...
require 'json' require 'sinatra' Dir["#{__dir__}/lib/*.rb"].each { |file| load file } not_found do status 404 'Seems like you are lost' end get '/' do status 200 'Running OK' end post '/jira' do content_type 'application/json' # return 401 unless request[:token] == ENV['SLACK_TOKEN'] status 200 text...
class Transportation < ApplicationRecord belongs_to :trip has_many :receipts, as: :imageable end
class Response < ActiveRecord::Base belongs_to :respondable, :polymorphic => true has_many :votes, :as => :votable belongs_to :user attr_accessible :user_id, :content validates :content, :presence => true def sum_vote self.votes.sum('value') end end
RSpec.describe 'raise_error matcher' do def some_method x end it 'can check for any error' do expect { some_method }.to raise_error(NameError) expect { 1 / 0}.to raise_error(ZeroDivisionError) end end
# encoding: utf-8 require_relative "command_line" require_relative "logger" require "digest/md5" module DCC class Git include CommandLine include Logger def initialize(name, id, url, branch, fallback_branch = nil, is_dependency = false) # FIXME: Tests @name = "#{name.gsub(/[^-_a-zA-Z0-9]/, ...
def turn_count(board) # counts positions taken turns = 0 board.each do |square| # looks at all board positions if square == "X" || square == "O" # checks for and X or O in each board position turns += 1 # for each O or X founds increases turn count end end return turns end def current_player(boa...
class CreateTrucks < ActiveRecord::Migration[5.0] def change create_table :trucks do |t| t.string :truck_no t.string :truck_driver t.string :driver_no t.datetime :day_start t.datetime :day_off t.references :user, foreign_key: true t.timestamps end end end
require 'rails_helper' describe Card do it 'original_text should be not equal translated_text' do card = Card.create(original_text:'original', translated_text:'original') expect(card.errors['original_text']).to include("can't be equal to translated_text") end end
class RemoveValueColumns < ActiveRecord::Migration def change # Grades remove_column :grades, :value add_column :grades, :name, :string # Identities remove_column :identities, :value # Languages remove_column :languages, :value add_column :languages, :name, :string # Organiz...
require 'spec_helper' describe "Verify database 'app_test' imported" do it "should have database 'app_test' created" do expect(db.query("SHOW DATABASES LIKE 'app_test'").entries.first['Database (app_test)']).to eq('app_test') end end describe "Verify 'app_test.app_test' table exists with imported content" do i...
# # Author:: Christopher Walters (<cw@opscode.com>) # Author:: Mark Anderson (<mark@opscode.com>) # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
# == Schema Information # # Table name: photos # # id :bigint(8) not null, primary key # url :string not null # spot_id :integer not null # class Photo < ApplicationRecord validates :url, :spot_id, presence: true belongs_to :spot end
class TasksController < ApplicationController before_action :find_task, only: [:show, :edit, :update, :destroy] def index if user_signed_in? @task = current_user.tasks.build @tasks = Task.where(:user_id => current_user.id).order("created_at DESC") else render 'intro' end end def new @task = ...
module MDB class Group < ActiveRecord::Base attr_accessible :title, :url, :description, :section acts_as_url :title has_many :memberships has_many :users, through: :memberships validates_presence_of :title scope :sections, where(section: true) def symbol url....
class Dashboard::SponsorshipsController < Dashboard::BaseController def index @sponsorships = Sponsorship.all.order(end_date: :desc) end def show @sponsorship = Sponsorship.includes(:transactions).where(id: params[:id]).first @parties = BirthdayParty.includes(:transactions).available_to_sponsor en...
require 'faraday' require 'uri' require 'json' require 'digest/md5' class HyperResource module Modules module HTTP # A (high) limit to the number of retries a coordinator can ask for. This # is to avoid breaking things if we have a buggy coordinator that retries # things over and over again. ...
# 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...
class MessagesController < ApplicationController before_action :authenticate_user! def index @messages = Message.where(conversation_id: params[:conversation_id]).order(created_at: :desc).reverse_order @message = current_user.messages.build(conversation_id: params[:conversation_id]) end def create ...
# attributes:things about object # methods: what makes the object have attributes # class is the blueprint from which individual objects are created. a class models: # attributes # behaviors # an instance:representatun of class # defining a class # class NameOfClass # end # example: # class College # end # co...
class Product < ApplicationRecord alias_attribute :product_name, :name alias_attribute :product_sku, :sku has_many :product_articles validates :sku, uniqueness: true validates :name, presence: true validates :sku, presence: true end
# frozen_string_literal: true module GraphQL module Execution # Execute multiple queries under the same multiplex "umbrella". # They can share a batching context and reduce redundant database hits. # # The flow is: # # - Multiplex instrumentation setup # - Query instrumentation setup #...
# Notes on self # self is an expression that evaluates – like all Ruby expressions – to an # object. # More precisely: `self` evaluates to the current default object. # what `self` evaluates to depends on the place where `self` is evaluted # (the current "context") # the current default object is the object on which...
class SocialSecurityNumberFormatValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) # This regex should match all rules of # http://en.wikipedia.org/wiki/Social_Security_number#Valid_SSNs #--------------------------------------------------------------- if value.nil? ...
class Report < ActiveRecord::Base belongs_to :user has_attached_file :file, :url => "/:attachment/:id/:style/:basename.:extension", :download=>false, :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension" validates_attachment_content_type :file, :content_type => ["application/pdf", "im...
class CreateFestivals < ActiveRecord::Migration[5.0] def change create_table :festivals do |t| t.float :cost t.date :start t.date :finish t.integer :minimum_age t.string :location t.text :details t.string :image t.timestamps end end end
class Category < ApplicationRecord has_ancestry has_many :items scope :ancestries, ->(ancestry) {where(ancestry: ancestry)} scope :name_not, ->(name) {where.not(name: name).pluck(:name)} end
FactoryGirl.define do factory :workstation, class: Workstation do |workstation| sequence(:name) { |n| "CUS North #{n}" } sequence(:abrev) { |n| "CUS#{n}" } job_type "td" sequence(:user_id) { |n| n } end end