text
stringlengths
10
2.61M
class ProgramsController < ApplicationController def new end def create @program = Program.new(program_params) @program.save redirect_to @program end def show @program = Program.find(params[:id]) @days_ago_s = ProgramsHelper.string_days_ago(@program.airing_date.to_time) end private def program...
class AddLegacyLtiUserIdIndex < ActiveRecord::Migration[6.1] def change add_index :users, :legacy_lti_user_id, unique: true end end
# Copyright 2012© MaestroDev. All rights reserved. require 'spec_helper' require 'v_sphere_worker' describe MaestroDev::Plugin::VSphereWorker, :provider => "vsphere" do let(:connection) { Fog::Compute.new( :provider => "vsphere", :vsphere_username => username, :vsphere_password => password, ...
require_relative './item_behavior' module Vault # "Conjured" items degrade in Quality twice as fast as normal items class Conjured < ItemBehavior def initialize(item) super(item) end def update_quality quality = item.sell_in < 0 ? 4 : 2 decrease_quality(quality) end end end
module ApplicationHelper def full_title page_title = "" base_title = I18n.t "helpers.application_helper.title" page_title.blank? ? base_title : page_title + " | " + base_title end def format_date datetime datetime.strftime I18n.t(".format_time") end def will_paginate_helper objects will_pagi...
class PigLatin def initialize(phrase) @words = phrase.split end def self.translate(word) PigLatin.new(word).translate end def translate @words.map do |word| case when word.start_with?('sch', 'thr') then apply_sch_thr(word) when word.start_with?('squ') ...
Gem::Specification.new do |s| s.name = 'apex' s.version = '0.0.1' s.summary = "Apex Light enable perse Apex code and convert like Java." s.description = "Apex Light enable perse Apex code and convert like Java." s.files = %w( lib/apex.rb lib/apex/class.rb lib/apex/methods_and_f...
module SurveyBuilder class Answer < ActiveRecord::Base belongs_to :question belongs_to :user belongs_to :survey_response validates :question, :presence => true before_save :validate_answer def get_question_type question.type end def validate_answer question.validate_answer(...
module Pawnee class Base module Roles def self.included(base) #:nodoc: base.extend ClassMethods end module ClassMethods # Assigns the role for this class def role(role_name) @role = role_name end def class_role @role.to_s ...
# -*- coding: utf-8 -*- require "benchmark" require "csv" module Drnbench module Publish class GradualRunner def initialize(params) @params = params @runner = Runner.new(:start_n_subscribers => @params[:start_n_subscribers], :n_publishings => @par...
module Wordbot module CLI class Mutilator < Thor desc 'version', 'Print the version' def version puts "mutilator version %s" % [ VERSION ] end map %w(-v --version) => :version desc 'generate', 'Generated some mutilated text' def generate *words ...
require 'rss/maker' module Feeds # Atom news feed generator. class NewsFeedGenerator # Generate atom feed for given news. # # @example Generate atom feed for given news # news = News.all # Feeds::NewsFeedGenerator.generate(news) # #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<f...
require 'config/environment' namespace :index do desc 'Index all records for search' task :all do t_start = Time.now puts "Starting to index at #{t_start}" Content.all.each{|c| Indexer.index(c) } t_end = Time.now puts "Completed indexing at #{t_end...
# Problem # - write a method # - that takes an array, and two optional string arguments # - the array holds the elements to be joined together # - the first optional string argument represents a separator to be used between # all of the elements of the array, except when there are only two elements # - the second optio...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable mount_uploader :avatar, AvatarUploader has_many :com...
class DotAtomVerifier def execute(local) [ ld1(local), ld2(local), ld3(local), ld4(local), ld5(local) ].all? end def ld1(local) except = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~." local.chars...
# frozen_string_literal: true module Admin # AdminController class AdminController < ::ApplicationController layout 'admin/layouts/application' before_action :authenticate_user! before_action :validate_permissions before_action :paginator_params before_action :set_setting before_action :can...
=begin input: integers (three of them) output: string rules - Explicit rules - Write a program to determine whether a triangle is equilateral, isosceles or scalene - All sides must be of length >0 - The sum of any two sides must be greater than or equal to the third side problem domain - Equila...
require 'spec_helper' describe Collins::Ipmi do subject { asset = Collins::Asset.from_json(CollinsFixture.full_asset(true)) asset.ipmi } it_behaves_like "flexible initializer", :id => 23, :address => "hello" it "#empty?" do subject.empty?.should be_false end it "#address" do subject.addr...
module Scavenger module ViewHelpers def compressor @compressor ||= Scavenger::Compressor.new(Scavenger::Config.svg_directory) end def svg_sprite_sheet content_tag :svg, compressor.compress_dir.html_safe, style: "display:none;" end def svg(ref, options = {}) options[:class] = sc...
# Build a student testing app. # The app should have a class of Student and the student should "login" # with their email and password before they can take a test. # The user should be able to take the test and receive feedback on answers. # Their score should be saved and printed at the end of the test. # If they...
class CreateStories < ActiveRecord::Migration[5.2] def change create_table :stories do |t| t.string :title t.integer :theme t.string :difficulty t.string :enemy t.string :enemy_gender t.boolean :enemy_prefix t.references :character, foreign_key: true t.timestamps ...
class Meeting < ApplicationRecord belongs_to :client belongs_to :user # before_save do # self.end_time = self.start_time.advance(hours: (self.duration_hours if attribute_present?("duration_hours")), minutes: (self.duration_minutes if attribute_present?("duration_minutes")) ) if attribute_present?("start_time")...
module Orocos class DefaultLoader < OroGen::Loaders::Aggregate # @return [Boolean] whether the types that get registered on {registry} # should be exported as Ruby constants attr_predicate :export_types? # The namespace in which the types should be exported if # {export_ty...
require 'rails_helper' RSpec.describe User, type: :model do it { should have_valid(:first_name).when('Link', 'Zelda') } it { should_not have_valid(:first_name).when(nil, '') } it { should have_valid(:last_name).when('Courage', 'Wisdom') } it { should_not have_valid(:last_name).when(nil, '') } it { should h...
class ChangeColumnAttr < ActiveRecord::Migration def change change_column :fees, :deleted, :boolean, :default => false change_column :users, :deleted, :boolean, :default => false change_column :addresscats, :deleted, :boolean, :default => false change_column :customers, :deleted, :boolean, :default => fal...
class User < ActiveRecord::Base before_save { self.email == email.downcase } before_create :create_remember_token validates :first_name, presence: true validates :last_name, presence: true, allow_blank: true validates :email, presence: true, uniqueness: { case_sensitive: false } validates :passwor...
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper.rb')) class BlocksStoriesTest < ActionController::IntegrationTest story "Create a new block" do scenario "Try to create a new block with invalid data" do visit "/" click_button :submit assert_contain "Code can't be...
class Especialidad < ActiveRecord::Base has_many :medicos end
# class Micropost < ActiveRecord::Base belongs_to :user validates :content, length: { maximum: 140} validates :user_id, presence: true validate :user_is_not_exist_or_is_race private def user_is_not_exist_or_is_race if !User.ids.include?(user_id) || User.find(user_id).name == "race" errors.a...
require 'rails_helper' def leave_review(thoughts, rating) visit '/restaurants' fill_in 'Thoughts', with: thoughts select rating, from: 'Rating' click_button 'Create Review' end describe 'writing reviews' do context 'a logged out user' do it 'should not see the review form' do visit '/restaurants' expect...
class Venue < ActiveRecord::Base has_many :addresses has_many :gigs has_many :artists end
require 'spec_helper' describe "SimpleDBAdapter ActiveRecord with optimistic locking" do before :each do ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection($config) ActiveRecord::Base.connection.create_domain($config[:domain_name]) end after :each do ActiveRe...
class User < ActiveRecord::Base has_many :invoices has_many :banks has_many :senders validates :email, presence: true, uniqueness: true validates :password_digest, presence: true end
require 'test_helper' class Backend::ModelExtensions::ProviderTest < ActiveSupport::TestCase def setup @storage = Backend::Storage.instance @storage.flushdb end context "provider account" do subject { FactoryBot.create :provider_account } should "update backend default_service when set and save...
require 'spec_helper' describe 'Issue API' do describe 'GET /api/service/v1/issues' do before do @issues = create_list(:issue, 20) get '/api/service/v1/issues' end it 'should be a valid request' do expect(response.status).to eq 200 end it 'should return json' do expect...
module Puffer module Inputs class Base attr_accessor :builder, :template, :field def self.render *args new(*args).render end def initialize builder, field @builder = builder @field = field @template = builder.instance_variable_get :@template end ...
class ContributionValidator < ActiveModel::Validator def validate(record) record.errors[:content] << "Comment cannot be blank" unless content_not_blank_or_link_or_embedded_snippet?(record) # This is needed but currently screws up the rspec tests. Don't have time rewrite all the specs right now, so we'll disr...
class Admin::StripeAccountsController < ApplicationController layout "store_merchant_layout" before_action :authenticate_user! before_filter :verify_is_merchant def account if current_user.stripe_account_id.blank? redirect_to admin_stripe_accounts_new_stripe_account_path else Stripe.api_key...
class PerShowPatronNotes < ActiveRecord::Migration def self.up add_column :shows, :patron_notes, :string, :null => true, :default => nil end def self.down remove_column :shows, :patron_notes end end
# == Schema Information # # Table name: lessons # # id :integer not null, primary key # name :string # title :string # overview :text # created_at :datetime not null # updated_at :datetime not null # c...
class Bid < ActiveRecord::Base belongs_to :admin belongs_to :order #validates :admin_id, presence: true validates :order_id, presence: true validates :price, numericality: {greater_than: 0} validates :subtotal, numericality: {greater_than: 0} validates :message, presence: true validates :pay_schedule, presence:...
require 'test_helper' class AdminformsControllerTest < ActionController::TestCase setup do @adminform = adminforms(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:adminforms) end test "should get new" do get :new assert_response :succ...
class GroupUsersController < ApplicationController before_action :authenticate_user def create params['user_id'] = current_user.id @group_user = GroupUser.new(group_users_params) if @group_user.save redirect_to group_url(@group_user.group_id), notice: 'グループに参加しました' else redirect_to grou...
module Svpply class Collection attr_reader :id, :title, :masthead, :masthead_height, :masthead_width, :preview_type, :preview_image, :representative_item_id, :representative_item_width, :representative_item_height, :products_count, :is_private, :is_wishlist, :date_created, :date_updated, :creator,...
require 'rails_helper' RSpec.describe Post, type: :model do describe 'validation' do it { should validate_presence_of(:title) } it { should validate_presence_of(:body) } it { should belong_to(:user) } it { should validate_uniqueness_of(:title).with_message("You can't have two posts with the same t...
ActiveAdmin.setup do |config| config.site_title = "Vidhata Cranes" config.site_title_link = "/" ## Rails url helpers do not work here config.authentication_method = :authenticate_admin_user! config.current_user_method = :current_admin_user config.logout_link_path = :destroy_admin_user_session_path confi...
# inspired by https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md class ConvertToActiveStorage < ActiveRecord::Migration[5.2] def up ActiveRecord::Base.transaction do source_by_blob_key = {} blobs = [] Source.all.each do |src| next if src.document.path.blank? key ...
# Admin Messages Controller: JSON response through Active Model Serializers class Api::V1::AdminMessagesController < MasterApiController respond_to :json def index render json: AdminMessage.all end def show render json: adminMessage end def create render json: AdminMessage.create(adminMessage_params) en...
class AddTakePartInToUser < ActiveRecord::Migration[5.0] def change add_column :users, :take_part_in, :boolean, default: :true end end
class BatchSerializer include JSONAPI::Serializer attributes :reference, :purchase_channel has_many :orders end
class Transaction < ActiveRecord::Base belongs_to :invoice def self.random all.shuffle.first end def self.find_invoices(params) find(params[:transaction_id]).invoice end def self.find_transactions(params) where(invoice_id: params[:invoice_id]) end def self.find_all_by_id(params) whe...
module AttendancesHelper def attendance_state(attendance) # 受け取ったAttendanceオブジェクトが当日と一致するか評価します。 if Date.current == attendance.worked_on return '出勤' if attendance.started_at.nil? return '退勤' if attendance.started_at.present? && attendance.finished_at.nil? end # どれにも当てはまらなかった場合はfalseを返しま...
# typed: true # frozen_string_literal: true module Packwerk # extracts a possible constant reference from a given AST node class ReferenceExtractor extend T::Sig sig do params( context_provider: Packwerk::ConstantDiscovery, constant_name_inspectors: T::Array[Packwerk::ConstantNameIns...
class CreateAppointments < ActiveRecord::Migration def change create_table :appointments do |t| t.integer :sender_id t.integer :recipient_id t.string :place t.string :latitude t.string :longitude t.string :placetype t.datetime :date t.timestamps end add_index :app...
class Online_Party # @return [Array<Online_Actor>] attr_reader :actors def initialize(data) json_party = base64_decode data party = JSON.decode json_party @actors = party.map{ |member_data| Online_Actor.new(member_data) } end end class Online_Actor < Game_Actor def setup(data) actor_id = da...
module Entities class UserSearchResultEntity < Grape::Entity expose :id expose :first_name expose :last_name expose :email end end
class AddVerificationCodeToPhones < ActiveRecord::Migration def change add_column :phones, :verification_code, 'CHAR(4)' end end
# coding: utf-8 # frozen_string_literal: true # This script installs the various files from the dotzshrc "ecosystem". require 'fileutils' $stdout.puts 'Installing zshrc aliases…' home_dirname = ENV.fetch('HOME') symlink_sources = File.expand_path('symlinks/dot.*', __dir__) Dir.glob(symlink_sources).each do |source_fi...
require 'rubygems' require 'openssl' require 'cgi' require 'base64' require 'openssl' require 'net/http' require 'net/https' require 'typhoeus' require 'json' TCA_ENV = 'production' unless defined?(TCA_ENV) THE_CITY_ADMIN_PATH = 'https://api.onthecity.org' unless defined?(THE_CITY_ADMIN_PATH) THE_CITY_ADMIN_API_VERSI...
require 'rails_helper' describe ItemsController, type: :controller do describe 'GET #index' do it "populates an array of tweets ordered by created_at DESC" do end it "renders the :index template" do end end end
class AddFieldsToSpreeUsers < ActiveRecord::Migration[5.2] def change add_column :spree_users, :name, :string add_column :spree_users, :phone, :string end end
require 'rails_helper' RSpec.describe SynchronizeIssueWorker, type: :worker do let(:issue) { create(:existing_issue, updated_at: 30.days.ago) } before do allow(Github::Issues).to receive(:synchronize).and_return(true) issue end describe '.perform' do it 'synchronizes the issue' do expect(Gi...
class CreateConditionsPeople < ActiveRecord::Migration def change create_table :conditions_people, :id => false do |t| t.references :condition, :null => false t.references :person, :null => false end end end
require 'spec_helper' describe CampRegistration do context "with no fields shown" do before(:each) do @camp_registration = CampRegistration.new(:registration_form_id => Factory(:registration_form).id) end it "should not save the camp registration without a name" do @camp_registration.name = ...
class AddAssociationToShifts < ActiveRecord::Migration[5.2] def change add_reference :shifts, :assignment, foreign_key: true end end
class NotesController < ApplicationController load_and_authorize_resource only: [:edit, :show, :update] def index end def new @user = User.new @note = @user.notes.build end def create if current_user @user = User.find(current_user.id) note = @user.notes.create(content: params[:...
# # Cookbook Name:: blockheads_server # Recipe:: mac_os_x # CHECKSUM = '170eb3a5489ea7b3a9332fbaf444e143ab0eb2423a381ce668948ca33a6c4a11' remote_file "#{Chef::Config[:file_cache_path]}/BlockheadsServer.zip" do source "http://theblockheads.net/share/BlockheadsServer.zip" #checksum "#{CHECKSUM}" notifies :run, 'e...
class CreateIntroductions < ActiveRecord::Migration[6.0] def change create_table :introductions do |t| t.bigint :users_id, null: false, foreign_key: true t.bigint :boards_id, null: false, foreign_key: true t.text :content,null: false t.integer :category_id,null: false ...
class RemoveTableGalleryAlbumsTags < ActiveRecord::Migration def change drop_table :albums_tags end end
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.ap...
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do @user = users(:taro) @other_user = users(:jiro) sign_in(@user) end test "should get index" do get users_url assert_response :success end test "should sho...
class ServicePrice < ActiveRecord::Base validates :price, :service_id, :role_id, presence: true validates :service, uniqueness: { scope: :role_id }, presence: true belongs_to :service belongs_to :role delegate :name, :description, to: :service, prefix: true end
class Owner < ApplicationRecord has_many :dogs validates :name, presence: true, length: {minimum: 2} end
#encoding: utf-8 module Restfuls class Dianbos < Grape::API #version 'v1', :using => :path format :json helpers DianboHelper resource 'dianbo' do desc '创建一个新的奇遇点拨接口' params do requires :session_key,type: String,desc: '会话key' requires :type,type: Integer,desc: '点拨类型id' end get "...
class UserGame < ActiveRecord::Base class << self def unplayed_games(user) games = user_games_from_steam(user.uid) games.select { |g| g['playtime_forever'] == 0 } end private def user_games_from_steam(uid) steam_addr = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001...
module VersatileRJS class Proxy module Jquery class EachProxy < VersatileRJS::Proxy::EachProxy def initialize(page) super add_statement(ActiveSupport::JSON::Variable.new("var #{variable_name} = $(#{tmp_variable_name})")) end def tmp_variable_name @tmp_v...
class HiLo attr_reader :lower attr_reader :upper def initialize(lower, upper) @lower = lower @upper = upper @number = rand(upper-lower) + lower end def guess(num) case num <=> @number when -1 puts "too low..." when 1 puts "too high..." else puts "found it!" end end...
#!/usr/bin/env ruby require 'fileutils' ############################## # # Standard Compile Script # # Supported compilers: # gcc, g++, and fpc. # ############################## def talk(str='') if ENV['TALKATIVE']!=nil puts str end if ENV['GRADER_LOGGING']!=nil log_fname = ENV['GRADER_LOGGING'] ...
class CreateConferences < ActiveRecord::Migration def self.up create_table :conferences do |t| t.string :name t.text :description t.datetime :start_time t.datetime :end_time t.string :room t.references :category t.float :fee t.integer :currency_id t.integer :p...
require 'spec_helper' feature "Visitor makes payment", { vcr: true, js: true } do background do visit new_payment_path end scenario "valid card number", driver: :selenium do pay_with_credit_card('4242424242424242') page.should have_content 'Thank you for your generous support' end scenario "in...
class AddEthnicityToProfile < ActiveRecord::Migration[5.0] def change add_column :profiles, :aspirations, :string add_column :profiles, :identity, :string end end
class Movie < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :synopsis, presence: true end
class Airport < ApplicationRecord has_many :departing_flights, class_name: "Flight", foreign_key: "departure_airport_id" has_many :arriving_flights, class_name: "Flight", foreign_key: "destination_airport_id" validates :code, presence: true validates :location, presence: true end
class AddDesignerToIdeas < ActiveRecord::Migration def change add_column :ideas, :designer, :integer end end
require 'json' require 'httparty' module RegisteredDomains module NameCom # Get the list of registered domains for an account from name.com # Returns an array of domain names. class Domains attr_reader :domains def initialize(user, api_key) @auth = {username: user, password: api_key...
UserDisconnectLoginAccountMutation = GraphQL::Relay::Mutation.define do name 'UserDisconnectLoginAccount' input_field :provider, !types.String input_field :uid, !types.String return_field :success, types.Boolean return_field :user, UserType resolve -> (_root, inputs, _ctx) { user = User.current ...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
module HealthInspector module Checklists class Cookbook < Struct.new(:name, :path, :server_version, :local_version) def git_repo? self.path && File.exist?("#{self.path}/.git") end end class CookbookCheck < Struct.new(:cookbook) include Check end class CheckLocalCopyExi...
require 'test_helper' class TeamsLayoutTest < ActionDispatch::IntegrationTest test "layout links" do get root_path assert_template 'teams/viewteams' assert_select "a[href=?]", root_path, count: 0 assert_select "a[href=?]", addteam_path, count: 1 end end
class User < ActiveRecord::Base has_secure_password has_many :user_events has_many :comments, dependent: :destroy has_many :events, :through => :user_events has_many :events, dependent: :destroy EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :first_name, :last_name, length: { minimum...
class CreateFileRecords < ActiveRecord::Migration[5.2] def change create_table :file_records do |t| t.string :timing t.string :class_name t.string :slot t.integer :uploaded_file_id t.integer :invigilator_id t.timestamps end end end
class Email < ActiveRecord::Base unloadable if Rails.env == 'development' belongs_to :contact validates_presence_of :address validates_length_of :address, :within => 6..100 #r@a.wk validates_format_of :address, :with => User::EMAIL_REGEX validates_uniqueness_o...
class Question < ActiveRecord::Base attr_accessible :description, :hit_id, :title, :video_url, :status, :response_id has_many :responses after_create :make_hits def make_hits HitCreator.create(self) end def turkee_task Turkee::TurkeeTask.where(:hit_id => hit_id).first end def response_url if Rails.en...
# frozen_string_literal: true class StudentsController < HtmlController include Pagy::Backend has_scope :exclude_deleted, only: :index, type: :boolean, default: true has_scope :exclude_empty, only: :performance, type: :boolean, default: true has_scope :table_order, only: :index, type: :hash has_scope :search...
class ChangePaymentFrequencyInLoan < ActiveRecord::Migration[5.0] def change change_column :loans, :payment_frequency, :integer, default: 1, :null => false end end
require 'test_helper' class BagsControllerTest < ActionDispatch::IntegrationTest setup do @bag = bags(:one) end test "should get index" do get bags_url assert_response :success end test "should get new" do get new_bag_url assert_response :success end test "should create bag" do ...
require 'spec_helper' describe "apps/edit.html.erb" do before(:each) do pwd = 'cloud$' @user = User.create! :first_name => 'Dale', :last_name => 'Olds', :display_name => 'Dale O.', :password => pwd, :confirm_password => pwd, :email => 'olds@vmware.com' sign_in @user @app = App.create! :display_name ...
#!/usr/bin/ruby require "prime" need_primes = 10001 generator = Prime::EratosthenesGenerator.new count = 0 until count == need_primes do count += 1 new_prime = generator.next end puts new_prime
# Polisher Bodhi Operations # # Licensed under the MIT license # Copyright (C) 2013 Red Hat, Inc. require 'pkgwat' module Polisher class Bodhi def self.versions_for(name, &bl) # fedora pkgwat provides a frontend to bodhi updates = Pkgwat.get_updates("rubygem-#{name}", 'all', 'all') # TODO set timeou...