text
stringlengths
10
2.61M
class AddFlagImageIdToRefineryLocations < ActiveRecord::Migration def change add_column :refinery_locations, :flag_image_id, :integer end end
class ClientMailer < ActionMailer::Base default from: "mirafloristeresina@gmail.com" def thanks_registration(client) @client = client @url = "http://mirafloris.com/login" mail(:to => client.email, :subject => "#{client.first_name} Obrigado por comecar seu futuro!") end end
class AddCompanyNameToUsersTable < ActiveRecord::Migration[5.2] def change change_table :users do |t| t.string :company_name, index: true t.string :full_name, index: true t.string :phone end end end
# -*- coding: utf-8 -*- require 'sinatra' get '/' do puts 'GET "/"' end post '/' do puts 'POST "/"' end put '/' do puts 'PUT "/"' end patch '/' do puts 'PATCH "/"' end delete '/' do puts 'DELETE "/"' end options '/' do puts 'OPTIONS "/"' end link '/' do puts 'LINK "/"' end unlink '/' do puts 'UN...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
json.array!(@categorizations) do |categorization| json.extract! categorization, :id, :post_id, :category_id json.url categorization_url(categorization, format: :json) end
require 'digest/md5' require 'open-uri' require 'fileutils' class Radio < ActiveRecord::Base belongs_to :radio_station def self.create_or_update_with_radios(radios) radios.each do |radio| create_or_update_with_radio(radio) end end def self.create_or_update_with_radio(radio) if radio.blank? ...
class User < ApplicationRecord has_secure_password has_many :visions has_many :goals has_one :squad has_many :projects end
class Admin::HappeningsController < Admin::BaseController before_action :_set_happening, except: %i[index new create parse_url] def index @happenings = Happening.all end def show; end def new @happening = Happening.new( club_id: params[:club_id] ) render partial: 'form', layout: false...
require 'test_helper' class FoosControllerTest < ActionDispatch::IntegrationTest setup do @foo = create(:foo) end test 'should get index' do get foos_url assert_response :success foos = parse_json_response foos.each { |o| assert_equal foo_json(@foo), o } end test 'should create foo' do...
class Journey def initialize(name, zone) @journey = {} @name = name @zone = zone end def see_journey @journey end def see_name @name end def see_zone @zone end end
Then(/^user is on Login page$/) do Pages::LoginPage.new.await end And(/^user taps Sign in button$/) do Pages::LoginPage.new.await.tap_sign_in_button end Then(/^successful sign in message is shown$/) do page = Pages::LoginPage.new.await Wait.until(timeout_message: "Successful sign in confirmation message shoul...
require 'spec_helper' require 'yt/models/asset' describe Yt::Asset do subject(:asset) { Yt::Asset.new data: data } describe '#id' do context 'given fetching a asset returns an id' do let(:data) { {"id"=>"A123456789012345"} } it { expect(asset.id).to eq 'A123456789012345' } end end describ...
class ShopsController < ApplicationController before_action :authenticate_admin!, except: %i[index show] before_action :set_shop, only: %i[edit update destroy show] before_action :user_can_edit?, only: %i[edit update destroy] def index @shops = Shop.order(updated_at: 'DESC').page(params[:page]).per(SHOP_PE...
class Series def initialize(numbers) @numbers = numbers.split('').map(&:to_i) end def slices(count) raise ArgumentError if count > @numbers.size @numbers.each_cons(count).to_a end end
class CreateAttachments < ActiveRecord::Migration def up create_table :attachments do |t| t.string 'uuid' t.integer 'business_user_id' t.string 'attachment_type' t.attachment t.timestamps end end def down drop_table :attachments end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program 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 Foundation; either version 2 of the License. # # This program ...
require 'spec_helper' require_relative '../../lib/kuhsaft/page_tree' require_relative '../../app/models/kuhsaft/page' # TODO: THESE SPECS ONLY WORK WHEN THE FULL SUITE IS RUN. FIX THAT! module Kuhsaft describe PageTree do let(:page_tree) do { '0' => { 'id' => '1', 'children' => { '0' => { 'id' => ...
class CsvFilePresenter < Presenter delegate :contents, :id, to: :model def to_hash { :id => id, :contents => File.readlines(contents.path).map{ |line| line.gsub(/\n$/, '') }[0..99] } rescue => e model.errors.add(:contents, :FILE_INVALID) raise ActiveRecord::RecordInvalid.new(model)...
require 'MiqVm/MiqVm' require 'disk/modules/AzureBlobDisk' require 'disk/modules/AzureManagedDisk' require 'disk/modules/miq_disk_cache' class MiqAzureVm < MiqVm def initialize(azure_handle, args) @azure_handle = azure_handle @uri = nil @disk_name = nil @resource_group = args[:resou...
require 'redis' require 'active_support/core_ext' require 'rails-pipeline/protobuf/encrypted_message.pb' # Pipeline forwarder base class that # - reads from redis queue using BRPOPLPUSH for reliable queue pattern # - keeps track of failed tasks in the in_progress queue # - designed to be used with e.g. IronmqPu...
namespace :products do desc "seed products" task :seed => [ :environment ] do puts "seeding products..." 50.times do fake_country = Faker::Address.country origin_country = [fake_country, fake_country, fake_country, "USA"] Product.create!(name: Faker::Food.ingredient, ...
require 'spec_helper' feature 'User can manage Todo items' do let(:authed_user) { create_logged_in_user } scenario 'by accessing the Todo index' do visit todos_path(authed_user) expect(page).to have_content("My List") end scenario 'Can see the Todo list headers' do visit todos_path(au...
class SetFinancialQuarterOnTransactions < ActiveRecord::Migration[6.0] def up Transaction.where.not(date: nil).find_each do |transaction| financial_quarter = FinancialQuarter.for_date(transaction.date) transaction.update_columns( financial_quarter: financial_quarter.quarter, financial...
class ChangeCartTotalInCarts < ActiveRecord::Migration[5.0] def change change_column :carts, :cart_total, :integer end end
class User < ActiveRecord::Base has_secure_password has_many :groups, :through => :memberships has_many :memberships validates :username, presence: true validates :password_digest, presence: true validates :email, presence: true def status_check errors.add(:status, ": Your account has been deactiva...
class PcrInspection < ApplicationRecord validates :subject_id, presence: true validates :clinic_id, presence: true validates :result, presence: true end
FactoryGirl.define do factory :transfer_notification do notice_type 1 amount "9.99" smx_transaction nil notified_by nil end end
require 'minitest/unit' require 'page_cell' MiniTest::Unit.autorun class Env attr_accessor :name def initialize @name = 'abc' end end class PageCellTest < MiniTest::Unit::TestCase def setup @env = Env.new end def render(source, options = {}, &block) tmpl = PageCell::Template.new(options[:file], ...
require "rails_helper" RSpec.describe 'TOC', js: true do let!(:article) { NewsArticle.create!({ title: 'first title', body: 'first body', subtitle: 'first subtitle', background_image_url: 'http://lvh.me/testing.png' }) } before do visit "/" end include_examples "layout" ...
require 'spec_helper' require_relative '../../lib/paths' using StringExtension module Jabverwock RSpec.describe 'css test' do subject(:img){IMG.new} it "single List" do expect(img.name ).to eq "img" end it "A tag" do ans = img.press expect(ans).to eq "<img>" end ...
require 'dm-gen/generators/plugin_generator' module DMGen class Is < Templater::Generator include PluginGenerator desc <<-eos Generates an 'is' plugin for DataMapper, such as dm-is-list. Use like dm-gen is plugin This generates the full plugin structure with skeleton code and spec...
# frozen_string_literal: true module Mutations class Login < GraphQL::Function argument :email, !types.String, 'Email of the user logging in' argument :password, !types.String, 'Password for user authentication' description 'Login given a successful email and password' type ::Types::LoginType d...
class AddActiveUsersTable < ActiveRecord::Migration def change create_table :active do |t| end add_reference :active, :user add_reference :active, :channel end end
module SectionsHelper def edit_section(section) if admin? link_to('Edit', edit_section_path(section)) else '' end end def delete_section_link(section) if admin? link_to 'Delete section', section, method: 'delete' else '' end end def render_section_content(sectio...
# input: string with uppercase, lowercase and neither # output: hash with keys for lowercase and uppercase characters as well as neither ones with their values as their respective percentages # integers count as neither # spaces count as neither # symbols count as neither # values of hash are percentages and can be flo...
class Rating < ActiveRecord::Base attr_accessible :value, :duser_id, :event_id belongs_to :event belongs_to :duser validates :value, presence: true end
class MembersController < ApplicationController def index members = Member.where(user_id: params[:user_id]) render json: members end def create member = Member.create(member_params) render json: member if member.save! end def update member = Member.find(params[:id]) member.update(...
# frozen_string_literal: true class Room < ApplicationRecord has_and_belongs_to_many :users has_many :messages end
class ProductReviewsController < ApplicationController before_action :authenticate def new @product = Product.find(params[:product_id]) @product_review = ProductReview.new end def create @product = Product.find(params[:product_id]) if current_user @product_review = ProductReview.new(prod...
class DispatcherController < ApplicationController #show all dispatchers route get '/dispatchers' do if logged_in? @dispatchers = Dispatcher.all erb :"dispatchers/show_all" else erb :"dispatchers/login" end end #dispatcher signup route ...
class ImagesController < ApplicationController def destroy @image = Image.find(params[:id]) @image.destroy redirect_to edit_product_path(@image.product.id) end end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'ehonda/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'ehonda' s.version = Ehonda::VERSION s.authors = ['Lee Henson'] s.email = ['lee.m.henson@gm...
class AddTeamsToPlayerIds < ActiveRecord::Migration def change add_column :player_ids, :teams, :text end end
module AdminHelper TIME_FORMATS = {long: '%B %-d, %Y %l:%M %P %Z', short: '%m/%d/%y %l:%M %P'} def alert_class(type) case type.to_s when 'info' # Blue. 'alert-info' when 'error', 'alert' # Red. 'alert-danger' else # Yellow. 'alert-warning' e...
require './spec/spec_helper' require './lib/gate.rb' require './lib/ticket.rb' RSpec.describe 'Gate Test' do it 'is OK' do def test_gate umeda = Gate.new(:umeda) juso = Gate.new(:juso) ticket = Ticket.new(150) umeda.enter(ticket) expect(juso.exit(ticket)).to be_truthy end end ...
require "rails_helper" describe MergeCall, type: :model do describe "#call" do it "moves participants from one call to another" do call_from = create(:incoming_call, :initiated) participant = create(:participant, call: call_from) call_to = create(:incoming_call) fake_connector = stub_cons...
require 'spec_helper' # The hypothetical API is accessible via a standard HTTP GET request. For example: # http://not_real.com/customer_scoring?income=50000&zipcode=60201&age=35 # A successful request to the API will return a JSON response resembling the following: # { # "propensity": 0.26532, # "ranking": "C" ...
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :login, :null => false t.string :encrypted_password t.string :encrypted_password_salt t.string :encrypted_password_iv t.string :username, :null => false, :default => '' t.integer :departm...
module Settings module Game NAME = 'Pingpong' WIDTH = 1366 HEIGHT = 768 end module Court BG_COLOR = '#000000' LINE_COLOR = '#FFFFFF' WALL_THICKNESS = 10 CENTER_THICKNESS = 4 end module Ball COLOR = '#FFFFFF' RADIUS = 25 SPEED = 7 # pixels every 1/60 of second end ...
require('pry') require('pg') require_relative('../db/sql_runner.rb') class Album attr_reader :id, :artist_id attr_accessor :title, :genre def initialize(album_hash) @title = album_hash['title'] @genre = album_hash['genre'] @artist_id = album_hash['artist_id'].to_i @id = album_hash['id'].to_i if...
class AddTitleLevelIndexToTest < ActiveRecord::Migration[5.2] def change # Composite Index # used for - validates :title, uniqueness: { scope: :level } add_index :tests, [:title, :level], unique: true end end
module RobotSimulator class TableTop def initialize(x_width, y_width) @x_width = x_width @y_width = y_width end def is_valid_position?(position) (position.x_axis.between?(0, @x_width-1) and position.y_axis.between?(0, @y_width-1)) ? true : false end def within_x_edge?(x) ...
class BaseJob < Struct.new(:params) def send_message_using_message_pub(subject, body, protocol, address) logger.debug("*** #{Time.now}: *** sending message pub #{protocol} to: #{address}, subject: #{subject}, body: #{body}") # create notification notification = MessagePub::Notification.new(:body => body...
require 'test_helper' class CrmCasesControllerTest < ActionController::TestCase setup do @crm_case = crm_cases(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:crm_cases) end test "should get new" do get :new assert_response :success ...
require 'rails_helper' feature 'User delete recipe' do scenario 'successfully' do user = User.create!(email: 'carinha@mail.com', password: '123456') recipe_type = RecipeType.create(name: 'Sobremesa') recipe = Recipe.create(title: 'Bolo de cenoura', difficulty: 'Médio', rec...
# frozen_string_literal: true require 'support/entities/secret' # @note Integration spec for Stannum::Entities::Associations. # - Tests a :one association with no foreign key or inverse. RSpec.describe Spec::Secret do subject(:secret) { described_class.new(**attributes, **associations) } shared_context 'when t...
class User < ActiveRecord::Base validates_presence_of :email, :name before_validation :setup_token, on: :create has_many :orders def admin? self.level == 'admin' end def self.from_omniauth(auth_hash) user = where( fb_uid: auth_hash[:uid] ).first_or_initialize user.name = auth_hash[:info][:na...
# lib/active_model/sleeping_king_studios/validations/relations/many.rb require 'active_model/sleeping_king_studios/validations/relations/base' module ActiveModel::SleepingKingStudios::Validations::Relations # The base validator for validating a one-to-many relation. class Many < ActiveModel::SleepingKingStudios::...
class CreateClubs < ActiveRecord::Migration[5.0] def change create_table :clubs do |t| t.string :iaru_region t.string :country t.string :callsign t.string :name t.string :website t.string :email t.string :phone t.string :contact_person t.string :contact_callsi...
require 'rails_helper' # Specs in this file have access to a helper object that includes # the CommentsHelper. For example: # # describe CommentsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # ...
class AddCoverUrlToBooks < ActiveRecord::Migration[5.2] def change add_column :books, :cover_url, :text, null: false end end
# == Schema Information # # Table name: release_order_application_with_versions # # id :integer not null, primary key # release_order_id :integer # application_with_version_id :integer # class ReleaseOrderApplicationWithVersion < ActiveRecord::Base belongs_to :release_...
feature 'add bookmark' do scenario 'user fills in form to add new bookmark' do visit('/') click_link('Bookmarks') fill_in('title', with: 'Goal') fill_in('url', with: 'http://www.goal.com') click_button('Submit') expect(page).to have_link('Goal', href: 'http://www.goal.com') end scenario ...
require 'spec_helper' Sequel.extension :mysql_json_ops describe 'Sequel::Mysql::JSONOp' do before do @db = Sequel.connect('mock://mysql2') @j = Sequel.mysql_json_op(:j) @l = proc{|o| @db.literal(o)} end it 'should have #extract accept a path selector' do @l[@j.extract('.foo')].must_equal "JSON_...
module Puffer class Fields < Array def field *args push Field.new(*args) last end def searchable @searchable ||= map { |f| f if f.column && [:text, :string, :integer, :decimal, :float].include?(f.column.type) }.compact end def searches query searchable.map { |f| "#{f.que...
require 'test_helper' class Admin::Api::BuyerAccountPlansTest < ActionDispatch::IntegrationTest def setup @provider = FactoryBot.create :provider_account, :domain => 'provider.example.com' @buyer = FactoryBot.create(:buyer_account, :provider_account => @provider) @buyer.buy! @provider.default_account_pl...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2017-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...
require 'active_support/core_ext/object/blank' module Hydramata module Works # Responsible for negotiating an object from persistence into memory module FromPersistence module_function def call(options = {}) pid = options.fetch(:pid) Hydramata.configuration.work_from_persistence_c...
# encoding: utf-8 class AddIndexToppageContents < ActiveRecord::Migration def up add_index :toppage_contents, :recommend_recipe_id end def down remove_index :toppage_contents, :recommend_recipe_id end end
class Hotel < ApplicationRecord geocoded_by :address after_validation :geocode, if: :address_changed? # GEM PARANOIA acts_as_paranoid # END GEM PARANOIA #cloudiary photo has_attachment :photo # VALIDATIONS AND ASSOCIATIONS has_many :services, dependent: :destroy has_many :rooms, dependent: :destr...
class CreateDenominaciones < ActiveRecord::Migration def change create_table :denominaciones do |t| t.string :nombre t.text :descripcion, :historia, :descripcion_tipos_uva end end end
class Vendy attr_reader :transaction_balance, :cash_balance def initialize @transaction_balance = 0 @cash_balance = 0 end def insert(coin_value) @transaction_balance += coin_value end def issue_refund refund = @transaction_balance @transaction_balance = 0 return refund end d...
class Category < ActiveRecord::Base validates :name, presence: true has_many :categorizations has_many :items, through: :categorizations scope :main_categories, -> { where(name: %w(Breakfast Appetizers Lunch Dinner Dessert)) } scope :special_categories, -> { where.not(name: %w(Breakfast Appetizers Lunch Di...
require File.join( File.dirname( __FILE__ ), "spec_helper" ) describe ProcessPool do before :each do @dummy_node = mock( "yutaro_node", :name => "yutaro_node" ) @ppool = ProcessPool.new end it "should dispatch a code block as a new sub-process" do Kernel.stub!( :fork ).and_yield.and_return( "PID" ...
class Aluno < ActiveRecord::Base validates :nome, :data_nasc, :local_nasc, :mae, presence: true has_many :notas end
require 'base64' # Base Controller class Ng::V1::BaseController < ApplicationController before_action :authenticate_user private def authenticate_user basic = ActionController::HttpAuthentication::Basic email, password = basic.decode_credentials(request).split(':') render_unauthorized and return unl...
class Bicycle attr_reader :color, :size, :style, :tire_width, :price include Discountable def initialize(input_options) @color = input_options[:color] @size = input_options[:size] @style = input_options[:style] @tire_width = input_options[:tire_width] @price = input_options[:price] end ...
Given(/^I navigate to the login page with query string parameters=(.*)$/) do |query_string| puts 'Processing ' + query_string login_page_url = on(LoginPage).login_page_url @browser.goto(login_page_url + query_string) end When(/^I login with a user type of (.*)$/) do |user_type| perform_login(get_user_data(user...
class Auction attr_reader :items def initialize @items = [] end def add_item(item) @items << item end def item_names @items.map do |item| item.name end end def unpopular_items @items.find_all do |item| item.bids.empty? end end def potential_revenue @items...
class Message < ApplicationRecord belongs_to :group belongs_to :user validates :body,presence: true validates :body, length: { maximum: 1000 } mount_uploader :image, ImageUploader end
require 'spec_helper' describe JobsController do fixtures :jobs, :job_templates, :job_steps let(:get_job_response) { { 'id' => '1234', 'stepsCompleted' => '1', 'status' => 'running' } } let(:create_response) { { 'id' => '1234' } } let(:fake_dray_client) do double(:fake_dray_client, get_job: g...
require 'benchmark' # Returns true if the given char arg is a letter. def letter?(lookAhead) lookAhead =~ /[[:alpha:]]/ end # Finds all triangle words inside the given file. def triangle_words # Generates the triangle sequence where t(n) = 1/2(n)(n+1). # The first 10 triangle numbers are: # 1, 3, 6, 10, 15, 2...
require 'rails_helper' RSpec.describe User, type: :model do it "validates presence of email" do user = User.new user.email = '' user.valid? expect(user.errors[:email]).to include("can't be blank") user.email = "test@test.com" user.valid? expect(user.errors[:email]).to_not include("can't ...
module DiscrepancyDetectors class SubscriberCount def self.get_discrepancies(channel_matrix:, normalized_channel:, account_email_subscriber_count:) result = [] existing_account_email_subscriber_count = channel_matrix[normalized_channel] unless existing_account_email_subscriber_count.nil? ...
include_recipe 'rbenv::system' template '/etc/profile.d/rbenv.sh' do owner 'root' group 'root' mode '644' end
class EasyPageTemplateTab < ActiveRecord::Base belongs_to :page_template_definition, :class_name => "EasyPageTemplate", :foreign_key => 'page_template_id' acts_as_list scope :page_template_tabs, lambda { |page_template, entity_id| { :conditions => EasyPageTemplateTab.tab_condition(page_template.id, entity...
require 'rails_helper' feature 'Linking structures to physical structures', :js do let!(:user) { create(:user) } let!(:audit) { create(:audit, user: user) } let!(:organization) do create(:organization, owner: user) end let!(:building_type) do create(:building_audit_strc_type, pa...
# encoding: utf-8 require File.join(File.dirname(__FILE__),'../lib/twitter_card') require 'spec_helper' describe TwitterCard do before(:each) do @twcard = TwitterCard.new end it "should have a name" do @twcard.title = "pepepe" @twcard.title.should == "pepepe" end it "should have a codenam...
class InventoryItemPhoto < ApplicationRecord belongs_to :inventory_item belongs_to :photo end
require "minitest/autorun" require_relative "../scanner/scanner" class TestScanner < Minitest::Test def test_it_skips_whitespace scanner = Scheme::Scanner.new(" hello") first_token = scanner.get_next_token assert_equal first_token.type, :IDENT end def test_it_skips_comments input = %Q( ;...
require "UnitTest" require "Proto_Auto_Call" class McallLEUserOptions attr_accessor :nb_calls, :dial_number, :call_duration end class Proto_Auto_Multi_Call_LE < UnitTest ##################################### # DEFAULT PARAMETERS # ##################################### @@DEFAULT_DIAL_...
# encoding: utf-8 require 'open-uri' require 'awesome_print' require 'nokogiri' require 'json' class SenScraper Fields = ["Nombre", "Entidad", "Partido", "Foto"] BaseURL = "http://www.senado.gob.mx/index.php?ver=int&mn=4&sm=10&id=SENADOR" def initialize len = 128 senadores = (1..len).ma...
# Create partial estimation table class CreatePartialEstimations < ActiveRecord::Migration[5.0] def change create_table :partial_estimations do |t| t.float :estimation t.timestamps end end end
require 'rails_helper' RSpec.describe "pages/about.html.erb", type: :view do it "have content Этапы проведения СП" do render expect(response.body).to match("Этапы проведения СП") end end
# frozen_string_literal: true # https://adventofcode.com/2019/day/2 require 'pry' require './boilerplate' require './intcode' def run_with(noun, verb) memory = input.split(',') memory[1] = noun memory[2] = verb program = Intcode.new(memory.join(',')) program.run(nil) program end def run(instructions) ...
class User < ActiveRecord::Base has_many :posts has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", ...
class TodosController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource :except => [:create, :destroy] def index @todos=current_user.todos.order("position") # @todos=Todo.order("position").joins(:project) end def create @todo=Todo.create(todo_params) @todo.sa...
require 'spec_helper' describe V1::DashboardController do let(:user) { create(:user) } before do sign_in user end describe "GET 'index'" do before { get :index } it { should respond_with(:success) } it { should render_template(:dashboard) } end end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you ...