text
stringlengths
10
2.61M
class Genre < ApplicationRecord has_many :items # 如想要刪除該Genre時,底下的items也一並刪除,加入dependent: :destroy, validates_presence_of :name end
# frozen_string_literal: true # class creates major model class Major < ActiveRecord::Base belongs_to :department has_many :students end
class CreateCombatStats < ActiveRecord::Migration def change create_table :combat_stats do |t| t.string :category t.string :status t.integer :range t.integer :range_bonus t.integer :aoe t.integer :aoe_bonus t.integer :damage t.integer :damage_bonus t.belongs_t...
class AddAuthorRefToTests < ActiveRecord::Migration[5.2] def change add_reference :tests, :author, foreign_key: { to_table: :users } # remove_column :tests, :user_id, :integer # remove_column :tests, :test_author_id, :integer end end
module Api module V1 class ServicesController < ApplicationController def index @service = Service.all render json: {status: 'SUCCESS', message:'Services lock and loaded', data:@service}, status: :ok end def show @service = Service.find(params[:id]) render json: {status: 'SUCCESS'...
module God module System @@kb_per_page = 4 # TODO: Need to make this portable @@hertz = 100 @@total_mem = nil @@num_of_cpu = nil @@uptime = nil @@meminfo = nil MeminfoPath = '/proc/meminfo' CpuinfoPath = '/proc/cpuinfo' UptimePath = '/proc/uptime' LoadAveragePath = '/pro...
namespace :station_attendant do desc "Extracts and loads all agencies from the GTFS Data Exchange API." task :find_data_exchange_feeds => :environment do DataExchangeExtractor.perform end desc "Extracts and loads all agencies and feeds from the Google Transit Data Feed wiki." task :find_google_transit_da...
require 'spec_helper' describe GdprService do let(:service) { described_class.new(user, ip) } let(:user) { nil } describe '#cookies_allowed?' do subject { service.cookies_allowed? } context 'UK' do let(:ip) { '82.1.185.172' } it 'should not allow cookies' do expect(subject).to eq f...
class AddDeletedAtToUsersCourses < ActiveRecord::Migration def change add_column :users_courses, :deleted_at, :datetime add_index :users_courses, :deleted_at end end
class AddAttachmentHighlightedToConfiguration < ActiveRecord::Migration def self.up add_column :configurations, :highlighted_file_name, :string add_column :configurations, :highlighted_content_type, :string add_column :configurations, :highlighted_file_size, :integer add_column :configurations, :highl...
require 'rails_helper' RSpec.describe "Users", type: :request do describe "GET /users" do subject { get '/users' } it_behaves_like 'HTTP 200 OK' end describe 'GET /users/:id' do context 'when user exists' do subject { get "/users/#{user.login}" } let(:user) { create(:user) } it_...
def check_customer_token if @customer_token != nil @has_customer_token = true else @has_customer_token = false end end def check_payment_token if @payment_token != nil @has_payment_token = true else @has_payment_token = false end end # This either loads the merchant value from the directory object or se...
require 'test_helper' class SurfCampReviewTest < ActiveSupport::TestCase def setup @user = users(:jeramae) @surf_camp = surf_camps(:first_surf_camp) @surf_camp_review = SurfCampReview.new(rating: 5, title: "Sample Review", comment: "Lorem ipsum", ...
class User < ActiveRecord::Base has_many :roles, dependent: :delete_all has_many :groups, through: :roles def self.import(file) CSV.foreach(file.path, headers: true) do |row| u = User.find_or_create_by(first_name: row['First Name'], last_name: row['Last Name']) g = Group.find_or_create_by(name: ...
class UserInfo attr_accessor :username, :password def initialize @username = "Ironhack" @password = "1234" @user_text = "" end def validation puts "What is your username? " username_input = gets.chomp puts "What is your password? " password_input = gets.chomp if username_input == @username && pass...
require 'id_generator' class Category attr_reader :id, :has_errors attr_accessor :name, :errors def initialize(name:) @id = generate_id @name = name @errors = [] @has_errors = false add_error if name.nil? end def self.create(name) new(name: name) end private def add_error ...
class ParamountMailer < ActionMailer::Base destination = false default from: 'inqueries@paramount.com.ph' layout 'mailer' def contact_email(contactData) @contactData = contactData @destination = destination(contactData[:sourcePage]) if @destination != false subject = contactData[:contactName] + "(" + con...
require_relative 'menumodule' class ChangePaymentDueDatePage include PageObject include MenuPanel include AccountsSubMenu include ServicesSubMenu include MyInfoSubMenu include MessagesAlertsSubMenu include PaymentsSubMenu table(:heading, :id => 'tblMain') select_list(:futureduedate...
task :populate_future_revenues => :environment do Stripe.api_key = AppConfig.stripe[:api_key] if File.exist?(Rails.root.to_s + '/log/populate_future_revenues.log') File.delete(Rails.root.to_s + '/log/populate_future_revenues.log') end FutureRevenue.delete_all! Account.all.each do |account| begin ...
# frozen_string_literal: true require "spec_helper" # These specs run on all Postgres versions RSpec.describe ActiveRecord::ConnectionAdapters::PostgreSQLAdapter do let(:table_name) { "t_#{SecureRandom.hex(6)}" } let(:child_table_name) { "t_#{SecureRandom.hex(6)}" } let(:sibling_table_name) { "t_#{SecureRandom....
class Product < ApplicationRecord has_many :line_items has_many :orders, through: :line_items before_create :has_avatar before_update :has_avatar before_destroy :ensure_not_referenced_by_any_line_item extend FriendlyId friendly_id :title, use: :slugged validates :title, :description, presence: true...
class ChargesController < ApplicationController layout 'application' before_action :require_user, only: [:new, :create] before_action :set_user, only: [:new] def new @@user = @user end def create # Amount in cents @amount = @@user.balance*100 customer = Stripe::Custome...
option = { "r" => "rock", "p" => "paper", "s" => "scissor"} def given_answer(x) case x when "r" puts " Rock, Crashes Scissor!" when "s" puts " Scisor, Cuts Paper!" when "p" puts " Paper Cuts Rock!" end end loop do begin puts "Choose R-ock, P-aper, S-cissor" answer = gets.chomp.down...
class User < ApplicationRecord include Rails.application.routes.url_helpers validates :name, presence: true, length: {maximum: 20} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i.freeze validates :email, length: {maximum: 255}, format: {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false} ...
class StoresController < ApplicationController before_action :set_store, only: [:show, :edit, :update, :destroy] def index @stores = current_user.stores end def new @store = Store.new @store.sellers.build end def create @store = Store.new(store_params) if params[:add_new_seller] ...
require 'spec_helper' describe HighriseCRM::Client do subject { HighriseCRM::Client.new } let(:token) { '12345abcde' } let(:base_site){ 'https://test.highrisehq.com' } let(:client) { HighriseCRM::Client.new(base_site, token) } let(:bad_token) { '12345abcd'} let(:bad_client) { HighriseCRM::Client.new(base_s...
require 'spec_helper' require_relative '../checkout' describe Checkout do let(:items) { %w(VOUCHER TSHIRT VOUCHER VOUCHER MUG TSHIRT TSHIRT) } context 'when all the items are valid' do context 'and bulk_discount and two_for_one are active' do it 'calculates the total with discounts' do checkout ...
class User < ApplicationRecord def self.from_omniauth(hash) where(hash.slice(:uid)).first_or_initialize.tap do |user| user.uid = hash.uid user.email = hash.info.email user.token = hash.credentials.token user.expires_at = Time.at(hash.credentials.expires_at) user.save! end end e...
# create the card class class Card attr_accessor :suit, :value def initialize(value, suit) @suit = suit @value = value end def to_s "#{value} of #{suit}" end end # create a deck class and populate with all cards class Deck attr_accessor :cards def initialize @cards = [] suits = ...
# frozen_string_literal: true # Copyright (C) 2015-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 # # Unless required by a...
module PipefyAdapters require 'rest_client' class BaseAdapter include ApplicationHelper cattr_accessor :base_url, :request self.base_url = ENV.fetch("PIPEFY_API_BASE_URL") def self.execute_request(pipefy_acess_token, values) begin headers = {:content_type => 'application/json', ...
#We know the problem will be solved when each input equals the correct output for the aformentioned rules #We want to use the software by inputing user prompts and relay back the correct output #Set ready to quit variable to false #display welcome message #get a user input #Begin while condition with ready to quit va...
class AddRejectedToStates < ActiveRecord::Migration[5.2] def change add_column :states, :rejected, :boolean, default: false end end
require 'spec_helper' RSpec.describe Indocker do before { setup_indocker(debug: true) } it "returns the list of invalid and missing containers" do result = Indocker.check(servers: [:external]) expect(result[:missing_containers]).to include("external_bad_container_start") end end
class ChangeGameTeamsName < ActiveRecord::Migration def change rename_table :game_team, :game_teams end end
# -*- coding: utf-8 -*- # # Copyright 2013 whiteleaf. All rights reserved. # require_relative "../inventory" require_relative "../commandbase" module Command class Init < CommandBase def self.oneline_help if Narou.already_init? "AozoraEpub3 の再設定を行います" else "現在のフォルダを小説用に初期化します" ...
class Product < ApplicationRecord has_attached_file :main_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :main_image, content_type: /\Aimage\/.*\z/ before_save :set_image_url private def set_image_url self.image_url ...
class AddNotesToBooks < ActiveRecord::Migration def change add_column :books, :notes, :string add_column :books, :author_id, :integer remove_column :books, :author_name, :string end end
require 'spec_helper' RSpec::Matchers.define :all_be_close do |expected| match do |actual| # Wrap in Array to also use for scalars actual = [actual] expected = [expected] return false unless _same_shape?(actual, expected) # TODO: allow custom absolute tolerance. For now us...
class Address < ApplicationRecord belongs_to :customer validates :postal_code, presence: true, length: { is: 7 }, numericality: { only_integer: true } validates :address, :name, presence: true end
require_relative "spec_helper" Sequel.extension :migration describe "pg_enum extension" do mod = Module.new do private def schema_parse_table(*) [[:a, {:oid=>1, :type=>:enum}], [:b, {:oid=>1234}]] end def _metadata_dataset super.with_fetch([[{:v=>1, :enumlabel=>'a'}, {:v=>1, :enumlabel=>...
class CardsController < ApplicationController protect_from_forgery with: :null_session def index @cards = Card.where get_conditions params p @cards render json: @cards end def create @card = Card.new params.require(:card).permit(:title, :card_group_id) if @card.save render json: { ...
#!/usr/bin/env ruby libdir = File.dirname(__FILE__) + "/../lib" libdir = File.expand_path(libdir) $: << libdir require 'pcapr_local' require 'optparse' PcaprLocal::Config.assert_environment include PcaprLocal config_file = nil opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [-f config_file]" ...
require_relative '../lib/grid.rb' require_relative '../lib/ship.rb' class Game attr_accessor :command_line attr_reader :state, :shots STATES = %w(initialized ready error terminated gameover) GRID_SIZE = 10 HIT_CHAR = 'X' MISS_CHAR = '_' NO_SHOT_CHAR = '.' SHIPS_DEFS = [ { size: 4, type: 'Battle...
module IOTA module Models class Bundle < Base attr_reader :transactions, :persistence, :attachmentTimestamp def initialize(transactions) if transactions.class != Array raise StandardError, "Invalid transactions array" end @transactions = [] transactions.each...
# Author: Jim Noble # jimnoble@xjjz.co.uk # # Player.rb # # A Rock/Paper/Scissors player. # # Valid strategies include: R, r, P, p, S, s # # p = Player.new("Jim Noble", "r") # # puts p class Player attr_accessor :name, :strategy def initialize(name, strategy) @name = name @strategy = strategy end de...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Rider do it { should have_db_column(:first_name) } it { should have_db_column(:last_name) } it { should belong_to(:pickup_route_stop) } it { should belong_to(:dropoff_route_stop) } it { should validate_presence_of(:first_name) } it { sh...
Promotion.class_eval do has_attached_file :leaderboard has_attached_file :half_leaderboard has_attached_file :full validates_attachment_content_type :leaderboard,{:content_type=> ["image/png","image/jpg","image/jpeg"], :message => I18n::t('flash.image_not_correct_con...
class Player attr_accessor :name, :score, :is_human, :tag def initialize name, tag, is_human=false @name = name @is_human = is_human #is the user an human? @tag = tag # Each user has a tag @score = 0 end end
class Medium < ApplicationRecord belongs_to :media_provider belongs_to :game end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_action :require_login, except: [:home, :new, :create] def home if logged_in? ...
class OrderExecution < ApplicationRecord MAX_VALID_TIME = 5.minutes extend Enumerize include AASM validates_presence_of :user_id, :exchange_id, :action scope :unfinished, -> {where.not(status: 'done')} belongs_to :user belongs_to :trader enumerize :action, in: [:open_position, :close_position] aasm...
module Monsove class Filesystem # Initialize a ne Filesystem object. # # @return [Filesytem] def initialize end # Compress the dump to an tar.bz2 archive. # # @param [String] path the path, where the dump is located. # # @return [nil] def compress(path) Monsove.log...
module Netzke module Basepack # Common parts of FieldConfig and ColumnConfig class AttrConfig < ActiveSupport::OrderedOptions def initialize(c, data_adapter) c = {name: c.to_s} if c.is_a?(Symbol) || c.is_a?(String) c[:name] = c[:name].to_s self.replace(c) @data_adapter =...
require 'printrun/core' module Printrun include Core extend self # careful of the bug of sourcify with double quotes (if still there at time of reading)... # @example # Printrun.on(STDOUT) do # a = 3 # puts a # end def on(io, world = proc { binding }[], &block) i = 0 line_eval(world,...
class HistoryVideo < ActiveRecord::Base attr_accessible :user_id, :video_id belongs_to :video belongs_to :user end
require 'spec_helper' describe PostsController do describe 'GET query' do context "with a location, start, and end" do let(:location) {"Test Location"} let(:start) {Time.current} let(:end_time) {Time.current+3.hours} let(:post1) {} before do post1 get :query, :format...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :post do title "Post Title" link "http://post.link.com/hello.html" end end
class DropTokens < ActiveRecord::Migration[5.2] def change drop_table :tokens do t.references :user, foreign_key: true, null: false t.string :body, null: false t.datetime :last_used_at, null: false t.timestamps t.datetime :deleted_at t.index :deleted_at t.index :body, u...
require 'test_helper' class ChassisControllerTest < ActionDispatch::IntegrationTest setup do @chassis = chassis(:one) end test "should get index" do get chassis_index_url assert_response :success end test "should get new" do get new_chassis_url assert_response :success end test "sh...
FactoryGirl.define do factory :experience, class: Experience do association :experienceable, factory: :user description { "Experience #{rand 1000}" } end end
require "spec_helper" module Scenic module Adapters describe Postgres, :db do describe "create_view" do it "successfully creates a view" do Postgres.create_view("greetings", "SELECT text 'hi' AS greeting") expect(Postgres.views.map(&:name)).to include("greetings") end ...
class CreateJoinTableTeamsDivisions < ActiveRecord::Migration[5.2] def change create_join_table :teams, :divisions do |t| t.index [:team_id, :division_id] t.index [:division_id, :team_id] end end end
require 'rails_helper' RSpec.describe "As a user" do describe "when i visit the homepage and select a house" do scenario "i see count of members and list of members" do visit "/" click_on "Search For Members" expect(current_path).to eq("/search") expect(page).to have_content("21 members...
require 'rails_helper' RSpec.describe Ability, :type => :model do let(:user) { nil } subject(:ability) { Ability.new(user) } describe "as not-signed-in user" do it { should be_able_to(:index, Post.new) } it { should_not be_able_to(:show, Post.new) } end describe "as signed-in user" do let(:us...
class CreateContests < ActiveRecord::Migration[5.1] def change create_table :contests do |t| t.string :NameofContest t.string :ContestLevel t.string :ContestLocation t.string :NumberOfPlayers t.timestamps end end end
class Hindrance < ActiveRecord::Base belongs_to :hindrance_type has_and_belongs_to_many :characters has_and_belongs_to_many :modifiers scope :non_racial, -> { joins(:hindrance_type).where('hindrance_types.name != ?', 'Racial') } def self.method_missing(method_name, *args, &block) find_by(name: method_na...
cookbook_file "script to install Firefox" do source "gtk-firefox.sh" path "/tmp/gtk-firefox.sh" end bash "install_firefox" do user "root" cwd "/tmp" code <<-EOH . /tmp/gtk-firefox.sh EOH end
module V1 class TodosController < ApplicationController def index @todos = current_user.todos.order(created_at: :desc).all render json: @todos, each_serializer: TodoSerializer end def show @todo = Todo.find(params[:id]) render json: @todo, serializer: TodoSerializer end ...
#!/usr/bin/env gem build lib = File.expand_path '../lib', __FILE__ $:.unshift lib unless $:.include? lib require 'shopware/version' Gem::Specification.new 'shopware', Shopware::VERSION do |spec| spec.summary = 'Ruby API client and CLI for Shopware' spec.author = 'Maik Kempe' spec.email ...
class Vaga < ApplicationRecord belongs_to :apartamento validates_presence_of :local, :apartamento_id, :modelo_carro, :car_carro, :placa_carro end
class AddNicknameToIndexUsers < ActiveRecord::Migration[5.1] def change add_column :index_users, :nickname, :string end end
class User < ApplicationRecord has_many :group_users has_many :groups, through: :group_users has_many :messages, dependent: :delete_all end
class ChangeTermOfOrders < ActiveRecord::Migration[5.2] def change change_column :orders, :term, :string, default: "0" end end
require 'net/smtp' module Smitty def self.smtp_connect(server, port, ssl, username, password, ignorecert) begin smtp_server = server.nil? ? 'localhost' : server smtp_port = port.nil? ? 25 : port.to_i smtp_conn = Net::SMTP.new(smtp_server, smtp_port) if ssl if ignorecert ...
require 'spec_helper' describe UserProfile do before(:each) do @profile = Factory(:user_profile) end it { should belong_to(:user) } it { should belong_to(:avatar) } it { should validate_presence_of(:language) } it { should allow_value('en').for(:language) } it { should allow_value('ar').for(:languag...
module Refinery module Careers module Admin class CareersController < ::Refinery::AdminController crudify :'refinery/careers/career', :title_attribute => 'career_title' private # Only allow a trusted parameter "white list" through. def career_params ...
module Reportable def has_full_report? File.exists?(full_report_path) end end
# frozen_string_literal: true require 'rspec/sleeping_king_studios/concerns/shared_example_group' require 'support/examples' module Spec::Support::Examples module ContractBuilderExamples extend RSpec::SleepingKingStudios::Concerns::SharedExampleGroup shared_examples 'should delegate to #constraint' do ...
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
class ProductsController < InheritedResources::Base after_filter :update_cart_total, :only => [:add_to_cart, :remove_from_cart, :clear_cart] def filter_products @products = Product.order(:name) category_id = Category.where("name = :name", {:name => "#{params[:category]}"}).first.id @products = @pro...
Rails.application.routes.draw do get 'logs/index' get 'sales/index' get 'drivers/index' devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "indices#home" get 'drivers', to: 'drivers#index', as: 'drivers' get 'drivers/new'...
require 'rails_helper' RSpec.describe GameResult do let(:successful_result) { GameResult.new(success: true) } let(:game_full_result) { GameResult.new(success: false, error_type: :game_full) } describe '#success?' do it 'is successful' do expect(successful_result.success?).to be true end end d...
# require 'spec_helper' # describe RechargesController do # describe "GET #new" do # context "logged in" do # it "renders new template" do # testorder = FactoryGirl.create(:order) # ApplicationController.any_instance.stub(:current_user).and_return(testorder.user) # get :new, orderid...
class Ability include CanCan::Ability def initialize(user) user ||= Use.new cannot :manage, :all can :read, :all cannot :read, User if user.permissions.where(:name => "allow_importing_spare_part").count > 0 can :create, Inventory end if user.permissions.where(:name => "allow_w...
namespace :nofrag do desc 'Import Nofrag news' task(:import => :environment) do require 'rss' rss = RSS::Parser.parse('http://www.nofrag.com/fb/nofrag.rss', true) rss.items.each do |item| remote_id = /\/([0-9]+)\/$/.match(item.guid.content)[1].to_s.to_i begin ImportedNofragItem.c...
require 'test_helper' class EventTest < ActiveSupport::TestCase should have_one :ticket should have_many :conflicts_as_conflicting should have_many :conflicts should have_many :event_attachments should have_many :event_feedbacks should have_many :event_people should have_many :event_ratings should have...
# encoding: utf-8 require 'spec_helper' describe TTY::Table::Operation::Filter, '#call' do let(:object) { described_class } let(:field) { TTY::Table::Field.new('a1') } let(:filter) { Proc.new { |val, row, col| 'new' } } let(:value) { 'new' } subject { object.new(filter) } it 'changes field value' do ...
class SessionsController < ApplicationController skip_before_action :authenticate_user def login login_service = Login.new(params.permit(:name, :email, :password)) respond login_service.call end def refresh_token respond RefreshToken.new(params[:refresh_token]).call end end
# frozen_string_literal: true require_relative 'color' # Player class class Player private attr_reader :num public attr_accessor :name def initialize(name, num) @name = num == 1 ? name.yellow : name.red @num = num end def first? num == 1 end end
class Food < ApplicationRecord validates :name, :description, :date, presence: true mount_uploader :image, ImageUploader end
require "elevators/version" module Elevators class Elevator # TODO - would like to have a queue of request stops # TODO - would like to have functionality so that elevators can report # the cost for them to satisfy a new request. attr_accessor :current_floor attr_accessor :target_floor ...
class CreateFileExtensionCache < ActiveRecord::Migration[5.0] def change create_table :cache_file_extension_stats_by_collection, id: false do |t| t.integer :collection_id, index: true t.integer :file_extension_id t.string :extension t.integer :file_count t.decimal :file_size end ...
class RemoveColumn < ActiveRecord::Migration[5.2] def change remove_column :subs, :moderator_id end end
# frozen_string_literal: true require 'spec_helper' require 'vagrant-bolt/config' require 'vagrant-bolt/provisioner' describe VagrantBolt::Provisioner do include_context 'vagrant-unit' subject { described_class.new(machine, config) } let(:iso_env) do env = isolated_environment env.vagrantfile <<-VAGRAN...
require "rails_helper" RSpec.describe InvalidPhoneNumberResponse do describe "#to_s" do it "generates xml that contains a message" do result = described_class.new.to_s expect(result).to include("</Say>") end end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'pages#show' # get 'home', to: 'pages#about' get "/api/v1/pronostic", to: 'pages#api' end
require 'text' require 'twilio-ruby' describe Text do it { is_expected.to respond_to :time } it { is_expected.to respond_to :send_text} describe '#send_text' do it 'should send text when order is placed' do client = double :client allow(client).to receive_message_chain(:messages, :create) ex...
require 'rails_helper' require 'database_cleaner' RSpec.describe Api::V1::Items::MostRevenueController, type: :controller do describe "GET /items/most_revenue" do it "returns the top x items ranked by total revenue generated" do c1 = Customer.create c2 = Customer.create m1 = Merchant.create ...
# == Schema Information # # Table name: audit_items # # id :integer not null, primary key # audit_id :integer # paragraph_id :integer # created_at :datetime not null # updated_at :datetime not null # class AuditItem < ActiveRecord::Base # Relations/Associations with ot...