text
stringlengths
10
2.61M
namespace :data do desc "import data from old ABJ database to Ruby database" task :import_prodlines => :environment do file = File.open("./lib/tasks/data/prodlines.csv") file.each_with_index do |line, i| next if i == 0 attrs = [] attrs_outer = line.split("|") attrs_outer.each do |val...
class TalenttoolsApi::Participant include Her::Model collection_path "/api/v1/projects" parse_root_in_json :participant include_root_in_json true use_api TalenttoolsApi.api custom_get :get_assessment_link, :get_assessment_status, :get_report_link class << self def create(project_id, params = {}) ...
require "include" require "runit/cui/testrunner" # tests the customization of Log4r levels class TestCustom < TestCase def test_validation assert_exception(TypeError) { Configurator.custom_levels "lowercase" } assert_exception(TypeError) { Configurator.custom_levels "With space" } end def test_create ...
class CreateReads < ActiveRecord::Migration[6.0] def change create_table :reads do |t| t.date :data_leitura t.integer :qtd_lido t.timestamps end end end
class OrderItemsController < ApplicationController before_action :set_order_item, only: [:destroy, :increase_quantity, :decrease_quantity] before_action :authenticate_user! def create order_item = current_order.order_items.find_by(product_id: params[:product_id]) if order_item.present? order_item.u...
require 'endpointer/errors/cached_item_not_found_error' require 'endpointer/errors/invalid_cache_dir_error' require 'endpointer/cache_container' require 'endpointer/cache_key_resolver' require 'endpointer/response_presenter' require 'yaml' module Endpointer class Cacher def initialize(path) initialize_pat...
require 'rails_helper' RSpec.describe 'the competition index page' do # User Story 1 - Competition Index # As a user # When I visit the competion index # Then I see the names of all competitions # Each competition name links to its show page it 'shows the name of all the competitions' do comp1 = Competition.c...
require 'app/models/brewery' require 'app/presenters/paginated_presenter' require 'app/presenters/location_presenter' require 'app/presenters/social_media_account_presenter' class BreweryPresenter < Jsonite properties :name, :alternate_names, :description, :website, :organic, :established property(:beers) { b...
class Player attr_accessor :nom, :valeur def initialize(nom= nil, valeur= nil) #S'il n'y a pas de nom de base, on demande au joueur de rentrer un nom if nom == nil puts "Quel est votre nom de guerre ?" nom = gets.chomp end @nom = nom #S'il n'y a pas de valeur de ba...
json.array!(@money_checks) do |money_check| json.extract! money_check, :id json.url money_check_url(money_check, format: :json) end
class AwardQuery def self.all relation.order(:title) end def self.find(id) relation.friendly.find(id) end def self.relation Award.all end end
class Review < ActiveRecord::Base validates :rental, :review, :review_text, presence: true belongs_to :rental has_one :listing, through: :rental has_one :reviewer, through: :rental, source: :lessee end
class ChatMailer < ApplicationMailer default from: "mogushare.net@gmail.com" def send_mail_about_new_chat(user, group, current_user) @user = user @current_user = current_user @group = group mail( subject: "【もぐシェア】メッセージが届きました", to: @user.email ) end end
# encoding: UTF-8 class Collecte # = main = # # Méthode principale pour procéder au parsing du dossier de # collecte. # # NOTES # * En fin de parsing, on sauve toutes les données # dans le fichier data/film.msh qui contient tout. # # +options+ # :debug Si true, on ouvre le fichier ...
class User < ApplicationRecord has_many :posts has_many :images, through: :posts has_many :likes has_many :liked_images, through: :likes, source: :images has_many :comments def images_and_comments liked_images.includes(:comments) end end
module SnakeCase module Bruteforce module_function def path_count(m, n) (0..(2**(m+n))).count { |x| x.to_s(2).chars.count("1") == n } end end module Factorial module_function def path_count(m, n) (m+n).downto(m+1).reduce(:*) / n.downto(1).reduce(:*) end end module Recur...
class MasterMindGame attr_accessor :colors_to_guess, :user_guesses, :total_colors, :total_positions, :start_time, :end_time def initialize(colors_to_guess=secret_colors_generator) @colors_to_guess = colors_to_guess @total_colors = total_colors @total_positions = total_positions @user_guesses = 0 ...
#!/bin/env ruby # encoding: utf-8 module Admin::RightsHelper # called by controllers on CRUD actions. Perform a redirect_to if unnecessary right # on index actions def index_right(element) if @ownerships_all.any? @elements = element.page(params[:page]).per_page(10) else if @ownerships_on_ownership.any? ...
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: 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.ap...
#puppet-gcloudsdk/spec/acceptance/standard_spec.rb require 'spec_helper_acceptance' describe 'gclogging class' do context 'default parameters' do # Using puppet_apply as a helper it 'should work with no errors based on the example' do pp = <<-EOS class { 'gclogging':} EOS # Run...
# -*- mode: ruby -*- # vi: set ft=ruby : require 'getoptlong' VAGRANTFILE_API_VERSION = "2" MANAGERS = 1 workers = <%= workers %> opts = GetoptLong.new( # Native Vagrant options [ '--force', '-f', GetoptLong::NO_ARGUMENT ], [ '--provision', '-p', GetoptLong::NO_ARGUMENT ], [ '--provision-with', G...
class ListSerializer < BaseSerializer attributes :name, :permissions has_many :items end
module Mastermind class Resource module Server class EC2 < Resource provider Mastermind::Provider::Server::EC2 actions :create, :destroy, :stop, :start, :restart, :reboot attribute :image_id, :type => String attribute :key_name, :type => String attribute :ami_launch_...
class MerchantsController < ApplicationController before_action :require_login, except: [:login] def login auth_hash = request.env["omniauth.auth"] @merchant = Merchant.find_by(uid: auth_hash[:uid], provider: "github") if @merchant # merchant was found in the database flash[:success] =...
class UnitsController < ApplicationController before_action :get_unit, only: [:update, :edit, :show, :destroy] before_action :get_race def index @units = @races.units end def new @unit = @race.units.new render "form" end def create @unit = @race.units.new(unit_params) if @unit.save ...
require "spec_helper" describe LaunchersController do describe "routing" do it "routes to #index" do get("/launchers").should route_to("launchers#index") end it "routes to #new" do get("/launchers/new").should route_to("launchers#new") end it "routes to #show" do get("/launch...
require 'delegate' module HamlUserTags module Helpers # Same as Haml::Buffer.attributes, but returns the hash instead of writing # the attributes to the buffer. def self.attributes_hash(class_id, obj_ref, *attributes_hashes) attributes = class_id attributes_hashes.each do |old| Haml::...
describe DatabaseConnection do describe '.setup' do it 'establishes a connection to the database using PG' do expect(PG).to receive(:connect).with(dbname: 'bookmarks_manager_test') DatabaseConnection.setup('bookmarks_manager_test') end end describe '.query' do it "executes the query passe...
class CreateVacations < ActiveRecord::Migration[6.1] def change create_table :vacations do |t| t.integer :traveler_id t.integer :country_id t.boolean :favorite t.timestamps end end end
# 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...
module PathHelper { root: '/', adverts: '/adverts', packages: '/packages', publishers: '/publishers', influencers: '/influencers', messages: '/messages', requests: '/requests' }.each do |name, path| define_method("#{name}_path") do |searches = nil| searches = CGI.unescape(searc...
class State < ActiveRecord::Base belongs_to :country has_many :cities validates :name, :presence=>true end
class BuildHistory < ActiveRecord::Base belongs_to :scenario include Steppable after_create :start_test enum result: { pending: 0, passed: 1, failed: 2, error: 3 } def started_at_string return nil unless self.started_at self.started_at.to_s(:datetime) end def finished_at_str...
# frozen_string_literal: true module Dmarcurator VERSION = "0.1.1" end
Given /^I've started to create a work "([^"]*)"$/ do |arg1| $title = arg1 $content = "This is my draft." @site.create_draft_flow(:rating => "General Audiences",:fandom => "Supernatural RPF",:title => $title,:content => $content) end Then /^I should be taken to the "([^"]*)" page$/ do |arg1| @site.header.heade...
# This is a service object that will create a new game class CreateGameService class << self def create_game(game_room_slug) @gr = GameRoom.find_by_url_slug(game_room_slug) destroy_previous_game new_game = create_new_game_object @gr.touch { success: true, id: new_game.id } end ...
class ApplicationController < Sinatra::Base disable :show_exceptions error Bunny::TCPConnectionFailedForAllHosts, Redis::CannotConnectError do render_error end set :raise_errors, true set :dump_errors, false set :show_exceptions, false attr_reader :body_params before do request.body.rewind ...
class CreateReviewOfRooms < ActiveRecord::Migration def change create_table :review_of_rooms do |t| t.integer :accuracy t.integer :communication t.integer :cleanliness t.integer :location t.integer :check_in t.integer :value t.text :content t.integer :guests_id ...
require 'test_helper' class CurrencyTest < ActiveSupport::TestCase def setup @c = Currency.new( symbol: "BTC" ) end test "it creates a Currency on Currency.new" do assert_instance_of Currency, @c, "Object not an instance of Currency" end test "Currency has a .cur_name method"...
require 'rails_helper' RSpec.describe "Articles", type: :routing do before(:each) do user = User.create({ name: "Nombre1", email: "nombre@nombre.com", password: "12345678", password_confirmation: "12345678" }) @article = Article.create({ ...
class CreateTracks < ActiveRecord::Migration def self.up create_table :tracks do |t| t.string :persistent_id t.string :name t.string :artist t.string :album t.float :duration t.integer :rating t.boolean :enabled, :default => true t.timestamps end end def s...
class ArtsType < ActiveRecord::Base has_and_belongs_to_many :media_items validates_presence_of :name validates_uniqueness_of :name end
# FakeFS::SpecHelpers provides a simple macro for RSpec example groups to turn FakeFS on and off. # To use it simply require 'fakefs/spec_helpers', then include FakeFS::SpecHelpers into any # example groups that you wish to use FakeFS in. For example: # # require 'fakefs/spec_helpers' # # describe "Some specs that ...
class DeliveryEntrySerializer def initialize(object) @entry = object end def to_serialized_json options = { include: { user: { only: [:username] }, methods: [:created], except: [:updated_at, :cr...
require 'rails_helper' describe ActiveAdmin::Views::SidebarSection do let(:options) { {} } let(:section) do ActiveAdmin::SidebarSection.new("Help Section", options) do span "Help Me" end end let(:html) do result = render_arbre_component section: section do sidebar_section(assigns[:se...
require_relative 'test_helper' require_relative '../lib/invoice_item' class InvoiceItemTest < Minitest::Test attr_reader :ii def setup @ii = InvoiceItem.new({ id: 999999, item_id: 111111, invoice_id: 234234, quantity: 34, unit_price...
require 'faraday' require 'faraday_middleware' require 'faraday/panoptes' require "panoptes/client/version" require "panoptes/client/me" require "panoptes/client/projects" require "panoptes/client/subjects" require "panoptes/client/subject_sets" require "panoptes/client/user_groups" require "panoptes/client/workflows"...
# frozen_string_literal: true # borzoi.rb # Author: William Woodruff # ----------------------- # Fetches a random picture of a Borzoi from the Dog CEO API. # ----------------------- # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require "open-uri" requir...
def fill_out_location # Hard-code values and should use parameterization select('Business', from: 'Address_Type_Select') fill_in('Street', with: '7950 Jones Branch Dr') fill_in('City', with: 'McLean') select('VA', from: 'Region') fill_in('Postal_Code', :with => '22102') end def continue_button find_butto...
class Presentation < ActiveRecord::Base belongs_to :room belongs_to :time_slot end
require 'net/http' require "rexml/document" class Reading < ActiveRecord::Base belongs_to :device has_one :stop_event belongs_to :geofence include ApplicationHelper acts_as_mappable :lat_column_name => :latitude,:lng_column_name => :longitude def self.per_page 25 end def speed read...
require "minitest/autorun" require "minitest/pride" require './lib/card' require './lib/deck' require "./lib/player" require "./lib/turn" class TurnTest < Minitest::Test def test_it_exists card1 = Card.new(:heart, "Jack", 11) card2 = Card.new(:heart, "10", 10) card3 = Card.new(:heart, "9", 9) card4 ...
class AddPriorityToContacts < ActiveRecord::Migration[5.0] def change add_column :contacts, :rush_priority, :integer add_column :contacts, :is_brother, :boolean, default: false end end
require 'spec_helper' module Alf describe AttrList do describe "coerce" do subject{ AttrList.coerce(arg) } describe "when passed a AttrList" do let(:arg){ [:a, :b] } it{ should eq(AttrList.new(arg)) } end describe "when passed an array" do let...
require 'albacore' require 'nokogiri' $connection_string = ENV['CONNECTION_STRING'] $aws_access_key = ENV['AWS_ACCESS_KEY'] $aws_secret_key = ENV['AWS_SECRET_KEY'] task :default => [:restore, :compile_this, :transform_config, :deploy] #https://github.com/Albacore/albacore/wiki/nugets_restore nugets_restore :restore ...
class OrderItem < ActiveRecord::Base belongs_to :order belongs_to :product def price product.price * quantity end end
class Goal < ActiveRecord::Base include TokenFinder validates_presence_of :title belongs_to :user has_many :memberships has_many :members, :source => :user, :through => :memberships, :conditions => "status = 'approved'" has_many :posts belongs_to :city before_save :parse_date before_save :set_c...
=begin 1 ---------------------------- Print 1-255 Write a program that would print all the numbers from 1 to 255. =end # Code 1 --------------- (1..255).each{|i| puts i} for i in 1..255 puts "#{i}" end =begin 2 ---------------------------- Print odd numbers between 1-255 Write a program that would print all the ...
require "spec_helper" describe Balanced::Account do use_vcr_cassette before do api_key = Balanced::ApiKey.new.save Balanced.configure api_key.secret @marketplace = Balanced::Marketplace.new.save end describe "merchant" do use_vcr_cassette before do @merchant_attributes = { :...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. before_filter :configure_permitted_parameters, if: :devise_controller? protected include PublicActivity::StoreController # ... hide_action :current_user #@a...
class AddPageDecriptionToPage < ActiveRecord::Migration def self.up add_column :pages, :page_description, :text end def self.down remove_column :pages, :page_description end end
class Store attr_reader :longname, :city, :distance, :phone, :type def initialize(attrs = {}) @longname = attrs["longName"] @city = attrs["city"] @distance = attrs["distance"] @phone = attrs["phone"] @type = attrs["storeType"] end def self.fetch_by_zip(zip) stores = BestbuyService.fetch...
class Member < ApplicationRecord searchkick has_many :matches has_many :matched_members, through: :matches, dependent: :destroy has_many :headers before_save :set_short_url, if: :original_url_changed? after_create :scrape_headings validates :name, :original_url, presence: true validates :original_url...
class MovieTitle STRINGS_TO_REMOVE = YAML.load(File.read("./configuration.yml"))["strings_to_remove"] attr_accessor :text def initialize(text:) @text = text end def format remove_periods() put_screen_resolution_in_brackets() remove_disallowed_strings() put_years_in_parens() remove_t...
Gem::Specification.new do |spec| spec.name = 'google_directions' spec.version = '0.2.0' spec.files = Dir['lib/**/*', 'test/**/*', 'README.textile', 'Gemfile', 'init.rb', 'Manifest', 'Rakefile'] spec.summary = 'Class for retrieving directions from the Google Directions API service' ...
class CreateCategoryz3Categories < ActiveRecord::Migration def change create_table :categoryz3_categories do |t| t.string :name t.references :parent t.integer :items_count , default: 0 t.integer :child_items_count , default: 0 t.integer :childrens_count , default: 0 t.t...
# In this exercise, you will be creating two classes AND the driver code to test them. # You will create a Tv class and a Remote class. # The Tv class will have the attributes: power, volume, and channel. class Television attr_accessor :power, :volume, :channel def initialize @power = false @volume = 0 ...
require 'find' require 'fileutils' require 'yaml' require 'ostruct' require 'zlib' class MiqFsUtil attr_accessor :verbose, :fromFs, :toFs def initialize(fromFs, toFs, us = nil) setUpdateSpec(us) @fromFs = fromFs @toFs = toFs @verbose = false end def updateSpec=(us) setUpdateSpec(us) en...
class CoursesController < ApplicationController def new @area = load_area_from_url @course = Course.new end def create @area = load_area_from_url @course = @area.courses.new(course_params) if @course.save course_entry = NewCourseEntry.create(course_id: @course.id) current_user.fee...
require 'assessment' class CorrectionOfQuarterly < Assessment def title "Correction of Quarterly" end def fields super + %w( A2200 A2300 B0100 B0200 B0300 B1000 B0600 B0700 B0800 B1200 C0100 C0200 C0300a C0300b C0300c C0400a C0400b C0400c C0500 C0700 C0800 C09...
class Comment < ActiveRecord::Base belongs_to :user belongs_to :articles end
class Node attr_accessor :val, :next def initialize(value,next_node = nil) @val = value @next = next_node end end
module LazySerializable extend ActiveSupport::Concern def serialize_lazy(annotations: false, facets: true, public: false) params = { params: { facet_items: facets, navigation_items: facets, public: public } } hash = lazy_serializer.new(self, params).serializable_hash[:data] if annotations annota...
class Repo < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :tools has_many :completions end
class Tag include Mongoid::Document include Mongoid::Timestamps::Short field :name, type: String validates :name, presence: true validates :name, uniqueness: { case_sensitive: false } end
class ChangeColumnToCollege < ActiveRecord::Migration[5.1] def change rename_column :colleges, :image_co, :image end end
# # The MIT License (MIT) # # Copyright (c) 2014 Wynand Pieterse # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, co...
module Returning module ActiveRecord module Adapter def to_sql(arel) if arel.respond_to?(:ast) visitor.accept(arel.ast) else arel end end def returning? !!@_returning end def exec_with_returning(sql, binds) records = @_ret...
module DiscourseSimpleCalendar class EventValidator def initialize(post) @post = post end def validate_event return false if @post.is_first_post? calendar_custom_field = @post.topic.first_post.custom_fields[DiscourseSimpleCalendar::CALENDAR_CUSTOM_FIELD] return false unless calen...
class Api::BaseController < ApplicationController rescue_from StandardError, with: :respond_with_error def respond_with_error(exe) logger.error(exe) render json: { message: exe.message, backtrace: exe.backtrace[0..5] }, status: :internal_server_error end def respond_with_success(res) ...
class CreateUfafees < ActiveRecord::Migration def change create_table :ufafees do |t| t.timestamp :created_on t.timestamp :updated_on t.string :number t.decimal :amount, precision: 10, scale: 2 t.integer :project_id t.integer :period_id t.decimal :service_UFA, precision: ...
class SysActionOnTable < ActiveRecord::Base attr_accessible :action, :table_name, :as => :role_new_update has_many :sys_user_groups, :through => :sys_user_rights validates_presence_of :action validates_presence_of :table_name validates :action, :uniqueness => {:scope => :table_name, :case_sensitive => ...
require 'sidekiq/testing' require 'rails_helper' RSpec.describe SyncHistoryOrderJob do let!(:user) { User.create!( email: 'foo@bar.com', password: 'abcdabcd', bitget_access_key: 'oo', bitget_secret_key: 'ooo', bitget_pass_phrase: '111' ) } it 'works' do Sidekiq::Testing...
class Post < ApplicationRecord before_create :generate_permalink after_create :generate_reference, :assign_tags, :assign_promotion_updated_at has_many_attached :images has_many :markers, dependent: :destroy has_one :meta_datum belongs_to :user, :counter_cache => true validates :permalink, :uniqueness => true ...
require 'spec_helper' describe Collins::SimpleCallback do def get_cb *args has_block = !args.find_index{|a| a.is_a?(Proc)}.nil? if not has_block then args.unshift(Proc.new{}) end Collins::SimpleCallback.new(*args) end it "#name" do get_cb(:fizz).name.should == :fizz end it "#option...
module Azendoo class Subject < AzResource has_many :tasks, class_name: 'Azendoo::Task' has_many :conversations, class_name: 'Azendoo::Conversation' def add_member(user) self.post(:add_member, user_id: user.id) end def remove_member(user) self.post(:remove_member, user_id: user.id) ...
# -*- mode: ruby -*- # vi: set ft=ruby : # This configuration requires Vagrant 1.5 or newer and two plugins: # # vagrant plugin install vagrant-hosts ~> 2.1.4 # vagrant plugin install vagrant-hostmanager # vagrant plugin install vagrant-auto_network ~> 1.0.0 # Vagrant.require_version ">= 1.7.2" require '...
class ReportsController < ApplicationController before_filter :authenticate_user! def call_traffic_data_range authorize :report, :call_traffic_data_range? calls = Call.data_for_report(params[:date_range]) formatted_report = Call.prepare_data_for_date_range(calls) render json: formatted_report, stat...
class AddWhyUseToUsers < ActiveRecord::Migration def change add_column :users, :whyUse, :string end end
class EventPerformersSplitService def initialize(event_performer_param,event_id) @event_id = event_id @event_performer_param = event_performer_param @event_performer = @event_performer_param.to_h['0']["performer"] end def execute # 改行コードで分割して、改行分レコードを作成する @even...
#!/usr/bin/env ruby # encoding: utf-8 require "open-uri" require "optparse" require_relative 'iconfinder_api' options = {} path = 'img' optparse = OptionParser.new do |opts| opts.banner = "Command-line tool for downloading icons from https://www.iconfinder.com\n" opts.banner += "Copyright (c) 2014 Zhussupov Zhas...
FactoryGirl.define do factory :bike_brand do brand {Faker::Commerce.product_name} end end
require "redis" require "json" # Note: By linking containers using the name redis, we get the following ENV: # # REDIS_NAME=/sleepy_galileo/redis # REDIS_PORT_6379_TCP_ADDR=172.17.0.14 # REDIS_PORT_6379_TCP_PORT=6379 # REDIS_PORT_6379_TCP=tcp://172.17.0.14:6379 # REDIS_PORT=tcp://172.17.0.14:6379 url = ENV['REDIS_POR...
class AddStatusToEnquiries < ActiveRecord::Migration def change add_column :enquiries, :status, :string, limit: 32, default: 'pending' end end
class AddPortAndPostgresPasswordToProjects < ActiveRecord::Migration[5.0] def change add_column :projects, :port, :integer, default: 80 add_column :projects, :db_admin_password, :string, default: '' end end
require 'spec_helper' describe 'POST recommendations/follow' do let!(:user) { stub_authentication } let!(:place) { create :place } let(:params) do { target_type: :place, target_id: place.id, emails: ['foo@bar.com'] } end subject { post recommendation_url, params; json } it { sub...
def da_boas_vindas puts "Bem vindo ao jogo da forca" puts "Qual é o seu nome?" nome = gets.strip puts "\n\n\n\n\n" puts "Começaremos o jogo para você, #{nome}" nome end def avisa_escolhendo_palavra_secreta puts "Escolhendo uma palavra secreta..." end def avisa_palavra_escolhida(palavra_secreta) puts "...
class CreateCyClickerSettings < ActiveRecord::Migration def change create_table :cy_clicker_settings do |t| t.boolean :studentsBlocked t.timestamps end end end
#!/usr/bin/env ruby $is_Jekyll = false begin require "jekyll" puts "testing cases using jekyll" $is_Jekyll = true rescue LoadError require "liquid" puts "testing cases using liquid" end def isJekyll $is_Jekyll end def assertEqual(expected, real) if expected != real raise "#{real} is not #{expected...
module OHOLFamilyTrees class CombinedLogfile def initialize(logfiles) @logfiles = logfiles end attr_reader :logfiles def path logfiles.last.path end def cache logfiles.last.cache end def file_path logfiles.last.file_path end def date logfiles....