text
stringlengths
10
2.61M
class TracksController < ApplicationController def show @track = Track.find_by(id: params[:id]) render :show end # GET /tracks/new def new @track = Track.new @parent_album = Album.find_by(id: params[:album_id]) render :new end # GET /tracks/1/edit def edit @track = Track.find_by...
# frozen_string_literal: true # # Include in specs for classes that are +AffiliateAccount+s. # Tests here expect an instance variable +@account_attrs+ to # exist. +@account_attrs+ should be a +Hash+ of attributes for # #creating!ing an instance of the class being tested module AffiliateAccountHelper def self.includ...
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" remote_user = ENV['ANSIBLE_REMOTE_USER'] raise "You need to set ANSIBLE_REMOTE_USER in your shell" unless remote_user # Add user #{remote_user} with group wheel $cr...
class FirstAssociatesTransaction < ActiveRecord::Base belongs_to :first_associates_report has_one :reconciliation, class: FirstAssociatesReconciliation def reconciled? !!reconciliation && reconciliation.persisted? end def reconcile!(other_account_id, current_admin) transaction do # database transact...
# Copyright (c) 2009-2011 VMware, Inc. $:.unshift(File.dirname(__FILE__)) require 'spec_helper' describe BackupManagerTests do it "should be able to terminated while manager is sleeping" do EM.run do pid = Process.pid manager = BackupManagerTests.create_manager("empty", "backups") EM.defer do ...
class Integer def factorial num = self if num < 0 return "You can\'t take the factorial of a negative number!" end if num <= 1 1 else num * (num-1).factorial end end end puts 4.factorial
class PersonTypeOfBirth < ActiveRecord::Base self.table_name = :person_type_of_births self.primary_key = :person_type_of_birth_id include EbrsMetadata has_many :person_birth_details, foreign_key: "person_type_of_birth_id" end
require "rubygems" begin require 'spec/rake/spectask' rescue LoadError desc "Run specs" task(:spec) { $stderr.puts '`gem install rspec` to run specs' } else desc "Run API and Core specs" Spec::Rake::SpecTask.new do |t| t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""] t.spec...
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/conn' require 'bolt_spec/files' require 'bolt_spec/integration' describe 'using module based plugins' do include BoltSpec::Conn include BoltSpec::Integration def with_boltdir(config: nil, inventory: nil, plan: nil) Dir.mktmpdir do |tmpd...
require 'date' class Puppet < Botpop::Plugin include Cinch::Plugin match(/^!pm (\#*\w+) (.*)/, use_prefix: false, method: :send_privmsg) match(/^!join (\#\w+)/, use_prefix: false, method: :join) match(/^!part (\#\w+)/, use_prefix: false, method: :part) # Email handlement EMAIL = '[[:alnum:]\.\-_]{1,64}@[...
class LibraryBuildingDe < ActiveRecord::Base # Relations belongs_to :library_building end
=begin Основная идея в том, что в треде дергаем set_lock чтобы привязать коннектор к треду. Пока тред не закончил работу или не дернули в нем release_lock коннектор пропускается при выборе. Выдвать коннекторы надо из main треда. Верней лучше из того потока где менеджер создан. Чтобы не получать 1 коннектор в разных...
module API # Timesheets API class Timesheets < Grape::API before { authenticate! } helpers do def compute_end(start) endDate = DateTime.strptime(start, "%Y%m%d") endDate += 6.days endDate.strftime("%Y%m%d") end def find_member(project_id, user_id) P...
# require 'active_support/all' class Player attr_accessor :live, :name, :id def initialize(live, name, id) @live = live @id = id @name = "Player #{name}" end def name=(name) @name = name end def live_update @live = @live - 1 end end
class AddWeightToOrderItem < ActiveRecord::Migration def self.up add_column :order_items, :product_weight, :integer,:default=>0 end def self.down remove_column :order_items, :product_weight end end
class CreateMatch < ActiveRecord::Migration def change create_table :matches do |t| t.integer :result t.datetime :date_played t.references :home_team, index: true t.references :visitor_team, index: true t.references :toto_form, index: true end end end
# == Schema Information # # Table name: characters # # banner_id :integer # created_at :datetime not null # description :text # id :integer not null, primary key # is_deleted :boolean default(FALSE) # name :string # slug :string # species :string # updat...
class FundingLevel < ActiveRecord::Base belongs_to :project has_many :pledges validates :project, :presence => true validates :reward_name, length: { minimum: 3 } validates :amount, numericality: { greater_than: 0 } end
require 'test_helper' class CassandraObject::BaseTest < CassandraObject::TestCase class Son < CassandraObject::Base end class Grandson < Son end test 'base_class' do assert_equal CassandraObject::Base, CassandraObject::Base assert_equal Son, Son.base_class assert_equal Son, Grandson.base_class ...
class PemFilesController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_pem_file, only: [:show, :edit, :update, :destroy] # GET /pem_files # GET /pem_files.json def index @pem_file = PemFile.where(email: session[:user_email]).where(status: PemFile::ACTIVE).last ...
class CreateTrackers < ActiveRecord::Migration def change create_table :trackers do |t| t.string :driver_name t.string :mobile_number t.string :imei t.string :truck_registration_number t.timestamps end end end
class AddApprovedColumnsToMemberApplications < ActiveRecord::Migration[5.0] def change add_column :member_applications, :approved_at, :datetime add_column :member_applications, :approver_id, :integer end end
# -*- mode: ruby -*- # vi: set ft=ruby sw=2 ts=2 sts=2 et : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # root off of the rackspace provider dummy box config.vm.box = "dummy" # rackspace sy...
require 'rails_helper' feature 'Twilio' do let(:message_params) { twilio_new_message_params } let(:status_params) { twilio_status_update_params from_number: message_params['From'], sms_sid: message_params['SmsSid'] } before do userone = create :user clientone = create :client, user: userone, phone_numbe...
# Replace in the "<???>" with the appropriate method (and arguments, if any). # Uncomment the calls to catch these methods red-handed. # When there's more than one suspect who could have # committed the crime, add additional calls to prove it. <<<<<<< HEAD p "iNvEsTiGaTiOn".swapcase # => "InVeStIgAtIoN” p "zom".inse...
class ScoresController < ApplicationController before_action :set_score, only: [:show, :edit, :update, :destroy] before_action :set_team before_action :set_cheats, only: [:new, :edit] before_action :set_holes, only: [:new, :edit] before_action :restore_cheats, only: [:destroy] after_action :update_cheats, o...
# caesar.rb # # Description:: Basic caesar-like cipher # Author:: Ollivier Robert <roberto@keltia.net> # Copyright:: 2001-2013 © by Ollivier Robert # # $Id: caesar.rb,v 9ea677b34eed 2013/03/10 18:49:14 roberto $ require 'key/caesar' require 'cipher/subst' module Cipher # == Caesar # # Caesar cipher, monoalphab...
# -*- mode: ruby -*- # vi: set ft=ruby : # bootstrap script partially copied from https://github.com/Lukx/vagrant-lamp $script = <<SCRIPT apt-get update apt-get -y install git mc golang apt-get -y install mercurial meld export GOPATH=~/ echo export GOPATH=$GOPATH >> ~/.bash_profile export PATH...
class Ipbt < Formula desc "Program for recording a UNIX terminal session" homepage "https://www.chiark.greenend.org.uk/~sgtatham/ipbt/" url "https://www.chiark.greenend.org.uk/~sgtatham/ipbt/ipbt-20170829.a9b4869.tar.gz" mirror "https://dl.bintray.com/homebrew/mirror/ipbt-20170829.tar.gz" version "20170829" ...
# frozen_string_literal: true FactoryBot.define do factory :collaborator do name { Faker::Company.name } email { Faker::Internet.safe_email } company manager { nil } end end
class ChangeMessageDefaultValues < ActiveRecord::Migration[5.0] def change change_column_default :messages, :approved, true change_column_default :messages, :votes, 0 end end
require 'spec_helper' describe Artist do let(:subject) { Artist.new(:similar_artists => [@similar_artist_name]) } before(:each) do @first_song = double @second_song = double @first_album = double(:tracks => [@first_song], :original_tracks => [@first_song]) @second_album = double(:tracks => [@...
module Troles::Adapters::ActiveRecord class Config < Troles::Common::Config attr_reader :models def initialize subject_class, options = {} super puts "models classes: #{subject_class}, #{object_model}, #{join_model}" @models = ::Schemaker::Models.new(subject_class, object_mode...
class Api::V1::TracksController < ApplicationController private def track_params params.require(:track).permit(:name, :length) params.permit(:query) end end
# EXCERXCISE 4 1. "FALSE" 2. "did you get it right?" 3. "Alright now!" # EXCERCISE 5 "You get this error message because this is no reserve word 'end', for the if/else statement. It is expecting the keyword 'end' to close equal_to_four method. That 'end' was not found. We want to place the additional 'end' on line 6...
class Cart attr_reader :id attr_accessor :x, :y, :dir, :turns LEFT = { "^" => "<", "v" => ">", "<" => "v", ">" => "^", } RIGHT = { "^" => ">", "v" => "<", "<" => "^", ">" => "v", } def self.next_id @id ||= 0 @id += 1 end def initialize(x, y, dir) @id = s...
=begin * Modelo de la tabla ProductLine de la base de datos * @author rails * @version 14-10-2017 =end class ProductLine < ApplicationRecord has_many :products validates :name, format: {with: /\A[a-zA-Z ]+\p{Latin}+\z/, message: "El nombre solo puede contener letras"}, length: { maximum: 50 }, presence: true ...
=begin #=============================================================================== Title: Effect: Add Self State Author: Hime Date: Apr 20, 2013 -------------------------------------------------------------------------------- ** Change log Apr 20, 2013 - initial release ------------------------------------...
class Ctrole < ActiveRecord::Base self.table_name = "ctrole" self.primary_key = "ctroleid" has_many :ctgxctxs end
class Model::Section::AddDocumentSection < SitePrism::Section element :tab, ".fieldset-title" element :internal_name, "#edit-field-generic-media-doc-exposed-filters-title" element :apply_button, "#edit-field-generic-media-doc-exposed-filters-submit" element :remove_document, "div[class$='remove'] label.option" ...
class Tile < ActiveRecord::Base belongs_to :board def self.ordered order('tiles.order') end end
class ChangeInviteLinkInServers < ActiveRecord::Migration[5.2] def change remove_column :servers, :invite_link, :string add_column :servers, :invite_link, :string, null: false end end
module Ojo class << self attr_accessor :configuration end def self.configure self.configuration ||= Configuration.new yield(configuration) if block_given? end class Configuration attr_accessor :fuzz attr_accessor :location attr_accessor :metric def initialize @location = ...
class AddColumnsToUsers < ActiveRecord::Migration def change add_column :users, :twitter_uid, :string add_column :users, :twitter_username, :string add_column :users, :twitter_user_description, :string add_column :users, :twitter_user_url, :string add_column :users, :twitter_profile_image_url, :st...
class Node < ActiveRecord::Base has_ancestry def self.node_from_positions(played_positions) parent = Node.find(1) played_positions.each do |position| node = parent.children.find_by_position(position) (node = Node.create!(parent: parent, position: position)) unless node.present? parent = n...
require 'gosu' require_relative 'collision' class RubyRays < Gosu::Window def initialize @source = Vector.new($screen_w/2,$screen_h/2,1,1) @font = Gosu::Font.new(15) @rays = [] @collisions = [] @objects = [] for i in 0..5 do @objects.push( WorldObject.new($rng.rand($screen_w),$...
FactoryGirl.define do # Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them. # # Example adding this to your spec_helper will load these Factories for use: # require 'spree_variant_state/factories' end FactoryGirl.modify do factory ...
FactoryBot.define do factory :comment do comment { Faker::Lorem.sentence } user message end end
# require 'susanoo/exports/page_creator' module Susanoo class MoveExport < self::Export self.lock_file = File.join(Dir.tmpdir, 'move_export.lock') # #=== Susanoo::Export処理 # def run # Creator の logger を move_export.log に変更するための設定 Susanoo::Exports::Helpers::Logger.logger = ::Logger.n...
class Category < ActiveRecord::Base attr_accessible :id, :name, :description has_many :artists end
class Province < ApplicationRecord belongs_to :region def full_name "Provincia de #{name}, #{region.full_name}" end end
require 'test_helper' class DocumentCollectionGroupMembershipTest < ActiveSupport::TestCase test 'maintain ordering of documents in a group' do group = create(:document_collection_group, document_collection: build(:document_collection)) documents = [build(:document), build(:document)] group.documents = d...
require 'test_helper' class AuthorTest < ActiveSupport::TestCase test "does not save without a name" do @author_without_name = Author.new(name: nil) assert @author_without_name.save == false end test "does save with valid params" do @valid_author = Author.new(name: "valid name") assert @valid_au...
# frozen_string_literal: true require "kafka/broker_pool" require "resolv" require "set" module Kafka # A cluster represents the state of a Kafka cluster. It needs to be initialized # with a non-empty list of seed brokers. The first seed broker that the cluster can connect # to will be asked for the cluster me...
module Mud module Entities module HasPlayers #find a player by its identification. def find_player name players.find{|p| p.is_named? name} end #retrieving the items from this character def players (@players ||= []).map{|id| W.find_player id}.freeze end #m...
class ApplicationController < ActionController::API before_action :check_headers private def check_headers if request.headers["HEADER"] == "password" return true else render json: { errors: ['Not Authenticated'] }, status: :unauthorized end end end
class RemoveRelationshipFromUser < ActiveRecord::Migration def change remove_column :users, :relationship remove_column :users, :user_id remove_column :users, :name end end
FactoryGirl.define do factory :payment_scope do name {Faker::Name.name} end end
require 'forwardable' module TemporalAttributes @global_time = 0 class << self def global_time @global_time end def set_global_time(time) @global_time = time end private :set_global_time def use_global_time(time) old_time = global_time set_global_time(time) ...
require 'spec_helper' describe "31171525 has_sage_flow_state adds is_saved? is_editable? is in that state" do before(:each) do class Foo < Sample has_sage_flow_states :foo, :zing end end it "Has a method for the first state" do Foo.method_defined?(:is_foo?).should be_true end it "Has a meth...
class VersioningService def initialize(migrator = ActiveRecord::Migrator) @migrator = migrator end def current_version migrator.current_version end private attr_reader :migrator end
json.array!(@port_panels) do |port_panel| json.extract! port_panel, json.url port_panel_url(port_panel, format: :json) end
class String def relative_path? return !self.start_with?('/') end end
# # Specifying rufus-tokyo # # Fri Aug 28 08:58:37 JST 2009 # require File.dirname(__FILE__) + '/spec_base' require 'rufus/tokyo' FileUtils.mkdir('tmp') rescue nil DB_FILE = "tmp/cabinet_btree_spec.tcb" describe 'Rufus::Tokyo::Cabinet .tcb' do before do FileUtils.rm(DB_FILE) if File.exist? DB_FILE @db...
json.array!(@author_requests) do |author_request| json.extract! author_request, :id, :ois_request_id, :person_id, :old_lastname, :is_teacher, :is_staffteacher, :is_student, :is_postgrad, :details json.url author_request_url(author_request, format: :json) end
class AddLastObservationToObservations < ActiveRecord::Migration[5.1] def change add_column :observations, :last_observation, :text end end
def caesar_cipher(phrase, shift) phrase = phrase.to_s if phrase.is_a?(String) == false puts "Shift should be an integer." if shift.is_a?(Integer) == false if shift.is_a?(Integer) == true code = "" phrase.each_char do |i| shift.times do i.next! i = "a" if i == "aa" i ...
module TwitterCldr module Timezones class Location attr_reader :tz def initialize(tz) @tz = tz end def tz_id tz.identifier end def resource @resource ||= TwitterCldr.get_locale_resource(tz.locale, :timezones)[tz.locale] end end end end
class AddOpponentToGames < ActiveRecord::Migration[5.0] def change add_column :games, :opponent, :string add_column :games, :home, :boolean end end
class HomesController < ApplicationController before_action :set_home, only: [:show, :edit, :update, :destroy] # GET /homes # GET /homes.json def index @php =File.read('./PHP/index.php') @phphtml =File.read('./PHP/template.html') @node = File.read('./nodejs/app.js') @nodehtml = File.re...
class AddSubmittedToProduct < ActiveRecord::Migration def change add_column :products, :submitter_twitter, :string add_column :products, :submission_id, :integer end end
require 'rspec' require 'card' describe 'Card class' do subject (:card) { Card.new(Value.value("ACE"), Suit.suit("CLUB")) } describe '#initialize' do it "has a value" do expect(card.value).to eq(Value.value("ACE")) end it "has a suit" do expect(card.suit).to eq(Suit.suit("CLUB")) end ...
require 'rails_helper' RSpec.feature 'Products', type: :feature do def sign_in(user) visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' end def submit_form find("form input[value='#{I18n.t('btn_search')}']").click end...
class ScoresController < ApplicationController def index scores = Score.select(:name, :score).order(score: :desc).limit(3) scores = scores.map { |score| "#{score.name}: #{score.score}" }.join("\n") render json: scores end def save_score if allow_request? Score.create(name: params[:name], s...
class Element < ActiveRecord::Base has_many :element_assignments, dependent: :destroy scope :elements, lambda { where(category: 'sentence_element') } scope :relations, lambda { where(category: 'sentence_relation') } with_options through: :element_assignments, source: :elementable do |element| element.has...
class Show < ApplicationRecord validates :artist, presence: true validates :venue, presence: true validates :event_on, presence: true belongs_to :artist belongs_to :venue end
require 'spec_helper' describe User do describe "validation" do context "on update" do subject { create :user } it { should validate_presence_of(:username) } it { should validate_presence_of(:first_name) } it { should validate_presence_of(:surname) } end end end
require 'sinatra' require 'rack' require 'github_api' require 'byebug' require 'dotenv/load' require 'faraday' require 'json' # start local server with shotgun # use ngrok to expose # http://1c4e8b5a.ngrok.io class App < Sinatra::Base get '/' do # this installs the app in a new workspace using Slack's OAuth 2....
class Color < ActiveRecord::Base # has_many :swatches # validates_presence_of :value # validates_length_of :value, :within => 4..7 # validates_uniqueness_of :value, :case_sensitive => false # validates_format_of :value, :with => /^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/ end
require 'test_helper' class CotizesccamsControllerTest < ActionDispatch::IntegrationTest setup do @cotizesccam = cotizesccams(:one) end test "should get index" do get cotizesccams_url assert_response :success end test "should get new" do get new_cotizesccam_url assert_response :success ...
module Fauve module Scheme # Representation of a section key as part of a wider scheme. # Holds a section name, which points to a top-level key within # a colour scheme. # Takes a section name (string) class Section attr_reader :name def initialize(name) @name = name....
require 'spec_helper' describe Api::V1::InfluencersController, type: :controller do describe "GET search" do before { @influencer = Influencer.make! name: "George Michael Bluth" } it "should assign @documents" do get :search, q: "George Michael Bluth", format: :json expect(assigns(:documents)).t...
class Geofence < ApplicationRecord validates_presence_of :description validates_presence_of :radius validates_presence_of :lat validates_presence_of :lng end
require 'rails_helper' feature 'user sees all existing ideas', js: true do scenario 'including title, body, and quality for each' do idea_1 = Idea.create(title: "This is idea #1", body: "The body of idea #1 should be here") idea_2 = Idea.create(title: "This is idea #2", ...
FactoryGirl.define do factory :hub do name "Beltrami County" percent_fee 1.5 end end
class ChangeColumnName < ActiveRecord::Migration[5.2] def change rename_column :schools, :school_type, :city end end
class Role < ActiveRecord::Base has_paper_trail has_many :role_users, dependent: :destroy validates :name, uniqueness: true, presence: true, length: {maximum: 32} def human() "Роль: #{self.name}" end def Role.models_human_name() "Роли" end end
class ReviewStatus < ActiveRecord::Base include HasValueField default_value_method :system, :not_reviewed, :reviewed end
require 'rails_helper' RSpec.describe "admin/topics/edit", type: :view do before(:each) do @admin_topic = assign(:admin_topic, Admin::Topic.create!()) end it "renders the edit admin_topic form" do render assert_select "form[action=?][method=?]", admin_topic_path(@admin_topic), "post" do end e...
class Timeslot < ApplicationRecord belongs_to :location has_many :seatings end
=begin For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase. For example: abcde fghij is a valid passphr...
class UsersController < ApplicationController include ActionController::HttpAuthentication::Token::ControllerMethods before_action :set_user, only: [:show, :update, :destroy] before_action :current_user_security, only: [:show, :update, :destroy] # GET /users def index @users = User.all render json:...
json.expenses @expenses.each do |expense| json.id expense.id json.created_at time_ago_in_words(expense.created_at) + ' ' + t('datetime.ago') + ' ' + t('datetime.at') + ' ' + expense.created_at.strftime('%H:%M') json.amount expense.amount json.comment expense.comment json.date expense.date.strftime('%d %b %Y')...
module ContentManagement module ViewHelper include Paths # 内容 render 系统, 我们使用 render 功能来输出模版,参数与 render 基础版本是一致的,我 # 们仅增加了,with: 参数来声名渲染的对象是谁,With 是一个 Model 对象, # @param name_or_options String, Hash Render 的参数 # @param options = {} [type] [description] # @option options ActiveRecord::Base...
module ApplicationHelper # @todo get experiments for current user only # def current_user_active_experiments Sliced::Experiment.find_all_in_list(:active) end def current_user_pending_experiments Sliced::Experiment.find_all_in_list(:pending) end def facebook_user_image(facebook_uid, size = 'square') ...
class MovieService class << self def movie(movie_id) response = conn.get("3/movie/#{movie_id}") parse_data(response) end def movie_reviews(movie_id) response = conn.get("3/movie/#{movie_id}/reviews") parse_data(response) end def movie_cast(movie_id) response = conn....
class UserMailer < ActionMailer::Base include ActionView::Helpers::TextHelper default from: "john@phaph.com" def app_name Rails.configuration.x.app_name end helper_method :app_name def app_url Rails.configuration.x.app_url end helper_method :app_url # When someone follows you. def f...
require_relative 'library_item' class Decorator < LibraryItem def initialize(library_item) @library_item = library_item end def display @library_item.display end end
require 'net/http' require 'rexml/document' include REXML Puppet::Type.type(:lm_virtualservice).provide(:ruby) do def exists? url = "https://#{resource[:host_ip]}/access/showvs?vs=#{resource[:ip]}&port=#{resource[:port]}&prot=#{resource[:protocol]}" response = Document.new webrequest(url, resour...
require 'pry' require 'rails' class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end def work(hours, rate) penalty = block_given? ? yield : 1 { name: name, hours: hours, dollars: hours * rate * penalty.to_f } end def commute(...