text
stringlengths
10
2.61M
require_relative 'app_spec_helper' describe "Delete" do describe "Delete Valid ID" do id = "56e40252133859262d000021" delete "/venues/#{id}" response = last_response it "should respond with status 204" do expect(response.status).to eql(204) end it "should respond with duration in th...
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken rescue_from Pagy::OverflowError, with: :render_pagination_error include Pagy::Backend around_action :switch_locale before_action :configure_permitted_parameters, if: :devise_controller?, except: :callback ...
class CreateContracts < ActiveRecord::Migration[6.0] def change create_table :contracts do |t| t.string :place t.string :name t.string :document_id t.integer :age t.string :marital_status t.integer :phone t.string :email t.string :service_to_hire t.string :car...
class CurrentUserSerializer < UserSerializer embed :ids, include: true attributes :email, :newUsername, :sfw_filter, :last_backup, :has_dropbox?, :has_facebook?, :confirmed?, :pro_expires_at, :import_status, ...
module Asyncapi::Server class JobWorker include Sidekiq::Worker sidekiq_options retry: false MAX_RETRIES = 2 def perform(job_id, retries=0) job = Job.find(job_id) runner_class = job.class_name.constantize job_status = :success job_message = runner_class.call(job.params) ...
class RemoveProjectConfirmationToProjects < ActiveRecord::Migration def change remove_column :projects, :project_confirmation, :boolean end end
class Offer < ActiveRecord::Base belongs_to :product has_one :counteroffer, dependent: :destroy end
require 'rails_helper' RSpec.describe Lesson, type: :model do it { is_expected.to validate_presence_of(:date_at) } it { is_expected.to validate_presence_of(:home_task) } it { is_expected.to validate_presence_of(:description) } it { is_expected.to allow_value('2021/04/21').for(:date_at)} end
#!/usr/bin/env ruby require 'optparse' require_relative 'lib/git_stat_tool_user' def get_user options = {} optparse = OptionParser.new do|opts| opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end options[:username] = false opts.on( '-u', '--username USERNAME', "GitHub username" ) do...
class AttachmentUploader < CarrierWave::Uploader::Base storage :qiniu def store_dir time = Time.now.strftime('%Y%m%d%H%M') "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/#{time}" end def filename original_filename end # def default_url # # For Rails 3.1+ asset pipeline compatibil...
class CreateEntries < ActiveRecord::Migration def change create_table :entries do |t| t.text :caption t.datetime :original_created_at t.string :source_name t.string :source_url t.string :title t.timestamps end end end
class AddColumnSpecialityToCostCenters < ActiveRecord::Migration def change add_column :cost_centers, :speciality, :string end end
require 'rails_helper' RSpec.describe Station, :type => :model do subject(:station) { create(:station) } it 'has the user' do expect(station.user).to be_a(User) end end
require 'active_collab/object' class ActiveCollab::Project < ActiveCollab::Object::Record include ActiveCollab::Object::Saveable has_routes({ :create => "/projects/add", :read => "/projects/:id", :update => "/projects/:id/edit", :index => "/projects" }) has_attributes :id, :name, :permal...
require 'data_mapper' class DmPortfolio include DataMapper::Resource validates_presence_of :weights validates_uniqueness_of :weights_md5_hash property :id, Serial property :weights, Json property :weights_md5_hash, String, index: true belongs_to :dm_efficient_frontier, r...
class Cell attr_accessor :row, :column, :content, :visited def initialize(row, column) @row = row @column = column @content = "#" @visited = false end def visited? @visited end def end? return true if @content == "E" return false end...
class BootstrapThumbnailCollectionRenderer < ResourceRenderer::CollectionRenderer::Base def render(&block) helper.capture do helper.content_tag(:div, class: 'row') do render_collection(&block) end end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Pitzi::V1::BaseAPI, type: :api do describe 'Configurations' do it 'has json format' do expect(described_class.format).to eq :json end it 'has v1 version' do expect(described_class.version).to eq :v1 end it 'mounts ...
require 'rails_helper' RSpec.describe Product, type: :model do before(:each) do @category = Category.new(name: 'furniture') @product = Product.new(name: 'big comfy couch', price_cents: 1000000, quantity: 2, category: @category) end describe 'Validations' do it 'should save a valid product' do ...
class ModifyRefernces < ActiveRecord::Migration[5.2] def self.up remove_reference :parking_slots, :floor, foreign_key: true add_reference :parking_slots, :block, foreign_key: true end def self.down add_reference :parking_slots, :floor, foreign_key: true remove_reference :parking_slots, :block, fo...
class RemoveNameFromPageAsset < ActiveRecord::Migration[5.0] def change remove_column :page_assets, :name, :string end end
#!/usr/bin/env ruby # RemoteObjectManager # # Copyright 2011 Voltaic # # 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 ...
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "superpowers" require "minitest/autorun" require 'rails' require 'rails/generators' class TestApp < Rails::Application config.root = File.dirname(__FILE__) end Rails.application = TestApp module Rails def self.root @root ||= File.expand_path...
class WorldMusicWorkshopRankService < ExperimentService class << self SONGS = 5 PAIRS = (0...SONGS).to_a.combination(3).to_a def create(options) raise NotFoundError.new('Experiment', 'Evaluation Not Finished') if Experiment.where( username: options['username'], model: 'WorldMusicWor...
module InterestedController extend ActiveSupport::Concern def create @interest = interest_class.new(interest_params) if @interest.save notification_worker_class.perform_async(@interest.id) acknowledgement_worker_class.perform_async(@interest.id) flash[:notice] = create_notice else ...
require 'dumped_api/operation' require 'dumped_api/import' module DumpedApi module Operations module GitRepos class Query < DumpedApi::Operation include Import['repositories.git_repos'] def call(params = {}) if language = params['language'] git_repos.by_language(lang...
require "rails_helper" RSpec.describe "Login Page" do before(:each) do @user = User.create!(name: "Elah Pillado", address: "123 Chase Rd", city: "Marietta", state: "GA", zip: 30008, email: "elah@email.com", password: "password", role: 0) @merchant = User.create!(name: "Sinai Pillado", address: "123 Chase Rd...
class CategoryService class << self include ApiClientRequests STATIC_SUPER_CATS = [ 'womens-fashion-accessories', 'mens-fashion-accessories', 'kids-babies', 'shoes-footwear', 'bags-luggage', 'beauty-health', 'computers-electronics' ] def fetch(params = {}) ...
namespace :deploy do desc 'Compile assets' task :compile_assets => [:set_hanami_env] do on release_roles(fetch(:assets_roles)) do within release_path do with hanami_env: fetch(:hanami_env) do execute :hanami, 'assets precompile' end end end end after 'deploy:update...
require "rails_helper" describe Candidate do let(:candidate){ FactoryGirl.create(:candidate) } it "is valid" do expect(candidate.valid?).to eq(true) end it "sanitizes the twitter_name" do expect(candidate.twitter_name).to eq("joe0") end it "has a token" do expect(candidate.token).to_not be_...
class AddCmcToCards < ActiveRecord::Migration[5.1] def change add_column :cards, :cmc, :integer add_column :cards, :set, :string end end
class SuportMailer < ApplicationMailer include ApplicationHelper def deliver_survey_mail_message recipient @recipient = recipient survey = recipient.survey mail_message = survey.mail_message recipient_data = survey.users_data[recipient.email] reply_link = build_reply_link_for_recipient recipie...
class CreateScenics < ActiveRecord::Migration def change create_table :scenics do |t| t.string :name, null:false t.string :picture, null:false t.string :manager_name, null:false t.string :manager_number, null: false t.integer :sys_admin_id t.timestamps null: false end end end
class Post < ActiveRecord::Base belongs_to :user belongs_to :parent, class_name: 'Post' has_many :replies, class_name: 'Post', foreign_key: :parent_id def self.roots where(parent_id: nil) end end
# -*- mode: ruby -*- # vi: set ft=ruby : require 'yaml' project_config = {} begin project_config = YAML.load_file('vagrant.yaml'); rescue Errno::ENOENT project_config = { name: nil, password: nil, ip: nil, url: nil } end # Run on first load, or if these are not set. if project_config['name'] ==...
class ChangeCompetitionPrivateToStatus < ActiveRecord::Migration[4.2] def up add_column :competitions, :status, :integer, null: false, default: 0 Competition.find_each do |comp| comp.status = comp.private? ? 0 : 1 end remove_column :competitions, :private end def down add_column :comp...
class Room attr_reader :name, :capacity, :rate, :price attr_accessor :songs_available, :current_guests def initialize(name, capacity, current_guests, price, songs_available) @name = name @capacity = capacity @current_guests = current_guests @price = price @songs_available = songs_available ...
# frozen_string_literal: true module Response class Base attr_reader :data def initialize(data = {}) @data = data end def success? self.class.name == 'Response::Success' end end end
#Site5 specific stuff set :use_sudo, false set :group_writable, false # Less releases, less space wasted set :keep_releases, 2 # The mandatory stuff set :application, "lafacroft" set :user, "lafacrof" #Git info default_run_options[:pty] = true set :repository, "git://github.com/chipmunk884/Lafacroft....
class OphtalmologyTemplates::TemplateFilesController < TemplateFilesController before_action :set_fileable private def set_fileable @fileable = OphtalmologyTemplate.find(params[:ophtalmology_template_id]) authenticate_doctor_for_template(@fileable) end end
require "scheme_maker_ext" module SchemeMaker class SchemeGenerator end class MaterialInfo attr_reader :color, :id def initialize(color, id) @color = color @id = id end end class CrossStitchSchemeGenerator end class SquareCellInfo attr_reader :size def initialize(size) ...
require 'digest/md5' require 'digest/sha1' puts "Введите слово или фразу для шифрования:" # Ввод слова для шифровки word = STDIN.gets.chomp puts "Каким способом зашифровать:\n"\ "1. MD5\n"\ "2. SHA1" # Ввод варианта шифровки answer = STDIN.gets.to_i # .between? - между значениями (min, max) # unt...
# -*- encoding : utf-8 -*- class CreatePayments < ActiveRecord::Migration def change create_table :payments do |t| t.date :data, null: false t.time :time, null: false t.decimal :value, precision: 6, scale: 2, null: false t.integer :user_id, null: false t.string :comment t.integ...
require 'rails_helper' RSpec.describe Company, type: :model do before { @company = FactoryGirl.build :company } subject { @company } @company_attributes = [:email, :password, :password_confirmation, :name, :phonenumber, :auth_code] it { should be_valid } # model should respond to attributes @company_at...
require "clockwork" require "timecop" require "clockwork/test/event" require "clockwork/test/job_history" require "clockwork/test/manager" require "clockwork/test/version" require "clockwork/test/rspec/matchers" module Clockwork module Methods def every(period, job, options={}, &block) ::Clockwork.manager...
class Customer < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :purchases, dependent: :nullify includ...
require File.dirname(__FILE__) + '/../spec_helper' describe FactoryGirl::Generate do before(:each) do @it = FactoryGirl::Generate.new end it "should return example value for number" do @it.value_for(User.columns_hash["number"]).should eql('1') end it "should return example value for string" ...
source 'https://rubygems.org' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git" end # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.2.2' # Improves performance of booting the applicati...
class HomeController < ApplicationController layout 'landing_page' def index @servers = Server.all if user_signed_in? redirect_to dashboard_path else end end end
require 'rails_helper' RSpec.describe User, type: :model do context "With valid attributes" do it "should save" do user = User.new( first_name: 'shane', last_name: 'chang', email: 'schang@codingdojo.com' ) expect(user).to be_valid end end context "With invalid a...
require 'rails_helper' RSpec.describe ContactService::IndexContact, type: :service do let(:user) { create(:user) } let(:contact) { create(:contact) } let(:csv_file) { FilesTestHelper.csv } context "when there are no contacts" do it "returns no contacts" do expect(described_class.call(user, nil).resu...
=begin Write a method that takes a string, and returns a new string in which every character is doubled. Examples =end def repeater(str) new_array = [] str.chars.each { |chr| new_array << (chr * 2)} new_array.join end puts repeater('Hello') == "HHeelllloo" puts repeater("Good job!") == "GGoooodd jjoobb!!"...
RSpec.describe Telegram::Bot::UpdatesController::Testing do include_context 'telegram/bot/updates_controller' let(:controller_class) do Class.new(Telegram::Bot::UpdatesController) do attr_accessor :ivar end end describe '#recycle!' do subject { -> { controller.recycle!(full) } } before do...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "scotch/box" config.vm.network "private_network", ip: "192.168.12.34" config.vm.hostname = "scotchbox" config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"] config.vm.synced_...
class ProfileCompCardsController < ApplicationController before_action :set_profile, only: [:index] def index json_response({ :profile_comp_card => { id: @profile_comp_card.id, comp_card_type: @profile_comp_card.comp_card_type, profile_comp_card_photos: @profile_comp_card...
# To change this template, choose Tools | Templates # and open the template in the editor. require 'rexml/document' require 'rubygems' require 'sqlite3' require 'inifile' module Bnicovideo class UserSession module MacOsX def self.init_from_firefox base_path = File.join(ENV['HOME'], 'Library', 'App...
class UserBlock < ActiveRecord::Base belongs_to :user enum status: [:active, :warning, :block] end
class AddExtraScreeningFields < ActiveRecord::Migration def change add_column :screenings, :subtitles, :string, array: true, default: [] end end
require "papa_carlo/version" require "fileutils" require "erb" module PapaCarlo extend self def root @root ||= begin File.expand_path("../../", __FILE__) end end def create_project(project) FileUtils.mkdir_p("#{project}/lib/#{project}") FileUtils.mkdir_p("#{project}/config/options") ...
class TasksController < ApplicationController def index @task_group = TaskGroup.find(params[:id]) @tasks= @task_group.tasks.all end def create @task_group = TaskGroup.find(params[:task_group_id]) @task_group = if @task = @task_group.tasks.create(params[:task]) redirect_to task_group_pat...
class CommentSerializer < ActiveModel::Serializer attributes :id, :author_name, :user_id, :body, :created_at, :updated_at def author_name object.author.email if object.user_id end end
require 'spec_helper' require './app/models/link' feature "view list of links" do scenario "User can view a list of links on the homepage" do Link.create(url: 'http://www.makersacademy.com' , title: 'Makers Academy') visit '/links' expect(page.status_code).to eq 200 within 'ul#links' do expe...
# More on Loops in Ruby k = 100 puts "The variable before the for loop k = #{k}" ## Basic For Loop in Ruby numbers = [3, 5 ,7] for k in numbers puts k end puts "You can still output the variable outside the for loop block of code. k = #{k}" ## Getting Index with Each colors = ["Red", "Blue", "Green", "Yellow"] ...
def hipsterfy(str) idx = str.rindex(/[aeiou]/) if idx.nil? str elsif idx < str.length - 1 str[0...idx] + str[(idx + 1)...str.length] else str[0...idx] end end def vowel_counts(str) result = Hash.new(0) vowels = "aeiou" arr = str.chars.select do |letter| v...
class AddInvoiceMeasureUnit < ActiveRecord::Migration def self.up add_column :invoice_items, :measure, :string end def self.down remove_column :invoice_items, :measure end end
class BackendController < ApplicationController def index puts "Showing Backend Menu" end end
require 'cosmicrawler' require 'kconv' require 'string-scrub' require 'nokogiri' require 'natto' class StaticPagesController < ApplicationController @@mecab = Natto::MeCab.new def home end def list_uris file = params[:file] if file.nil? @fine_name = "ファイルが選択されていません" @uris = [] else ...
require 'rimac' module Chillon class Handler def initialize(token) @access = Rimac::API.new(token) end def process(parser) if parser.multiple_results? results = Hash.new parser.guids.map do |guid| results[guid] = get_from_access(guid) end results else get_from_access(pars...
class Bakery < ActiveRecord::Base has_many :baked_goods end
require 'rails_helper' RSpec.feature "Static", type: :feature do context 'view index page' do scenario 'should be successful' do visit root_path expect(page).to have_content('A simple list application') end end context 'view about page' do scenario 'should be successful' do visit ...
require 'test_helper' class StockAuditsControllerTest < ActionController::TestCase setup do @stock_audit = stock_audits(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:stock_audits) end test "should get new" do get :new assert_respons...
# The game is a large case statement with child case statements within it. I wanted to create a story/path for the player to follow. # At this time, since I have many different deaths to track, I stayed away from using variables for deaths. # I tailored each death out to the path the player chose. # In the future, I...
Given 'the config file:' do |body| CommandLineHelpers.set_config_file body end Given 'the mustache:' do |body| CommandLineHelpers.set_mustache_file body end When "I ride the mustache with '$args'" do |args| @last_invocation = CommandLineHelpers.invoke_mustache_file_with args end Then 'I see:' do |output| @la...
Sequel.migration do up do alter_table(:users_seasons_matches) do add_column :game_wins, Integer, :null => false, :default => 0 end alter_table(:matches) do add_column :best_of, Integer, :null => false, :default => 3 end end down do alter_table(:users_seasons_matches) do drop_...
require "pry" require "sinatra/base" require "sinatra/json" require "./db/setup" require "./lib/all" require "rack/cors" require "httparty" require "uri" class Plock < Sinatra::Base set :logging, true set :show_exceptions, false use Rack::Cors do allow do origins "*" resource "*", headers: :any,...
# frozen_string_literal: true require_relative "vm_translator/version" require_relative "vm_translator/lexer" require_relative "vm_translator/parser" require_relative "vm_translator/compiler" require_relative "vm_translator/commands/push" require_relative "vm_translator/commands/pop" require_relative "vm_translator/co...
require 'spec_helper' describe SaldoBancarioHistorico do before do @user = Factory(:user) @fecha = "25/09/2012 23:06" @saldo = Factory(:saldo_bancario, :user => @user, :updated_at => @fecha) @attr = {:user_id => @user.id, :saldo_bancario => @saldo, :valor => @saldo.valor_cents, :valor_currency => @sa...
#-- # FIXME: # # Should use permalink. # If permalinks can cross instances, URI must be scoped. #++ # This resource represents an ArticleCategory within the system. It contains # all of the properties and associations of an ArticleCategory. # # ArticleCategory resources are exclusive to Article resources. ...
class ChangeDataTypeMasterContactsId < ActiveRecord::Migration def up change_column :purchase_contacts, :master_contact_ids, :text end def down change_column :purchase_contacts, :master_contact_ids, :varchar end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :phone do association :contact phone {"123-555-1234"} phone_type 'home' end end
class ServiceCategory < ApplicationRecord has_many :services, through: :service_sub_categories end
class Group < ActiveRecord::Base validates :name, presence: true, length: {maximum: 20}, uniqueness: true has_many :user_groups has_many :users, :through => :user_groups end
class CreateTaxes < ActiveRecord::Migration def change create_table :taxes do |t| t.string :full_name t.string :reference t.string :ic_new t.string :ic_old t.boolean :citizen_of_malaysia t.string :sex t.string :marital_status t.date :marital_date t.string :ty...
class ExpensesController < ApplicationController def index respond_to do |format| format.html format.json { @expenses = Datatable.new(params, ExpensesSearch.new) } end end def approve change_expense_status("Approved") end def reject change_expense_status("Rejected") end def ...
class Snapchat attr_accessor :username, :snap_story, :memories def initiative(user) @user = user end def snap
FactoryGirl.define do factory :user do fullname "MyString" email "MyString" password "MyString" end end # t.string :domain # t.string :fullname # t.string :email # t.string :password_digest
class Comment < ActiveRecord::Base belongs_to :user belongs_to :finstagram_post has_many :comment_likes validates_presence_of :text, :user, :finstagram_post end def like_count self.likes.size end
require 'rails_helper' RSpec.configure do |config| config.swagger_root = Rails.root.to_s + '/swagger' config.swagger_docs = { 'v1/swagger.json' => { openapi: '3.0.1', info: { title: 'API V1', version: 'v1', description: 'This is the first version of my API...
require 'set' # @param {Character[][]} board # @return {Boolean} def is_valid_sudoku(board) #check 3 x 3 squares for row_start in (0..6).step(3) do for col_start in (0..6).step(3) do set = Set.new for i in (0..2) do for j in (0..2) do cur_val = board[i+row_start][j+col_start] ...
class ReviewsController < ApplicationController before_action :authenticate_user! before_action :find_products def new @review = Review.new end def create @review = Review.new(review_params) @review.user_id = current_user.id @review.product_id = @product.id if @review.save redirect_t...
class AddPlayersCountToMatches < ActiveRecord::Migration def change add_column :matches, :players_count, :integer, default: 0, null: false, after: :started_at end end
class CreateFollows < ActiveRecord::Migration[5.2] def change create_table :follows do |t| t.integer :follower_id t.integer :followed_id t.index [:follower_id, :followed_id], unique: true end end end
class JoinTableEleSimulationContract < ApplicationRecord belongs_to :ele_simulation belongs_to :ele_contract end
# == Schema Information # # Table name: virtual_tourisms # # id :integer not null, primary key # title :string(255) # description :string(255) # created_at :datetime not null # updated_at :datetime not null # vid...
require 'httparty' require 'apicake' require 'json' require 'ostruct' class Newsapi < APICake::Base base_uri 'https://newsapi.org' attr_reader :api_key, :last_payload, :parsed_response def initialize(api_key) @api_key = api_key end def default_query { apiKey: @api_key } end ...
class CreateSongs < ActiveRecord::Migration def up create_table :songs do |s| s.string :name s.text :description end end def down drop_table :songs end end
class BoardController < ApplicationController layout 'board' def index @people = Person.all end end
require "identity_robotargeter/engine" module IdentityRobotargeter SYSTEM_NAME = 'robotargeter' SYNCING = 'campaign' CONTACT_TYPE = 'call' ACTIVE_STATUS = 'active' FINALISED_STATUS = 'finalised' FAILED_STATUS = 'failed' PULL_JOBS = [[:fetch_new_calls, 30.minutes], [:fetch_new_redirects, 30.minutes], [:fe...
# 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...
require "application_system_test_case" class AnalysisRequestItemsTest < ApplicationSystemTestCase setup do @analysis_request_item = analysis_request_items(:one) end test "visiting the index" do visit analysis_request_items_url assert_selector "h1", text: "Analysis Request Items" end test "creat...