text
stringlengths
10
2.61M
class Passenger attr_reader :name @@all = [] def initialize (name) @name = name @@all << self unless @@all.any?(self) end def drivers rides.all.map {|ride| ride.driver } end def rides Ride.all.select {|ride| ride.passenger == self} end def total_d...
require 'logger' require 'open3' require 'erb' module Dotpkgbuilder class Stage attr_reader :context, :log delegate :working_dir, to: :context def initialize(context, options = {}) @context = context @log = options[:log] || Logger.new(STDOUT) end def run; end protected ...
#!/usr/bin/ruby require 'optparse' require 'json' def cmd_line() options = {} optparse = OptionParser.new do |opts| opts.banner = "Usage: #{opts.program_name}" opts.on("-s","--session [STRING]","session name") do |s| options[:session] = s end opts.on("-l","--host_list [STRING]","path to h...
#encoding: UTF-8 require 'mongoid' require 'rubygems' require 'nokogiri' require 'open-uri' require 'pp' require_relative "common" Dir.glob("#{File.dirname(__FILE__)}/app/models/*.rb") do |lib| require lib end ENV['MONGOID_ENV'] = 'local' Mongoid.load!("config/mongoid.yml") class GetCarAndDetail i...
class Smpp::Transceiver < Smpp::Base # Expects a config hash, # a proc to invoke for incoming (MO) messages, # a proc to invoke for delivery reports, # and optionally a hash-like storage for pending delivery reports. def initialize(config, mo_proc, dr_proc, pdr_storage={}) super(config) @state = :un...
# BackgrounDRb Worker to reprocess assets. class ProcessorReprocessWorker < BackgrounDRb::Rails # Reprocess and attactment - and sets it's backgroundrb_job_key to nil when it's done. # Expects args to be a hash - with values for the :class and :id of the Model Object to reprocess. # def do_work(args) # asset_cl...
class AddConsumerToExternals < ActiveRecord::Migration def change add_column :externals, :consumer_id, :integer add_column :externals, :consumer_type, :string end end
require 'rails_helper' RSpec.describe AppsController, type: :controller do let(:user) { create(:user) } before(:each) { login(user) } describe "GET #index" do it "returns a success response" do create(:app, user: user) get :index expect(response).to be_successful end end describe...
class Asset < ActiveRecord::Base belongs_to :uploadable, polymorphic: true acts_as_list scope :ordered, -> { order(:position) } class << self def permitted_params [ :id, :attachment, :uploadable_type, :uploadable_id, :description, :position, :_destroy ] end end def scope_condition "...
require 'tadb' require_relative '../src/PersistentAttribute' module Persistible def self.table(table_name) TADB::Table.new(table_name) end module ClassMethods def all_instances classes_to_instance = descendants.clone << self classes_to_instance.map do |klass| Persistible.table(klas...
module AutoPublishedAt extend ActiveSupport::Concern included do before_validation :set_published_at_to_now, :if => -> { self.published? && self.published_at.blank? } before_validation :set_published_at_to_nil, :if => -> { !self.published? && self.published_at.present? ...
class CaipinsController < ApplicationController before_action :set_admincaipin, only: [:show, :edit, :update, :destroy] def index @caipins = Caipin.all @caipinclas = Caipincla.all end def show end # GET /tests/new def new @admincaipin = Caipin.new end # GET /tests/1/edit def edi...
# # Cookbook Name:: postgresql # Provider:: conf # # Copyright 2012 Damien DUPORTAL <damien.duportal@gmail.com> # https://github.com/dduportal/dadou-chef-recipes # # This provider implements the postgresql_conf resource # # => Inspired by the chef comunity postgresql cookbook : https://github.com/opscode-cookbooks/post...
class PayGradeRate < ApplicationRecord belongs_to :pay_grade before_destroy :is_destroyable validates_numericality_of :rate, :greater_than =>0 scope :current, -> { where('end_date IS NULL') } scope :chronological, -> { order('start_date') } scope :for_date, ->(date) { where("start_date <...
#!/usr/bin/env ruby # Here we have another similar code # Except the customer's age # is hanlded with a case puts "Enter the customer's age: " age = gets.to_i case when (age <= 12) cost = 9 when (age >= 65) cost = 12 else cost = 18 end puts "Ticket cost: " + cost.to_s
require 'resolv' class DomainsController < ApplicationController def index domains = Domain.all if (hostname = params[:hostname]) domains = domains.where hostname: hostname end if (ip_address = params[:ip_address]) domains = domains.where ip_address: ip_address end if (account_id ...
class Report include ActionView::Helpers::NumberHelper # Required dependency for ActiveModel::Errors extend ActiveModel::Naming extend ActiveModel::Translation attr_reader :errors def initialize(params) @params = params @errors = ActiveModel::Errors.new(self) end def valid? self.class::V...
class Favorite < ActiveRecord::Base belongs_to :profile belongs_to :favable, polymorphic: true belongs_to :favorite_folder has_many :tidbits, as: :targetable, dependent: :destroy validates :profile_id, :favable_id, :favable_type, presence: true validates :favable_id, uniqueness: { scope: [:profile_id, :fa...
Rails.application.routes.draw do resources :home, only: :index root 'home#index' get '/auth/:provider/callback', to: 'sessions#create' get '/logout', to: 'sessions#destroy' end
require_relative 'lib/page_desc' module Button extend PageDesc::Action also_extend PageDesc::Types::Clickable action :on_click do puts browser_element[:onclick] end end class More < PageDesc::Section selector css: '#more-less-button' before :on_click do puts 'before CALLED' end after :on_c...
require "test_helper" require "database/setup" require "mini_magick" class ActiveStorage::Previewer::OfficePreviewerTest < ActiveSupport::TestCase test "previewing a Word document" do blob = create_file_blob \ filename: "hello.docx", content_type: "application/vnd.openxmlformats-officedocument.wordp...
class CreateWireStories < ActiveRecord::Migration[5.1] def change create_table :wire_stories do |t| t.date :send_date t.string :content_id t.string :category_code t.string :category_name t.string :region_code t.string :region_name t.string :credit t.string :source ...
require "rails_helper" RSpec.describe HomeController do describe "index" do it "renders the home page" do get :index expect(response).to be_success end end end
class AddOneTicketPerPieceToVendorPrinters < ActiveRecord::Migration def change add_column :vendor_printers, :one_ticket_per_piece, :boolean end end
Rails.application.routes.draw do root 'welcome#index' resources :articles do resources :comments#This creates comments as a nested resource within articles. end end
# frozen_string_literal: true module Api::V1::SC::Billing::Stripe class SubscriptionSerializer < Api::V1::BaseSerializer type 'subscriptions' attributes :id, :current_period_start_at, :current_period_end_at, :trial_start_at, :trial_end_at, ...
class Experience < ApplicationRecord has_many :tag_experiences has_many :tags, through: :tag_experiences has_many :list_items end
require 'active_record' require 'cxbrank/master/base' require 'cxbrank/master/music' module CxbRank module Master class Monthly < Base belongs_to :music def self.last_modified return self.maximum(:updated_at) end def self.get_csv_columns return [ {:name => :tex...
class User < ActiveRecord::Base attr_accessible :name has_many :user_candies has_many :candies, :through => :user_candies def primary_candy Candy.primary_for(self).first end end
# encoding: utf-8 $: << 'RspecTests/url' require 'generated/url' include UrlModule describe Paths do before(:all) do @base_url = ENV['StubServerURI'] dummyToken = 'dummy12321343423' @credentials = MsRest::TokenCredentials.new(dummyToken) client = AutoRestUrlTestService.new(@creden...
require 'redcarpet' require 'pygments.rb' class LazyDownRender < Redcarpet::Render::XHTML def doc_header() github_css = File.join File.dirname(__FILE__), 'github.css' '<style>' + File.read(github_css) + '</style><article class="markdown-body">' end def doc_footer '</article>' end def...
# frozen_string_literal: true # require_relative 'cargo_train' # require_relative 'passenger_train' require_relative 'manufacturer' require_relative 'instance_counter' require_relative 'validator' class Train include Manufacturer include InstanceCounter include Validation NUM = /^\w{3}-?\w{2}$/i attr_read...
class TypeContractsController < ApplicationController before_action :set_type_contract, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] # GET /type_contracts # GET /type_contracts.json def index @type_contracts = TypeContract.all end # GET /type_con...
# frozen_string_literal: true module FileReaderTest module Read def test_read_without_internal_encoding file = file_containing("kākāpō", external_encoding: "UTF-8", internal_encoding: nil) assert_equal "kākāpō", file.read end def test_read_with_internal_encoding file = file_containing...
class Api::V1::SearchesController < ApplicationController include SortAndFilterHelper api :GET, '/v1/searches' param :order, String, required: false, desc: "provide 'asc' or 'desc' to sort by date" param :filter, String, required: false, desc: "provide 'alpha-asc' or alpha-desc' to sort alphabetically" def i...
class AddUnreadNotificationToUserProfile < ActiveRecord::Migration[5.0] def self.up add_column :user_profiles, :num_unread_notification, :integer add_column :user_profiles, :unread_notifications, :text end def self.down remove_column :user_profiles, :num_unread_notification, :integer remove_colum...
FactoryGirl.define do factory :bs_elawa_segment, class: 'Bs::Elawa::Segment' do name "MyString" start_date "2016-04-18 01:30:41" end_date "2016-04-18 01:30:41" event_id 1 end end
module Types class QueryType < Types::BaseObject # Add root-level fields here. # They will be entry points for queries on your schema. field :all_users, [UserType], null: true field :me, UserType, null: true field :all_venues, [VenueType], null:true do argument :id, Integer, required: false...
# frozen_string_literal: true # Advent of Code 2020 # # Robert Haines # # Public Domain require 'test_helper' require 'aoc2020/ticket_translation' class AOC2020::TicketTranslationTest < MiniTest::Test INPUT = <<~EOINPUT class: 1-3 or 5-7 row: 6-11 or 33-44 seat: 13-40 or 45-50 your ticket: 7,1...
require 'rails_helper' describe User do it { should have_many(:characters) } end
# frozen_string_literal: true module Decidim module Opinions module Admin # A form object to be used when admin users wants to merge two or more # opinions into a new one to another opinion component in the same space. class OpinionsMergeForm < OpinionsForkForm validates :opinions, leng...
class UsersController < ApplicationController before_filter :require_staff, except: [ :create, :login, :logout ] def create user = User.create( first_name: params[:first_name], last_name: params[:last_name], email: params[:email] ) if user render text: "Thanks #{user.first_name...
class CreateRecordsTable < ActiveRecord::Migration[6.0] def change create_table :records do |t| t.integer :character_id t.integer :item_id t.boolean :item_used? t.integer :escape_id end end end
template "/etc/default/varnish" do mode '0755' owner 'root' # group deploy[:group] source "varnish.erb" # variables(:deploy => deploy, :application => application) end # service "varnish" do # action :restart # end
class CreateMaps < ActiveRecord::Migration[6.0] def change create_table :maps do |t| t.string :name t.string :type t.integer :price t.string :closing_day t.time :open_time t.text :website t.text :photo1 t.text :photo2 t.text :photo3 t.boolean :beji ...
require('spec_helper') describe('path through the stores pages', {:type => :feature}) do it('shows message when no stores are in database') do visit('/') click_link('Stores') expect(page).to have_content("There are no stores in the database. Add a store now.") end it('allows user to add a store to d...
require 'rails_helper' RSpec.describe Cognito::SignInUser do describe '#call' do let(:email) { 'user@email.com' } let(:password) { 'ValidPass123!' } let(:challenge_name) { 'Challenge name' } let(:session) { 'Session' } let(:user_id_for_srp) { 'User id' } let(:cookies_disabled) { false } ...
class AddEnvironmentToServers < ActiveRecord::Migration def change add_column :servers, :environment_id, :int end end
json.array!(@vehicles) do |vehicle| json.extract! vehicle, :id, :marca, :modelo, :ano, :color, :npass, :tipo, :driver_id json.url vehicle_url(vehicle, format: :json) end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, :only => [:create] protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:enrollment_number, :full_name ,:contact_number , :branch, :semester ,:password_...
require 'gosu' require_relative 'level' require_relative 'player' class Game LEVEL1 = [ "+------------------+", "|S.|....T..........|", "|..|.--------..|++.|", "|..|.|....|T|..|T..|", "|.+|.|.E|.|....|...|", "|..|.|---.|.|--|...|", "|..|.|....|.|......|", "|+.|.|......|.....
class FirstAssociatesReport < ActiveRecord::Base belongs_to :admin has_many :first_associates_transactions end
class AddColumnsForEquipmentToExercise < ActiveRecord::Migration[5.2] def change add_column :exercises, :common_exercise_id, :integer, null: false add_column :exercises, :common_equipment_id, :integer, null: false end end
class QuotationPolicy < ApplicationPolicy class Scope < Scope def resolve_for_commissioner if user.present? scope.where("quotations.commissioner_id = ? OR quotations.public_for_commissioner = ?", user.id, true) else scope.where("quotations.public_for_commissioner = ?", true) end ...
require 'rails_helper' RSpec.describe "/shelters", type: :feature do it "allows user to see all shelter names" do shelter1 = Shelter.create(name: 'FuzzTime', address: "895 Fuzz St.", city: "Westminster", state: "CO", ...
# # hermeneutics/mail.rb -- A mail # require "hermeneutics/message" module Hermeneutics class Mail < Message # :stopdoc: class FromReader class <<self def open file i = new file yield i end private :new end attr_reader :from def initia...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure('2') do |config| config.vm.box = 'precise32' config.vm.box_url = 'http://boxes.cogini.com/precise32.box' config.vm.network :forwarded_port, guest: 80, host: 9020 config.vm.network :forwarded_port, guest: 22, host: 9021, id: "ssh", auto_correc...
class ReorderPythonImports < Formula include Language::Python::Virtualenv desc "Rewrites source to reorder python imports" homepage "https://github.com/asottile/reorder_python_imports" url "https://github.com/asottile/reorder_python_imports/archive/v2.3.6.tar.gz" sha256 "33df7db05db1557c743ddb3fe24cbf2d5d29b...
class CreateRemixes < ActiveRecord::Migration def change create_table :remixes do |t| t.string :name t.string :download_url t.references :circle t.references :stem t.references :remixer t.timestamps end end end
require 'rails_helper' RSpec.describe "EmailProcessor", :type => :request do describe "with a valid email posted to EmailProcessor" do let(:email) { fake_sendgrid_params("This is a test") } describe "when there is a matching user in the database" do let!(:user) { FactoryGirl.create(:user, mtname:'g...
class TripsController < ApplicationController before_action :logged_in_admin, only: :new before_action :admin_user, only: [:create, :destroy] def index @trips = Trip.paginate(page: params[:page]) end def show @trip = Trip.find(params[:id]) end def new @trip = Trip.new end def create ...
# frozen_string_literal: true require "rails_helper" RSpec.describe HomeworksController, type: :routing do before do user = FactoryBot.create(:user) sign_in user end describe "routing" do it "routes to #edit" do expect(get: "/subjects/1/courses/1/homeworks/1/edit").to route_to("homeworks#edit...
require "rails_helper" RSpec.describe Queries::ContestantType do subject { Queries::ContestantType } context "fields" do let(:fields) { %w(id model_id first_name last_name residence description points pool eliminated scores) } it "has the proper fields" do expect(subject.fields.keys).to match_array...
class Role include DataMapper::Resource property :id, Serial property :instrument, String property :player, String def fill(person) return if person.empty? self.player = person self.save end def found 'found' if self.player end def to_hash Hash[self.instrument, self.player] e...
require 'test/test_helper' require 'flog' describe 'flog command' do before :each do @flog = stub('Flog', :flog_files => true, :report => true, :exit => nil, :puts => nil) # Flog.stubs(:new).returns(@flog) end def run_command # HACK...
# -*- coding: utf-8 -*- =begin Faça um programa de forma que se possa trabalhar com vários comandos digitados de uma só vez. Atualmente, apenas um comando pode ser inserido por vez. Altere-o de forma a considerar operação como uma string. Exemplo: FFFAAAS significaria três novos clientes, três novos atendimentos e, f...
# Create a new list # define an empty hash # def list # # grocery_list={} # {} # end list = {} my_list = {} your_list = {} # Add an item with a quantity to the list # input: three items, hash list, one for name of item, one for quantity, # body: add items to hash # output: return hash def add_item(...
#encoding:utf-8 class ApplicationController < ActionController::Base include SessionsHelper protect_from_forgery with: :exception helper_method :signed_in?, :current_user before_action :set_locale private def set_locale # 可以將 ["en", "zh-TW"] 設定為 VALID_LANG 放到 config/environment.rb 中 if params[:l...
FactoryBot.define do factory :position, class: IGMarkets::Position do contract_size 1000.0 controlled_risk false created_date '2015/08/17 10:27:28:000' created_date_utc '2015-07-24T09:12:37' currency 'USD' deal_id 'DEAL' deal_reference 'reference' direction 'BUY' level 100.0 li...
require 'spec_helper' require_relative '../../models/site' require_relative '../../models/user' require_relative '../../mappers/site_mapper' describe SiteMapper do describe "persist" do let(:db) {Database.new} let(:mapper) {SiteMapper.new(db)} let(:user) {User.new("test@test.com", "testpassword", ...
class CreateHeadlineWidget < ::RailsConnector::Migration def up create_obj_class( name: 'HeadlineWidget', type: 'publication', title: 'Headline widget', attributes: [ {:name=>"headline", :type=>:string, :title=>"Headline"}, ], preset_attributes: {}, mandatory_attr...
class ChangeColumns < ActiveRecord::Migration[5.2] def change change_column :sections, :departments_id, :text change_column :sections, :teachers_id, :text change_column :students, :section_id, :text change_column :subjects, :department_id, :text end end
require_dependency 'juridical/application_controller' module Juridical class DefendantsController < ApplicationController # :nodoc: before_action :set_legal_advice def new @defendant = ActiveCodhab::Juridical::ManagerDefendant::DefendantForm.new end def create @defendant = ActiveCodhab:...
module Resourceful module CanCanMethods extend ActiveSupport::Concern included do alias_method_chain :can_create?, :cancan alias_method_chain :can_update?, :cancan alias_method_chain :can_show?, :cancan alias_method_chain :can_destroy?, :cancan end def can_create_wi...
class Statement < ApplicationRecord belongs_to :topic before_create :randomize_id private def randomize_id begin self.id = SecureRandom.random_number(1_000_000) end while Statement.where(id: self.id).exists? end end
class Review < ActiveRecord::Base attr_accessible :why_livingsocial, :why_hungry, :candidate_id, :reviewer_id, :status, :recommendation belongs_to :candidate belongs_to :reviewer belongs_to :milestone RATINGS = %w( recommendation ) def completed? !why_livingsocial.blank? && !why_hungry.blank? end ...
class Api::V1::ProductsController < ApplicationController def index @products = Product.all render json: @products end def create @product = Product.create(Product_params) params['pieces'].each do |piece| Product_content.create(piece_id: piece['piece_id'], product_id: @product['id']) ...
class CreateServices < ActiveRecord::Migration[5.0] def change create_table :services do |t| t.string :name t.references :user, foreign_key: true t.references :category, foreign_key: true t.references :district, foreign_key: true t.text :description t.string :permalink t....
class AddProjecttypeToProject < ActiveRecord::Migration[5.1] def change add_column :projects, :projecttype, :string end end
def save_scores(paper,day) @day = Date.parse(day) mixed_score = Story.on_date(@day).where(source:paper).map(&:mixed).get_average.round(2) if mixed_score.nan? || mixed_score.nil? p "Score on #{day} not valid" return else @sc = Score.on_date(@day).where(source: paper).first_or_create! do |sc| #ensures only one...
require 'redmine' Redmine::Plugin.register :redmine_remaining_time do name 'Redmine Remaining Time plugin' author 'Kazuyuki Ohgushi' description 'This is a plugin for managing remaining time' version '0.0.1' url 'https://github.com/kzgs/redmine_remaining_time' author_url 'https://github.com/kzgs' end requ...
class Acronym class << self def abbreviate(word) word.scan(/(\w)\w*/).join.upcase end end end
#!/usr/bin/env ruby # ner0 https://www.github.com/real-ner0 # knock4 : Implementation of ping (ICMP) for IPv4 Server # I'm still working for pinging IPv6 Servers # Check for arguments if ARGV.empty? puts "Usage: knock <host_name>" puts "host_name could be hostname or host addrress" exit end # Load the librari...
class UserPassedTestsController < ApplicationController before_action :find_user_passed_test, only: %i[show update result gist] def show; end def result; end def update @user_passed_test.accept!(params[:answer_ids]) if @user_passed_test.completed? awards = BadgeRuleService.new(@user_passed_tes...
require 'thor' require 'food' require 'food/generators/recipe' module Food class CLI < Thor desc "portray ITEM", "Determines if a piece of food is gross or delicious" def portray(name) puts Food.portray(name) end desc "pluralize", "Pluralizes a word" method_option :word, aliases: "-w" def pluralize ...
class PaypalIpn < ActiveRecord::Base attr_accessible :data, :txn_id, :state, :subscr_id, :txn_type, :subscription, :subscription_id, :custom, :payment_status, :receiver_email belongs_to :user OK = 'ok' NOT_UNIQUE = 'not_unique' NOT_COMPLETED = 'not_completed' WRONG_SELLER = 'wrong_seller' USER_NOT_FOUND...
class AddBuzzSumoFieldtoUrls < ActiveRecord::Migration[5.1] def change add_column :urls, :buzzsumo, :integer end end
require 'spec_helper' describe Landlord do context 'phone format' do it 'converts phone number to only numbers and no special characters' do landlord1 = FactoryGirl.create(:landlord, phone: '(310)-123/4561') expect(landlord1.phone).to eql('3101234561') end it 'returns invalid if phone lengt...
class RecipeIngredient < ActiveRecord::Base has_many :ingredients has_many :recipes end
class MenuSolver attr_reader :price, :menu, :orders def initialize(price, menu) @price = price @menu = menu @orders = [] end def possible_orders find_orders orders.empty? ? "No solutions found" : orders end def find_orders(money=price, order=[], start_index=0) menu.each_with_in...
CarrierWave.configure do |config| if ENV['AWS_BUCKET'] and !Rails.env.test? config.storage = :aws config.aws_bucket = ENV.fetch('AWS_BUCKET') config.aws_acl = 'private' # Optionally define an asset host for configurations that are fronted by a config.asset_host = "https://s3-#{ENV.fetch('A...
# Plugin's routes # See: http://guides.rubyonrails.org/routing.html #get 'global_roadmap', :to => 'global_roadmap#index' get '/projects/:project_id/global_roadmap' , :to => "global_roadmap#index", :as => :global_roadmap
include_recipe 'chef-openstack::common' prereq_packages = %w[openvswitch-datapath-dkms] common_packages = %w[openvswitch-switch neutron-plugin-openvswitch-agent neutron-lbaas-agent haproxy] network_services = %w[openvswitch-switch neu...
# encoding: UTF-8 control "local-file-check" do title "Compliance check for local file." desc " Check local file for contents. " impact 0.5 describe file("/home/ec2-user/chef.txt") do its("content") { should match("Chef is good.") } end end
class User < ActiveRecord::Base has_secure_password has_many :tweets def self.is_logged_in?(session) !!session[:user_id] end def self.current_user(session) user = User.find_by_id(session[:user_id]) user end def slug slug = self.username.split(" ").join("-") end def self.find_by_sl...
class PreviewsController < ApplicationController # GET /previews # GET /previews.json def index @previews = Preview.all respond_to do |format| format.html # index.html.erb format.json { render json: @previews } end end # GET /previews/1 # GET /previews/1.json def show @previe...
Avocado::Engine.routes.draw do root to: 'specs#index' resources :specs, only: [:create] end
# The Google Maps Results representing class class Gmresult include DataMapper::Resource property :id, Serial property :email, String, required: true, length: 255 property :formatted_address, Text, required: true property :place_id, Text, required: true property :created_...
class BikesController < ApplicationController before_action :authenticate_user!, :except => [:index] before_action :set_bike, :only => [ :show, :edit, :update, :destroy] def index @bikes = Bike.all @bikes = Bike.page(params[:page]).per(5) end def new @bike = Bike.new end def create @b...
class Restaurant @@filepath = nil def self.filepath=(path=nil) @@filepath = File.join(APP_ROOT, path) end #checks if restaurant file exists def self.file_exists? #class should know if the restaurant file file_exists if @@filepath && File.exists?(@@filepath) return true else return false end end...