text
stringlengths
10
2.61M
class Forecasts::InvestorsController < ApplicationController before_action :set_forecast before_action :set_investor, only: [:show, :edit, :update, :destroy] def new @investor = Investor.new @investor.forecast_id = @forecast.id end def create @investor = Investor.new(investor_params) respon...
class Placetextblock < ActiveRecord::Base belongs_to :showplace, :inverse_of => :placetextblocks belongs_to :textblock, :inverse_of => :placetextblocks belongs_to :othershowplace, :class_name => 'Showplace', :foreign_key => 'othershowplace_id' attr_accessible :textblock_id, :caption attr_accessible :country_i...
class AddOwnerRefToConnector < ActiveRecord::Migration[5.2] def change add_reference :connectors, :owner, foreign_key: { to_table: :users } end end
require 'rubygems' require 'ohm' require 'uri' require '../lib/wave' class WaveServer < Ohm::Model collection :waves, :Wave, :waveserver attribute :url unique :url index :url def[](waveid) return Wave.create :waveid=>waveid.to_s, :waveserver=>self if self.waves.find(:waveid => waveid.to_s).empty? #...
require "rails_helper" RSpec.describe User do it 'has a valid factory' do factory = FactoryGirl.create(:user) expect(factory).to be_valid end it 'is valid with valid attributes' do user = FactoryGirl.build(:user) expect(user).to be_valid end it 'is not valid without a email' do user = F...
json.array!(@survivors) do |survivor| json.extract! survivor, :id, :name, :picture json.url survivor_url(survivor, format: :json) end
require 'chefspec' RSpec.configure do |config| config.cookbook_path = 'cookbooks' end describe 'outside' do it 'renders template with partial from inside' do runner = ChefSpec::Runner.new runner.converge("recipe[outside]") expect(runner).to render_file('/tmp/partial_from_inside.txt').with_content('...
class Organisation < ActiveRecord::Base has_many :gameplans attr_accessible :name end
class LocationsController < ApplicationController ##inheriting from the application controller #ACTIONS ->index, show, create, destroy def index render :json => Location.all, :include => :movie end def show #show the locations @location = Location.find(params[:movie_id,])#w...
class User < ApplicationRecord self.table_name = 'users' has_secure_password belongs_to :device, class_name: 'GlobalDevice', required: false has_one :profile, class_name: 'User::Profile' has_many :orders, class_name: 'Order' has_many :favorites, class_name: 'User::Favorite' has_many :transactions, class_...
require_relative "../config/environment.rb" require 'active_support/inflector' class InteractiveRecord def self.table_name self.to_s.downcase.pluralize end def self.column_names table_info = DB[:conn].execute("PRAGMA table_info('#{self.table_name}')") column_names = [] table_info.each do |colum...
class CreateRevisions < ActiveRecord::Migration def change create_table :revisions do |t| t.text :name_review t.text :location_review t.text :season_review t.text :trailtype_review t.text :gps_review t.text :traildirections_review t.references :trail, index: true t....
class AddShopIdToBoatForSale < ActiveRecord::Migration[5.0] def change add_column :boat_for_sales, :shop_id, :integer end end
FactoryGirl.define do factory :item do name "MyString" description "MyString" image_data "MyText" starting_bid 1 bid_increment 1 lot_number 1 category "MyString" auction nil end end
require 'thor' require 'thor/actions' require 'couchwatcher' require 'couchpack' module CouchPack class CLI < ::Thor include Thor::Actions class_option "version", :type => :boolean, :aliases => '-v', :banner => "print version and exit" default_task :help def initialize(*) ...
require "rails_helper" RSpec.describe RoomsController, type: :controller do let(:room_type) {FactoryBot.create :room_type} let(:room) {FactoryBot.create :room, room_type_id: room_type.id} describe "GET /show" do context "when room exist" do it "should redirect to room page" do get :show, params...
# Shower simulator -- With Extras!! Buy the season pass for an extra ending! puts 'You wake up. What do you do?' puts '-' * 20 puts "Do you 'Get out of bed' or do you 'Stay in bed'?" puts '-' * 20 wakeup = gets.chomp.downcase if wakeup == 'get out of bed' puts '-' * 20 puts 'You got out of bed.' puts '-' ...
#!/usr/bin/env ruby # == Synopsis # # start.rb: Starts up an EnWikiBot and connects it to a specified IRC server and channel # # == Usage # # ruby start.rb OPTIONS # # -h, --help: # show help # # --server hostname, -s hostname: # required, the hostname of the server to connect to # # --channel name, -c name: # ...
class CreateSoccerFields < ActiveRecord::Migration def change create_table :soccer_fields do |t| t.references :league t.references :team t.string :name, :null => false t.string :address, :null => false end end end
class Taxonomy < ActiveRecord::Migration def self.up create_table :taxon_families do |t| t.string :name, :null => false t.boolean :can_have_only_one, :default => false t.boolean :for_issues, :default => false t.boolean :for_users, :default => false t.boolean :for_blogs, :default => f...
module ActualResults class SubmittionState attr_reader :problem_id attr_reader :tests attr_reader :passed_tests attr_reader :attemps attr_reader :penalty_time attr_reader :last_run_time attr_reader :points def initialize(problem_id) @problem_id = problem_id @test...
cask 'taskpaper' do version '1.0' sha256 '45f4c0715990580a9b7ba716089fcf03e5423ebdd849e4761c5e33d7fe6a6a99' url "https://www.taskpaper.com/assets/app/TaskPaper-#{version}.zip" name 'TaskPaper' homepage 'https://www.taskpaper.com/' app "TaskPaper-#{version}.app" end
module Minstrel class Authentication < Sequel::Model many_to_one :user many_to_one :identity def validate super validates_presence [:user_id, :identity_id] end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def check_for_users if !parent_signed_in? && !sitter_signed_in? authenticate_parent! end end end
# frozen_string_literal: true FactoryBot.define do factory :organization do slug { SecureRandom.uuid } name { SecureRandom.uuid } end end
require 'pry' require 'yaml/store' require_relative 'tasks.rb' class TodoList attr_reader :tasks, :user def initialize(user) @todo_store = YAML::Store.new("./public/tasks.yml") @tasks = [] @user = user end def save @todo_store.transaction do @todo_store[@us...
class AddEmployeeToRole < ActiveRecord::Migration[6.1] def change add_reference :roles, :employee, null: false, foreign_key: true end end
class RenameTotalBudgetForOffers < ActiveRecord::Migration def up rename_column :offers, :total_budget, :total_budget_cents end def down rename_column :offers, :total_budget_cents, :total_budget end end
class CreatePatients < ActiveRecord::Migration def change create_table :patients do |t| t.integer :location_id t.string :first_name t.string :last_name t.string :address_street1 t.string :address_street2 t.string :address_city t.string :address_state t.string :addre...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :signed_in?, :is_current_user? before_filter { |controller| session[:restore_url] = request.url if controller.controller_name != "sessions" && !request.xhr? } rescue_from CanCan::AccessDenied do |exception| ...
require "includes" class SongSwingerTest < Minitest::Test def test_full_song_swing_rate_8 base_path = File.dirname(__FILE__) + "/sounds" song, _ = SongParser.parse(base_path, File.read("test/fixtures/valid/example_mono_16_base_path.txt")) shuffled_song = Transforms::SongSwinger.transform(song, 8) a...
class PostsController < ApplicationController before_action :set_post, only: [:show,:edit,:update,:destroy] before_action :authenticate_user!, except: [:index,:show] def show #byebug #@post=Post.find(params[:id]) @comments= @post.comments.order('comments.created_at DESC') end ...
# Install and manage worklist service # Config dcm4che_prefix = '/usr/local' dcm4che_zipfile = node[:wicoris][:worklist][:dcm4che_source].split('/').last dcm4che_basedir = File.join(dcm4che_prefix, dcm4che_zipfile[/^(.*)-bin\.zip$/,1]) dcm4che_logdir = '/var/log/dcm4che' # Dcm4che dcm4...
class Tournament::NotReady < Tournament::Result def initialize ; end def to_partial_path 'tournaments/result_not_ready' end end
require 'chemistry/element' Chemistry::Element.define "Rhodium" do symbol "Rh" atomic_number 45 atomic_weight 102.90550 melting_point '2239K' end
class FontMigu1c < Formula version "20150712" sha256 "62aba11af4e5343b5437c866e3747366d084b63885539c92636222d2978999f1" url "https://osdn.dl.osdn.jp/mix-mplus-ipa/63545/migu-1c-#{version}.zip" desc "Migu 1C" homepage "https://mix-mplus-ipa.osdn.jp/migu/#migu1c" def install parent = File.dirname(Dir.pwd)...
class CreateRecommendations < ActiveRecord::Migration def change create_table :recommendations do |t| t.integer :price t.string :review t.string :strengths, array: true t.string :ambiences, array: true t.references :user, index: true t.references :restaurant, index: true ...
require 'machinist/mongo_mapper' # or mongoid CollectorWorker.blueprint do url { "http://#{sn}.collector.com" } end AccessToken.blueprint do key { "test_key_#{sn}" } user_application { UserApplication.make! } end UserApplication.blueprint do name { "#{sn}_application"} user { User.make! } end User.bluep...
class ReservationsController < ApplicationController before_action :set_reservation, only: [:show, :edit, :update, :destroy] def index @reservations = Reservation.all end def new @reservation = Reservation.new end def create user_id = current_user.id @reservation = Reservation.new(reserva...
class IgnoredSuperClass def instance_method #shouldn't be documented end end module IgnoredModule def instance_method #shouldn't be documented super end end class TestClass < IgnoredSuperClass include IgnoredModule # DDOC 2018-06-17 # @return [String] Example "class_method return value" #...
#!/usr/bin/env ruby require 'pathname' require 'fileutils' include FileUtils # path to your application root. APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) def system!(*args) system(*args) || abort("\n== Command #{args} failed ==") end chdir APP_ROOT do # This script is a starting point to setup y...
# frozen_string_literal: true module ActiveAny class Relation module FinderMethods def find_by(condition) where(condition).take end def first(limit = nil) if loaded limit ? records.first(limit) : records.first else limit ? spawn.records.first(limit) ...
class ResBoardsController < ApplicationController before_action :set_res_board, only: [:show, :edit, :update, :destroy] # GET /res_boards # GET /res_boards.json def index @res_boards = ResBoard.all end # GET /res_boards/1 # GET /res_boards/1.json def show end # GET /res_boards/new def new ...
require 'google_drive' require 'faker' require 'pp' class Attendance def initialize @session = GoogleDrive.saved_session("config.json") @sheet = @session.spreadsheet_by_title("2019-2020 Attendance Tracker") @hours = @sheet.worksheets[0] end def session @session end def set(row, col,value...
class Session < ApplicationRecord belongs_to :user before_create :set_attributes attr_accessor :token, :remember_token scope :expired, -> { where("expires_at < ?", Time.current) } scope :available, -> { where("expires_at > ?", Time.current).where(remember_digest: nil) } def token_matches?(t) BCrypt:...
# coding: utf-8 module Paperclip class ManualCroper < Thumbnail def transformation_command crop_command + super.reject { |t| t =~ /-crop/ } end private def crop_command model = @attachment.instance reduction_scale = image_reduction_scale(@attachment, model) crop_w = (Intege...
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". root 'fetches#index' post 'fetches' => 'fetches#create' end
# frozen_string_literal: true require 'bundler/setup' require 'irb' require 'dry-schema' schema = Dry::Schema.Params do required(:name).filled(:string) required(:age).filled(:integer) end input = { name: 'Seb', age: '19' } result = schema.call(input) result.success? # => true result.to_h # => { name: 'Seb', age...
# # Cookbook Name:: deploy_user # Recipe:: default # # Copyright 2013, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # node_user = node['deploy_user']['user'] node_group = node['deploy_user']['group'] user node_user group node_group group "wheel" do action [:modify] members [node_user] append...
# frozen_string_literal: true module NotificationDetail def self.[](type) Module.new do extend ActiveSupport::Concern included do belongs_to :notification validates :notification, presence: true delegate :title, to: :notification end class_methods do defin...
require 'fastlane/action' require_relative '../helper/jira_issue_link_helper' module Fastlane module Actions class JiraIssueLinkAction < Action def self.run(params) Actions.verify_gem!('jira-ruby') require 'jira-ruby' site = params[:url] auth_type = :basic ...
# frozen_string_literal: true Gem::Specification.new do |s| s.name = 'send_file_with_range' s.description = 'A Rails addition which will allow sending of files with appropriate range headers' s.summary = s.description s.homepage = 'https://github.com/adamcooke/send_file_with_rangeit' s....
class Country < ApplicationRecord has_many :users validates_presence_of :code, :name validates_uniqueness_of :code, :name end
class CreatePlants < ActiveRecord::Migration[5.0] def change create_table :plants do |t| t.string :plant_type t.string :genus t.string :species t.string :common_name t.string :source t.date :acquired_date t.boolean :grown_from_seed t.date :planted_date t.integ...
class CreateEdges < ActiveRecord::Migration[6.0] def change create_table :edges do |t| t.string :name t.string :source t.string :destiny t.integer :value end end end
class Category < ActiveRecord::Base attr_accessible :title, :parent_id, :discription, :user_id validates_presence_of :title, :message => "Title can't be nill" validates_presence_of :user_id belongs_to :user has_many :depots has_ancestry def self.arrange_as_array(options = {}, hash = nil) hash ||= arra...
class FontBesley < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/besley" desc "Besley" desc "Designed by owen earl (indestructible type*)" homepage "https://fonts.google.com/specimen/Besley" def install (share/"fonts").install "Bes...
class Game def initialize(player1, player2) @player1 = player1 @player2 = player2 @players = [@player1, @player2] end BEATS = {rock: :scissors, scissors: :paper, paper: :rock} attr_reader :players, :player1, :player2 def winner return "Draw" if player1.pick == player2.pick return player1 if BEATS[no...
class CategoriesController < ApplicationController load_and_authorize_resource def index @categories = Category.all end def show end def new end def edit end def create if @category.save(category_params) redirect_to @category, notice: t("success.notices.create", resource: "Categor...
module CDI module V1 module Discussions class PostDiscussionToSubscribersService < BaseService def initialize discussion, options={} @discussion = discussion super options end def execute if can_execute? users.each { |user| create_subscribe...
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '商品出品の保存' do context "商品情報が保存できる場合" do it "全ての情報が入力されていればは保存される" do expect(@item).to be_valid end end context "商品情報が保存できない場合" do it "商品名がないと商品情報は保存できない" do...
# frozen_string_literal: true describe Zafira::Api::ZafiraStatus do let(:client) { build(:zafira_client, :with_environment, :rspec) } let(:environment) { client.environment } let(:token) { Zafira::Api::ZafiraStatus.new(client) } describe '#get' do before do stub_request(:get, /#{environment.zafira_...
require 'simplecov' require "veyor" require "test/unit" class TestProjectHistory < Test::Unit::TestCase def test_project_history_basic res = Veyor.project_history(project: 'cowsay') assert_equal(Hash, res.class) assert_equal(Array, res['builds'].collect { |x| x['status'] }.class) assert_equal('sckot...
class AddTeacherIdToWorkGroup < ActiveRecord::Migration def change add_column :work_groups, :teacher_id, :integer, null: false, default: 0 add_index :work_groups, :teacher_id end end
# frozen_string_literal: true require 'integration_helper' module Vacuum class TestRequest < IntegrationTest def test_get_browse_nodes requests.each do |request| response = request.get_browse_nodes(browse_node_ids: ['3045']) assert_equal 200, response.status end end def test...
# frozen_string_literal: true module Kruger class Client module Divisions def divisions get('/divisions', access_token: @access_token) end end end end
# frozen_string_literal: true class UserEntry < ApplicationRecord belongs_to :user belongs_to :entry validates :entry_id, uniqueness: { scope: :user_id, message: 'No duplicate entries allowed' } end
module PageDesc module Types module Element extend Action action :text do browser_element.text end action :has_text? do |text| browser_element.has_text?(text) end action :css_class do browser_element[:class] end action :attribute do |attr...
json.array! pages do |page| json.id page.id.to_s json.uid page.uid json.username page.username end
class CreatePhysicaldetails < ActiveRecord::Migration def change create_table :physicaldetails do |t| t.integer :user_id t.decimal :height t.decimal :weight t.string :skin_tone t.string :hair_color t.string :eye_color t.string :physical_status t.string :body_type ...
class Jobrog < Formula desc "Command-line time tracking and note taking utility" homepage "https://github.com/dfhoughton/jobrog" url "https://github.com/dfhoughton/jobrog/archive/1.0.2.tar.gz" sha256 "1af0c8b66da09b1c12aaab745a62c2ddfa07333fbada67d0fc0183dbdc863b8b" revision 3 depends_on "rust" => :build ...
module AerospikeRecord class LogSubscriber < ActiveSupport::LogSubscriber def logger AerospikeRecord::Base.logger end end end AerospikeRecord::LogSubscriber.attach_to :aerospike_record
class Api::V1::AddressSerializer < ActiveModel::Serializer attributes :id, :street, :city, :state, :zip, :provider_id embed :ids, include: true has_one :provider, key: :providers, root: :providers, serializer: Api::V1::ProviderSerializer ...
class Editconnectionworkshop < ActiveRecord::Migration def change remove_column :workshop_images, :workshops_id add_column :workshop_images, :workshop_id, :integer end end
title = ['Chapter 1: Getting Started','Chapter 2: Numbers','Chapter 3: Letters'] pages = ['Page 1','page 9','page 13'] linewidth = 30 center = linewidth / 2 puts header = '*Table of Contents*' puts header.center linewidth puts title.zip(pages) do |title, pages| puts "#{title.ljust(center)} #{pages.rjust(cente...
require 'spec_helper' describe 'locations/none' do let(:organizers) { [build(:user, id: 123)] } let(:stats) { { participants: 10, topics: 2 } } it 'renders successfully' do %w[en de].each do |locale| I18n.with_locale(locale) do allow(view).to receive_messages(organizers:, stats:) rende...
module Darksky class Client attr_accessor :configuration def initialize(configuration = Darksky.configuration) @configuration = configuration end def forecast(latitude, longitude, opts={}) url = "#{@configuration.host}/forecast/#{@configuration.api_key}/#{latitude},#{long...
class RemoveExcProcFromLog < ActiveRecord::Migration def change remove_column :task_logs, :exc_process, :string end end
module MangoPayV1 # In order to make an expense you need to get a list of expense sites and then redirect a user to ExpenseURL. # When the user selects a product and pays, you will be notified about an expense through the notification mechanism. class Expense < MangoPayV1::Ressource # Get an expense # ...
include Chef::Mixin::ShellOut def load_current_resource @zpool = Chef::Resource::Zpool.new(new_resource.name) @zpool.name(new_resource.name) @zpool.disks(new_resource.disks) @zpool.info(info) @zpool.state(state) end action :create do if created? if online? @zpool.disks.each do |disk| sh...
require 'rails_helper' RSpec.describe User, type: :model do pending "not sure how to get these working" do it{ should normalize_attribute( :last_callsign ).from(' red XIII ').to('red xiii') } it{ should normalize_attribute( :last_callsign ).from(' ').to( nil ) } end it "should default status to acti...
class CreateTransportFeeCollectionAssignments < ActiveRecord::Migration def self.up create_table :transport_fee_collection_assignments do |t| t.references :transport_fee_collection t.string :assignee_type t.integer :assignee_id t.integer :school_id t.timestamps end end def ...
# 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!(@available_times) do |available_time| json.extract! available_time, :id, :debate_id, :proposed_by, :proposed_to, :proposed_time, :status json.url available_time_url(available_time, format: :json) end
require 'rails_helper' feature 'sending mass messages', active_job: true do let(:message_body) { 'You have an appointment tomorrow at 10am' } let(:long_message_body) { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent aliquam consequat mauris id sollicitudin. Aenean nisi nibh, ullamcorper non just...
class Api::V1::ReportsController < Api::V1::ApiController before_action :authenticate! api :GET, '/reports', 'Report yaumiyah bulanan' param_group :auth, Api::V1::ApiController param :user_id, String, desc: "User ID" param :month, Integer, desc: 'Januari: 1, Februari: 2, Maret: 3, dll', required: true para...
# frozen_string_literal: true describe Zafira::Operations::User::RefreshToken do let(:client) do build(:zafira_client, :with_environment, :rspec) end let(:env) { client.environment } let(:refresher) { Zafira::Operations::User::RefreshToken.new(client) } before do logger_mock = double('refresher.lo...
class AddDefaultForRatings < ActiveRecord::Migration def change change_column :reviews, :personal_rating, :float, default: 0 change_column :reviews, :location_rating, :float, default: 0 change_column :reviews, :infrastructure_rating, :float, :default => 0 change_column :reviews, :field_rating, :float,...
class DisciplineMonitorProfessor < ApplicationRecord validates :professor, presence: true validates :discipline_monitor, presence: true belongs_to :professor belongs_to :discipline_monitor accepts_nested_attributes_for :professor, reject_if: :all_blank, allow_destroy: true end
require 'data_mapper' require 'dm-paperclip' require 'digest' Paperclip.configure do |config| config.use_dm_validations = true end class Track include DataMapper::Resource include Paperclip::Resource property :id, Serial property :title, String, required: true property :difficulty, String property :pla...
class ChangeColumnType < ActiveRecord::Migration def change change_column :pages, :prelude, :text change_column :pages, :preview, :text end end
class AddLoadDateToLaboratoryWork < ActiveRecord::Migration[5.1] def change add_column :laboratory_works, :load_date, :date end end
class RestoAdmin::RestaurantController < RestoAdmin::BaseApiController def show @restaurant = @branch_group.restaurant end def update @restaurant = @branch_group.restaurant @restaurant.assign_attributes(restaurant_params) @restaurant.logo = decode_image if params[:img] if @restaurant.save ...
require_relative 'floor' # A room in the dungeon. class Room def initialize(seed) @rng = Random.new(seed) @length = @rng.rand(4..10) # y-axis @width = @rng.rand(4..10) # x-axis @origin = { x: 0, y: 0 } @plan = Array.new(@length) { Array.new(@width) { Floor.new } } end attr_reader :plan a...
class ChangeOptColumnToBanks < ActiveRecord::Migration[5.0] def change change_column(:banks, :opt, :string) end end
class MarketsController < ApplicationController # GET /markets def index @markets = Market.all render json: @markets end end
module Utils module CorsMixin def cors_preflight_check if request.method == :options headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, PATCH, DELETE, GET, OPTIONS' headers['Access-Control-Request-Method'] = '*' headers['Access-Con...
class CreateItems < ActiveRecord::Migration def change create_table :items do |t| t.string :description t.float :amount t.string :date t.integer :list_id t.integer :user_id end end end
json.event do json.partial! @event json.event_times @event.event_times.pluck :start_time json.tags @event.tags.pluck :id json.users @event.users.pluck :id json.venue_name @event.venue.name unless @event.venue.nil? json.venue_slug @event.venue.slug unless @event.venue.nil? json.city @event.city.id end jso...
require "codefly/version" # we need to hack ActiveRecord to read :connection variable from the thread module ActiveRecord module ConnectionAdapters class ConnectionHandler def retrieve_connection(klass) #:nodoc: pool = retrieve_connection_pool(klass) raise ConnectionNotEstablished, "No conn...