text
stringlengths
10
2.61M
# -*- encoding : utf-8 -*- class ExplanatoryNotsController < ApplicationController # GET /explanatory_nots before_filter :check_auth # GET /explanatory_nots.json def index @explanatory_nots = ExplanatoryNot.all respond_to do |format| format.html # index.html.erb format.json { rend...
class TslRobinMap < Formula desc "C++ hash map which preserves the order of insertion" homepage "https://tessil.github.io/" url "https://github.com/Tessil/robin-map/archive/v0.6.3.tar.gz" sha256 "e6654c8c2598f63eb0b1d52ff8bdf39cfcc91d81dd5d05274a6dca91241cd72f" license "MIT" depends_on "cmake" => :build ...
require 'fileutils' module FeatureLock def self.included (base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def lock_with_feature (feature, options={}) feature = feature.to_s filter_chain.prepend_filter_to_chain([options], :before) do |co...
Sequel.migration do up do create_table :images do primary_key :id String :filename Text :caption Integer :height Integer :width DateTime :date end end down do drop_table :images end end
pwd = Faker::Internet.password FactoryGirl.define do factory :user do sequence(:email) { Faker::Internet.email } password pwd password_confirmation pwd end end
class AddGoogleEventIdToEvents < ActiveRecord::Migration[5.1] def change add_column :events, :google_event_id, :integer, unique: true end end
module TroleGroups module Macros module StaticRoleGroups def static_rolegroups? true end end end end
class CashRegister attr_reader :total, :discount def initialize(discount = 0) @total = 0 @discount = discount @items = {} end def total=(total) @total = total end def add_item(title, price, optional = 1) @items[title] = {price: price.to_f*optional.to_f, times: optional.to_f} ...
class Player < ApplicationRecord has_many :scores has_many :doubles has_one :round end
class ProfileImageUploader < BaseImageUploader include Piet::CarrierWaveExtension include ::CarrierWave::Backgrounder::Delay unless Rails.env.development? VERSIONS = { medium: { size: [400, 400], process: true }, thumb: { size: [200, 200] }, mini_thumb: { size: [60, ...
require_relative '../../../../spec_helper' describe 'govuk::app::envvar::rabbitmq', :type => :define do let(:title) { 'giraffe' } context "with some good parameters" do let(:params) {{ :user => "postgresql", :password => "super_secret", :hosts => ["db-1.example.com", "db-2.example.com"], ...
require File.expand_path File.join(File.dirname(__FILE__), '..', 'spec_helper') describe XMLPipes::Indexer do before(:all) do @temporary = SPEC_ROOT.join('fixtures/tmp/testing') XMLPipes::Configuration.configure do |config| config.root = SPEC_ROOT.join('fixtures') config.environment = 'testing'...
class Accounts < ActiveRecord::Base attr_accessible :account_number, :department_id, :name has_many :jobs belongs_to :department end
require 'spec_helper' describe Jangomail::Mailer do subject { Jangomail::Mailer.new(:user_name => 'abc', :password => '123', :options => { :OpenTrack => true }) } let(:mail) do Mail.new("From: \"Some Body\" <sender@example.com>\r\nTo: joe@example.com\r\nSubject: Hello\r\n\r\nHi there!").tap do |mail| mai...
class Movie < ActiveRecord::Base attr_accessible :title, :budget, :box_office_performance, :user_id, :total_box_office has_and_belongs_to_many :users end
FactoryBot.define do factory :lunch do date { Faker::Date.between(from: Date.new(2019, 8, 1), to: Date.current) } end end
require 'pry' def second_supply_for_fourth_of_july(holiday_hash) holiday_hash[:summer][:fourth_of_july][1] end def add_supply_to_winter_holidays(holiday_hash, supply) holiday_hash[:winter][:christmas] << supply holiday_hash[:winter][:new_years] << supply end def add_supply_to_memorial_day(holiday_hash, supply...
namespace :tag_indexing do desc "default task" task :default, [:skip] => :environment do total = Tag.count - skip.to_i current = 0 Tag.skip(skip.to_i).each do |t| TagIndexingWorker.perform_async(:index, t.id.to_s) current += 1 puts "#{current}/#{total}" if (current % 1000) == 0 end...
require 'rails_helper' RSpec.describe Usecase::SpawnAttachments do let(:form_builder_payload) do { submissionAnswers: {}, attachments: [ { url: 'https://www.example.com/image.png', encryption_key: 'some_encryption_key', encryption_iv: 'some_encryption_iv' ...
FactoryGirl.define do factory :card_order do wx_card_id "MyString" paid false withdrew false pmo_grab_id 1 one_money_id 1 item nil end end
class CreateAtms < ActiveRecord::Migration # 自动柜员机 atm # #是否穿墙 through_the_wall #是否带存款模块 deposit_module  #操作系统类型 system #钞箱数量 cash_box_qty #是否为触摸屏 touch_screen #是否有监控 monitor def self.up create_table :atms do |t| t.string "through_the_wall" t.string "deposit_module" t.string "c...
module EasyAuth::Models::Identities::Oauth2::AngelList def authorize_url 'https://angel.co/api/oauth/authorize' end def oauth2_scope 'email' end def user_info_url '/1/me' end def token_url 'https://angel.co/api/oauth/token' end def site_url 'https://api.angel.co' end def r...
require 'vcr' require 'webmock/rspec' VCR.configure do |c| c.allow_http_connections_when_no_cassette = false c.cassette_library_dir = 'spec/fixtures/vcr_cassettes' c.hook_into :webmock # or :fakeweb c.configure_rspec_metadata! %w(user_id access_token device_id).each do |config_key| c.filter_sensitive_...
class ChangeTokenOnApiKeys < ActiveRecord::Migration def change remove_index :api_keys, :authentication_token remove_column :api_keys, :authentication_token, :string add_column :api_keys, :token_digest, :string add_index :api_keys, :token_digest, unique: true end end
require 'spec_helper' describe "personals/index.html.erb" do before(:each) do assign(:personals, [ stub_model(Personal, :name => "Name", :description => "Description" ), stub_model(Personal, :name => "Name", :description => "Description" ) ]) end i...
# RSPEC SNIPPETS (DOES NOT INCLUDE CAPYBARA) # Credit:: https://www.udemy.com/course/testing-ruby-with-rspec/ RSpec.describe 'a random double' do # remember, doubles are in the context of 'stand ins' for real objects in the app it 'only allows defined methods to be invoked' do # syntax option 1 ...
require "spec_helper" RSpec.describe Humi::Middleware::Authentication::Token do let(:options) do { refresh_token: "refresh_token", client_id: "client_id", client_secret: "client_secret", } end it_behaves_like "authentication middleware" do let(:success_request) do stub_lo...
require_relative 'user_mapper' class SiteMapper def initialize(db) @db = db end def persist(site) code = create_unique_code(site) id = @db.connection.collection('sites').insert( { "user_id" => site.user.id, "url" => site.url, "code" => code } ) site.code = code site.id = id end def get_s...
word = "D&CT@A345CAD*&$EM43Y" # Remove all characters other than alphabets # Given a string consisting of alphabets and others characters, the task is to remove all the characters other than alphabets and print the string so formed. # Example # Input : # D&^CT @A345CAD*&$EM43Y # Output : # DCTACADEMY hash = {} ('...
class Course < ActiveRecord::Base belongs_to :departments has_many :teachers has_many :coursestudents has_many :students, :through => :coursestudents end
include_recipe 'chef-openstack::neutron-common' bash 'grant privileges' do not_if 'grep neutron /etc/sudoers' code <<-CODE echo 'neutron ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers CODE end template 'Neutron compute node config' do path '/etc/neutron/neutron.conf' owner 'root' group 'neutron' mode '0644'...
json.array!(@players) do |player| json.username player.username end
class ChangeReviewFormsReviewQuestionsTableNameToReviewFormReviewQuestions < ActiveRecord::Migration def self.up rename_table :review_forms_review_questions, :review_form_review_questions end def self.down rename_table :review_form_review_questions, :review_forms_review_questions end end
class CleanUsers < ActiveRecord::Migration def change remove_column :users, :'{:default => false}' end end
class Notifications < ActionMailer::Base default from: "notes@capsulo.us" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.notifications.new_note.subject # def new_note(note) @greeting = "Hi there!" @id = note.id @notemaker = note.user.name...
class CategoriesController < ApplicationController def index @categories = current_user.categories.order(:name) end end
json.array! @restaurants do |restaurant| json.id restaurant[:id] json.name restaurant[:name] json.address restaurant[:address] json.origin restaurant[:origin] json.name_and_address restaurant[:name_and_address] end
class PersonalBoard < ActiveRecord::Base has_many :users def member_ids member_id_array = [] member_id_array.push(boardmember1_id.to_s) member_id_array.push(boardmember2_id.to_s) member_id_array.push(boardmember3_id.to_s) member_id_array.push(boardmember4_id.to_s) member_id_array.push(bo...
require_relative '../helpers/palindrome_counter' class OEIS # Number of strings of length n over a 10 letter alphabet that do not begin # with a palindrome. def self.a252703(n) nonpalindrome_count(n, 10) end end
ansible_provision = proc do |ansible| ansible.playbook = 'ansible/netplugin/site.yml' proxy_env = { } %w[http_proxy https_proxy].each do |name| if ENV[name] proxy_env[name] = ENV[name] end end # In a production deployment, these should be secret ansible.extra_vars = { proxy_env: proxy_e...
#{{{ Marathon Fixture require 'default' #}}} Marathon Fixture require 'assertions/assert_settings' require 'settings/on_setting_window' def test java_recorded_version = '1.6.0_20' original_replace_stamp = get_setting('ReplaceStamp') original_stamp_space = get_setting('StampSpace') original_...
class User < ActiveRecord::Base has_secure_password has_many :pools def slug self.username.downcase.gsub(" ", "-") end def self.find_by_slug(slug) self.all.find { |user| user.slug == slug } end end
#Pets and Summons (Compatibility) v1.6a #----------# #Features: Allows you to set skills that summons pets (actors) into battle, which # can last for the duration of the battle, until dead, or by timer. # #Usage: Plug and play, Customize as needed # Skill/Item Notetag: # <SUMMON actor_...
# rotation_2.rb # Write a method that can rotate the last `n` digits of a number. # Note that rotating just 1 digit results in the original number being # returned. # You may use the `rotate_array` method from the previous exercise if you want. # (Recommended!) # You may assume that `n` is always a positive integer....
class AddPriceToCommand < ActiveRecord::Migration[5.2] def change add_column :commands, :price, :decimal end end
PadrinoWeb.controllers :guides, :cache => true do get :search, :map => "/guides/search", :cache => false do if params[:q] && params[:q].size >= 4 @search = params[:q] @guides = Guide.search(@search, :order => "position", :page => (params[:page] || 1), :draft => false, :paginate => true) end ...
require 'thread' class CyclicBarrier def initialize(n_threads) @n_threads = n_threads @counter = 0 @queue = ConditionVariable.new @mutex = Mutex.new end def await @mutex.synchronize do @counter += 1 if @counter >= n_threads @counter = 0 @q...
module Omniship class UPS < Carrier self.retry_safe = true cattr_accessor :default_options cattr_reader :name @@name = "UPS" TEST_URL = 'https://wwwcie.ups.com' LIVE_URL = 'https://onlinetools.ups.com' RESOURCES = { :rates => 'ups.app/xml/Rate', :track => 'ups.app/xml/Tr...
class DropInsertions < ActiveRecord::Migration def change drop_table :insertions end end
require 'net/http' require 'json' require 'cgi' require 'addressable/uri' module FormhubRuby class ApiConnector attr_reader :formname, :filetype, :username, :password, :data attr_accessor :query, :start, :limit, :sort, :fields, :cast_integers def initialize(args) @username = args[:username] || F...
class NodeTypes::VolumesController < ApplicationController layout 'buttoned' include NodeTypesHelper before_action :must_admin! before_action :get_node_type def new @volume = NtVolume.new render 'new' end def create @volume = NtVolume.new params.require(:nt_volume).permit(:t_path, :s_path)...
class Api::V1::WorkoutsController < ApplicationController def index workouts = Workout.all # render json: WorkoutSerializer.new(workouts) options = { include: [:category] } render json: WorkoutSerializer.new(workouts, options) end def create wor...
When('I click on the {string} button belonging to the {string} location') do |button_name, location_title| match = false all('.card').each do |card| if card.has_content?(location_title) match = true within(card) { click_link button_name } end end expect(match).to ...
FactoryGirl.define do factory :operator do name "OperatorName" description "OperatorDescription" end factory :invalid_operator, class: 'Operator' do name nil description nil end end
require 'rails_helper' RSpec.describe DealershipController do before(:each) do admin = FactoryBot.create(:user) sign_in admin end describe 'GET #index' do context 'when logged in' do it 'should display all the dealerships' do get :index expect(response.status).to eq(200) ...
module CloudStats def self.serialize(server_key, sysinfo) { version: CloudStats::VERSION, server_key: server_key, server: { agent_version: CloudStats::VERSION, services: sysinfo.safe_get(:services), cpu_usage: sysinfo.safe_get(:cpu, :usage), disk_us...
json.array!(@shifts) do |shift| json.extract! shift, :id, :shiftname, :shortcode, :colorcode, :shiftstarttime, :shiftendtime, :mealstarttime, :mealendtime json.url shift_url(shift, format: :json) end
class AddSphereClientDataToShops < ActiveRecord::Migration def change add_column :shops, :sphere_client_id, :string add_column :shops, :sphere_client_secret, :string end end
class Admin::ArticlesController < AdminController before_action :find_article, only: [:edit, :update, :destroy] before_action :select_author, except: [:index, :destroy] def index if params[:query] #pg_search @admin_articles = Article.search(params[:query]).order(created_at: :desc).page(params[:page])...
require 'rails_helper' describe User do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録がうまくいくとき' do it "family_name、first_name、email、password、password_confirmationが存在すれば登録できる" do expect(@user).to be_valid end it "passwordが6文字以上であれば登録できる" do ...
module LolKek module Cashable INITIAL_BALANCE = 10 def self.included(klass) klass.extend(ClassMethods) end def cash self.class.balance end def add(amount) self.class.balance = cash + amount end module ClassMethods def balance @balance || 0 end ...
source 'https://rubygems.org' ruby '2.3.0' # ------------------------------------ # Stack # ------------------------------------ # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '>= 5.0.0.rc1', '< 5.1' # Use PostgreSQL for the back end DB gem 'pg' # Use Redis adapter to run Action Cable in ...
module TaskMaster RSpec.describe CustomRequest do def expect_custom_request_to_post_to_fancyhands(request, response = JSON.parse(File.read(File.expand_path("../../../fixtures/custom_requests/response.json", __FILE__)))) client = Client.new expect(Client).to receive(:new).at_least(:once).and_return(cl...
require 'rails_helper' RSpec.describe Contract, :type => :model do example do expect(described_class).to equal(Contract) end end
Rails.application.routes.draw do mount_devise_token_auth_for 'User', at: 'auth' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :admins, only: [:index, :show, :create, :update, :destroy] resources :agents, only: [:index, :show, :create, :update, :de...
class DeliverySerializer < ActiveModel::Serializer attributes :id, :purchase_order_id, :delivery_dt, :warehouse_id, :moved_from_warehouse_id, :without_delivery_note, :delivery_note, :comment has_many :delivered_items end
require File.expand_path(File.dirname(__FILE__)) + "/test_helper" require 'schema' require 'filtered_relation/dsl' class DSLTest < ActiveSupport::TestCase setup do setup_db @caelum = Post.create :body => "CaelumObjects training and inovation" @guilherme = Post.create :body => "Guilherme Silveira" ...
# frozen_string_literal: true RSpec.describe ActiveEncryption::Configuration::Store do subject(:store) { described_class.new } it 'stores values' do expected = :some_symbol store.default_encryption_setting_id = expected expect(store.default_encryption_setting_id).to eq expected end describe '#res...
module LeanMotion class CloudQuery < AVQuery def setClassObject(classObject) @classObject = classObject self end def initWithClassNameAndClassObject(className, classObject:myClassObject) @className = className self.initWithClassName(className) self.setClassObject(myClas...
# == Schema Information # Schema version: 20110122205957 # # Table name: personals # # id :integer(4) not null, primary key # name :string(255) # description :string(255) # created_at :datetime # updated_at :datetime # imgs_folder_name :string(255) # class Personal...
# typed: true class CreateBanalBrainstorms < ActiveRecord::Migration[6.0] def change create_table :banal_brainstorms do |t| t.text :idea t.string :main_category t.string :priority t.string :status t.text :comments t.string :idea_owner t.timestamps end end end
require 'test/unit' class TestAlias < Test::Unit::TestCase class Alias0 def foo; "foo" end end class Alias1<Alias0 alias bar foo def foo; "foo+" + super end end class Alias2<Alias1 alias baz foo undef foo end class Alias3<Alias2 def foo defined? super end def bar ...
class Area < ApplicationRecord has_many :spaces, dependent: :destroy has_many :restaurants, dependent: :destroy end
class CreateNodes < ActiveRecord::Migration def change create_table :nodes do |t| t.string :name t.integer :model_id t.integer :y t.integer :x t.boolean :equally_output, :default => true t.text :handlers t.boolean :priority_type t.boolean :step_type t.string :...
require "pry" def consolidate_cart(cart) keys = [] consolidate_cart = {} cart.each do |x| x.each do |k, v| keys << k consolidate_cart[k] = v #binding.pry end end cart.map do |x| x.map do |k, v| consolidate_cart[k][:count] = keys.count(k) end end consolidate_cart...
class Response < ActiveRecord::Base default_scope -> { order(created_at: :asc) } belongs_to :response belongs_to :question belongs_to :user has_many :comments, class_name: "Response" validates :user_id, presence: true validates :question_id, presence: true validates :content, presence: true has...
require 'test_helper.rb' class AdminControllerTest < ActionController::TestCase test "Owners should GET user administration" do login(users(:owner)) get :users assert_response :success end test "Admins should GET user administration" do login(users(:admin)) get :users assert_response...
# frozen_string_literal: true # Agency model class Agency < ApplicationRecord # This is the jurisdiction of the agency enum jurisdiction: { unknown: 'unknown', local: 'local', state: 'state', federal: 'federal', university: 'university', commercial: 'commercial' }.freeze has_paper_trai...
class InitSchema < ActiveRecord::Migration[4.2] def change create_table "apps" do |t| t.string "name", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "user_id", null: false t.string "api", null: false t.string "os_version", null: ...
module Regaliator class Response attr_reader :success attr_reader :data def initialize(http_response) @success = http_response.kind_of?(Net::HTTPSuccess) @data = begin JSON::parse(http_response.body) rescue {message: 'Server returned a non-json er...
# frozen_string_literal: true # == Schema Information # # Table name: projects # # id :integer not null, primary key # name :string not null # description :string # created_at :datetime not null # updated_at :datetime not null # account_id :integer # # Indexe...
require 'spec_helper' describe "Search for business support" do before do @graduate_start_up_attrs = { "id" => "https://www.gov.uk/graduate-start-up.json", "title" => "Graduate start-up scheme", "web_url" => "https://www.gov.uk/graduate-start-up", "identifier" => "graduate-start-up", ...
# == Schema Information # # Table name: card_members # # id :integer not null, primary key # card_id :integer not null # member_id :integer not null # created_at :datetime # updated_at :datetime # # Indexes # # index_card_members_on_card_id (card_id) # index_...
cask :v1 => 'league-of-legends' do version :latest sha256 :no_check url 'http://l3cdn.riotgames.com/Installer/NA_Mac_Installer/League%20of%20Legends%20NA.dmg' homepage 'http://signup.leagueoflegends.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated pl...
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "ActiverecordPostgresHstore" do it "should convert hash to hstore string" do ["('a'=>'1') || ('b'=>'2')", "('b'=>'2') || ('a'=>'1')"].should include({:a => 1, :b => 2}.to_hstore) end it "should convert hstore string to hash" do ...
class MazeFinder MARKS = [:*, :S, :E] attr_accessor :maze, :mazetrail def initialize( maze = File.readlines("maze1.txt")) @maze = maze @mazetrail = Array.new end def maze_format @maze.map!.each do |line| line.split("") end @maze.map! do |line| line.delete("\n") line.map! ...
class LeaveApplicationsController < ApplicationController before_action :set_leave_application, only: [:show, :edit, :update, :destroy] # GET /leave_applications # GET /leave_applications.json def index @leave_applications = LeaveApplication.page(params[:page]) end # GET /leave_applications/1 # GET ...
require 'data_generator/mutation/base' module DataGenerator module Mutation # Takes 'odds' parameter to determine whether to perform this mutation or not. class Random < Base def odds properties['odds'] || 1.0 end def apply(value, entity) if rand < odds.to_f _appl...
class BookmarksController < ApplicationController before_filter :authenticate_user! def index @bookmarks = current_user.bookmarks.reverse end def show @bookmark = current_user.bookmarks.find_by_id(params[:id]) redirect_to root_path if @bookmark.nil? end def new @bookmark = Bookmark.new ...
# frozen_string_literal: true module Tikkie module Api module V1 module Responses # Bank account of a user. class BankAccount < Base def bank_account_token data[:bankAccountToken] end def bank_account_label data[:bankAccountLabel] ...
class Departamento < ActiveRecord::Base belongs_to :empresa validates_presence_of :nome, :empresa_id validates_uniqueness_of :nome, :scope => :empresa_id end
module Sunspot module Query # # A query component that provides access to hit highlighting in Solr # class Highlighting #:nodoc: def initialize end def to_params { 'hl' => 'on', 'hl.simple.pre' => '@@@hl@@@', 'hl.simple.post' => '@@@endhl@...
require "./app/config/generic_http_client" class ShieldGenerator module Colors BRIGHT_GREEN = "brightgreen".freeze GREEN = "geen".freeze YELLOW_GREEN = "yellowgreen".freeze YELLOW = "yellow".freeze ORANGE = "orange".freeze RED = "red".freeze LIGHT_GRAY = "lightgray".freeze BLUE = "blu...
# encoding: utf-8 require "logstash/filters/base" require "logstash/namespace" require "mongo" # This example filter will replace the contents of the default # message field with whatever you specify in the configuration. # # It is only intended to be used as an example. class LogStash::Filters::Mongodb < LogStash::F...
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe "/admin/blogs/edit.html.erb" do include Admin::BlogsHelper before do @blog = mock_model(Blog) @blog.stub!(:title).and_return("MyString") @blog.stub!(:short_name).and_return("MyString") @blog.stub!(:in_draft).and_...
module CamaleonCms module CustomFieldsRead extend ActiveSupport::Concern included do before_destroy :_destroy_custom_field_groups # DEPRECATED, INSTEAD USE: custom_fields has_many :fields, lambda { |object| where(object_class: object.class.to_s.gsub('Decorator', '')...
class RenameNurseToHealthcareWorkerInRoles < ActiveRecord::Migration def change rename_column :roles, :nurse, :healthcare_worker end end
class OverTime attr_accessor :working_days, :daily_working_hours, :holidays, :ineffective_code @@otsetup = YAML.load_file(RAILS_ROOT + "/config/overtime_setup.yml") def initialize @working_days = @@otsetup["working_days"] @daily_working_hours = @@otsetup["daily_working_hours"] @holidays = @@otsetup["...
cask "luna-display" do version "4.5.0" sha256 "4d833f40333fe7139e741470c250abe171bc0013a51378934f19fb534379dfaf" url "https://s3.amazonaws.com/s3.lunadisplay.com/downloads/LunaDisplay-#{version}.dmg", verified: "s3.amazonaws.com/s3.lunadisplay.com/downloads/" name "Luna Display" desc "Use your iPad as ...
class AnimalsController < ApplicationController def index animals = Animal.all render json:animals end def show animal = Animal.find(params[:id]) render json:animal.to_json(:include => :sightings) end def create animal = Animal.new(animal_params) if animal.save render json: an...