text
stringlengths
10
2.61M
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
module EcoApps class Profile < ActiveRecord::Base acts_as_readonly EcoApps.master_app, :table_name => "profiles" %w{roles update_profiles update_profile}.each do |column| delegate column, :to => :profile_by_service, :allow_nil => true end def profile_by_service @profile_by_service ||= ...
module ControllerMacros RSpec.configure do |config| config.before :each, type: :controller do @ability = Object.new @ability.extend(CanCan::Ability) allow(controller).to receive(:current_ability).and_return(@ability) end end def allow_user_to(*args) before(:each) do @ability.c...
class ApplicationController < ActionController::Base before_filter :search_object protect_from_forgery include SessionsHelper def search_object @search = Resource.search(params[:q]) end def signed_in_user unless signed_in? store_location redirect_to signin_url, notice: "Please sign in." ...
class Api::UsersController < Api::BaseController include JSONAPI::ActsAsResourceController before_action :authenticate_user!, except: :create before_action :set_user, only: [ :update, :password ] authorize_resource def me render json: current_user end def create @user = User.new(user_params) ...
class CreateOraviewAdmins < ActiveRecord::Migration def change create_table :oraview_admins do |t| t.string :host_name, null: false t.text :description t.integer :port, null: false t.string :service_name, null: false t.string :username, null: false t.strin...
class Producer < ApplicationRecord attr_accessor :remember_token, :reset_token before_save :downcase_email belongs_to :area, optional: true has_many :favorites, dependent: :destroy has_many :users, through: :favorites has_many :products, dependent: :destroy mount_uploader :image, ImageUploader validat...
# code here! class School attr_accessor :roster def initialize(roster) @roster = {} end def roster @roster end def add_student(student, grade) if @roster.key?(grade) == false @roster[grade] = [] @roster[grade].append(student) else ...
class Projenitor::Template class FileMapping ################ # # # Declarations # # # ################ attr_reader :project, :template_file, :local_path ############### # # # Constructor # # # ############### d...
class Collaborator < ActiveRecord::Base belongs_to :project validates :email, presence: true end
class CreateMissions < ActiveRecord::Migration[5.2] def change create_table :missions do |t| t.integer :result_no t.integer :generate_no t.integer :e_no t.integer :mission_id t.integer :type t.integer :status t.string :col t.integer :lv t.timestamps end ...
# frozen_string_literal: true module Vedeu # Provides methods to be used by {Vedeu::ApplicationController}. # module Controller # @macro module_singleton_methods module SingletonMethods attr_writer :controller_name # Specifying the controller name in your controller provides # Vedeu...
module SessionsHelper def sign_in(user) remember_token = User.new_remember_token cookies.permanent[:remember_token] = remember_token # Rails lets us treat cookies like hashes. Under the hood, calling permanent actually sets the expiration time to 20.years.from_now. user.update_attribute :remember_toke...
class User < ActiveRecord::Base has_many :investments,dependent: :destroy has_many :likes,dependent: :destroy has_many :candidates, through: :investments validates :name, presence: true , uniqueness: true, numericality:{only_integer: true}, length:{is: 8} end
class Color < ActiveRecord::Base has_many :products_colors validates_uniqueness_of :name end
module Playercenter::Backend class MetaData PREFIX = 'playerMeta' def self.to_graph(data) Hash[data.map do |key, value| ensure_value_is_valid!(key, value) ["#{PREFIX}#{key}", value] end] end def self.from_graph(data) data ||= {} Hash[data.select{|key,value| k...
class AnswerTextboxesController < ApplicationUsersController before_action :set_survey before_action :set_answer_textbox, only: %i[edit update] def create @answer = Answer.create(question_id: params[:question_id], user_id: current_user.id, survey_id: @survey.id) AnswerTextbox.create(params.require(:answe...
dwarf_names=["Doc", "Dopey", "Bashful", "Grumpy"] def roll_call_dwarves(dwarves) dwarves.each_with_index.map do |dwarf, index| index_plus_one = index + 1 puts "#{index_plus_one}. #{dwarf}! " end end def summon_captain_planet(veggies) veggies.collect do |call| call.capitalize + "...
module Antlr4::Runtime class BasicState < ATNState def initialize super end def state_type BASIC end end end
class PowerGeneratorsController < ApplicationController before_action :pagination, only: %i[index show] def index; end def show @power_generator = PowerGenerator.find(params[:id]) return unless params[:cep].present? @address = calculate_cep return flash.now[:notice] = 'CEP não encontrado' if @a...
class CreateUnivs < ActiveRecord::Migration def change create_table :univs do |t| t.string :academy t.integer :limit_locker_num #한계치 로커Number t.integer :numbering, :default => 0 t.timestamps null: false end end end
Given(/a registered customer has logged in$/) do @redirect_url = @page.login.open @page.login.with_existing_account(@email_address, @password) expect(@page.current_page).to be_logged_in end When(/^I try to log in with (an|a) (valid|incorrect|invalid) (password|email)$/) do |arg, negate, email_password| case em...
# -*- encoding : utf-8 -*- class AddColumnsToSupportTickets < ActiveRecord::Migration[5.1] def change add_column :support_tickets, :admin_assigned, :string add_column :support_tickets, :isAdminMessage, :boolean end end
class CreateProductDiscounts < ActiveRecord::Migration def change create_table :product_discounts do |t| t.string :code t.integer :price t.references :product t.timestamps end add_index :product_discounts, :product_id end end
class CreateComponents < ActiveRecord::Migration def change create_table :components do |t| t.string :component_code t.string :combo_code t.string :unit_code t.string :ancestry t.integer :ancestry_depth, :default => 0 t.string :name t.integer :location_id t.str...
class Patient < ActiveRecord::Base attr_accessible :address, :born, :card, :hasscan, :ltreatment_id, :name validates_presence_of :address, :born, :card, :name has_many :treatments belongs_to :lasttreatment, :class_name => "Treatment", :foreign_key => "ltreatment_id", :include => [:doctor, :diagnosis] def self.se...
class CreateProjectTimeSheets < ActiveRecord::Migration def change create_table :project_time_sheets do |t| t.date :duration_in_hours t.datetime :date_time t.string :comments t.string :timesheet_status t.integer :approved_by t.integer :project_master_id t.integer :task_st...
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? def after_sign_in_path_for(resource) root_path end def after_sign_out_path_for(resource) case params[:logout] when "0" root_path when "1" new_admin_session_pa...
require 'wicked_pdf' module UnsFeeder class StoryArchiveJob < ActiveJob::Base attr_accessor :jid queue_as Rails.application.config.app_domain def perform(*args) story = self.arguments.first opts = self.arguments.second || {} unless story.nil? begin story.archived = T...
class PagesController < ApplicationController # GET /pages # GET /pages.xml def index @pages = Page.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @pages } end end def search_results page = params[:page] query = params[:q] @query = ...
## # CacheController # # Cache partials for content. # class CacheController < AbstractController::Base abstract! include AbstractController::Logger include AbstractController::Rendering include AbstractController::Layouts include AbstractController::Helpers include AbstractController::Translation incl...
class ChangePatientTypeColumnToBeIntegerInPatients < ActiveRecord::Migration[5.2] def up change_column :patients, :patient_type, :integer, using: 'patient_type::integer', default: 0, index: true end def down change_column :patients, :patient_type, :string end end
class RemoveTcUserIdFromDriver < ActiveRecord::Migration def up remove_column :drivers, :tc_user_id end def down add_column :drivers, :tc_user_id, :string, :after => :user_id end end
require File.dirname(__FILE__) + '/../../spec_helper' describe "/enlaces/edit.html.erb" do include EnlacesHelper before do @enlace = mock_model(Enlace) @enlace.stub!(:titulo).and_return("MyString") @enlace.stub!(:enlace).and_return("MyString") @enlace.stub!(:imagen).and_return("MyString") @e...
require 'rails_helper' describe Topic do it { should validate_presence_of(:name) } it { should validate_presence_of(:author) } describe '#state' do it 'should have open state by default' do expect(Topic.new.open?).to be_truthy end end end
require 'rails_helper' RSpec.describe ClientCompanySize, type: :model do it 'has a valid factory' do expect(create :client_company_size).to be_valid end it { should validate_presence_of :name } it { should have_many :clients } end
# frozen_string_literal: true module LazyLazer # The gem's semantic version number. VERSION = '0.8.1' end
class VenmoController < ApplicationController def authorize Rails.logger.debug "SESSION: #{session[:user_id].inspect}" # if session[:user_id] # redirect_to params['redirect_url'] and return # end session[:redirect_on_venmo_callback] = params['redirect_url'] redirect_to User.client.auth_code...
class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.string :campaign t.date :weekend t.integer :play_exp t.integer :clean_exp t.timestamps null: false end end end
class CreateAttendeeShifts < ActiveRecord::Migration[5.2] def change create_table :attendee_shifts do |t| t.belongs_to :shift t.belongs_to :event_attendee t.timestamps end add_index :attendee_shifts, [:event_attendee_id, :shift_id], unique: true end end
require "spec_helper" describe "Uploading images for an article" do include Capybara::DSL include Pharrell::Injectable injected :article_service, Persistence::ArticleService before do Capybara.app = Tangent.new page.driver.browser.basic_authorize("admin", "admin") end it "can be done on create" ...
feature 'User' do scenario 'can sign in' do visit '/images' click_button 'Sign In' sign_in() expect(page).to have_content('Welcome to Nick-Sta-Gram!') expect(page).to have_button('Post an Image') end end
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'walrat' module Walrat # Make subclasses of this for use in Abstract Syntax Trees (ASTs). class Node include Walrat::LocationTracking attr_reader :lexeme def initialize lexeme ...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe TwitterCldr::Shared::DayPeriods do let(:day_periods) { described_class.instance(:en) } describe '#period_type_for' do subject { day_periods.period_type_for(time) } context 'noon' ...
module XPash class Frame def self.display(xpash) print "xpash:#{xpash.query} > " input = $stdin.gets unless input puts return end result = xpash.eval(input.chomp) puts "=> #{result}" if result rescue XPash::ReturnSignal rescue OptionParser::InvalidOpt...
class User < ActiveRecord::Base has_secure_password has_many :submissions has_many :samples, through: :submissions has_many :songs, through: :submissions has_many :artists, through: :submissions has_many :albums, through: :submissions end
module Vanity module Adapters # Base class for all adapters. Adapters wrap underlying connection to a # datastore and implement an API that Vanity can use to store/access # metrics, experiments, etc. class AbstractAdapter # Returns true if connected. def active? false end ...
class CreateMenus < ActiveRecord::Migration def self.up create_table :menus do |t| t.string :name t.integer :location_id t.date :date_of_menu t.integer :day t.integer :month t.integer :year t.boolean :is_sectioned t.boolean :is_approved t.integer :currency_id ...
class RenameDistrictNumber < ActiveRecord::Migration def self.up rename_column :mail_clients, :distrinct_number, :district_number end def self.down end end
class ArticlePublishSystem def initialize(article) @article = article end #add callback for publishing def save(submit_type) if to_publish?(submit_type) @article.save make_clone else @article.save end end #add callback for publishing def update(article_params, submit_ty...
class BillboardsController < ApplicationController before_action :set_bd, only: [:show, :edit, :update, :destroy] def index @bd = Billboard.all end def show end def new @bd = Billboard.new render partial: 'form' end def create @bd = Billboard.new(bd_params) if @bd.save redirec...
module DataAbstraction::Unit class Generic def self.unit_table(a) h = Hash.new a.each do | ent | val = ent[0] ent[1..-1].each do | e | h[e] = val end end h end def value(unit = @unit) unit = unit.to_s if ( unit.instance_of? Symbol ) if ...
class UpdateMessageCommand include ActiveModel::Model include ActiveEvent::Command form_name 'Message' attributes :id, :head, :body, :author, :email def persisted?; true end end
require_relative '../lib/invoice' require_relative '../test/test_helper' class InvoiceTest < Minitest::Test def setup @parent = mock("parent") @invoice = Invoice.new({ :id => 6, :customer_id => 7, :merchant_id => 8,...
require 'spec_helper' require 'pry-debugger' describe Stormpath::Resource::Account, :vcr do describe "instances" do let(:directory) { test_api_client.directories.create name: 'testDirectory' } let(:given_name) { 'Ruby SDK' } let(:middle_name) { 'Gruby' } let(:surname) { 'SDK' } subject(:ac...
require_relative 'lib/rely/version' Gem::Specification.new do |spec| spec.name = 'rely' spec.version = Rely::VERSION spec.authors = ['Tyler Hunt'] spec.email = %w(tyler@tylerhunt.com) spec.summary = 'A small library for simplifying dependency injection.' spec.homepage = 'https://github.com/tylerhunt/rely' ...
require 'rails_helper' RSpec.describe User, type: :model do context "associations" do [:assigned_books, :read_entries].each do |assoc| it { should have_many(assoc) } end it { should have_many(:books).through(:assigned_books) } end end
class RemoveIntervening < ActiveRecord::Migration def change drop_table :isolates_variants end end
class AddCoursesToInstructors < ActiveRecord::Migration[5.2] def change add_reference :courses, :instructor end end
module BardBot class Config attr_accessor :prefix, :max_length attr_writer :character, :character_dir def initialize @character = :hamlet @prefix = 2 @max_length = 100 @character_dir = :default end def character_dir if @character_dir == :default return File....
class Comment < ActiveRecord::Base belongs_to :idea, counter_cache: true belongs_to :user def idea_id idea.id end end
require 'rails_helper' module FacilitiesManagement RSpec.describe BuyerAccountController, type: :controller do describe 'GET #buyer_account' do it 'returns http success' do get :buyer_account expect(response).to have_http_status(:found) end context 'when logged in' do lo...
# == Schema Information # # Table name: deposit_responses # # id :integer not null, primary key # deposit_request_id :integer # status :integer # data :text # created_at :datetime not null # updated_at :datetime not null # class D...
require 'rails_helper' describe Author do it "is valid with a author" do expect(build(:author)).to be_valid end it "is invalid without a fName" do author = build(:author, fName: nil) author.valid? expect(author.errors[:fName]).to include("is too short (minimum is 2 characters)") end it "is...
require 'test/unit' require_relative 'person' require_relative 'phonograph' require_relative 'eight_track' class MixinTest < Test::Unit::TestCase def test_1 p Phonograph.new('XXX').who_am_i? p EightTrack.new('YYY').who_am_i? end def test_2 # il modulo Comparable presuppone che nella classe sia defi...
Rails.application.routes.draw do # This is copy/pasted from the Graphiti docs. It's saying "please make Vandal available at /vandal". And my API routes live in here as per the docs. This also tells them to default to the jsonapi format, not plain json. In my JS, I can be explicit about which format I want. scope p...
require 'test_helper' class FlyerTest < ActiveSupport::TestCase def test_fixtures assert_equal 3, Flyer.count end def test_bullshit flyer = flyers(:one) assert_equal 'Flyer about Bullshit1', flyer.title assert_equal 10, flyer.page_count.to_i end def test_flyer_full_title flyer = flyers(...
Given(/^I have brigades titled (.+)$/) do |titles| titles.split(', ').each{ |arg| FactoryGirl.create(:brigade, name: arg) } end Given(/^I have no brigades$/) do Brigade.delete_all end Given(/^I have countries titled (.+)$/) do |titles| titles.split(', ').each{ |arg| FactoryGirl.create(:country, name: arg) } end...
module FluxHue # Models an individual lightbulb in the Hue system, providing means of # both reading and updating the state/configuration of the bulb. class Light include TranslateKeys include EditableState HUE_RANGE = 0..65_535 # TODO: Bridge is clamping us to 254 on these. Enforc...
require_relative '../test_helper' describe RallyOrgApi::Request do before { @model = RallyOrgApi::Request.new('token') } it { RallyOrgApi::Request.must_be_kind_of Class } describe ".new" do it "assigns the access token" do @model.instance_variable_get(:@access_token).must_equal 'token' end end ...
class TrackManagerController < ApplicationController before_filter :store_params_and_authenticate # skip_before_filter :check_for_current_event, :only => [:index] def index session[:username] = nil @ready_to_race = Heat.ready_to_race(@event) end private def store_params_and_authenticate sess...
class PowerOrder < ActiveRecord::Base belongs_to :group has_one :fes_year, through: :group validates :group_id, :item, :power, :manufacturer, :model, :item_url, presence: true # 必須項目 validate :is_correct_url scope :year, -> (year) {joins(:group).where(groups: {fes_year_id: year})} def stage? group_ca...
class AddSizeToBike < ActiveRecord::Migration[5.0] def change add_column :bikes, :size, :integer, array: true end end
# hashes_ex_4.rb # given person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'} # access name of person # solution p person[:name]
#!/usr/bin/env ruby require './microtest' def solve(input) target = parse(input) vx = 0 vy = 0 n = 0 # There's probably a nice mathematical solution to this, # but nested for loops go brrrrr (0..500).each do |vx| (-500..500).each do |vy| if attempt([vx, vy], target) n += 1 end end end n end ...
# bill_spec.rb require 'rubygems' require 'spec' require 'order' require 'bill' require 'bill_manager' =begin Spec::Matchers.define :be_more_than do |expected| match do |actual| actual > expected end failure_message_for_should do |actual| "expected that #{actual} would be a more than #{expected}" end...
require_relative('../db/sql_runner.rb') require_relative('./workout.rb') require_relative('./gymclass.rb') class Member attr_reader :id attr_accessor :member_name, :email, :premium_membership def initialize(options) @id = options['id'].to_i() if options['id'] @member_name = options['member_name'] @...
Rails.application.routes.draw do devise_for :users, skip: [:registrations], controllers: { sessions: 'users/sessions' } # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html resources :cryptocurrencies, only: %i[index show] do get 'favorite', on: :member ...
require_relative '../../../../spec_helper' describe 'govuk_jenkins::ssh_key', :type => :class do private_key_filename = '/var/lib/jenkins/.ssh/id_rsa' context 'when a keypair is not provided (by default)' do it { is_expected.to contain_exec('Creating key pair for jenkins').with_creates(private_key_filename) }...
class AddImageReferencesToMessage < ActiveRecord::Migration def change add_column :messages, :image_ref_id, :integer add_column :messages, :image, :hstore end end
require "jani/from_json/builder" FactoryGirl.define do factory :builder, class: Jani::FromJson::Builder do json_data '{ "uuid": "cfcce0c6-e046-429f-89c0-8a24202ecf89", "frame_width": 640, "frame_height": 360, "fps": 13, ...
class Location < ActiveRecord::Base has_many :course_classes attr_accessible :address_1, :address_2, :city, :company, :contact, :directions, :email, :fax, :phone_1, :phone_2, :state, :website, :zip, :old_id validates_presence_of :address_1, :city, :company, :state, :zip def full_address address = ...
class SaveFacilityDestroySection prepend SimpleCommand def initialize(facility_id, room_id, section_id) @facility_id = facility_id @room_id = room_id @section_id = section_id end def call save_record end private def save_record facility = Facility.find(@facility_id) room = faci...
# == Schema Information # # Table name: users # # id :bigint not null, primary key # username :string not null # email :string not null # password_digest :string not null # session_token :string not null # title :string # ...
class Guest attr_reader :name, :balance, :fav_song def initialize(name, balance, fav_song) @name = name @balance = balance @fav_song = fav_song end def can_guest_afford(value) if @balance - value >= 0 return true else return false end end end
# By using the symbol ':user', we get Factory Girl to simulate the User model Factory.define :user do |user| user.name "Test User" user.email "example@test.com" user.password "foobar" user.password_confirmation "foobar" end Factory.sequence :email do |n| "per...
class RefundRequestDecorator < ApplicationDecorator delegate_all def created_at h.content_tag :span, class: 'time' do object.created_at.strftime("%a %m-%d-%Y") end end def delete_link h.link_to 'Delete', object, method: :delete, data: { confirm: 'Are you sure?' } end def d...
module CommentsHelper def comment_display(comment) content_tag :p do [ comment.comment_text, comment.created_at, "<br />", ].join(' ').html_safe end end end
class RushClassesController < ApplicationController before_action :authenticate_user! before_action :set_rush_class, only: [:show, :edit, :update, :destroy] # GET /rush_classes # GET /rush_classes.json def index sleep 1.seconds @rush_classes = current_user.rush_classes end # GET /rush_classes/1 ...
require "spec_helper" describe LibraryController do it "should load songs from dir" do post :create, :dir => 'spec/support_files' response.should be_success result = JSON.parse(response.body) result["message"].should == "Library is now updating from: spec/support_files" Song.count.should == 2 ...
class Campaign < ApplicationRecord belongs_to :user has_many :comments, dependent: :destroy validates :title, presence: true, uniqueness: true validates :img_url, format: URI::regexp(%w[http https]), presence: true, uniqueness: true validates :content, presence: true, uniqueness: true end
class AddFeeAccountIdToFinanceFeeCollection < ActiveRecord::Migration def self.up add_column :finance_fee_collections, :fee_account_id, :integer end def self.down remove_column :finance_fee_collections, :fee_account_id end end
# Welcome. # In this kata you are required to, given a string, replace every letter with its position in the alphabet. # If anything in the text isn't a letter, ignore it and don't return it. # "a" = 1, "b" = 2, etc. # Example # alphabet_position("The sunset sets at twelve o' clock.") # Should return "20 8 5 19 21 ...
module AwesomeBinPack class RectangleAlgorithms attr_accessor :orig_bin, :orig_rectangles def initialize(bin, rectangles) @orig_bin = bin @orig_rectangles = rectangles end def calculate_by_lower_square bin = @orig_bin.dup end def calculate_by_higher_area bin = @orig...
Rails.application.routes.draw do resources :admin_users, only:[:index, :new, :create, :edit, :update, :destroy, :show] resources :admin_accounts, only:[:edit, :update, :destroy, :show, :index, :save] get '/admin_account/approve/:id', to: 'admin_accounts#approve', as: :admin_account_approve get '/admin_account...
require "csv" class Importer attr_reader :filename, :klass def initialize(klass, filename) @filename = filename @klass = klass end def import ActiveRecord::Base.transaction do entries.each do |e| klass.new(e).save end end end def entries @_entries ||= values.map d...
class CompatiblesController < ApplicationController before_action :only_admin before_action :set_compa, only: [:edit, :update, :delete_compatible] layout "account" def new @compatible = Compatible.new @compatibles = Compatible.all.order('created_at desc') end def create @compatible = Compatib...
# frozen_string_literal: true require "spec_helper" describe "GraphQL::Execution::Errors" do class ErrorsTestSchema < GraphQL::Schema class ErrorA < RuntimeError; end class ErrorB < RuntimeError; end class ErrorC < RuntimeError attr_reader :value def initialize(value:) @value = value ...
require 'dropbox_sdk' require 'securerandom' module Polidea::Artifacts::Uploaders class DropboxUploader def initialize end def authorize(dropbox_app_key, dropbox_app_secret) flow = DropboxOAuth2FlowNoRedirect.new(dropbox_app_key, dropbox_app_secret) authorize_url = flow.start # Have...
module Usermanagement class User < ActiveRecord::Base after_create :create_person # Include default devise modules. Others available are: # :confirmable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :lockable, :tim...