text
stringlengths
10
2.61M
require 'action_mailer' set :application, "resident-desk" set :current_path, "clt-resdesk.previewfor.net" set :prod_path, "residentdesk.com" set :prod_app, "#{prod_path}" set :prod_static_path, "shindy@shindyapin.com:/home/shindy/static.residentdesk.com" default_run_options[:pty] = true set :scm, :git role :web, ...
class DrinkLiquor < ActiveRecord::Base belongs_to :drink belongs_to :liquor end
# frozen_string_literal: true # Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru> require 'rails_helper' RSpec.describe TelegramWebhooksController, telegram_bot: :rails do # Main method is #dispatch(update). Some helpers are: # dispatch_message(text, options = {}) # dispatch_command(cmd, *args) descri...
module Machinist class AbstractAdapter # :api: private def self.inherited(klass) Machinist.add_adapter klass end # Use this to set the priority of your adapter # If you have a very specific test to see if this adapter should be used in # use_for_class? then the priority should be se...
# 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...
require "player" describe Player do subject(:jade) {described_class.new("Jade")} subject(:lubos) {described_class.new("Lubos")} describe '#name' do it "gives the players name" do expect(jade.name).to eq "Jade" end end describe '#HP' do it "gives the players HP" do expect(jade.hp).t...
require "ibm_watson" require("ibm_watson/tone_analyzer_v3") require("json") class TextInputsController < ApplicationController # GET /text_inputs def index @text_inputs = TextInput.all render json: @text_inputs end # GET /text_inputs/:id def show render json: @text_inputs end def create ...
module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user rescue_from StandardError, with: :report_error def connect self.current_user = find_verified_user end def disconnect self.current_user.logout end private def find_verifi...
require 'rails_helper' describe Account do describe "#create" do let!(:user){create(:user)} context "can save" do it "user_idが存在すれば項目が全てみたされていても登録できる事" do account = build(:account, user_id: user.id) expect(account).to be_valid end it "user_idが存在すれば項目が全て未入力でも登録できる事" do ...
class Authenticator def self.encryptor PasswordEncryptor end def self.repository User end def self.authenticate(email, password) user = repository.find_by(email: email) return unless user user if encryptor.valid?(user.password_hash, password) end end
set :application, "netzke-demo" set :domain, "netzke" set :repository, "git://github.com/skozlov/netzke-demo.git" set :use_sudo, false set :deploy_to, "/u/apps/#{application}" set :scm, "git" role :app, domain role :web, domain role :db, domain, :primary => true namespace :deploy do desc "Restar...
class Voucher < ApplicationRecord before_create :create_uuid before_create :set_to_not_used private def create_uuid self.uuid = SecureRandom.uuid end def set_to_not_used self.used = false end end
class Admin::SubscriptionSettingsController < Admin::BaseController crudify :refinery_setting, :title_attribute => "name", :order => 'name asc', :redirect_to_url => "admin_subscriptions_url" before_filter :set_url_override?, :only => [:edit, :update] after_filter :save_subject_for_...
class ChangeColumnName < ActiveRecord::Migration[5.2] def change rename_column :flights, :when, :date_of_flight end end
RSpec.describe AllocateKitInventoryService, type: :service do let(:organization) { create :organization } let(:item) { create(:item, name: "Item", organization: organization, on_hand_minimum_quantity: 5) } let(:item_out_of_stock) { create(:item, name: "Item out of stock", organization: organization, on_hand_minim...
require 'hanami/utils/class_attribute' require 'hanami/http/status' require 'hanami/action/rack/errors' module Hanami module Action # Throw API # # @since 0.1.0 # # @see Hanami::Action::Throwable::ClassMethods#handle_exception # @see Hanami::Action::Throwable#halt # @see Hanami::Action::T...
class AddCryptoIdToPrices < ActiveRecord::Migration[5.1] def change add_column :prices, :crypto_id, :integer add_index :prices, :crypto_id end end
# frozen_string_literal: true module Might # Converts array of parameters to hash familiar to ransack gem # class RansackableSortParametersAdapter def initialize(app) @app = app end def call(env) scope, params = env ransackable_parameters = Array(params[:sort]).map do |parameter| ...
# == Schema Information # # Table name: horses # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # race_id :integer # name :string # meeting_id :integer # tip_id :integer # horse_options...
require "redis" require "json" require "securerandom" module Ag module Adapters class RedisPush def initialize(redis) @redis = redis end def connect(consumer, producer) @redis.pipelined do |redis| redis.zadd(producer.key("consumers"), Time.now.to_f, consumer.key) ...
# frozen_string_literal: true # A stub for the Scout agent, so we can make assertions about how it is used if defined?(ScoutApm) raise "Expected ScoutApm to be undefined, so that we could define a stub for it." end class ScoutApm TRANSACTION_NAMES = [] def self.clear_all TRANSACTION_NAMES.clear end mod...
class TagSerializer < ActiveModel::Serializer attributes :text, :items_count def items_count object.taggings_count end end
shared_examples 'maestro master' do |hostname = 'myhostname.acme.com'| it 'should honor hiera configuration' do should contain_class('maestro::maestro').with_version('present') end it { should contain_user('maestro') } it { should contain_group('maestro') } # it { should contain_user('jenkins') } it { ...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "money_column/version" Gem::Specification.new do |s| s.name = "money_column" s.version = MoneyColumn::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Tobias Lütke"] s.email = ["tobi@shopify.com"] s...
require 'yaml' require 'prowler' class Hash def symbolize_keys self.inject({}){|res, (key, val)| nkey = case key when String key.to_sym else key end nval = case val when Hash val.symbolize_keys else val end res[nkey] = nval ...
require 'minitest/autorun' require '../game' require '../player' require '../alien' class GameTest < MiniTest::Unit::TestCase def setup @game = Game.new end def test_initialize_positions assert_equal "0.0", @game.player.position end def test_set_coordinates_to_axis assert_equal "0.1", @game.ax...
module DefaultPageContent extend ActiveSupport::Concern included do before_action :set_title end def set_title @page_title = 'Udemy Portfolio' @seo_keywords = 'Alex Kibler Udemy Ruby Rails Portfolio' end end
class ChangeColumnToStage < ActiveRecord::Migration[4.2] def up remove_column :stages, :is_sunny, :boolean add_column :stages, :enable_sunny, :boolean, :default => false add_column :stages, :enable_rainy, :boolean, :default => false change_column :stages, :name_ja , :string , :null =>...
require "spec_helper" class CustomBuilder < ApiBlueprint::Builder end class PlainModel < ApiBlueprint::Model end class ConfiguredModel < ApiBlueprint::Model attribute :foo, Types::Any configure do |config| config.host = "http://foobar.com" config.parser = nil config.builder = CustomBuilder.new c...
require 'spec_helper' describe 'vault::install', :type => :class do context "On a Debian OS" do let :facts do { :osfamily => 'Debian', :operatingsystemrelease => '7', :concat_basedir => '/tmp', :lsbdistid => 'Debian', } end ...
module MicroserviceMinter extend ActiveSupport::Concern ## This overrides the default behavior, which is to ask Fedora for an id # @see ActiveFedora::Persistence.assign_id def assign_id service.mint_id_get.id if configured? end private def service @service ||= NulibMicroservices::DefaultApi...
class Report < ApplicationRecord has_many_attached :pre_damage_pictures has_many_attached :post_damage_pictures belongs_to :accident belongs_to :user accepts_nested_attributes_for :accident end
require_relative "journey.rb" require_relative "journeylog.rb" class Oystercard attr_reader :balance BALANCE_LIMIT = 90 MIN_FARE = 1 PEN_FARE = 6 def initialize @balance = 0 @journey_log = JourneyLog.new # @journey = Journey.new end def top_up(amount) raise "Max is #{BALANCE_LIMIT}" i...
class CreateSearches < ActiveRecord::Migration def change create_table :searches do |t| t.string :address_1 t.string :address_2 t.float :lat1 t.float :lng1 t.float :lat2 t.float :lng2 t.float :distance_traveled t.timestamps null: false end end end
namespace :app do desc "pass a file, get a solution for code night #3" task :solve, [:in_file, :out_file] => :environment do |t, args| iterations, cave = CaveFileParser.parse(args[:in_file]) p = ProgressBar.create(:title => "Contemplating...", :total => iterations) final_cave = App.new.solve(iteratio...
namespace :db do desc "Erase and fill database" task :populate => :environment do require 'populator' [Article, Category, Tag, Tagging].each(&:delete_all) Category.populate 4 do |category| category.name = Populator.words(1..3).titleize category.description = Populator.sentences(2..10) ...
class CreateRadios < ActiveRecord::Migration[5.0] def change create_table :radios do |t| t.string "num_serie" t.string "num_radio" t.string "identidade" t.string "prefixo" t.string "modelo" t.string "tipo" t.string "situacao" t.integer "work_place_id" t.timest...
module SponsorPay class Offer def initialize(data) @data = data end def thumbnail if @data['thumbnail']['lowres'] @data['thumbnail'] && @data['thumbnail']['lowres'] else '/static/images/no-thumb.png' end end def method_missing(method, *args, &block) ...
class ChangePictureOfCustomer < ActiveRecord::Migration def change rename_column :customers, :picture_uid, :picture_url end end
class Admission < ActiveRecord::Base validates_presence_of :patient, :moment belongs_to :patient has_many :diagnoses, as: :owner has_many :symptoms has_many :observations has_many :medications has_many :treatments has_many :diagnostic_procedures after_create :update_patient def get_patient_diagnose...
require 'rails_helper' RSpec.describe CourseApi do let(:stubs) { Faraday::Adapter::Test::Stubs.new } let(:conn) { Faraday.new { |b| b.adapter(:test, stubs) } } let(:course_api_client) { described_class.new(conn) } describe "retrieve course information based on course term and individual courses" do before...
require 'itpkg/services/site' class Projects::StoriesController < ApplicationController before_action :authenticate_user! before_action :check_user_authority before_action :prepare_story, except: [:new, :create, :index] def index @buttons = [] @stories = [] @story_type = params.delete(:type_name) ...
class AddFrontPageToPhotos < ActiveRecord::Migration def change add_column :photos, :front_page, :boolean, default: false end end
# frozen_string_literal: true class Course::Survey::Controller < Course::ComponentController load_and_authorize_resource :survey, through: :course, class: Course::Survey.name add_breadcrumb :index, :course_surveys_path private # Define survey component for the check whether the component is defined. # # @...
# # Migrate Payment Data From Heroku Application # # Usage: # bundle exec rails r ./script/migration_payment.rb migrate -f=#{path} # # Example: # bundle exec rails r ./script/migration_payment.rb migrate -f ./lib/tasks/input.json class MigrationPayment < Thor require 'json' ID_MAPPING_TABLE = { '54d30a520b0add0...
namespace :tasks do desc "Recomputes computed attribute values for all tasks stored in DB" task :recompute_attributes => :environment do user = User if ENV['user'] user = user.where :login => ENV['user'] end user.all.each do |user| puts "Recomputing tasks for #{user.login}" storage...
# == Schema Information # # Table name: cells # # id :bigint(8) not null, primary key # x :integer # y :integer # board_id :bigint(8) # created_at :datetime not null # updated_at :datetime not null # kind :integer # play...
# uppercase_check.rb # Write a method that takes a string argument, and returns `true` if all of the # alphabetic characters inside the string are uppercase, `false` otherwise. # Characters that are not alphabetic should be ignored. # Pseudo-code: # Data Structure: # input: a string # output: a boolean--true if all a...
# frozen_string_literal: true require "test_helper" class JobTest < ActiveSupport::TestCase %i[sample].each do |job| test "jobs(:#{job}) is valid" do model = jobs(job) assert model.valid?, "Expected jobs(:#{job}) to be valid, got errors: #{model.errors.full_messages.to_sentence}" end end end
require 'spec_helper' describe Temple do it { should validate_presence_of(:name) } it { should validate_presence_of(:country_id) } it { should validate_presence_of(:latitude) } it { should validate_presence_of(:longitude) } it { should belong_to(:country) } end
# -*- coding: utf-8 -*- class OperaWatir::Browser attr_accessor :driver, :active_window def self.settings=(settings={}) @opera_driver_settings = nil # Bust cache @settings = settings.merge! :launcher => OperaWatir::Platform.launcher, :path => OperaWatir::Platform.opera,...
class Favorite < ActiveRecord::Base belongs_to :user belongs_to :movie validates :movie_id, presence: true validates :user_id, presence: true end
#! /usr/bin/env ruby require 'nokogiri' require 'open-uri' require 'json' require 'gemoji' module SerialChapter #todo: Implement author method #Generic chapter reading class class Chapter def initialize(url, useragent="ruby", path = Dir.getwd + "/tmp") @doc = Nokogiri::HTML URI.open(url, {'User-Agent' => user...
require 'rails_helper' RSpec.describe Robot, type: :model do let!(:user) {User.create(username: 'test', email: 'test@gmail.com', password: 'password')} let!(:manufacturer) {Manufacturer.create!(name: "LKDVDLnjldksjldskj")} let!(:model) {Model.create!(model_designation: "RX113", manufacturer_id: manufacturer.id)}...
class CreateGroups < ActiveRecord::Migration def self.up create_table :groups do |t| t.column :name, :string, :default => "", :null => false t.column :owner_id, :integer t.column :created_at, :datetime end end def self.down drop_table :groups end end
class AddFieldsToResponses < ActiveRecord::Migration def change add_column :responses, :response_question, :string add_column :responses, :response_answer, :string end end
class Passenger < ApplicationRecord has_and_belongs_to_many :rides end
require "spec_helper" describe "Project collection list", reset: true do before(:each) do load_page :search, q: 'Minute (FIFE)' target_collection_result.click_link "Add collection to the current project" target_collection_result('30 Minute Rainfall Data (FIFE)').click_link "Add collection to the current...
# == Schema Information # # Table name: ingredients # # id :integer not null, primary key # description :text(200) not null # fresh :boolean default(FALSE), not null # name :string(50) not null # created_at :datetime not null # updated_at :datetime ...
class Dose < ApplicationRecord belongs_to :cocktail belongs_to :ingredient validates :description, presence: true validates :cocktail, presence: true validates :ingredient, presence: true validates_uniqueness_of :cocktail, scope: :ingredient end #A dose must have a description, a cocktail and an ingredient,...
require 'spec_helper' require 'ostruct' class MockImportable < OpenStruct include Topographer::Importer::Importable def self.create(params) self.new(params) end def valid? self.errors = OpenStruct.new(full_messages: []) if field_2 == 'datum2' true else self.errors = OpenStruct.new...
# == Schema Information # # Table name: records # # id :integer not null, primary key # doctor_id :integer # patient_id :integer # confirm :boolean default(FALSE) # finish :boolean default(FALSE) # created_at :datetime not null # updated_at :datetime not...
require 'active_support/concern' module MapperCommon extend ActiveSupport::Concern module ClassMethods DATE_REGEX = /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/ DATETIME_REGEX = /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+([01][0-9]|2[0-3]):([0-5][0-9])$/ def assig...
class ShoppingPointRecord < ActiveRecord::Base belongs_to :shopping_point belongs_to :order end
class Favorite < ActiveRecord::Base belongs_to :user belongs_to :favorite, :class_name => "User" def as_json(options) super(:include => { :user => {:only => [:uid, :name]}, :favorite => { :only => [:uid, :name] }}) end end
require 'date' feature "Says happy birthday if users birthday today" do scenario "User enters birthday and is shown page saying happy birthday" do time = Time.new day = time.day month = Date::MONTHNAMES[Date.today.month] visit('/') fill_in 'user_name', with: 'Ben' fill_in 'day', with: day ...
require 'rails_helper' feature 'User clicks on client in list', :js do describe 'and sees the messages page' do let!(:myuser) { create :user } let!(:myclient) { create :client, user: myuser } let(:rr) { ReportingRelationship.find_by(user: myuser, client: myclient) } context 'on the client list page'...
class MailLog < ApplicationRecord THRSHLD = 1.hour def self.sleep? latest = self.order('time DESC').first latest.time.localtime < Time.now - THRSHLD end end
=begin Copyright (C) 2011 Elliot Laster 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, copy, modify, merge, publish, distribut...
# Manage newsletter email template and emails class NewslettersController < ApplicationController before_action :set_newsletter, only: [:show, :preview, :edit, :update, :destroy] before_action :set_email, only: [:show, :preview] http_basic_authenticate_with name: 'naceda', password: 'vaidehi', ...
class Cocktail < ApplicationRecord belongs_to :search validates :recipe, presence: true validates :search_id, presence: :true end
# frozen_string_literal: true class BlocksController < ApplicationController before_action :logged_in_user def create @user = User.find(params[:blocked_id]) @current_user.block(@user) @current_user.unfollow(@user) if current_user.following?(@user) redirect_to "/users/#{@user.id}" flash[:noti...
FactoryBot.define do factory :price do category_id { 1 } age_id { 1 } free_price { Faker::Number.number } not_free_price { Faker::Number.number } end end
class AddRealToAsks < ActiveRecord::Migration def change add_column :asks, :real, :boolean end end
module TroleGroups::Api module Read def roles_from_rolegroups group_store.display_roles end def roles_for *names group_store.display_roles_for *names end # any? on rolegroups_list def in_rolegroup? rolegroup rolegroup_list.include? rolegroup.to_sym end alias...
module MessageDialog # 初期ステータスと現れた敵の表示 def initial_message(brave:,monster:) TermColor.blue puts <<~EOS =================== NAME:#{brave.name} HP:#{brave.hp} OFFENSE:#{brave.offense} DEFENSE:#{brave.defense} ITEM1:#{brave.item1} ITEM2:#{brave.item2} =================== E...
require 'oauth/controllers/provider_controller' class SessionsController < ApplicationController skip_before_filter :require_login def new unless current_user.nil? redirect_to current_user end end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authent...
class AddAgeGroupsToChurchCounts < ActiveRecord::Migration def change add_column :church_counts, :age_group, :string end end
class Ticket < ActiveRecord::Base belongs_to :llamada belongs_to :usuario has_many :historials has_many :adjuntos # acts_as_attachment :storage => :db_system, # :max_size => 1.megabytes, #validates_as_attachment validates_presence_of :prioridad, :estado, :enviar_a, :message => "no debe se...
module CloudCapacitor module Err class InvalidConfigurationError < ArgumentError end end end
require 'openssl' require_relative 'prf' module EncryptMessageHandler attr_accessor :pre_master, :encrypt_pre_master, :master, :version def initialize(server_random, client_random, certificate, version_major = 0x03, version_minor = 0x03) @version = [version_major, version_minor] ...
require 'micro_service/node' require 'logger' require 'rspec' require 'factory_girl' require 'database_cleaner' require 'webmock/rspec' WebMock.disable_net_connect!(allow_localhost: true) # Trigger AR to initialize ActiveRecord::Base #ActiveRecord::Base.logger = Logger.new(STDOUT) module Rails def self.root ...
class CocktailSerializer include FastJsonapi::ObjectSerializer attributes :id, :recipe end
module Todoable module ItemHelper BASE_URL = 'http://todoable.teachable.tech/api/lists'.freeze def create_item(list_id, name) response = invoke(:post, items_url(list_id), { item: { name: name } }) JSON.parse(response) end def mark_complete(list_id, item_id) invoke(:put,...
# -*- coding: utf-8 -*- # # Finder # domain = "com.apple.finder" # Display full POSIX path as Finder window title osx_defaults(domain, "_FXShowPosixPathInTitle" ){ value node[:osx_prefs][:finder][:show_full_path] } osx_defaults(domain, "ShowHardDrivesOnDesktop" ){ value node[:osx_prefs][:finder][:show_hard_drive...
require 'forwardable' module MarsRover class InvalidOrientationError < StandardError; end class Orientation extend Forwardable def_delegators :@direction, :move def initialize(direction) klass = case direction when 'N' then North when 'E' then East when 'S...
class AddDefaultToTitle < ActiveRecord::Migration def change change_column :pictures, :title, :string, default: "*" end end
require 'open-uri' class Xvideo < ActiveRecord::Base before_validation :set_title_and_thumb_url has_many :watch_histories, dependent: :destroy has_many :watched_users, through: :watch_histories, source: :user has_many :favorite_videos, dependent: :destroy has_many :favorited_users, through: :favorite_video...
# # Author:: Celso Fernandes (<fernandes@zertico.com>) # © Copyright IBM Corporation 2015. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # require 'fog/core/model' module Fog module Softlayer class Product class Package < Fog::Model # A package's internal identifier. Everything regarding ...
class IaScoresController < ApplicationController before_filter [:login_required,:check_icse_configuration] filter_access_to [:ia_scores,:update_ia_score],:attribute_check=>true, :load_method => lambda { Exam.find params[:exam_id] } check_request_fingerprint :update_ia_score def ia_scores fa_score_data ...
module Fastlane module Actions class CollateHtmlReportsAction < Action def self.run(params) report_filepaths = params[:reports] if report_filepaths.size == 1 FileUtils.cp(report_filepaths[0], params[:collated_report]) else reports = opened_reports(report_filepaths...
class AddColumnsToUserGroup < ActiveRecord::Migration def change add_column :user_groups, :user_name, :string end end
=begin EST - SIMPLE EVENT PAGES CONTROLLER v.1.2a Author: Estriole also credits: 1) Tsukihime for giving me inspiration to create this script. 2) Killozapit for giving me idea to use actual event pages so it can used by other event Version History v.1.0 - 2013-01-13 - finish the script v.1.1 - 2013-01-16 - add a...
# RenameVM.rb # # Description: This method renames a VM in vCenter # require 'savon' def login(client, username, password) result = client.call(:login) do message( :_this => "SessionManager", :userName => username, :password => password ) end client.globals.headers({ "Cookie" => result.http.headers["Set-Coo...
module Reuters module Namespaces module Search # Represents the Search All namespace that can be # used to query for information about all types of listings module All # @!parse include Base include Base # Year for the Search Equity endpoint. mattr_accessor :ye...
prefix = File.dirname( __FILE__ ) # Directory variables src_dir = File.join( prefix, 'src' ) build_dir = File.join( prefix, 'build' ) test_dir = File.join( prefix, 'test' ) # A different destination directory can be set by # setting DIST_DIR before calling rake dist_dir = ENV['DIST_DIR'] || File.join( prefix, ...
require "spec_helper" RSpec.describe Veeqo::DeliveryMethod do describe ".list" do it "retrieves all the develiery methods" do filters = { page: 1, page_size: 12 } stub_veeqo_delivery_method_list_api(filters) delivery_methods = Veeqo::DeliveryMethod.list(filters) expect(delivery_methods....
# Read about factories at https://github.com/thoughtbot/factory_bot FactoryBot.define do factory :observation_collection do observations do |o| array = [] 10.times { array << build(:observation) } array end trait :full_day do observations do |o| array = [] (0..23)...
require 'sinatra' require 'sinatra/reloader'if development? get '/' do def caesar(string,shift) letter = string.downcase.split("").map do |str| small = str.ord + shift if str.ord < 97 && str.ord > 26 str = str elsif str.ord+shift > 122 str = str....
class Event < ApplicationRecord has_many :participants, dependent: :destroy end