text
stringlengths
10
2.61M
def pad!(array, min_size, value = nil) #destructive if array.count >= min_size return array else (min_size - array.count).times do array << value end return array end end def pad(array, min_size, value = nil) #non-destructive new_array = Array.new(array) (min_size - array.count).times...
class CreateCartedDrinks < ActiveRecord::Migration[5.0] def change create_table :carted_drinks do |t| t.integer :order_id t.integer :user_id t.integer :drink_id t.integer :quantity t.timestamps end end end
class EventUpdaterForm include ActiveModel::Model attr_accessor :title, :description, :owner, :event_id, :event_date, :event_time, :street, :city, :province, :zip validates :title, :description, :owner, :event_id, presence: true validate :title_uniqueness_for_owner validate :event_belongs_to_owner ...
module ApplicationHelper def bootstrap_alert_type_for(flash_type) case flash_type when :success "success" when :error "danger" when :alert "warning" when :notice "info" else flash_type.to_s end end def flash_message(flash) return n...
# Accepts an array, Sorts and returns the array def sort_array(arr) if arr.respond_to?(:sort) && arr.class == Array && arr.length > 0 sorted = arr.sort min = arr[0] max = arr[arr.length-1] all_numbers = (min..max).to_a return all_numbers - sorted elsif arr.length == 0 &&...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Project, type: :model do subject { build(:project) } it { is_expected.to respond_to :name } it { is_expected.to respond_to :description } it { is_expected.to respond_to :creator_id } it { is_expected.to be_valid } it { is_expected.to h...
require 'statement' require 'bigdecimal' describe Statement do let(:statement_class) { described_class } let(:credit_transaction) { double :transaction, amount: BigDecimal('20'), date: Date.today } let(:debit_transaction) { double :transaction, amount:BigDecimal('-20'), date: Date.today } let(:transactions) d...
require 'spec_helper' feature "creating a group", :type => :feature do scenario "allows a user to create a group, add members and add an expense" do group_name = "A New Group" visit('/groups/new') fill_in 'Name', :with => group_name click_button 'Create group' expect(page).to have_content(gr...
module Enumerable def my_each i=0 while i < self.size yield(self[i]) i += 1 end self end def my_each_with_index i = 0 while i < self.size yield(self[i], i) i += 1 end self end def my_select retur...
class RemoveBilirubinFromClinicalBloodRecords < ActiveRecord::Migration def change remove_column :clinical_blood_records, :bilirubin, :text end end
Puppet::Type.newtype(:glusterfs_pool) do desc 'Native type for managing glusterfs pools' ensurable do defaultto(:present) newvalue(:present) do provider.create end newvalue(:absent) do provider.destroy end end newparam(:peer, :namevar=>true) do desc 'Trusted server peer' ...
require 'rails_helper' # Specs in this file have access to a helper object that includes # the SessionsHelper. For example: # # describe SessionsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # ...
require 'knife-pkg' include Knife::Pkg describe 'Package' do describe '#new' do it 'should create an instance of Package' do p = Package.new('test') expect(p).to be_an_instance_of Package expect(p.version).to eq('0.0') expect(p.name).to eq('test') end end describe '#version_to_s...
class AddManufacturerToPowerOrders < ActiveRecord::Migration[4.2] def change add_column :power_orders, :manufacturer, :string, null: false, default: 'No Data' add_column :power_orders, :model, :string, null: false, default: 'No Data' end end
module Result class VarResult < ::Result::AbstractResult attr_reader :current, :previous def initialize(current, previous, source_entity) super(source_entity) @current = current.to_f @previous = previous.to_f end def notification_triggered? ...
module Twitch module Chat class Client MODERATOR_MESSAGES_COUNT = 100 USER_MESSAGES_COUNT = 20 TWITCH_PERIOD = 30.0 attr_accessor :host, :port, :nickname, :password, :connection attr_reader :channel, :callbacks def initialize(options = {}, &blk) options.symbolize_keys...
require 'thor' module Xcadaptor class Adapt < Thor include Thor::Actions desc "ios [version] [--category]" , "adapt xcode project to the verison ios" long_desc <<-LONGDESC adapt xcode project to the verison ios ios [version] [--category] version : ios version. eg: 9.0 options: ...
# frozen_string_literal: true class Item < ApplicationRecord belongs_to :product belongs_to :cart validates :quantity, numericality: { greater_than_or_equal_to: 0 } end
require 'formula' class Wireshark <Formula url 'http://media-2.cacetech.com/wireshark/src/wireshark-1.4.3.tar.bz2' md5 'ac3dcc8c128c38d9ef3d9c93d1dec83e' homepage 'http://www.wireshark.org' depends_on 'gnutls' => :optional depends_on 'pcre' => :optional depends_on 'glib' depends_on 'gtk+' if ARGV.includ...
class FontRubikMoonrocks < Formula head "https://github.com/google/fonts/raw/main/ofl/rubikmoonrocks/RubikMoonrocks-Regular.ttf", verified: "github.com/google/fonts/" desc "Rubik Moonrocks" homepage "https://fonts.google.com/specimen/Rubik+Moonrocks" def install (share/"fonts").install "RubikMoonrocks-Regul...
require 'spec_helper' describe "conferences/edit" do before(:each) do @league = FactoryGirl.create(:league) @conference = assign(:conference, stub_model(Conference, :name => "MyString", :league_id => @league.id )) end it "renders the edit conference form" do render # Run the gen...
~~~console bundle exec rails g model sports name:string ~~~ ~~~console invoke active_record create db/migrate/20120815201524_create_sports.rb create app/models/sport.rb invoke rspec create spec/models/sport_spec.rb invoke factory_girl create spec/fac...
require 'spec_helper' require 'support/integrations_tools' RSpec.describe "Request a ggroup delete", type: :integration do let(:before_start_proc) {Proc.new{LogMessageHandler.listen_to 'reply.mailinglist.delete'}} let(:message) {GorgService::Message.new(event:'request.mailinglist.delete', ...
class AddCopiedMessageIdToMessages < ActiveRecord::Migration def change add_column :messages, :copied_message_id, :integer end end
module Dateable def difference_in_months(start_date, end_date) start_date, end_date = end_date, start_date if start_date > end_date no_of_months = (end_date.year - start_date.year) * 12 + end_date.month - start_date.month - one_day_if_needed(end_date, start_date) no_of_months + half_month(start_date, end...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
require 'submitorder' describe SubmitOrder do account_sid = 'private' auth_token = 'secret' let(:client) {double(:client)} let(:sendthing) {double(:sendthing)} subject {SubmitOrder.new sendthing, account_sid, auth_token} let(:order) {double(:order)} let(:total1) {10} from_mobile = '+44999999999' to_...
class TrialHasManySites < ActiveRecord::Migration def change add_reference :sites, :trial end end
class AddStatusToPurchases < ActiveRecord::Migration def up add_column :purchases, :status, :string add_column :ipn_logs, :ipn_string, :string end def down remove_column :purchases, :status remove_column :ipn_logs, :ipn_string end end
1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0 0 _ __ __ __ 1 1 /' \ __ /'__`\ /\ \__ /'__`\ 0 0 /\_, \ ___ /\_\/\_\ \ \ ___\ \ ,_\/\ \/\ \ _ ___ 1 1 \/_/\ \ /' _ `\ \/\ \/_/_...
class ParticipantstudysiteController < ApplicationController before_action :set_participantstudysite, only: [:show, :edit, :update, :destroy] # GET /participants # GET /participants.json def index @participants = Participant.all end # GET /participants/1 # GET /participants/1.json def show end ...
class UserQuery < ApplicationRecord # validations validates :name, :email, :description, presence: true validates :name, format: { with: /\A[a-zA-Z]+\z/, message: ":Only letters allowed." }, if: "name.present?" # RegEx below for Email might not be perfect validates :email, format: { with: /\A[\w+\-.]+@...
class FilterProfile < ActiveRecord::Base belongs_to :profile belongs_to :filter validates :profile_id, uniqueness: { scope: [:filter_id] } scope :approved, -> { where(is_approved: true) } end
require 'test_helper' class SiteLayoutTest < ActionDispatch::IntegrationTest test "layout links for guests" do get root_path assert_template 'store/index' assert_select "a[href=?]", root_path, count: 4 end end
require 'spec_helper' describe Event do before(:each) do @venue = FactoryGirl.create(:venue) @attr = { :name => 'Event!', :price => 20, :venue_id => @venue.id } end it "should create a new instance with valid attributes" do event = Event.create!(@attr) end it "should requi...
class AddRegistrationToConvocation < ActiveRecord::Migration[5.2] def change add_reference :convocations, :registration, foreign_key: true remove_reference :convocations, :user, foreign_key: true end end
require 'test_helper' class ItensFaturasControllerTest < ActionDispatch::IntegrationTest setup do @itens_fatura = itens_faturas(:one) end test "should get index" do get itens_faturas_url assert_response :success end test "should get new" do get new_itens_fatura_url assert_response :succ...
FactoryBot.define do factory :user do nickname { Faker::Name } email { Faker::Internet.free_email } password { '1a' + Faker::Internet.password(min_length: 6) } password_confirmation { password } last_name { '月面' } first_name { '伊五輪' } last_name_kana { 'アンポ' } first_name_kana { 'サハラカク' ...
## League Zones ## You should be able to define zones for a league's stats to describe ## things like promotion, relegation or qualification for tournaments class Leaguezone < ActiveRecord::Base include Auditable attr_accessible :league_id, :name, :description, :start_rank, :end_rank, :style belongs_to :league ...
template node['grafana']['conf_ini'] do source 'grafana.ini.erb' mode '600' owner node['grafana']['user'] group node['grafana']['group'] notifies :restart, 'service[grafana-server]', :delayed end template "#{node['grafana']['ldap_config_file']}" do source 'ldap.toml.sample.erb' owner node['grafana']['use...
ActiveAdmin.register Subcategory do permit_params :title end
# -*- mode: ruby -*- # vi: set ft=ruby :</ruby> # Vagrant è un DSL in Ruby: usa la sintassi del Ruby leggermante modificata VAGRANTFILE_API_VERSION = '2' Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Questa linea indica l'immagine di partenza da usare: ho scelto una Debian config.vm.box = 'puphpet/debia...
json.array!(@materials) do |material| json.extract! material, :id, :title, :point, :strategy, :cers, :promotion json.url material_url(material, format: :json) end
require "spec_helper" require "ostruct" module TephueMemoryRepo describe QuerySolver do let(:solver) { QuerySolver.new(:fake_query) } describe "#solve_condition" do let(:model) { {a: 1, b: 2} } conditions = %w( contains equals greater_than greater_than_or_equal_...
class RatingPeriod < ApplicationRecord belongs_to :tournament has_many :ratings, :dependent => :destroy validates_presence_of :tournament_id, :period_at validates_uniqueness_of :period_at, :scope => :tournament_id def previous_rating_period @previous_rating_period ||= tournament.rating_periods. w...
class DashboardsController < ApplicationController skip_after_action :verify_authorized, only: :show after_action :verify_policy_scoped, only: :show def show @categories = policy_scope(Category) # authorize :dashboard, :show? # @categories = Category.all #authorize @categories end end
module Events module Card class ChangedTitle < Base::Event attr_reader :id, :board_id, :title def initialize(id:, board_id:, title:) super(id:) @board_id = board_id @title = title end end end end
module Onebox module Engine class GooglePresentationOnebox include Engine include LayoutSupport include HTML matches_regexp(/^(?<reference>http(s)?:\/\/docs\.google\.com\/(\S)*presentation\/d\/(\S)*\/)(\S)*/) def to_html "<iframe src=\"#{reference}embed?start=false&loop=fal...
# frozen_string_literal: true require "dry/logic/predicates" RSpec.describe Dry::Logic::Predicates do it "can be included in another module" do mod = Module.new { include Dry::Logic::Predicates } expect(mod[:key?]).to be_a(Method) end describe ".predicate" do it "defines a predicate method" do ...
class AddPlayerIdToSubstituteAppearances < ActiveRecord::Migration[5.1] def change add_column :substitute_appearances, :player_id, :integer add_column :substitute_appearances, :match_id, :integer add_column :substitute_appearances, :opponent_team_id, :integer end end
#require "asciiart/version" # This was code from a gem I wanted to use but I couldn't get the gem to work so # I copied the code that I wanted from it. It converts images into ASCII art! #require 'rmagick' #require 'uri' #require 'open-uri' #require 'rainbow' #require 'rainbow/ext/string' class AsciiArt ...
class Site::PagesController < ApplicationController before_filter :init def init @root = Page.find_root @first_children = Page.first_children @links = ShortLink.published end def index @page = params[:code] ? Page.published(params[:code]) : @root render_page end def preview ...
require_relative '../lib/board' require 'pry' describe Board do let(:valid_board_string) { '1XXX2XXX3XXX4XXX' } it 'must be initialized with a string with N2xN2 length' do expect { Board.new('1XXX') }.to raise_error 'Invalid Board' expect { Board.new(valid_board_string) }.to_not raise_error end it 's...
# frozen_string_literal: true module Gauss # Gauss::Messages - save all the cmds for gauss module Commands REQUESTS = { reload: ['Load'], help: ['Help'], fetch_product: ['Give me'], inventory: ['What do you have?'], process_transaction: ['Take'] }.freeze end module Message...
module Locationable extend ActiveSupport::Concern included do belongs_to :city, optional: true def province city.try(:province) end def province_id city.try(:province_id) end end end
class Api::V1::CustomersController < ApplicationController before_action :set_customer, only: [:show, :update, :destroy] skip_before_action :verify_authenticity_token protect_from_forgery with: :null_session def index customers = Customer.return_customers( params[:order], params[:searchTerm], params[...
class CreateStudents < ActiveRecord::Migration[5.1] def change create_table :students do |t| t.string :name end end end # Define a method called change and use the Active Record # create_table method within that method to create the table. # The table should have a :name column with a type string.
require 'test_helper' class TailorsControllerTest < ActionController::TestCase setup do @tailor = tailors(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:tailors) end test "should get new" do get :new assert_response :success end ...
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "geerlingguy/ubuntu1604" config.ssh.insert_key = false config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.network :forwarded_port, guest: 54444, host: 45...
module Fog module DNS def self.[](provider) new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # prevent delete from having side effects case provider = attributes.delete(:provider).to_s.downcase.to_sym when :stormondemand require "fog/dns/...
json.buildings @buildings do |building| json.(building, :id, :name) json.classrooms building.classrooms do |classroom| json.(classroom, :id, :name) json.temperature classroom.try(:device).try(:temperature) json.options classroom.options do |option| json.(option, :id, :name) end end end
module Ambition module Adapters module ActiveRecord class Query @@select = 'SELECT * FROM %s %s' def kick owner.find(:all, to_hash) end def size owner.count(to_hash) end alias_method :length, :size def to_hash hash = {}...
require_relative "../test_helper" class CanCreateANewResturantTest < Capybara::Rails::TestCase test "can view restaurant registration page" do FactoryGirl.create(:user) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' with...
=begin In the previous exercise, you wrote a program to solicit a password. In this exercise, you should modify the program so it also requires a user name. The program should solicit both the user name and the password, then validate both, and issue a generic error message if one or both are incorrect; the error messa...
class User < ApplicationRecord has_secure_password has_secure_token :api_key validates_presence_of :email, :password_confirmation validates_uniqueness_of :email end
# == Schema Information # # Table name: services # # id :bigint(8) not null, primary key # how_to_use :string # id_unid_gestora :integer # main_link :string # more_info :string # responsible :string # service_type :string # status :string # title :...
class HomeController < ApplicationController def show @user = current_user end end
class Intersection < ActiveRecord::Base self.primary_key = :osm acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude has_and_belongs_to_many :streets has_many :empties def self.query_intersections(latitude, longitude) return Intersection.within(0.2, :origin =>...
class BcSchool < ActiveRecord::Base has_many :business_cards attr_accessible :name, :address, :city, :state, :zip, :default_phone, :default_fax end
class RemoveArtistIdFromGenresTable < ActiveRecord::Migration def change remove_column(:genres, :artist_id) end end
class Item < Asset include Assignable::Single include AssignToable multisearchable( against: [:name, :asset_tag, :serial], additional_attributes: ->(record) { { label: record.name } }, ) tracked resourcify validates_presence_of :model has_many :nics, dependent: :destroy has_many :ips, -> {...
require 'rails_helper' RSpec.describe TwitterClient do describe '#client' do let(:configured_client) { double('ConfiguredTwitterClient').as_null_object } let(:access_secret) { SecureRandom.uuid } before do allow(Twitter::REST::Client) .to receive(:new) .and_yield(configured_client)...
class AddVkColumnToPosts < ActiveRecord::Migration def change add_column :posts, :vk, :string end end
require_relative 'bucket' module VagrantPlugins module Cachier class Action class Install def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant::cachier::action::install") end def call(env) return @app.call(env) unless env[:machin...
#!/usr/bin/env ruby require 'curses' def hex_to_4rgb(hex) m = hex.match /#(..)(..)(..)/ [m[1].hex*4, m[2].hex*4, m[3].hex*4] end Pair = Struct.new(:fg_number, :bg_number) PairChange = Struct.new(:number, :old_pair, :new_pair) Colour = Struct.new(:number, :new_colour, :old_colour) # do # OFFSET = 17 # def pair...
class Admin::System < System validates :site_name, presence: true end
class Page < TopicMap::Topic TYPES = [:page, :association_type, :occurrence_type] unique_id :name key_reader :name key_accessor :content view_by :name view_by :content timestamps! def type=(type) self['type'] = TYPES.include?(type) ? type : :page end def type se...
Rails.application.routes.draw do root 'links#index' namespace :api, defaults: { format: :json } do namespace :v1 do resources :links end end scope controller: :users do post 'users/create' => :create, as: :new_user get 'users/sign_up' => :new, as: :sign_up end scope controller: :lin...
# frozen_string_literal: true module GraphQL module Introspection class DynamicFields < Introspection::BaseObject field :__typename, String, "The name of this type", null: false def __typename object.class.graphql_name end end end end
# == Informacion de la tabla # # Nombre de la tabla: *dbm_documentos_de_interes* # # idDocumentosInteres :integer(11) not null, primary key # titulo :string(255) default(""), not null # idDocumentos :integer(11) not null # # Se asocia un Documento con una entrada a documentos de inter...
# TODO: Refactor so as not to use CSS selectors module ET3 module Test class FormSubmissionPage < BasePage set_url '/respond/form_submission' element :submission_confirmation, :css, '.submission-confirmation' element :reference_number, :css, '.reference-number' element :submission_date,...
# LSchool OO TicTacToe Spike example require 'pry' class Board WINNING_SETS = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ].freeze def initialize @squares = {} reset end # rubocop:disable Metrics/AbcSize def draw puts " | |" ...
class FibonacciApp def call(env) @env = env if n <= 1 base_case else induction_step end end private # Fibonacci(0) => 0, Fibonacci(1) => 1 def base_case [200, { 'Content-Type' => 'text/plain' }, [n]] end def induction_step res = get_fibonacci(n-1) + get_fibonacci(n-2...
class GenerateTurn def self.run_first(game) player = get_next_player(game.id) Turn.create!(game_id: game.id, player_id: player.id, start_space_id: player.space_id) end def self.run(previous_turn) player = get_next_player(previous_turn.game_id, previous_turn.player_id) Turn.create!(game_id: previo...
class OrdersController < ApplicationController def create order = Order.new(order_params) if order.save render json: { order: order }, status: :created else render json: { errors: order.errors }, status: :unprocessable_entity end end def reference_status order = Order.find_by(refe...
class ProjectsListScreen < BaseClass element(:synchronize_button) { 'projectListContextMenuSynchronizeNow' } element(:favourite_icon) { 'projectListContextMenuFavouriteAdd' } element(:text_synchronize) { 'Will synchronize on next login.' } element(:info_synchronize) { 'projectItemSyncInfo' } value(...
class FindUsersController < ApplicationController before_action :set_find_user, only: [:show, :edit, :update, :destroy] before_filter :authenticate_user! # GET /find_users # GET /find_users.json def index @search_results = User.ransack(params[:f]) if !params[:f].nil? current_city = params[...
class ShopperAssignment < ActiveRecord::Base belongs_to :assignment_collection belongs_to :shopper has_many :store_assignments, dependent: :destroy has_many :order_assignments, dependent: :destroy def convert_to_json { shopper: shopper.username, store_assignments: store_assignments.collec...
class RenameFood < ActiveRecord::Migration def change rename_table :food, :foods end end
#Final resting place of the stories class ArssStory attr_accessor :title, :published_date, :text def full_title "#{published_date}: #{title}" end end
class Applicant < ActiveRecord::Base require 'set' require 'fileutils' serialize :subject_ids serialize :normal_subject_ids serialize :subject_amounts has_many :applicant_guardians, :dependent => :destroy has_one :applicant_previous_data, :dependent => :destroy has_many :applicant_addl_values, :depe...
module Charts class UnassignedTask prepend SimpleCommand def initialize(current_user, args = {}) @user = current_user @args = args @facility_id = @args[:facility_id].split(',').map(&:to_bson_id) @limit = args[:limit] end def call start_date = Time.current.beginning_of_m...
class CarrersController < ApplicationController before_action :set_carrer, only: [:show, :edit, :update, :destroy] # GET /carrers # GET /carrers.json def index @carrers = Carrer.all end # GET /carrers/1 # GET /carrers/1.json def show end # GET /carrers/new def new @carrer = Carrer.new ...
class CreatePotentialPartners < ActiveRecord::Migration def change create_table :potential_partners do |t| t.string :studio_name t.string :person_to_contact t.string :contact_number t.string :email t.string :web_address t.text :how_did_you_hear_partner t.timestamps e...
class AddQuerSpotPlaceToQuerySpots < ActiveRecord::Migration[5.2] def change add_column :query_spots, :quer_spot_place, :string end end
class ResponsibleBody::Devices::SchoolsController < ResponsibleBody::BaseController before_action :load_schools_by_order_status, only: %i[show index] def index @show_devices_ordered_column = lacks_virtual_cap? end def show @school = @responsible_body.schools.where_urn_or_ukprn_or_provision_urn(params[...
class CompanyController < ApplicationController include SetLayout before_action :find_organization before_action :check_iframe around_action :company_time_zone layout :company def prepare_calendar_options @start = Time.parse(params[:start]) if params[:start] @end = Time.parse(params[:end]) if param...
require 'twitter' require 'twitter_oauth' require 'json' require 'time' require_relative 'oauth' def my_followers $client.followers(include_user_entities: true) end @force_unfo_list = [] def force_unfo(user, reason) puts "#{user.uri} #{reason}" @force_unfo_list << [user, reason] end KEYWORDS_BLACKLIST = File....
require 'spec_helper' require 'gnawrnip/screenshot' module Gnawrnip describe Screenshot do context 'Not support save_screenshot' do describe '.tale' do before do allow_any_instance_of(GnawrnipTest::Session).to receive(:save_screenshot) do raise Capybara::NotSupportedByDriverEr...
module ControllerMacros def login_user(user=nil) let(:current_user) { user || create(:user) } before :each do session[:user_id] = current_user.id end end def login_student let(:current_user) { create(:student) } before :each do session[:user_id] = current_user.id end end ...