text
stringlengths
10
2.61M
class ChurchesPerson < ActiveRecord::Base belongs_to :church belongs_to :person validates :end_date_month, exclusion: { in: [0], message: "Can't be zero"} validates :start_date_month, exclusion: { in: [0], message: "Can't be zero"} validates :start_date_day, :inclusion => { :in => 1..31, :message => "Start...
require 'spec_helper' describe Board do subject(:board) { Board.new } def print(board) board_string = "" Board::RANKS.reverse.each do |rank| board_string << "| " Board::FILES.each do |file| piece = board.find_piece_by_position("#{file}#{rank}") board_string << (piece ? [piece.c...
class Node attr_accessor :data, :next_node def initialize(data) @data = data end def self.kth_to_last_node(place, head_node) list_length = 1 current_node = head_node while current_node.next_node != nil current_node = current_node.next_node list_length += 1 end index = list...
require 'spec_helper' describe Filepreviews::HTTP do let(:http) { Filepreviews::HTTP } describe '.default_connection' do it 'returns a Faraday connection instance' do expect(http.default_connection).to be_an_instance_of(Faraday::Connection) end context 'Overrides Faraday defaults' do it '...
require File.expand_path(File.dirname(__FILE__) + "/../test_helper") class HostgroupsControllerTest < ActionController::TestCase test "create a new host group" do assert_difference("Hostgroup.count") do post :create, :hostgroup => { :name => "some group" } end assert_redirected_to(:controller => ...
# frozen_string_literal: true module Slug extend ActiveSupport::Concern included do acts_as_url :uuid, url_attribute: :slug end def to_param slug end private def uuid Random.new.rand(1_000_000...10_000_000) end end
class Api::BattleFacesController < ApplicationController respond_to :json def index respond_with BattleFace.all.where(master_face: current_master_face).where(status: :active) end def show respond_with BattleFace.find(params[:id]) end def new proposal = current_master_face.battle_faces.where(s...
class Parcel define_method(:initialize) do |length, width, height, weight, distance, gift_wrapping = false| @length = length @width = width @height = height @weight = weight @distance = distance @gift_wrapping = gift_wrapping @surface_area = 4 * (length *...
module Avarteq module Paginator def self.included(base) base.extend(ClassMethods) # Named scope so that records can be ordered like this: MyClass.scoped_by_attr.order("id DESC") base.send(:named_scope, :order, lambda {|order| { :order => order } }) end module ClassMethods ...
class AddNotificationSystem < ActiveRecord::Migration def self.up create_table :events do |t| t.string :type t.string :source_type t.integer :source_id t.string :data t.timestamps end create_table :notifications do |t| t.string :type ...
class Api::V1::StudentsLabelsController < ApplicationController before_action :set_student def index render json: @student.labels end def create label = Label.find(params[:id]) @student.labels << label if @student.save render json: { status: 200 } else render json: { errors: @...
class Message < ActiveRecord::Base attr_accessor :recipient_user_id attr_accessor :fwd_note attr_accessor :require_recipient attr_accessor :require_type attr_accessor :require_subject validates_presence_of :recipient_user_id, :if => :require_recipient validates_presence_of :message_type_id, :if => :requi...
# # @author Kristian Mandrup # # Sngle role storage that stores a role as a Role instance reference # module Trole::Storage class RefOne < BaseOne # constructor # @param [Symbol] the role subject def initialize role_subject super end # display the role as a list of one symbol #...
module Sappy module Responses class AccountInfo < Response attr_reader :available_monitors, :setup_monitors, :sms_alerts def success(hash) accountinfo = hash["accountinfo"].first @available_monitors = accountinfo["availablemonitors"].to_i @setup_monitors = accountinfo["setupmo...
class AddCountyIdToUsers < ActiveRecord::Migration def change add_column :users, :county_id, :integer add_index :users, :county_id end end
require 'spec_helper' describe SignHost::ApiClient do it 'parses the response' do stub_transaction_request_with_status(200) parsed_response = SignHost::ApiClient.new($configuration).post_transaction({}) expect(parsed_response.class).to eq(Hash) end it 'raises an error when something went wrong' do ...
module JsonTableSchema module Types class GeoJSON < Base def name 'geojson' end def self.supported_constraints [ 'required', 'pattern', 'enum' ] end def type ::Hash end def cast_default(value) value...
class RenameFriendIdToFollowerId < ActiveRecord::Migration[5.0] def change rename_column :friends, :friend_id, :follower_id end end
require 'spec_helper' describe SpyFu::Requests::TrackingApi do subject { SpyFu::Requests::TrackingApi } describe '#add_terms' do it 'fails without groupName or domainName or isSeo or isPpc or keywordCsv' do expect { subject.add_terms({}, '') }.to raise_error SpyFu::Errors::MissingRequireParameters e...
class Company < ActiveRecord::Base include Sluggable include AlphabeticalOrder has_many :speakers validates :name, presence: true, uniqueness: true scope :with_events, -> { where(arel_table[:events_count].gt(0)) } scope :no_events, -> { where(events_count: 0) } has_attached_file :logo, styles: { l...
require 'find' module ForgottenStepDefinitions class CukeInspector def step_definitions @step_definitions ||= Find.find(step_definitions_path).map {|file| step_definition_parser.parse(file) if ruby_file?(file) }.flatten.compact end def cuke_steps @cuke_steps ||= Find.find(cuke...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'spoofer/version' Gem::Specification.new do |spec| spec.name = "spoofer" spec.version = Spoofer::VERSION spec.authors = ["Justin Smestad"] spec.email = "justin.smestad@gmail...
require "spec_helper" describe CityHallsController do describe "routing" do it "routes to #index" do get("/city_halls").should route_to("city_halls#index") end it "routes to #new" do get("/city_halls/new").should route_to("city_halls#new") end it "routes to #show" do get("/ci...
# frozen_string_literal: true require 'forwardable' module HealthQuest module PatientGeneratedData module QuestionnaireResponse ## # A service object for isolating dependencies from the questionnaire_responses controller. # # @!attribute session_service # @return [HealthQuest::Se...
class FontCommissioner < Formula head "https://github.com/google/fonts/raw/main/ofl/commissioner/Commissioner%5BFLAR%2CVOLM%2Cslnt%2Cwght%5D.ttf", verified: "github.com/google/fonts/" desc "Commissioner" desc "Low-contrast humanist sans-serif font with almost classical proportions" homepage "https://fonts.googl...
class AddDefaultToPublishedtofb < ActiveRecord::Migration def change change_column :articles, :published_to_fb, :boolean, :default => false end end
require 'thor' require 'socket' require 'stringio' require 'backport' module Readapt class Shell < Thor map %w[--version -v] => :version desc "--version, -v", "Print the version" def version puts Readapt::VERSION end desc 'serve', 'Run a DAP server' option :host, type: :string, aliase...
class ParticipantsController < ApplicationController before_action :authenticate_user! def create @participant = Participant.new(user: current_user, event: event) authorize @participant @participant.save! render json: @participant end def destroy @participant = Participant.find(params[:id...
class CreateFilms < ActiveRecord::Migration def change create_table :films do |t| t.text :name_f, null: false t.text :genre_f, null: false t.text :lasting_f, null: false t.text :country_f, null: false t.text :companies_f, null: false t.integer :min_age, null: false t.tim...
class Api::ChannelsController < ApplicationController def index @channels = Channel.all render :index end def show @channel = Channel.find(params[:id]) if @channel render :show else render json: ['Channel does not exist'], status: 404 ...
require 'rails_helper' describe 'homepage' do describe 'starting a club' do let(:club_name) { Faker::Team.name } it 'adds the club link to the homepage' do visit root_path within '.hamburger-menu' do click_link 'New Club' end fill_in :club_name, with: club_name click_bu...
class AddColumnForDoctorWeekMoney < ActiveRecord::Migration def change add_column :doctors, :doctor_week_price, :float end end
require_relative "../Modules" require_relative "../Piece" class Pawn < Piece attr_reader :symbol, :color include Stepable def initialize(name, start_pos, color, board) super(name, start_pos, color, board) @symbol = :P @color = color end def move_dirs return [ [1, 1], [-1, -1], ...
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{config_object} s.version = "1.0.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :requ...
require 'rails_helper' RSpec.describe "Contents", type: :system do before do @content = FactoryBot.create(:content) @content_title = "111112222233333" end context 'コンテンツ投稿ができるとき'do it 'ログインしたユーザーは新規投稿できる' do # ログインする visit new_user_session_path fill_in 'user[email]', with: @content....
require 'spec_helper' describe "ApiKey pages" do subject { page } describe "api key creation" do let(:admin) { FactoryGirl.create(:admin) } before do sign_in admin visit user_path(admin) end it "should create an api key" do expect { click_button "Create API Key" }.to change(ApiKey, ...
class AddNewsletterToPreference < ActiveRecord::Migration def change add_column :preferences, :newsletter, :boolean, default: true end end
class Model attr_accessor :db attr_reader :id def self.all data = ForumDatabase.instance.execute('SELECT * FROM #{@db}') data.map {|datum| self.new(datum)} end def self.find(findby) @findby = findby end def self.find_by(@findby) model_db = ForumDatabase.instance.execute(<<-SQL, find_by...
module Jekyll module Assets class Cached < Sprockets::CachedEnvironment attr_reader :jekyll, :parent def initialize(env) @parent = env @jekyll = env.jekyll super env end end end end
class Input def initialize(skip_start = false) if skip_start == true Input.player_input end puts "Ready. Type 'start'" response = gets.chomp if response == "start" || response == "play" puts "Okay!" I...
class MQ class Header include AMQP def initialize(mq, header_obj) @mq = mq @header_obj = header_obj end def properties @header_obj.properties end # Acknowledges the receipt of this message with the server. def ack @mq.callback do @mq.send Protocol::Basic:...
# Set up for the application and database. DO NOT CHANGE. ############################# require "sequel" # connection_string = ENV['DATABASE_URL'] || "sqlite://#{Dir.pwd}/development.sqlite3" # DB = Sequel.connect(connection_string) ...
require File.dirname(__FILE__) + "/spec_helper" include Cookies describe CookieJar do before(:each) do cookie_str = "myCookie=a=1&b=2; path=/; domain=bob.com;" cookie_str = cookie_str + "; cookie2=blarg; path=blarg.com/; domain=weirdthings.com" cookie_str = cookie_str + "; cookie3=foo, path=foo.com/, ...
class EmployeesController < ApplicationController # before_action :authenticate_user! def index @employees = Employee.all end def new @employee = Employee.new @employee.build_user end def edit @employee = Employee.find(params[:id]) end def create @employee = Employee.new(employee_params) i...
require_relative 'Dice' require_relative 'Warrior' class Weapon attr_reader :from, :degats, :opt, :bonus def initialize from, degats, opt, bonus, attack_opt={} @from = from @bonus = from.bab.map{|e| e + bonus} @degats = Dice.new(degats + "+#{(from.bstr * 1.5).ceil}") @hands = opt[:hands] || 1 ...
class Color < ActiveRecord::Base has_many :rooms has_many :looks end
# Write a method, `ordered_vowel_words(str)` that takes a string of # lowercase words and returns a string with just the words containing # all their vowels (excluding "y") in alphabetical order. Vowels may # be repeated (`"afoot"` is an ordered vowel word). # # You will probably want a helper method, `ordered_vowel_wo...
class ShopsController < ApplicationController before_action :set_shop, except: [:index, :new, :create] before_action :set_user, except: [:edit, :update] # GET /shops # GET /shops.json def index @shops = Shop.all end # GET /shops/1 # GET /shops/1.json def show @users = User.all end # GE...
class RemoveCouponUniqueness < ActiveRecord::Migration[6.0] def change remove_index :orders, :coupon_id add_index :orders, :coupon_id end end
require_relative "./bench_helper" Post = Struct.new(:id, :title, :updated_at) module PostView extend Knuckles::View def self.root :posts end def self.data(object, _) {id: object.id, title: object.title, updated_at: object.updated_at} end end models = 100.times.map { |i| Post.new(i, "tit...
# frozen_string_literal: true require "cell/partial" module Decidim module Opinions # This cell renders the link to the source collaborative draft of a opinion. class OpinionLinkToCollaborativeDraftCell < OpinionLinkedResourcesCell private def linked_resource @linked_resource ||= model....
module Concerns::BoardComment::Validation extend ActiveSupport::Concern included do validates :from, presence: true validates :body, presence: true validates :board_id, presence: true end end
require 'fakeredis/rspec' RSpec.configure do |config| config.before(:each) do | example | # clears out redis before each test Redis.new.flushall end end # https://github.com/guilleiguaran/fakeredis/issues/66 redis_opts = { url: 'redis://127.0.0.1:6379/1' } # If fakeredis is loaded, use it explicitly red...
require_relative '../utils/strings.rb' class DocumentationHelpCommand < MoreUtils class << self def run descriptions puts "#{ascii_art} Rails Plus Plus Version: #{gem_version} Rails Plus Plus: Command Line Interface to make your life easier. => The Rails Plus Plus command is 'railspp'. To bla...
class EmployerdomainsController < ApplicationController before_filter :authenticate_user! layout 'admin' def index @employerdomain = Employerdomain.search(params[:status]) respond_to do |format| format.html # index.html.erb format.json { render json: @employerdomain } end end ...
class User < ActiveRecord::Base before_validation :smart_add_url_protocol before_save :capitalize_attributes mount_uploader :resume, ResumeUploader # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerabl...
class User < ActiveRecord::Base validates :password_digest, presence: true validates :session_token, presence: true, uniqueness: true validates :username, presence: true, uniqueness: true validates :password, length: { minimum: 6, allow_nil: true } has_many :friendships, class_name: "Friendship", pri...
ActiveAdmin.register Assignment do menu :if => proc{ can?(:manage, Assignment) } controller.authorize_resource controller do def new super do resource.material_assignments.build resource.labor_assignments.build end end def update emp = Employee.find_by_name(par...
# System library as opposed to gem, so we have to load it. require 'mapscript' # For some reason the previous code had # include Mapscript # but it always references it with the namespace, so unsure why # including...
INPUT_FORMAT = /position=<\s*?([\d-]+),\s*?([\d-]+)> velocity=<\s*?([\d-]+),\s*?([\d-]+)>/ class Light attr_reader :x, :y def initialize(x, y, dx, dy) @x = x @y = y @dx = dx @dy = dy end def move! @x += @dx @y += @dy end def back! @x -= @dx @y -= @dy end end class Sk...
class MicropostsController < ApplicationController before_action :logged_in_person, only: [:create, :destroy] before_action :correct_person, only: :destroy def create @micropost = current_person.microposts.build(micropost_params) if @micropost.save flash[:success] = "Micropost created!" @ge...
xml.instruct! :xml, :version=>"1.0" xml.rss(:version=>"2.0"){ xml.channel{ xml.title("#{config['plugins.tog_core.site.name']} #{I18n.t('tog_social.projects.site.last_projects')}") xml.link projects_url xml.description("#{@projects.size} #{I18n.t('tog_social.projects.site.last_projects')}") xml.langua...
class UsersController < ApplicationController before_action :confirm_logged_in #------------------------------------------------- def index @users = User.all end #------------------------------------------------- def show @user = User.find_by(id: params[:id].to_i) if @user.blank? return missing_page en...
class Tweet < ActiveRecord::Base validates :status, presence: true, length: { minimum: 3 } belongs_to :zombie end #validates_presence_of :status #validates_numericality_of :fingers # => number #validates_uniqueness_of :toothmarks #validates_confirmation_of :password # => matches 2 identical #validates_ac...
#!/usr/bin/env ruby require 'yaml' require 'json' require 'bundler' Bundler.require(:default) raise "No config" unless File.exist?('config.yml') $config = YAML.safe_load(IO.read('config.yml')) class IngestLogger def initialize(path) @file = File.open(path, 'a') @lock = Mutex.new end %I|debug info warn ...
json.total @total json.favorites @favorites do |favorite| json.extract! favorite, :id, :favoritable_type, :favoritable_id, :created_at json.favoritable favorite.favoritable json.favoritable_url url_for(favorite.favoritable) end
class StockController < ApplicationController def show id = params[:id].to_i span = params[:span] ? params[:span].to_i : 100 @stocks = Stock.order("code DESC").all[id*span..id*span+(span-1)] end end
class RenameTypeToItemType < ActiveRecord::Migration[6.0] def change rename_column :sent_items, :type, :item_type end end
class AnswerSerializer include FastJsonapi::ObjectSerializer attributes :id, :question_id, :question, :course_id, :student_id, :answer_type, :text_answer, :updated_at, :cre...
class MascotaController < ApplicationController before_action :set_mascotum, only: [:show, :edit, :update, :destroy] # GET /mascota # GET /mascota.json def index @mascota = Mascotum.all end # GET /mascota/1 # GET /mascota/1.json def show end def atenciones @mascota = Mascotum.find(params[:...
module RSpec module Rest module Matchers class HaveHttpHeader < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(expected_header) @expected = expected_header @actual = nil end # @param [Object] response object providing an http code to match # @retur...
class AddColumnToInvoices2 < ActiveRecord::Migration def change add_column :invoices, :c_qbupdate, :date add_column :invoices, :c_qbcreate, :date end end
class Api::V1::UserSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :id, :username, :first_name, :last_name, :birthday, :address, :partner_name, :partner_birthday, :venmo_handle, :flowers, :own_events, :followed_events, :your_followers, :you_follow, :profile_picture, :wis...
require 'rails_helper' describe User do describe "#create" do it "should validate uniqueness of email address" do user = create_user expect(user).to be_valid user_1 = create_user(email_address: user.email_address) user_1.valid? expect(user_1.errors[:email_address]).to include("has ...
class Users::RegistrationsController < Devise::RegistrationsController ssl_required :new, :create, :edit, :update before_filter :set_title, only: [:new, :create] layout :set_layout protected def after_inactive_sign_up_path_for(resource) user_confirmation_sent_path end def after_update_path_for(re...
# encoding: utf-8 class MessagesController < ApplicationController # GET /messages # GET /messages.json def index @messages = Message.all respond_to do |format| format.html # index.html.erb format.json { render json: @messages } end end # GET /messages/1 # GET /messages/1.json de...
require 'rails_helper' require 'integration_specs/abstract_flow' RSpec.describe 'admin reading user flow', :type => :request do include AbstractFlow let(:user) {{email: 'admin10@admin.admin', password: '1234567890'}} let(:sign_up_path) {'/admins/'} let(:admin){create(:admin)} let(:agent){create(:agent, creat...
class CreateProposals < ActiveRecord::Migration def change create_table :proposals do |t| t.string :status#only accept [accepted, refused, open] canceled not MVP t.string :proposed_idea t.uuid :participation_id t.timestamps null: false end add_foreign_key :proposals,...
cask "synology-drive" do version "2.0.4,11112" sha256 "19b8f03ece1dc8443da1e6df469d2ddf8916c4d2d15d7c9a04c0e84deb93c33b" url "https://global.download.synology.com/download/Utility/SynologyDriveClient/#{version.before_comma}-#{version.after_comma}/Mac/Installer/synology-drive-client-#{version.after_comma}.dmg" ...
require 'json' require 'rest_client' module Coveralls class API if ENV['COVERALLS_ENDPOINT'] API_HOST = ENV['COVERALLS_ENDPOINT'] API_DOMAIN = ENV['COVERALLS_ENDPOINT'] else API_HOST = ENV['COVERALLS_DEVELOPMENT'] ? "localhost:3000" : "coveralls.io" API_PROTOCOL = ENV['COVERALLS_DEVEL...
class Report < ActiveRecord::Base has_many :collaborators, class_name: 'AuthorizedCollaborator', as: 'authorizable' attr_accessible :description, :name end
class Middleclick < Cask url 'http://clement.beffa.org/labs/downloads/MiddleClick-maverick.zip' homepage 'http://clement.beffa.org/labs/projects/middleclick' version 'latest' no_checksum link 'MiddleClick.app' def caveats; <<-EOS.undent This cask requires OS X 10.9 Mavericks for the installed applicati...
class Api::MessagesController < ApplicationController before_action :set_group def index respond_to do |format| format.json {@new_messages = @group.messages.includes(:group).where('id > ?',params[:id])} end end private def set_group @group = Group.find(params[:group_id]) end end
class AdminController < ApplicationController layout 'admin' before_action :logged_in_user, :admin_user end
RSpec.describe "calling a missing method" do it "raises" do expect { Object.new.foo }.to raise_error(NameError) end end RSpec.describe "matching error message with a string" do it "matches the error message" do expect { raise StandardError, 'this message exactly'}.to raise_error('this message exactly') ...
class AddTagDescriptionToPackages < ActiveRecord::Migration def change add_column :lists, :tag_description, :string end end
require 'rails_helper' describe User::UsersController do before { sign_in(user) } let(:user) { create(:user, email: 'email@example.com') } describe 'PATCH #update' do before { patch :update, params } context 'success' do let(:params) do { user: { email: ...
class Trnascan < Formula # cite Lowe_1997: "https://doi.org/10.1093/nar/25.5.0955" desc "Search for tRNA genes in genomic sequence" homepage "http://lowelab.ucsc.edu/tRNAscan-SE/" url "http://lowelab.ucsc.edu/software/tRNAscan-SE-1.3.1.tar.gz" sha256 "862924d869453d1c111ba02f47d4cd86c7d6896ff5ec9e975f18586822...
class Seat < ActiveRecord::Base belongs_to :district belongs_to :state has_many :nominations end
require 'erb' module Api module Mailers class BaseMailer DEFAULT_FROM = "no-reply@example.org" def render_sample template("sample") end def send(opts) current_mailer_method = caller_locations(1,1)[0].label html = template(current_mailer_method) mail = Ma...
# Сообщения между пользователями class MessagesController < ApplicationController # Создание нового сообщения def create @user = User.find(params[:user_id]) message = @user.messages.new(message_params) message.title = @current_user.username message.save redirect_to user_path(@user) end pri...
module BuildKit module Tasks def self.xcode_build runner, task_opts task = XcodeBuildTask.new({ runner: runner, opts: task_opts }) task.run! end private class XcodeBuildTask < BuildKitTask attr_reader :output def run! run_command! complete_task! en...
class AddExamTypeToOnlineExamGroups < ActiveRecord::Migration def self.up add_column :online_exam_groups, :exam_type, :string add_column :online_exam_groups, :exam_format, :string add_column :online_exam_groups, :result_published, :boolean, :default=>false end def self.down remove_column :online_...
class ArticlePhotosController < ApplicationController before_action :set_article_photo, only: [:show, :edit, :update, :destroy] # GET /article_photos # GET /article_photos.json def index @article_photos = ArticlePhoto.all end # GET /article_photos/1 # GET /article_photos/1.json def show end #...
class UserPaymentDirectly < ApplicationRecord attr_accessor :order has_many :orders, as: :payment_method enum status: { rejected: 0, pending: 1, accepted: 2 } validates :name, presence: true validates :email, presence: true, length: { maximum: 255 }, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/...
#Q9 Once you complete the previous exercise, change the way the users are displayed: print them grouped by cohorts. To do this, you'll need to get a list of all existing cohorts (the map() method may be useful but it's not the only option), iterate over it and only print the students from that cohort. #====== =begin m...
# https://gist.github.com/leemachin/2366832#file-modulo-filter-rb module Jekyll module ModuloFilter def mod(input, modulus) input.to_i % modulus.to_i end end end Liquid::Template.register_filter(Jekyll::ModuloFilter)
# == Schema Information # # Table name: activities # # id :integer not null, primary key # action :integer not null # trackable_id :integer not null # trackable_type :string not null # user_id :integer not null # created_at :datetime ...
FactoryGirl.define do factory :comment do user rate { Faker::Number.between(1, 5) } description { Faker::Lorem.sentence } book end end
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # Model object. # # class TestReportStats # @return [Float] attr_accessor :o...