text
stringlengths
10
2.61M
require File.dirname(__FILE__) + '/spec_helper' def get_month(val) months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months[val - 1] end def get_options(from_val,to_val, hash = {}) options = "" range = (from_val..to_val) if ha...
Rails.application.routes.draw do root 'pages#index' #resources :pages get 'property', to: 'pages#show' get 'property_card', to: 'pages#property_card' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
module Garrison class AwsHelper def self.whoami @whoami ||= Aws::STS::Client.new(region: 'us-east-1').get_caller_identity.account end def self.all_regions Aws::Partitions.partition('aws').service('SQS').regions end def self.list_sqs_queues(region, attributes) if ENV['AWS_ASSUM...
class AddPlanetIdToReplies < ActiveRecord::Migration[5.2] def change add_column :replies, :planet_id, :integer end end
class Achievement < ActiveRecord::Base belongs_to :user belongs_to :achievement_category belongs_to :achievement_result has_many :groups, through: :user has_and_belongs_to_many :attachments, dependent: :destroy validates :event_name, :achievement_category_id, :achievement_result_id, :event_date, presence...
require 'adcenter_wrapper_entities' require 'soap/mapping' module AdCenterWrapper module SecureDataManagementServiceMappingRegistry EncodedRegistry = ::SOAP::Mapping::EncodedRegistry.new LiteralRegistry = ::SOAP::Mapping::LiteralRegistry.new NsAdapiMicrosoftCom = "https://adapi.microsoft.com" NsC_Exception = ...
# courtesy of abhishekkr # https://gist.github.com/abhishekkr/3610174#file-term_color-rb # get colored terminal output using these String methods class String def colortxt(txt, term_color_code) "\e[#{term_color_code}m#{txt}\e[0m" end def bold; colortxt(self, 1); end def thin; ...
# Encoding: utf-8 require_relative '../CartoCSSHelper/lib/cartocss_helper' require_relative '../CartoCSSHelper/lib/cartocss_helper/configuration' require_relative '../CartoCSSHelper/lib/cartocss_helper/visualise_changes_image_generation' require_relative '../CartoCSSHelper/lib/cartocss_helper/util/filehelper' require_r...
require "test_helper" describe OrderItemsController do let (:product1) { products(:cake1) } let (:product2) { products(:cake3) } let (:order_item_hash1) { { order_item: { product_id: product1.id, qty: 5 } } } let (:order_item_hash2) { { order_item: { p...
json.array!(@sites) do |sites| json.extract! sites, :id, :name, :url, :rss_url end
# -*- encoding : utf-8 -*- module Retailigence #:nodoc: # Raised when Retailigence doesn't find any results class NoResults < StandardError; end # Raised when any other exception occurs from the API class APIException < StandardError; end end
class CreateQuestions < ActiveRecord::Migration def up create_table :questions do |t| t.references :control, :null => false t.string :name t.string :description t.integer :answer_id t.timestamps end add_foreign_key :questions, :controls end def down drop_table :quest...
class UpNickLimit < ActiveRecord::Migration def change change_column :users, :Nick, :text end end
class CreateActions < ActiveRecord::Migration def change create_table(:actions) do |t| t.string :parent_type t.integer :parent_id t.string :name t.string :link t.string :target t.text :requirements t.text :outcomes end end end
require 'rails_helper' RSpec.describe VotesController, type: :controller do describe '#create' do let(:voteable) { FactoryBot.create(:article) } let(:user) { FactoryBot.create(:user) } let(:params) do { voteable_id: voteable.id, voteable_type: voteable.class.to_s } end ...
# == Schema Information # # Table name: users # # id :bigint not null, primary key # user_name :string not null # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime ...
class Longtask < Simpletask validates :porcentaje, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 100, message: "debe ser entre 0 y 100" } end
require 'yaml' module SidekiqRunner class SidekiqConfiguration include Enumerable RUNNER_ATTRIBUTES = [:config_file] RUNNER_ATTRIBUTES.each { |att| attr_accessor att } attr_reader :sidekiqs def initialize @config_file = if defined?(Rails) File.join(Rails.root, 'config',...
class JobsController < ApplicationController def index @q = JobPosting.current_jobs.ransack(params[:q]) @jobs = @q.result(distinct: true) end def show @job = JobPosting.find(params[:id]) end def create @job = JobPosting.new(job_params) if @job.save redirect_to job_path(@job), noti...
class WeatherDependency include Mongoid::Document store_in client: 'labels' field :clear_sky, type: Boolean, default: false field :dew_point, type: Boolean, default: false field :humidity, type: Boolean, default: false field :precipitation, type: Boolean, default: false field :pressure, type: Boolean, de...
# frozen_string_literal: true require "English" require "net/http" unless LightStep::VERSION == '0.10.9' raise <<-MSG This monkey patch needs to be reviewed for LightStep versions other than 0.10.9. To review, diff the changes between the `LightStep::Transport::HTTPJSON#report` method and the `HubStep::...
require 'rspec' require_relative '../../src/stm' require_relative 'concurrently' require_relative 'real_bank_account' describe 'Testing BankAccount operations' do def expect_balance(account_sym, expected_balance) balance_msg = Proc.new do |account_sym, expected| "El balance de #{account_sym} es #{instance_...
class CreatePhase5 < ActiveRecord::Migration def change create_table :phase5s do |t| t.string :mobile_responsive t.string :mobile_contact_info t.string :mobile_phone_number t.string :mobile_directions t.string :mobile_font_size t.string :mobile_buttons t.strin...
require "spec_helper" class MyLogger; end class MyDbConnection; def exec; end; end class MyQueue; end describe PgQueue do before do described_class.connection = MyDbConnection.new described_class.logger = Logger.new("/dev/null") end context "logging" do before do described_class.logger = nil ...
class Event < ApplicationRecord include ActiveModel::Validations has_many :users_events, dependent: :destroy has_many :users, through: :users_events # @event.users validates_presence_of :title, :category, :address, :city, :state, :zip, :time, :about_content validates :zip, length...
class CreateBills < ActiveRecord::Migration def change create_table :bills do |t| t.column :name, :string, :null => false t.column :description, :string t.column :user_id, :integer, :foreign_key => true #ou então t.reference :users, :foreign_key => true t.column :date, :datetime, :null => fals...
require "rails_helper" describe Team do let(:attributes) do { name: "lakeshow", city: "LA", mascot: "Lake" } end # # # it "is considered valid" do # # expect(Team.new(attributes)).to be_valid # # end let(:missing_name) { attributes.except(:name) } let(:missing_city) { attributes...
Pod::Spec.new do |s| s.name = "SSKeychain" s.summary = "SSKeychain is a simple wrapper for using the system Keychain on Mac OS X and iOS." s.version = "1.2.2" s.license = 'MIT' s.homepage = 'https://github.com/soffes/sskeychain' s.author = { 'Sam Soffes' =>...
require File.dirname(__FILE__) + "/spec_helper" describe Sequel::Schema::DbColumn do before :each do @column = Sequel::Schema::DbColumn.new(:foo, :integer, false, 10, true, 10, nil) end it "should return a #define_statement" do expect(@column.define_statement).to eql("integer :foo, :null => false, :def...
require "strscan" class QueryTokenizer def tokenize(str) tokens = [] @warnings = [] s = StringScanner.new(str) until s.eos? if s.scan(/[\s,]+/i) # pass elsif s.scan(/and\b/i) # and is default, skip it elsif s.scan(/or\b/i) tokens << [:or] elsif s.scan(%...
$LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'jekyll-haml-markup' require 'minitest/autorun' def root_dir(*subdirs) File.expand_path(File.join('..', *subdirs), __dir__) end def test_dir(*subdirs) root_dir('test', *subdirs) end def source_dir(*subdirs) test_dir('fixtures', *subdirs) end def ...
module Rockauth module Controllers::UnsafeParameters class UnsafeParametersError < ActionController::BadRequest; end extend ActiveSupport::Concern included do before_filter :reject_unsafe_parameters! rescue_from UnsafeParametersError do render_error 400, I18n.t("rockauth.errors.unsa...
json.array!(@finance_plans) do |finance_plan| json.extract! finance_plan, :id, :description json.url finance_plan_url(finance_plan, format: :json) end
module SportsDataApi module Mlb class Players include Enumerable ## # Initialize by passing the raw XML returned from the API def initialize(xml) @players = [] xml = xml.first if xml.is_a? Nokogiri::XML::NodeSet if xml.is_a? Nokogiri::XML::Element xml.xpa...
class HarmonicOscilatorParticle attr_accessor :r, :v, :f, :m, :a, :r1, :r2, :r3, :r4, :r5 M = 70.0 K = 10000.0 GAMMA = 100.0 R_D = 1 V_D = - GAMMA / M / 2 def initialize(r = R_D, v = V_D) @r = r @v = v @m = M @f = - (K * r + GAMMA * v) @a = @f / @m init_r end def init_r ...
require "spec_helper" describe ParentsController do describe "routing" do it "routes to #index" do get("/parents").should route_to("parents#index") end it "routes to #new" do get("/parents/new").should route_to("parents#new") end it "routes to #show" do get("/parents/1").shou...
class AddLogoToUsers < ActiveRecord::Migration def self.up add_column :users, :logo, :text add_column :users, :organization, :boolean, :default => false end def self.down remove_column :users, :organization remove_column :users, :logo end end
class CreateSeos < ActiveRecord::Migration[5.2] def change create_table :seos do |t| t.integer :position t.datetime :deleted_at t.timestamps end add_index :seos, :deleted_at end end
Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_pos' s.version = '1.1' s.summary = 'Point of sale screen for Spree' s.required_ruby_version = '>= 1.8.7' s.author = 'Torsten R' s.email = 'torsten@villataika.fi' s.files = Dir...
$:.unshift(File.expand_path('./lib', ENV['rvm_path'])) # Add RVM's lib directory to the load path. require "bundler/capistrano" require "rvm/capistrano" # Load RVM's capistrano plugin. set :rvm_type, :user set :application, "masasx" set :domain, "ci.masas-sics.ca" set :repository, "git://github.com/j...
class AdminFriendsPercentageWorker < BaseWorker def self.category; :admin end def self.metric; :friends_percentage end def perform perform_with_tracking do AdminMetrics.new.fetch_friend_metrics! end end statsd_measure :perform, metric_prefix end
class SessionControllerController < ApplicationController def show end private def user_params params.require(:users).permit(:email,:password) end def new # sign in form end def create # attempt login, from form user = User.find_by_credenti...
=begin input: non empty string output: return the middle character or characters data: array, string algorithm: split the array into characters (including space) divide size by 2 if its remainder is 1 return middle number if remainder is 0 return middle and middle + 1 =end def center_of(string) array...
class GoalsController < ApplicationController def new @resolution = Resolution.find(params[:resolution_id]) @goal = Goal.new end def create goal = resolution.goals.where(goal_params).first_or_create if goal.save flash[:notice] = "Goal created for #{resolution.title}" redirect_to dashb...
require 'spec_helper' describe User do it "processes omniauth from existing user" do auth = { :provider => "twitter", :uid => "1234567", :info => { :nickname => "hafizbadrie" } } user = FactoryGirl.create(:user) tested_user = User.process_omniauth(auth) expect(tes...
# 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...
users = [ { name: 'Fahad', orders: [ { description: 'a bike' } ] }, { name: 'Abdulrahman', orders: [ { description: 'bees' }, { description: 'fishing rod' } ]...
SIZE = 2 class Candidate attr_accessor :ractor def initialize @ractor = Ractor.new do value = Ractor.receive loop { Ractor.yield value } end end end class Group attr_reader :candidate_ractors, :candidates def initialize(candidates) @candidates = candidates @candidate_ractors = ...
require 'rails_helper' RSpec.feature 'Admin signs in' do scenario 'they are redirected to admin dashboard' do user = create(:user, admin: true) visit root_path find('#username-sign-in').set(user.username) find('#password-sign-in').set(user.password) click_button 'Submit' expect(current_path...
module Api module V1 class GalleriesController < Api::V1::BaseController def show @gallery = Gallery.find(params[:id]) if @gallery.user == current_user || current_user.admin? render json: @gallery else render json: { message: "Access denied. You are not authorize...
# frozen_string_literal: true require "resque" module Sentry module Resque def perform if Sentry.initialized? SentryReporter.record(queue, worker, payload) do super end else super end end class SentryReporter class << self def record(que...
class StaticPagesController < ApplicationController # This action uses the signed_in? method from sessions_helper # to see if the user is signed in. # Called when a user navigates to root def home if signed_in? redirect_to room_rooms_path(current_user.username) end # These are variables ...
class AuthorSerializer < ActiveModel::Serializer attributes :username, :email end
class Competition < ApplicationRecord validates :name, :phone, :email, :presence => true end
# simple UDP logger require 'logstasher/device' require 'socket' module LogStasher module Device class UDP include ::LogStasher::Device attr_reader :options, :socket def initialize(options = {}) @options = default_options.merge(stringify_keys(options)) @socket = UDPSocket.ne...
module TeamUserMutations MUTATION_TARGET = 'team_user'.freeze PARENTS = ['user','team'].freeze module SharedCreateAndUpdateFields extend ActiveSupport::Concern included do argument :role, GraphQL::Types::String, required: false end end class Create < Mutations::CreateMutation include ...
class Mechanic < ApplicationRecord validates_presence_of :name, :years_experience has_many :mechanic_rides has_many :rides, through: :mechanic_rides def self.average_experience average(:years_experience) end def open_rides rides.where(open: true).order('thrill_rating DESC')...
class MealPlan < ApplicationRecord belongs_to :user has_many :meals, inverse_of: :meal_plan, dependent: :destroy validates :start_date, presence: true validates :end_date, presence: true validates :user, presence: true accepts_nested_attributes_for :meals def build_meals user_reci...
class Favorite < ApplicationRecord belongs_to :user belongs_to :cook validates_uniqueness_of :cook_id, scope: :user_id end
# frozen_string_literal: true # == Schema Information # # Table name: tasks # # id :integer not null, primary key # name :string # completed :boolean # created_at :datetime not null # updated_at :datetime not null # class Task < ActiveRecord::Base validates :name, :list...
# frozen_string_literal: true require 'rspec' require './roman_to_int' describe RomanToInt do let(:roman_number) do { "I": 1, "V": 5, "X": 10, "C": 100, "L": 50, "D": 500, "M": 1000 } end context 'Convert the RomanToInt response' do describe 'Call Covert met...
require 'spec_helper' describe "groups/show.html.erb" do before(:each) do pwd = 'cloud$' @user = User.create! :first_name => 'Dale', :last_name => 'Olds', :display_name => 'Dale O.', :password => pwd, :confirm_password => pwd, :email => 'olds@vmware.com' sign_in @user @org = assign(:org, stub_model...
class AclController < ApplicationController def acl render json: User.current_user.tocat_role.try(:permissions).to_json end end
require 'app/models/social_media_account' require 'app/presenters/paginated_presenter' class SocialMediaAccountPresenter < Jsonite properties :website, :handle link(:external) { url } end class SocialMediaAccountsPresenter < PaginatedPresenter property(:social_media_accounts, with: SocialMediaAccountPresenter)...
class HomeController < ApplicationController def index @conference = Builderscon::Conference.current end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable #...
class OpenSource::CLI def call #greets user puts "" puts "Welcome to our Facebook Open Source Projects CLI!" menu end def menu #scrape categories and list them puts " " list_categories #select category puts "Please select a category (#) you would like to see projects of or ty...
describe Bothan::App do context 'Dashboards' do before(:each) do basic_authorize ENV['METRICS_API_USERNAME'], ENV['METRICS_API_PASSWORD'] end let(:dashboard_hash) { { dashboard: { name: 'My Awesome Dashboard', slug: 'my-awesome-dashboard', rows: 2, ...
# Simple Role Syntax # ================== # Supports bulk-adding hosts to roles, the primary server in each group # is considered to be the first unless any hosts have the primary # property set. Don't declare `role :all`, it's a meta role. SERVER_IP = '178.62.61.203' USERNAME = 'deploy' role :app, ["#{USERNAME}@#{SE...
# frozen_string_literal: true Sequel.migration do change do create_table(:teams) do primary_key :id column :name, :text column :created_at, 'timestamp with time zone' column :updated_at, 'timestamp with time zone' end end end
class DictionarySearcher attr_reader :dict def initialize(dict) <<<<<<< HEAD @dict = dict end def search(type, term) case type when 1 exact(term) when 2 partial(term) when 3 begins_with(term) when 4 ends_with(term) end end def exact(term) @matches =...
# typed: false require "spec_helper" describe Vndb::Client do describe ".new" do it "can be created" do login_string = "login {\"protocol\":1,\"client\":\"vndb-ruby\",\"clientver\":\"0.1.0\"}\u0004" command_mock = Minitest::Mock.new command_mock.expect(:to_s, login_string) command_spy = ...
require 'benchmark' n = 10_000 m = 1.upto(1000).inject({}) { |m, i| m[i] = i; m } Benchmark.benchmark do |bm| puts "#{n} times - ruby #{RUBY_VERSION}" puts puts "each_value" 3.times do bm.report do n.times do m.each_value {} end end end puts puts "values.each" 3.times ...
class ElasticsearchWorker < BaseWorker def self.category; :elasticsearch end def self.metric; :index end def perform(operation, class_name, id, update_attrs = {}) perform_with_tracking(operation, class_name, id, update_attrs) do model = class_name.constantize object = model.respond_to?(:find) ? m...
class PageViewsController < ApplicationController before_action :set_page_views, only: :index before_action :set_page_view, only: [:show, :update, :destroy] before_action :set_session def index respond_with(@page_views) end def show respond_with(@page_view) end def create @page_view = Pag...
# encoding: utf-8 describe JmesPath do let :jmespath do described_class.new end describe '#compile' do it 'compiles an expression' do expression = jmespath.compile('foo.bar') expect(expression).to_not be_nil end context 'when there is a syntax error' do it 'raises an error' do...
require 'spec_helper' describe Tapbot do it 'has a version number' do expect(Tapbot::VERSION).not_to be nil end describe "CLIENT" do it "should be a Tapbot::Client" do expect(Tapbot.client).to be_a Tapbot::Client end end describe "BASE URI" do it "should return the default base ur...
class AddIsAdminToUser < ActiveRecord::Migration def change add_column :users, :is_admin, :boolean, default: false User.create!(email: 'admin@gmail.com', password: '12345678',password_confirmation: '12345678', is_admin: true) end end
# frozen_string_literal: true class Ingredient < ApplicationRecord has_many :measured_ingredients has_many :dishes, through: :measured_ingredients validates :name, presence: true end
class Game def initialize @hero = Hero.new initialize_dungeon() end def hero @hero end def dungeon @dungeon end def dungeon_cleared? cleared = true @dungeon.each {|level| level.each{|room| cleared = false if not room.cleared? } } cleared end ...
module ReportHelper def generate_filepath_and_name(scenario) project_dir = File.expand_path(File.dirname(__FILE__) + '/../../..') $time_fixed ||= Time.now.strftime('%Y-%m-%d_%H-%M-%S') time = Time.now.strftime('%Y-%m-%d_%H-%M-%S') feature_name = scenario.feature.title.unders...
class CreateAccessers < ActiveRecord::Migration[5.1] def change create_table :accessers do |t| t.boolean :access_granted t.integer :viewing_id t.integer :viewable_profile t.timestamps end add_index :accessers, :viewing_id add_index :accessers, :viewable_profile end end
class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| t.column :name, :string t.column :street, :string t.column :city, :string t.column :text, :text t.timestamps end end def self.down drop_table :orders end end
require 'rib/test' require 'rib/shell' describe Rib::Shell do paste :rib describe '#loop' do def input str=Rib::Skip mock(shell).get_input{if block_given? then yield else str end} shell.loop ok end would 'exit' do input('exit' ) end would 'also...
class TourDriver < ActiveRecord::Base belongs_to :tour belongs_to :driver validates :driver, presence: true end
class TasksController < ApplicationController before_action :set_task, only: [:show, :edit, :update, :destroy] def sort params[:order].each do |key,value| Task.find(value[:id]).update_attribute(:priority,value[:position]) end render :nothing => true end # GET /tasks def index @tasks = ...
module Store::Indices def self.table_name_prefix 'store_indices_' end end
class StudiosController < ApplicationController before_action :set_thing, only: [:show, :edit, :update, :destroy, :toggle_status] access all: [:index, :show], user: {except: [:destroy, :new, :create, :update, :edit]}, admin: :all def index q_param = params[:q] page = params[:page] @q = Studio.published...
Rails.application.routes.draw do #devise_for :adminusers devise_for :adminusers, :controllers => { registrations: 'registrations' } #get 'welcome/index' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have ...
class CreateWildernesses < ActiveRecord::Migration[5.1] def change create_table :wildernesses do |t| t.string :name t.string :coords, limit: 9 t.integer :world_id t.blob :data t.timestamps end end end
require 'colorize' class Jar attr_reader :path, :files def initialize(path) @path = path @files = %x[jar tf #{path} 2>&1 ].lines end def match?(re) @matches = @files.select{|f| f =~ re} not @matches.empty? end def matches path.colorize(:light_blue) + "\n" + @matches.join + "\n" en...
# -*- mode: ruby -*- # vi: set ft=ruby : num_of_nodes = 1 # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "centos-6.5-x86_64" config.vm.box_url = "packer/build/#{config.vm.box}.b...
require 'rails_helper' RSpec.describe Transaction, type: :model do describe 'associations' do it { should belong_to(:lender).class_name('User') } it { should belong_to(:borrower).class_name('User') } it { should belong_to(:thing) } it { should have_db_index(:borrower_id) } it { should have_db_in...
class Like < ActiveRecord::Base belongs_to :answer belongs_to :user validates_uniqueness_of :answer_id, scope: :user_id end
require 'cells_helper' RSpec.describe Balance::Cell::Index do let(:account) { create_account } let(:owner) { account.owner } let(:current_account) { account } it 'asks me to connect to AwardWallet' do rendered = cell(account).() expect(rendered).to have_content 'Connect your AwardWallet account to Ab...
module Type class EditPresenter def record @record ||= Setting.find_by!(key: 'type') end def available_types ::Runner::ContainerBuilder::TYPE_LABEL_MAPPING end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime...
# # Cookbook Name:: git # Recipe:: windows # # Copyright 2008-2012, Opscode, 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 # # Unless...
require 'skit/amqp/runner' describe Skit::AMQP::Runner do let(:instance) { Skit::AMQP::Runner.new } before :all do DaemonKit::Initializer.run.initialize_logger end describe '.new' do subject { instance } it 'loads amqp config' do expect(subject.instance_variable_get('@config')).to be_insta...
# ---------------------------------------------------------------------------- # Frozen-string-literal: true # Copyright: 2012 - 2016 - MIT License # Encoding: utf-8 # ---------------------------------------------------------------------------- require "nokogiri" module Jekyll module RSpecHelpers class ContextT...