text
stringlengths
10
2.61M
class ElementsController < ApplicationController before_filter :set_element, :only => [:create] before_filter :get_topic, :only => [:index,:create,:topic] def index @element_types = ElementType.find(:all).collect{|et| et unless @topic.element_types.include? et }.compact render :layout => false end def c...
require 'spec_helper' describe EssayDetail::Transcript do let(:issue) { double(Issue, id: 1, friendly_id: 'fid')} let(:essay) { double(Essay, embed: "embed", alt_body: double(MarkdownContent, content: "alt_body"), issue: issue) } subject { described_class.new(essay) } describe 'self_render' do it "inst...
require 'rails_helper' describe BankStatement do context 'with invalid attribute' do before :all do @bank_statement = BankStatement.new end it 'should not be valid' do @bank_statement.valid? @bank_statement.errors.full_messages.should match_array([ "Bank code is missing", ...
class Community::BaseController < ApplicationController layout 'community' #before_filter :parse_query, :filter_customer_cid before_filter :parse_query, :authenticate_openid!, :except => [ :select_instance, :echo ] before_filter :oauth_38, :only => [ :echo ] after_filter :track_logger helper_method :curren...
module Bosh::Director::Links class LinksParser include Bosh::Director::ValidationHelper MANUAL_LINK_KEYS = %w[instances properties address].freeze class LinkProvidersParser include Bosh::Director::ValidationHelper def initialize @logger = Bosh::Director::Config.logger @link_h...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2018-2020 MongoDB 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 # # U...
class TranslateForm include ActiveModel::Model FIELDS = %i[column_name locale column_value].freeze attr_accessor :record, *FIELDS def initialize(attributes) super self.locale ||= I18n.locale self.column_value ||= record.send("#{column_name}_backend").read(locale) end def save record.send...
class UserMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.user_mailer.signup.subject # def signup(user) @user = user @greeting = "Thanks for signing up! Your email address is #{@user.email}." mail( to: @user...
class ExpensesController < ApplicationController def expenses @category = 'gerais' @expenses = Expense.where(category: @category) @report = true @title = 'Despesas' render :index end def advances @category = 'vale funcionario' @expenses = Expense.where(category: @category) @report = true @title =...
require './canhelplib' require 'csv' module CanhelpPlugin include Canhelp def self.get_teacher_count( canvas_url=prompt(:canvas_url), account_id=prompt(:account_id), teacher_role_id = prompt(:teacher_role_id) ) token = get_token subaccount_ids = get_json_paginated(token, "#{canvas_url}/api/v...
if node.has_key?(:website) website = node[:website] directory website[:log_dir] do owner "root" group "root" mode "0755" action :create not_if "test #{website[:log_dir]}" end web_app website[:server_name] do template "site.conf.erb" server_name website[:serve...
# ============================================================================== # test - active record test # ============================================================================== require 'test_helper' require 'active_record' db = :sqlite3 silence_warnings do ActiveRecord::Migration.verbose = false Acti...
class AddOwnerRanks < ActiveRecord::Migration[5.2] def change create_table "draft_owner_ranks", id: :integer, force: :cascade do |t| t.integer "owner_id", default: 0 t.integer "draft_player_id", default: 0 t.integer "overall", default: 9999 t.datetime "created_at" t.datetime "updated...
log " ********************************************** * * * Recipe:#{recipe_name} * * * ********************************************** " thisdir = node[:clone12_2][:machprep][:wo...
class CreateServices < ActiveRecord::Migration[5.1] def change create_table :services do |t| t.string :name t.references :equipment, foreign_key: true t.references :company, foreign_key: true t.references :costumer, foreign_key: true t.date :done_at t.date :next_service ...
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string not null # description :text # created_at :datetime not null # updated_at :datetime ...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
class ChatShuttleGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) hook_for :orm end
module VotableControllerMixin def submit_upvote(model, user) vote(model, user, 'up') end def submit_downvote(model, user) vote(model, user, 'down') end private def vote(model, user, direction) # Make sure we've specified a direction raise "No direction parameter specified to #vote action."...
$imported = {} if $imported == nil $imported["H87_Escape"] = true #=============================================================================== # ** Probabilità di fuga ** # Versione: 1.1 (19/11/2019) # Difficoltà utente: ★★ #=============================================================================== # DESCRIZIO...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB 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 # # U...
class ShowProgramTag < ActiveRecord::Base belongs_to :show_program belongs_to :tag belongs_to :api_user attr_accessible :show_program, :tag, :api_user validates :show_program, :presence => true validates :tag, :presence => true validates :api_user, :presence => true # validates :api_user...
class CreateHistories < ActiveRecord::Migration def change create_table :histories do |t| t.belongs_to :clinic t.belongs_to :patient t.text :pathological t.text :nonpathological t.text :family t.text :surgical t.text :allergies t.text :medicines t.float :weigh...
require 'rails_helper' feature 'Confirm step' do let!(:address) { create(:address, address_type: 'both') } let!(:book) { create(:book) } let!(:order_item) { create(:order_item, book: book) } background do @user = create(:user) login_as(@user, scope: :user) @order = create(:order, order_items: [ord...
# frozen_string_literal: true # == Schema Information # # Table name: stations # # id :bigint not null, primary key # free_bikes :integer # latitude :float # longitude :float # name :string # sid :string # created_at :datetime not null # updated_at :datetime no...
ActiveAdmin.register Genre do permit_params :genre end
#### # # AccountDebit # # Debits due on an account - structure used for display in a view page # #### # class AccountDebit include Comparable attr_reader :amount, :date_due, :charge_type, :property_refs def initialize(date_due:, charge_type:, property_ref:, amount:) @date_due = date_due @charge_type = cha...
# frozen_string_literal: true require "active_support/core_ext/module/attribute_accessors" module ActiveRecord module AttributeMethods module Dirty extend ActiveSupport::Concern include ActiveModel::Dirty included do if self < ::ActiveRecord::Timestamp raise "You cannot inc...
require "rails_helper" describe DealCards, type: :service do fixtures :all let(:game) { Game.create! } let(:base_round) { game.rounds.create!(odd_players_score: 0, even_players_score: 0, order_in_game: 0) } let(:round) ...
# frozen_string_literal: true require 'structures/queue' RSpec.describe Structures::Queue do context 'when empty' do subject(:empty_queue) { described_class.new } it 'is empty' do expect(empty_queue).to be_empty end describe '#poll' do it 'raises an error' do expect { empty_que...
class AddUpdatedAt < MassMigrator::Migration def up add_column table_name, :updated_at, DateTime end def down drop_column table_name, :updated_at end end
require 'spec_helper' describe PartnerAccount do subject { FactoryGirl.create :partner_account } it 'always subscribes to unlimited plan by default' do subject.subscription.plan.should be_unlimited end end
Given /^Navigate to Index Page$/ do visit root_path end When /^I click on Organization Menu and click on Create New Organization sub menu$/ do within("#org") do click_link 'orga' end within("#neworg") do click_link 'orgnew' end end Then /^I should see Organization Form$/ do page.should have_content('City') ...
require 'prawn_charts/components/component' module PrawnCharts module Components # Component used to limit other visual components to a certain area on the graph. class Viewport < Component include PrawnCharts::Helpers::Canvas def initialize(*args, &block) super(*args) self.co...
module Student::BookBorrow::BookBorrowHelper def pre_processing case action_name when 'create' @action = Create.new(params: params) when 'index' @action = Index.new(params: params) when 'destroy' @action = Destroy.new(params: params) end implementation end def implement...
# A representation of the database view for Q-V Mapping # # This cannot be used for creating, updating or deleting, but provides # a quick way to view question-variable mapping. # # === Properties # * id # * source # * variable class QvMapping < ReadOnlyRecord # Use id as a primary key self.primary_key = :id # E...
module Microprocess module Protocol PROTOCOL_LINE_MAX = 1.kilobytes macro_def :line do |options| i = options.fetch(:i, :chunk) o = options.fetch(:o, :line) max = options.fetch(:max, PROTOCOL_LINE_MAX) @line_buffer = "" on i do |chunk| if chunk.nil? emit(o, ...
require "rails_helper" feature "react finds questionsets_controller" do before(:each) do Paragraphtype.create(name: "Introduction") Questionset.create( paragraphtype_id: 1, name: "Vassar HIST 454 Penguin Introduction" ) end scenario "#new has correct path" do visit new_questionset_pa...
require 'test_helper' class IncidentfollowupsControllerTest < ActionDispatch::IntegrationTest setup do @incidentfollowup = incidentfollowups(:one) end test "should get index" do get incidentfollowups_url assert_response :success end test "should get new" do get new_incidentfollowup_url ...
#GET request get '/sample-8-how-to-return-a-url-representing-a-single-page-of-a-document' do haml :sample08 end #POST request post '/sample-8-how-to-return-a-url-representing-a-single-page-of-a-document' do #Set variables set :client_id, params[:clientId] set :private_key, params[:privateKey] set :guid, para...
require 'spec_helper' require 'kintone/api/guest' require 'kintone/api' describe Kintone::Api::Guest do let(:target) { Kintone::Api::Guest.new(space, api) } let(:space) { 1 } let(:api) { Kintone::Api.new("example.cybozu.com", "Administrator", "cybozu") } describe "#get_url" do subject { target.get_url(com...
# encoding: utf-8 class CreateMailTemplates < ActiveRecord::Migration def change create_table :mail_templates do |t| t.string :title, null: false, default: "" t.text :content, null: false, default: "" t.datetime :opened_at, null: true t.datetime :closed_at, null: true t....
require 'test_helper' class TodoitemTest < ActiveSupport::TestCase test 'Should not save todoitem without todo' do todo = Todoitem.new assert_not todo.save end test 'Should save valid todo item' do todo = Todoitem.new todo.todo = 'sample checklist' todo.task_id = tasks(:two).id assert to...
class Manual < ActiveRecord::Base belongs_to :tag validates_presence_of :tag_id, :iteration_id, :scenario validates_numericality_of :jira, :allow_nil => true # validates_numericality_of :bug, :allow_nil => true validates_numericality_of :count, :allow_nil => true named_scope :fail, :conditions => {:st...
class AdminController < ApplicationController before_filter :authenticate def authenticate authenticate_or_request_with_http_basic('Administration') do |username, password| password = Digest::MD5.hexdigest(password) username == 'username' && password == '5f4dcc3b5aa765d61d8327deb882cf99' end e...
#Some of the basic math methods you will need for simple to more complex calculations puts 5 ** 2 # exponent so 5 to the 2nd power is 25 puts 16 ** 0.5 # output will be 4 -- to get the square root of any number..( number to the power of 0.5) puts 7 / 3 # out put will give you 2 as 3 goes in to 7 a total of 2 times...
class UserRegistrationType < User attr_accessible :password, :password_confirmation validates :password, presence: true validates :password_confirmation, presence: true validates :email, presence: true, email: true end
class Customer < User has_many :events def event_requests events.inject([]) {|requests, e| requests += e.event_requests} end end
require_relative 'spec_helper' describe 'call_next' do context 'the prototyped object has an internal prototype' do context 'with params' do it 'calls the next implementation' do saludador_normal = prototyped saludador_normal.saludar = proc { |nombre| "Hola #{nombre}." } expect(salu...
class RawCommand def initialize(unit, options = {}) @unit = unit @command = options[:invoked_command] || :raws end def help "/#{self.command} <text to send> - sends the specified text 'raw'." end def command @command end def opmsg? false end # TODO: can we eliminate ...
class RegistrationsController < ApplicationController def create @event = Event.find(params[:event_id]) @user = User.find(params[:user_id]) registration = @event.registrations.create(user_id: @user.id) if registration.save flash[:success] = "You're going to #{@event.name}!" redirect_to ev...
class Dentist < ActiveRecord::Base has_many :patients has_secure_password validates_uniqueness_of :username validates_presence_of :name, :username, :email, :password end
module RSence module Plugins # Include this module in your plugin class to automatically create, update and connect/disconnect a sqlite database file. # # The Plugin instances including this module will have a +@db+ Sequel[http://sequel.rubyforge.org/] object referring to the sqlite datab...
require 'formula' class Gflags < Formula homepage 'http://code.google.com/p/google-gflags/' url 'https://gflags.googlecode.com/files/gflags-2.0.tar.gz' sha1 'dfb0add1b59433308749875ac42796c41e824908' def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make i...
class Oystercard attr_reader :balance attr_reader :in_use attr_reader :entry_station attr_reader :exit_station attr_accessor :journeys LIMIT = 90 MINIMUM_FARE = 1 def initialize @balance = 0 @in_use = false #@entry_station = nil #@exit_station = nil @journeys = nil end def t...
class Project < ApplicationRecord has_and_belongs_to_many :tags scope :filter, -> (tag_id) { joins(:tags).where("tags.id = ?", tag_id) } # Scope eh uma ferramenta fornecida pelo rails em que podemos criar um metodo # (nesse caso filter) para fazermos uma "query". # Então se escrevermos Project.filter(3) teremos t...
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new @user.password = params[:user][:password] @user.username = params[:user][:username] if @user.save redirect_to root_path, notice: "User account created!" else render 'new' end end def show ...
class Card < ApplicationRecord has_many :cards, through: :decks end
module API module V1 class Base < Dispatch format :json version 'v1' default_error_formatter :json content_type :json, 'application/json' rescue_from :all do |e| eclass = e.class.to_s status = case when eclass.match('RecordNotFound'), e.message.matc...
# frozen_string_literal: true require_relative '../helpers/spec_helper.rb' require_relative '../helpers/vcr_helper.rb' require_relative '../helpers/database_helper.rb' describe 'Integration Tests of MLB API and Database' do VcrHelper.setup_vcr DatabaseHelper.setup_database_cleaner before do VcrHelper.confi...
class Answer < ActiveRecord::Base belongs_to :question belongs_to :user has_many :likes, dependent: :destroy has_many :liked_by, through: :likes, source: :user validates_length_of :contents, minimum: 1, allow_blank: false, message: "is required" def accept self.accepted = true self.user.add_points ...
# frozen_string_literal: true class DateTimePickerInput < InputGroupInput def new_html_options super.merge(autocomplete: 'off', data: { bs_datepicker: 'date' }) end def prepend_icon 'calendar' end def input_group_append @builder.text_field("#{attribute_name}_time", new_h...
Given /^I visit (.*?) page$/ do |path| case path when 'sign up' then visit(new_user_registration_path) when 'sign in' then visit(new_user_session_path) when 'refinery' then visit('/refinery') else visit(eval("#{path}_path")) end end
require 'spec_helper' describe APICoder::Registry do subject { described_class.new(:Test) } it { should delegate_method(:key?).to(:items) } it { should delegate_method(:clear).to(:items) } it { should delegate_method(:find).to(:values) } it { should delegate_method(:each).to(:values) } it 'should alias #...
class CreateSites < ActiveRecord::Migration def change create_table :sites do |t| t.string :name #t.string :subdomain_name # I do not know if domain name should be separated out. But I will separate the storage for convenience. t.string :hostname # Avoiding using the naked word domain/subdomain ...
class Reservation < ActiveRecord::Base belongs_to :restaurant belongs_to :user #validate :date validate :not_in_past validate :availability validates :party_size, :presence=>true, :numericality => {:only_integer=>true} private def availability if !restaurant.availability(party_size, party_time) erro...
class CardMailer < ApplicationMailer def cards_for_review @users = User.with_unreviewed_cards @users.each do |user| @user = user mail(to: @user.email, subject: 'You have cards for review') end end end
namespace :menu do namespace :allmenus do desc "Add menus for a city" task :import_city do city = ENV["CITY"].to_s # e.g. chicago state = ENV["STATE"].to_s # e.g. il isleep = ENV["SLEEP"] ? ENV["SLEEP"].to_i : 3 limit = ENV["LIMIT"] ? ENV["LIMIT"].to_i : 10 ...
class Admin::VenuesController < Admin::BaseController before_action :_set_venue, except: %i[index new create] def index @venues = Venue.all end def show; end def new @venue = Venue.new render partial: 'form', layout: false end def edit render partial: 'form', layout: false end # J...
# Suspect: skin, eye, gender, hair, name # Guess_who: number_of_guesses, guilty person, suspects # Guess_who # 1. Creates suspects, put into suspects array # 2. Randomly selects guilty person # 1. Print out list of suspects # 2. User chooses an attribute (skin, eye, gender, or hair) # 3. Choose _eye_ color (brown...
# frozen_string_literal: true ROM::SQL.migration do up do alter_table :coin_insertions do drop_column :coin_id end drop_table :coins rename_table :coin_insertions, :coins alter_table :coins do add_column :denomination, String, null: false, index: true end end down do r...
require 'rails_helper' describe 'A visitor' do context 'visits stations show page with station name url' do it 'sees stations with name, dock count, city, installation date, longitude and latitude' do station_1 = Station.create!(name: 'City hall', dock_count: 20, city: 'San Jose', installation_date: Time.n...
require 'test_helper' class EmployerInfosControllerTest < ActionController::TestCase setup do @employer_info = employer_infos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:employer_infos) end test "should get new" do get :new assert...
class AddAuthenticateToUsers < ActiveRecord::Migration[5.1] def self.up change_table :users do |t| t.string :encrypted_password, limit: 128 t.string :session_token, limit: 128 t.datetime :current_sign_in_at t.string :current_sign_in_ip, limit: 128 t.datetime :last_sign_in_at t....
def line(katz_deli) if katz_deli.count == 0 puts "The line is currently empty." else line = "The line is currently:" katz_deli.each_with_index do |value, index| line << " #{index + 1}. #{value}" end puts line end end def take_a_number(katz_deli, name) katz_deli.push(name) gree...
require "helpers/integration_test_helper" class TestRoutes < FogIntegrationTest def setup @subject = Fog::Compute[:google].routes end def test_all assert_operator(@subject.all.size, :>=, 2, "Number of all routes should be greater or equal than 2 - default GW and default routes") en...
require 'test_helper' class GuarderiaControllerTest < ActionDispatch::IntegrationTest setup do @guarderium = guarderia(:one) end test "should get index" do get guarderia_url assert_response :success end test "should get new" do get new_guarderium_url assert_response :success end te...
class Category < ApplicationRecord has_many :items validates :name, uniqueness: true end
#!/usr/bin/ruby require "mysql2" require_relative "SampleWeights" class WaterSample def initialize(id, site, chloroform = 0, bromoform = 0, bromodichloromethane = 0, dibromichloromethane = 0) @id = id @site = site @chloroform = chloroform @bromoform = bromoform @bromodichloromethane = bromodichl...
require_relative 'train' class PassangerTrain < Train def initialize(company_name, number) @type = :passenger_train super end def add_wagon(company_name = 'unknown') if speed.zero? wagon = PassangerWagon.new(company_name) self.wagon << wagon else puts 'Поезд всё еще в движении,...
class Panel::BaseController < ApplicationController layout 'application_panel' before_action :authenticate_user! end
class HomeController < ApplicationController def index if guest_signed_in? @home_bg = 'home-in-bg' @title = "Welcome, #{current_guest.first_name}" else @title = 'Home' @home_bg = 'home-bg' end end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Fields::Types::ActiveRecordEnum, active_record: true do it_behaves_like 'a generic field type', :string_enum_field describe '#pretty_value' do context 'when column name is format' do before do class FormatAsE...
class Step100Proc < ActiveRecord::Migration def up connection.execute(%q{ CREATE OR REPLACE FUNCTION public.proc_step_100( process_representative integer, experience_period_lower_date date, experience_period_upper_date date, current_payroll_period_lower_date date, curre...
module Alf class Environment # # Specialization of Environment to work on files of a given folder. # # This kind of environment resolves datasets by simply looking at # recognized files in a specific folder. "Recognized" files are simply # those for which a Reader subclass has been previously...
Given(/^open page ([^"]*)$/) do |url| DRIVER.get(url) end When(/^create screenshot$/) do screenshot end And(/^input to search line "([^"]*)"$/) do |text| DRIVER.find_element(:css, '.gLFyf.gsfi').send_keys(text) end And(/^push a keyboard "([^"]*)"$/) do |key| DRIVER.action.send_keys(elementVisible, :return).p...
When(/^I make a request after logging in$/) do User.create!(email: 'bob@example.com', password: 'secret') page.driver.post "/api/authenticate", { email: 'bob@example.com', password: 'secret' } @last_response = page.driver.get "/api/jobs" end When(/^I make a request without logging in$/) do @last_re...
# frozen_string_literal: true Factory.define(:product) do |f| f.name { fake(:commerce, :product_name) } f.price { fake(:commerce, :price).to_d } f.quantity_in_stock { fake(:number, :within, range: 1..10) } end
And(/^I fill in item mass edit fields:$/) do |table| table.raw.each do |label, value| field = label.gsub(' ', '_').underscore check "mass_action_allow_blank_#{field}" fill_in "mass_action_#{field}", with: value end end
class ChangeVisitorTeamIdToBeStringInGames < ActiveRecord::Migration[6.0] def change change_column :games, :visitor_team_id, :string end end
class AddUuidToFaxAccounts < ActiveRecord::Migration def change add_column :fax_accounts, :uuid, :string end end
module Report module Timelog class TaskTimelogGeneralInfo def data *args task_id = args.first timelogs = ::Timelog.eager_load(:user).where("task_id = ? AND stopped_at IS NOT NULL", task_id) count = timelogs.count total_time = 0 total_time = timelogs.collect { |t| t...
Rails.application.routes.draw do devise_for :users, skip: [:registrations] # defaults to dashboard root :to => redirect('/singleview') # view routes get '/singleview' => 'singleview#index' resources :pieces do collection do get :archived end post 'restore' end resources :clients d...
# Pling Plang Plong # # Write a program that converts a number to a string per the following rules: # # If the number contains 3 as a factor, output 'Pling'. If the number contains 5 as a factor, output 'Plang'. If the number contains 7 as a factor, output 'Plong'. # # If the number does not contain 3, 5, or 7 as a fac...
class Director extend Creation::ClassMethods include Creation::InstanceMethods attr_accessor :name attr_reader :movies @@all = [] def initialize(name) @name = name @movies = [] @@all << self end def add_movie(movie) if !@movies.include?(movie) ...
class GigsController < ApplicationController def index @gigs = Gig.asc(:created_at) end end
# Strings like 'yes' and 'true' and '1' are true; other stuff is false class String def to_bool if to_i.zero? %w[yes y true on].any? {|s| s == downcase} else true # strings like "1" end end end # 0 is false; other number true class Integer # rubocop: disable Lint/UnifiedInteger def to_boo...
# lib/vagrant-yml/plugin.rb require "vagrant" module VagrantPlugins module VagrantJson class Plugin < Vagrant.plugin('2') name 'VagrantJson' description "The `json` command gives you a starting point for json configurations" config(:json) do require_relative "config/json" Conf...
require 'test_helper' class UUIDTest < ActiveSupport::TestCase # test that all models the have a uuid column included the HasUuid module def test_has_uuid_with_database Rails.application.eager_load! ApplicationRecord.descendants.each do |model| table_uuid_column_exists = model.column_names.include?("...
require_dependency "account_controller" module PluginStronger module AccountController # Maximum number of failed attempts before locking MAX_FAILED_ATTEMPTS = 5 LOCKED_FOR_MINUTES = 20 # Patch #invalid_credentials to add a brute force attack counter # # The counter increments each time the...