text
stringlengths
10
2.61M
class CreateUserInks < ActiveRecord::Migration def change create_table :user_inks do |t| t.belongs_to :ink, null: false t.belongs_to :user, null: false t.string :color_family t.boolean :is_cartridge, null: false, default: false t.boolean :is_bottled, null: false, default: false ...
module Rooms class FindGuests include Interactor delegate :room, to: :context def call context.guests = context.room.guests end end end
Given /^a spec file named "([^"]*)" with:$/ do |file_name, string| steps %Q{ Given a file named "#{file_name}" with: """ruby require 'rock_candy' #{string} """ } end When /^I set environment variable "(.*?)" to "(.*?)"$/ do |variable, value| set_env(variable, value) end Then /^the examples?...
Sagashi::Engine.routes.draw do root "tokens#index" end
require 'simplecov' SimpleCov.start do # Code groupings add_filter '/spec/' add_group 'Algorithms', 'lib/algorithm' add_group 'Utilities', 'lib/ants' add_group 'Agents', 'lib/colony' add_group 'Simulations', 'lib/sims' # Simplecov config minimum_coverage 90 end
require 'rails_helper' RSpec.describe ConversationsController, type: :controller do login_user describe "GET #index" do it "returns http success" do get :index expect(response).to have_http_status(:success) end it "renders the index template" do get :index expect(response).to r...
class MailTemplatesController < ApplicationController before_filter :require_user before_filter :obtain_parameters, :only => :show inherit_resources actions :all, :except => :index respond_to :html, :xml, :json belongs_to :project def index redirect_to project_path(params[:project_id]) end pr...
module Services module State class AwaitingContactConfirmation < Base def process(user_input) store_answer(body: user_input, user: conversation.user) case user_input when User::CONFIRM_YES conversation_strategy.confirm_choise when User::CONFIRM_WRONG_EMAIL ...
class Account < Account.superclass module Cell module MonthlySpending class TableRow < Abroaders::Cell::Base property :couples? property :monthly_spending_usd def show content_tag :tr do content_tag(:td, label) << content_tag(:td, value) end e...
class LogbooksController < ApplicationController before_action :set_logbook, only: [:show, :edit, :update, :destroy] respond_to :html def index @logbooks = Logbook.all @customers = Customer.all respond_with(@customers, @logbooks) end def manage @logbooks = Logbook.all.paginate(:per_page => 1...
require 'ap' require 'persistent_spec_helper' require 'rack/test' require_relative '../../api' require_relative 'shared' module DiceOfDebt shared_context 'api test' do include Rack::Test::Methods before do insert_data :games, id: 1, score: 0 end after do delete_all_data :rolls de...
require 'selenium-webdriver' class SeleniumWrapper def initialize(browser = :firefox, mobile = false) profile = Selenium::WebDriver::Firefox::Profile.new profile["network.proxy.type"] = 1 profile["network.proxy.http"] = "127.0.0.1" profile["network.proxy.http_port"] = 9999 p...
class Product < ActiveRecord::Base attr_accessible :name, :price validates :name, presence: true, length: {minimum:5} end
class Mutations::UpdateOrganizationRole < Mutations::BaseMutation field :organization_role, Types::OrganizationRoleType, null: false argument :id, Integer, required: true, camelize: false argument :organization_role, Types::OrganizationRoleInputType, required: true, camelize: false argument :add_user_ids, [Int...
module BreweryDB module Webhooks class Beer < Base def process @beer = ::Beer.find_or_initialize_by(brewerydb_id: @brewerydb_id) self.send(@action) end private def insert(attributes = nil) params = { withBreweries: 'Y', withSocialAccount...
# frozen_string_literal: true Class.new(Nanoc::Filter) do identifier :remove_lang_from_pre def run(content, _params = {}) content.lines.reject { |l| l =~ /^\s+#!/ }.join end end
class User < ActiveRecord::Base after_initialize :default_values has_many :armies, :dependent => :destroy before_save { email.downcase! } before_create :create_remember_token has_secure_password validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z...
class LocationsController < ApplicationController before_action :authenticate_user! before_action :set_location, except: [:create] def create @new_location = current_user.create_location(location_params[:name]) @new_location.update(location_params) unless @new_location.errors.any? @location = ...
Pod::Spec.new do |s| s.name = "Ready4AirPlayer" s.homepage = "http://valtech.com" s.license = 'Commercial' s.author = { "Jeffrey Thompson" => "jeffrey.thompson@neonstingray.com" } s.summary = "Ready4Air Player Component" s.version = "1.0.0.002" s.source = ...
require 'spec_helper' RSpec.describe Smite::GodStats do let(:agni) { Smite::Game.god('agni') } let(:smite_obj) { agni.stats } let(:items) do [ Smite::Game.item('Soul Reaver'), Smite::Game.item('Sovereignty') ] end describe '#initialize' do it 'bounds the level between 1 and 20' ...
require 'spec_helper' describe Book do it { should validate_presence_of :title} it { should validate_presence_of :author} it { should validate_numericality_of :rating} it { should have_valid(:rating).when(0, 20, 100) } it { should_not have_valid(:rating).when(-1, "ten", 101) } it { should have_many(:checko...
class AddAccumulatedMeasuredToValorizationitems < ActiveRecord::Migration def change add_column :valorizationitems, :accumulated_measured, :float end end
# frozen_string_literal: true module NotificationMailerPatch def event_received(event, event_class_name, resource, user, extra) if extra[:template] send_custom_email(event, event_class_name, resource, user, extra) else with_user(user) do @organization = resource.organization e...
module Reservable module ClassMethods def highest_ratio_res_to_listings all.max { |a, b| a.res_to_listings <=> b.res_to_listings } end def most_res all.max { |a, b| a.reservations.count <=> b.reservations.count } end end module InstanceMethods def res_to_listings return 0 i...
require 'support/number_helper' require 'fileutils' require 'tempfile' class Restaurant include NumberHelper @@filepath = nil def self.filepath=(path=nil) @@filepath = File.join(APP_ROOT,path) end def self.file_exists? # class should know if the restaurant files file exists if @@filepath && File.exists?...
# -*- mode: ruby -*- # vi: set ft=ruby : # # @ansible_home = "/home/vagrant/.ansible" Vagrant.configure("2") do |config| config.vm.box = 'ubuntu/bionic64' config.vm.box_url = 'https://cloud-images.ubuntu.com/bionic/current/bionic-server-cloudimg-amd64-vagrant.box' config.vm.hostname = "ansible-test" confi...
class User < ActiveRecord::Base has_many :articles before_save {self.email = email.downcase} validates :username,presence: true, uniqueness:{case_sensitive:false},length:{minimum: 3, maximum: 25} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence:true, uniqueness:{case_sensitive:...
class Song <ActiveRecord::Base belongs_to :artist has_many :genres, through: :song_genres has_many :song_genres extend Slugger::ClassMethods include Slugger::InstanceMethods end
class Admin::ItemsController < ApplicationController def index @items=Item.all end def new @item=Item.new @genres=Genre.all end def create @item=Item.new(item_params) if @item.save flash[:notice] = "商品の登録に成功しました" redirect_to admin_item_path(@item) else render :new ...
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # 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 required by appli...
class Parcial < ActiveRecord::Base has_many :actividads belongs_to :materia_alumno end
# == Schema Information # # Table name: bill_items # # id :integer not null, primary key # label :string # amount :decimal(19, 4) # type :string # account_id :integer # bill_id :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes...
class Equipment < ApplicationRecord belongs_to :organization, optional: true enum kind: { laptop: 0, desktop: 1 } end
################################ # Client Page # # Encapsulates the Client Page (new and edit) # # The layer hides the Capybara calls to make the functional RSpec tests that # use this class simpler. # # rubocop: disable Metrics/ParameterLists # class ClientPage include Capybara::DSL def load id: nil if id.nil...
class StaticPagesController < ApplicationController before_action :authenticate_user! before_action :check_admin before_action :check_trial, only: :create def home @books = Book.book_actived(current_user.id).select(:id, :name, :code, :bookcover, :book_type, :role) end def create @number_book = par...
# # Copyright:: Copyright (c) 2015 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
# Creates a follow of an target for a user. If one already exists, it # is returned. Expects to work idempotently. class CreateFollow def initialize(user, target, options={}) @user = user @target = target @options = options.symbolize_keys end def call() @follow = @user.follows.find_by target: @t...
Gem::Specification.new do |s| s.name = 'rpmbuild' s.version = '0.6.6' s.date = '2014-02-10' s.summary = "Create RPMs" s.description = "A wrapper around rpmbuild for generating custom RPMs" s.authors = ["Albert Dixon"] s.email = "adixon415n@gmail.com" s.license = "GPLv3" s.files = ["lib/rpmbuild.rb"] ...
class CreateBikeWheelSizes < ActiveRecord::Migration def up create_table(:bike_wheel_sizes) do |t| t.integer :twmm t.integer :rdmm t.string :twin t.string :rdin t.string :twfr t.string :rdfr t.string :description t.string :tire_common_score end end def down...
module Refinery module NewsItems class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::NewsItems engine_name :refinery_news_items initializer "register refinerycms_news_items plugin" do Refinery::Plugin.register do |plugin| plugin.name = "new...
class Vacation < ActiveRecord::Base def vacations_with_desc vacaciones = fill_zeros("#{period}") "#{vacaciones}/#{year}" end def fill_zeros(vacaciones) "#{vacaciones}".to_s.rjust(2, '0') end end
class Recipe < ApplicationRecord has_many :foodables has_many :foods, through: :foodables has_many :favorites # validates_uniqueness_of :recipe end
require 'light_remote' class LightRemote::Flame def initialize(light, loop_callback=nil) @light = light @loop_callback = loop_callback ? loop_callback.to_proc : nil end # This loop makes a smooth-fading fire. (A bit too smooth.) # TODO: Add some flicker. def run(initial_rgb=nil) cur = initial_...
require('minitest/autorun') require('minitest/rg') require_relative('../person') # Duck Test inherets from MiniTest :: Test is the module class PersonTest < MiniTest::Test def setup @person = Person.new("Adrian", "Tuckwell") end def test_person_first_name assert_equal("Adrian", @person.first_name) en...
class ChangeEventsLogPayloadColumn < ActiveRecord::Migration def up change_column :'denormalization.events_log', :payload, :text end def down change_column :'denormalization.events_log', :payload, :string, limit: 512 end end
require 'spec_helper' require 'turnip_formatter/step_template/exception' describe TurnipFormatter::StepTemplate::Exception do after do TurnipFormatter.step_templates.pop end let!(:template) do described_class.new end describe '#build_failed' do subject { template.build_failed(failed_example) } ...
require 'spec_helper' require 'yt/constants/geography' describe 'Yt::COUNTRIES' do it 'returns all country codes and names' do expect(Yt::COUNTRIES[:US]).to eq 'United States' expect(Yt::COUNTRIES['IT']).to eq 'Italy' end end describe 'Yt::US_STATES' do it 'returns all U.S. state codes and names' do ...
class Review < ApplicationRecord belongs_to :product validates :rating, presence: true validates :rating, :inclusion => {:in => 1..5, :message => " %{value} is not a valid rating " } validates :comment, presence: true, length: {maximum: 255}, on: :create, allow_nil: false end
module Mastermind class Code attr_accessor :code attr_reader :min_digit, :max_digit, :code_size, :valid def initialize @code = "" @min_digit = 1 @max_digit = 6 @code_size = 4 @valid = Validate.new(@code_size, @min_digit, @max_digit) end end end
class Package < ApplicationRecord has_many :contacts belongs_to :type, optional: true end
require File.join(Dir.pwd, 'spec', 'spec_helper') describe 'Experian::DataDictionary 313HH' do context 'valid lookup' do it { expect( Experian::DataDictionary.lookup('313HH','A01') ).to eq('American Royalty') } it { expect( Experian::DataDictionary.lookup('313HH','B07') ).to eq('Generational Soup') } it...
require 'rails_helper' RSpec.describe BuyerAddress, type: :model do before do @user = FactoryBot.create(:user) @item = FactoryBot.create(:item) @buyer_address = FactoryBot.build(:buyer_address, user_id: @user.id, item_id: @item.id) end describe '購入者情報の保存' do context '購入者情報の保存がうまくいくとき' do i...
class CreateUsers < ActiveRecord::Migration def self.up create_table :users, :id => false, :primary_key => 'id' do |t| # 客户管理系统同步数据 t.integer :id t.string :username t.string :email t.string :encrypted_password # 密码和令牌 t.string :crypted_password t.string :pass...
class IssueHeader include RailsHelpers def self.render(issue, show_full_image) self.new(issue, show_full_image).render end attr_accessor :issue def initialize(issue, show_full_image) @issue = issue @show_full_image = show_full_image end def css_class 'home' end def image hel...
require "securerandom" class AuthController < ApplicationController skip_before_action :require_login skip_before_action :require_setup def signup render(status: 200) end def create_user user = User.new user.name = params[:name] user.email = params[:email] user.password = params[:passwo...
require "helper" describe Bridge::Points::Chicago do it "raises ArgumentError when invalid honour card points provided" do assert_raises(ArgumentError) do Bridge::Points::Chicago.new(:hcp => 15, :points => 100) end end it "set default vulnerable to false" do imp = Bridge::Points::Chicago.new(:...
require "keg" module StickyLink def self.link(kegs, mode, options) linked_kegs = [] kegs.each do |keg| keg_only = Homebrew.keg_only?(keg.rack) if HOMEBREW_PREFIX.to_s == "/usr/local" && keg_only && keg.name.start_with?("openssl", "libressl") opoo <<-EOS.undent Refusing ...
Given /^Opening Home Page$/ do visit root_path end When /^I click on Group Menu$/ do page.should have_selector 'h1', text: 'Organization Information System' within("#group") do click_link 'grp' end end When /^I click on View Users Under Group sub Menu$/ do within("#grpusers") do click_link 'usersgrp' end en...
module AdminLte class ApplicationController < ActionController::Base protect_from_forgery with: :exception # before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user! before_action :check_admin_user layout :layout_by_resource # def index # ...
class SubscribersController < ApplicationController before_action :authenticate_user! before_filter :load_catalog, only: [:new, :create] def new @subscriber = Subscriber.new end def create @subscriber = @catalog. subscribers. find_or_initialize_by(email: params[:email]) if @subscrib...
class RatingsController < ApplicationController before_action :authenticate_user! def update @rating = Rating.find(params[:id]) @coach = @rating.coach if @rating.update_attributes(rating: params[:rating]) respond_to do |format| format.js end end end private ...
class Rule < ApplicationRecord TYPES = %i[level category score attempts].freeze belongs_to :badge def self.values_by_type(type) send "#{type}_values" end def self.level_values Quiz.all.pluck(:level).uniq.map { |level| [level, level] } end def self.category_values Category.all.map { |catego...
require_relative '../aws_helper' require_relative '../aws_stubs' require_relative '../aws_refresher_spec_common' describe ManageIQ::Providers::Amazon::NetworkManager::Refresher do include AwsRefresherSpecCommon include AwsStubs describe "refresh" do before do _guid, _server, zone = EvmSpecHelper.creat...
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Img2Vid Configuration" do before(:all) do @configuration = Img2Vid.configure do |config| config.video_file = 'results.mpg' config.temp_path = '/tmp' config.ffmpeg_command = '/usr/local/bin/ffmpeg' end end...
class Admin::BaseController < ApplicationController layout "admin_layout" before_action :require_admin private def require_admin unless current_user.role_name == Settings.role_admin redirect_to root_path flash[:notice] = t "admin_only" end end end
require 'rails_helper' describe 'PasswordReset', type: :request do describe '#new' do before { get new_password_reset_url } it { expect(response).to be_success } it { expect(response).to render_template 'new' } end describe '#create' do subject { response } let(:user) { create(:user) } ...
class HObject def initialize(data={}) @data = data end def to_json(options={}) data.to_json end end
module Rfm # The Record object represents a single FileMaker record. You typically get them from ResultSet objects. # For example, you might use a Layout object to find some records: # # results = myLayout.find({"First Name" => "Bill"}) # # The +results+ variable in this example now contains a ResultSet o...
# encoding: utf-8 require 'csv' module ApplicationHelper include DataFormat include DateHelper def period_label action_name = :report if action_name.to_s == 'report' '报告起止日期' elsif action_name.to_s == 'bill' '账单起止日期' else '交易起止日期' end end def period_values obj,action_name...
class Adminpanel::KrowspacesController < ApplicationController before_action :authenticate_user! before_action :admin_only before_action :set_krowspace , only: [:createseats,:show, :edit, :update, :destroy] # GET /krowspaces # GET /krowspaces.json def createseats end def index @krowspaces = Krowspa...
require 'spec_helper' describe AppJournal do subject do Class.new do include AppJournal def services [ Service.new(name: 's1'), Service.new(name: 's2') ] end end.new end describe '#journal' do let(:journal) { hash_from_fixture('journal') } ...
#coding: utf-8 class Book < ActiveRecord::Base # attr_accessible :user_id, :user, :name, :book_file, :book_file_path has_attached_file :book_file, url: ":rails_root/books/:year/:month/:day/:id.book", path: ":rails_root/books/:year/:month/:day/:id.book" do_not_validate_attachment_file_type :book_file vali...
# Instead of using spec_helper, I'm using the twice as fast custom helper # for active record objects. require 'spec_active_record_helper' require 'hydramata/works/predicates/storage' require 'hydramata/works/linters/implement_predicate_interface_matcher' module Hydramata module Works module Predicates de...
class Membership < ApplicationRecord belongs_to :beerclub belongs_to :user end
Rails.application.routes.draw do resources :patients resources :doctors resources :appointments, only: [:show] end
class Sponsor < ApplicationRecord has_many :menus end
module Hoarder class Storage def initialize(path) @absolute_path = path @config = load_config("#{@absolute_path}/hoarder.yml") @public = @config['public'] || true @connection = set_connection(@config['provider'], @config) @locker = set_locker(@config['container'], @public) end ...
class CommentSerializer < ActiveModel::Serializer attributes :id, :text, :rating, :created_at belongs_to :meme end
# encoding: utf-8 control "V-54031" do title "Procedures and restrictions for import of production data to development databases must be documented, implemented, and followed." desc "Data export from production databases may include sensitive data. Application developers may not be cleared for or have need-to-know t...
require 'func/call_instance' require 'func/callable' require 'func/init_ivars' require 'func/version' class Func extend CallInstance include InitIvars include Callable def call raise NotImplementedError, 'Func must be subclassed with a no-arg `call` method' end end
require 'vanagon/engine/base' describe 'Vanagon::Engine::Base' do let (:platform_without_ssh_port) { plat = Vanagon::Platform::DSL.new('debian-6-i386') plat.instance_eval("platform 'debian-6-i386' do |plat| plat.ssh_port nil end") plat._platform } let (:plat...
# frozen_string_literal: true require 'stats_console_writer' describe StatsConsoleWriter do before do @stats_service = PageStatsService.new log_reader = LogFileReader.new @visits = log_reader.read(path: "#{RSPEC_ROOT}/fixtures/webserver.log") end describe 'write_total_visits' do it 'prints tota...
class Post < ApplicationRecord has_one_attached :image, dependent: :destroy validates_presence_of :title, :content validates_uniqueness_of :title before_validation :set_slug private def set_slug self.slug = title.downcase.strip.gsub(' ', '-').gsub(/[^0-9a-z- ]/i, '') end end
namespace :dummy do desc "Hydrate the database with some dummy data to make it easier to develop" task :reset => :environment do # Write some Ruby to quickly create some records in your tables. # If it's helpful, you can use methods from the Faker gem for random data: # https://github.com/stympy/faker...
class ProMonitor class_attribute :current_aggregation def self.handle_action(action, model) begin return unless enabled? change = ProMonitor::Change.create(action, model) if ProMonitor.aggregating? ProMonitor.current_aggregation << change else publish_changes(...
class AddFieldsFromRrhh < ActiveRecord::Migration def change [:especialidades_medicas_cantidad_cad, :cirugia_general_cantidad_cad, :medicina_emergencia_cantidad_cad].each do |meta| add_column :providers, meta, :decimal unless column_exists?(:providers, meta) end end end
require "usersession" require "userdata" require "userids" require "userlogindata" require "configdata" require "participant" require "controller" require "connections" include Datasave ############################################################################## class AgeismExperiment ############################...
class J0850 attr_reader :options, :name, :field_type, :node def initialize @name = "Frequency of Indicator of Pain or Possible Pain in the last 5 days (J0850)" @field_type = DROPDOWN @node = "J0850" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("1", "...
class Api::V1::UserInterestsController < ApplicationController before_action :authenticate_user, only: [:update, :destroy] # Add a user's new selected interest. def create if !params["user"]["interests"].nil? UserInterest.create(user_id: current_user.id, interest_id: params["user"]["interests"]["...
require 'rails_helper' feature 'Product rendering', type: :feature do include_context 'synced products' scenario 'Visitor is presented with 10 products along with information' do visit '/' expect(page).to have_selector('.product', count: 10) expect(page).to have_selector('.product img', count: 10) ...
class Sistema::Usuario < ApplicationRecord has_secure_password before_create :generar_numero_cuenta, :asignar_saldo_regalo has_many :transacciones, class_name: 'Finanzas::Transaccion' has_many :depositos, class_name: 'Finanzas::Deposito' has_many :retiros, class_name: 'Finanzas::Retiro' has_many :transfer...
module Ricer::Plug::Settings class DurationSetting < FloatSetting def self.db_value(input) lib.human_to_seconds(input) end def self.to_label(input) lib.human_duration(input) end def self.to_hint(options) I18n.t('ricer.plug.settings.hint.duration', min: lib.human_du...
# frozen_string_literal: true # == Schema Information # # Table name: slots # # id :bigint not null, primary key # temp :string # created_at :datetime not null # updated_at :datetime not null # vending_machine_id :bigint # # Indexes # # inde...
require './hand' require './winning_strategy' require './prob_strategy' require './player' seed1 = Random.new(314) seed2 = Random.new(15) player1 = Player.new('Taro', WinningStrategy.new(seed1.rand(0..2))) player2 = Player.new('Hana', ProbStrategy.new(seed2.rand(0..2))) 100.times do |i| next_hand1 = player1.next_h...
class TasksController < ApplicationController before_action :authenticate_user! before_action :load_task, only: %i[update destroy] before_action :load_report, only: %i[create update] after_action :publish_task, only: [:create] respond_to :js def create @task = @report.tasks.new(task_params.merge(user...
require 'rspec' require_relative '../../src/core/object_change' describe ObjectChange do context 'Test object change on custom class object' do before do class MyObject attr_accessor :internal_var def initialize @internal_var = 1 end end @custom_class_object =...
# frozen_string_literal: true require 'spec_helper' describe 'mongocryptd prose tests' do require_libmongocrypt require_enterprise min_server_version '7.0.0-rc0' include_context 'define shared FLE helpers' include_context 'with local kms_providers' let(:mongocryptd_uri) { 'mongodb://localhost:27777' } ...
require 'spec_helper' describe 'scopes' do let!(:user1) { User.create! :name => 'Mr. White' do |user| user.properties(:dashboard).theme = 'white' end } let!(:user2) { User.create! :name => 'Mr. Blue' } it "should find objects with existing properties" do expect(User.with_properties).to eq([user1]) end ...
FactoryGirl.define do factory :article do tag_list 'tag1, tag2' sequence(:article_type) {|n| n} sequence(:link) { |n| "http://vimeo.com/1228033#{n}" } end end
require 'open-uri' require 'json' module Location class GoogleAPI def initialize @root = "https://maps.googleapis.com/maps/api/geocode/json?address=" end def set_location(address) @search = address @search.sub! ' ', '+' @request_url = @root + @search fetch_data end def fetch_data @data =...