text
stringlengths
10
2.61M
class RemoveIntegerFromVenues < ActiveRecord::Migration def change remove_column :venues, :integer, :string end end
class CreateServiceItemProductAutoModelShips < ActiveRecord::Migration def change create_table :service_item_product_auto_model_ships do |t| t.integer :service_item_product_id t.integer :auto_model_id t.timestamps end end end
class AgentPropagateJob < ActiveJob::Base queue_as :default def perform Agent.receive! end end
module Jekyll module SummarizeFilter def summarize(content) content.split('<!--start-->').last.split('<!--end-->').first end end end Liquid::Template.register_filter(Jekyll::SummarizeFilter)
class PagesController < ApplicationController before_filter :authenticate_user! before_filter :check_access_control access_control :allow_access?, :filter => false do allow "Instructional Designers" allow "Managers" end #TODO dry this mofo out. #TODO also, probably put some security around here....
class CollaboratorsController < ApplicationController def create @wiki = Wiki.find(params[:wiki_id]) @user = User.where('username LIKE :query OR email LIKE :query', query: "%#{params[:search]}%") .all_except(current_user) .first if @user @collaboration = Collaborator.new(...
require 'spec_helper' # be_no_wider_than # be_no_taller_than # have_dimensions # be_no_larger_than # have_directory_permissions # have_permissions # be_identical_to describe ImageUploader do include CarrierWave::Test::Matchers context "Imageable For All" do before do path_to_file = File.join(Rails.roo...
module SyflNewswireCache class Config OPTION_KEYS = %w{host port} def initialize(environment = "development") filename = File.join(File.dirname(__FILE__), "../config/default.yml") @settings = YAML::load_file(filename)[environment] end def self.from(options) @settings = options.dup...
class BoardpostsController < ApplicationController def show @boardpost = Boardpost.find(params[:id]) @country = @boardpost.country @user = @boardpost.user @postcomment = Postcomment.new @postcomments = @boardpost.postcomments.order("created_at DESC") end def create @country = Country.find...
class Schedule < ApplicationRecord belongs_to :experience has_many :bookings, dependent: :destroy validates :date, presence: :true end
class TodoList < ApplicationRecord belongs_to :user belongs_to :campaign has_many :todos has_many :comments, as: :commentable end
# coding: utf-8 # # collapsium-config # https://github.com/jfinkhaeuser/collapsium-config # # Copyright (c) 2016-2017 Jens Finkhaeuser and other collapsium-config contributors. # All rights reserved. # require 'collapsium' require 'collapsium-config/support/values' module Collapsium module Config ## # The ...
RSpec.describe EventsController, type: :controller do describe 'GET #index' do before { get :index, params: { locale: 'en' } } it 'renders events#index' do expect(response).to render_template :index end end describe 'GET #new' do before { get :new, params: { loc...
require 'game' describe Game do let(:player1) { double :player, health: 69 } let(:player2) { double :player, health: 69 } let(:test_game) { Game.new(player1, player2) } it "iniializes with two players" do test = Game.new(player1, player2) expect(test).to be_instance_of(Game) end describe "#attack"...
class ChunkFeed < ApplicationRecord belongs_to :user has_many :chunks def head chunks.max_by(&:created_at) end def tail _head, *tail = chunks.sort_by(&:created_at).reverse! tail end def sorted chunks.sort_by(&:created_at).reverse! end end
class Contact < ActiveRecord::Base validates :email, :message, presence: true end
# encoding: utf-8 require File.expand_path('../google_movies/http_capture', __FILE__) require 'nokogiri' require 'open-uri' module GoogleMovies class Client ROOT_URL = "http://google.com/movies" def initialize(city) @city = city @http_client = HttpCapture::Client.new("#{ROOT_URL}?near=#{@city...
require 'securerandom' class ResetPasswordToken include MongoMapper::Document belongs_to :user, class_name: "User" key :token, String, unique: true timestamps! before_save :create_unique_id def create_unique_id unless self.token unique_id = SecureRandom.uuid self.token = unique_id e...
# frozen_string_literal: true require 'orangetheses' namespace :orangetheses do desc 'Index all the metadata using OAI at SOLR=http://...' task index_all_oai: :environment do harvester = Orangetheses::Harvester.new indexer = Orangetheses::Indexer.new(solr_uri) harvester.index_all(indexer) end de...
require 'ysd_service_postal' unless defined?ServicePostal require 'ysd_md_cms' unless defined?ContentManagerSystem::Template require 'dm-core' require 'delayed_job' module BookingDataSystem module Notifier # # Notifies the manager that a new request has been received # def self.notify_manager...
require './test_helper.rb' class TestUpcase < MiniTest::Unit::TestCase def setup @register = Upcase.new end def test_ assert_equal 'HELLO WORLD', @register.upcase('hello world') end end
require 'spec_helper' describe User do it "should not allow insecure passwords" do client = create(:client, users_attributes: [attributes_for(:user)]) build(:user, password: "matt", client_id: client.id).should_not be_valid end it "should not allow a non-email address" do client = create(:client, users_attrib...
module RepairsHelper # 未進捗件数 def no_progress_count Repair.where(progress: 1).count.to_i end # 修理中件数 def in_progress_count Repair.where(progress: 2).count.to_i end # 修理済で未引渡し件数 def no_delivery_count Repair.where(progress: 3).where(delivery: 1).count.to_i end # 受付番号表示 def format_rece...
# frozen_string_literal: true module Inferno VERSION = '1.3.0' end
class PaytherentsController < ApplicationController before_action :set_paytherent, only: [:show, :edit, :update, :destroy] # GET /paytherents # GET /paytherents.json def index @selectdates = Paytherent.order("senddate DESC").pluck(:senddate).uniq if current_user.admin == 1 paytherents= [] u...
# frozen_string_literal: true class Users::RegistrationsController < Devise::RegistrationsController before_action :configure_sign_up_params, only: [:create] before_action :configure_account_update_params, only: [:update] before_action :authorize_account_edit, only: %i[edit update] def create super Cr...
require_relative 'db' loop do puts "1. View all books" puts "2. Add a book" puts "3. Delete a book" puts "4. Edit a book" puts "5. Exit" choice = gets.chomp.to_i case choice when 1 then view when 2 then add when 3 then suppr when 4 then edit when 5 then break end end
class UsersController < ApplicationController def new redirect_back fallback_location: root_path if logged_in? end def create user ||= User.new(user_params) if user.save flash[:success] = "You have successfully registered to MessageMe" session[:user_id] = user.id redirect_to root_p...
# frozen_string_literal: true Sequel.migration do change do create_table(:suggestions) do Integer :id, identity: true, primary_key: true column :created, 'timestamp with time zone', null: false, default: Sequel.lit('CURRENT_TIMESTAMP') column :updated, 'timestamp with time zone', null: false, d...
require 'rbconfig' module Purgeable class InstallGenerator < ::Rails::Generators::Base def generate copy_file "purgeable.yml", "config/purgeable.yml" end def self.gem_root File.expand_path("../../../../", __FILE__) end def self.source_root File.join(gem_root, 'templates/insta...
require "language/go" # we're using an ugly workaround here, because the tar is being extracted in builddir, # and we need to build into the $GOPATH/src/github.com/minio/mc/. Softlinking isn't working # with every shell. So we're using the go_resource to go get the correct revision, while # actually not using the tar ...
Rails.application.routes.draw do get "/auth/:provider/callback", to: "sessions#create" get "/pages/:page", to: "pages#show" resource :statement_imports, only: :create resource :session, only: [], path: "" do get :new, path: "login", as: :new delete :destroy, path: "logout", as: :destroy end resour...
require 'test/helper' class StampingTests < Test::Unit::TestCase # :nodoc: def setup reset_to_defaults User.stamper = @zeus Person.stamper = @delynn end def test_person_creation_with_stamped_object assert_equal @zeus.id, User.stamper person = Person.create(:name => "David") assert_...
require 'spec_helper' require 'capybara/rspec' require 'capybara/rails' describe "LayoutLinks" do it "should have a home page" do visit root_path expect(page).to have_title("Home"); end it "should have a help page" do visit help_path expect(page).to have_title("Help"); end it "shou...
Factory.define(:ban) do |f| f.reason {Faker::Lorem.words.join(" ")} f.duration 60 end
require "spec_helper" require "shared/order_as_specified_examples" require "config/test_setup_migration" RSpec.describe "PostgreSQL" do before :all do ActiveRecord::Base.establish_connection(:postgresql_test) TestSetupMigration.migrate(:up) end after(:all) { ActiveRecord::Base.remove_connection } inc...
Fabricator(:event) do name { Faker::Lorem.word } date { Faker::Date.forward(500) } event_type { Faker::Lorem.word } slug { 'test-event' } end
#!/usr/bin/env ruby class ImportDb def initialize @work_dir = '/var/www/html/' @mysql_host = 'db' @mysql_user = 'root' @mysql_password = 'qwerty' end def unpack_all_db packed_dbs = [] Dir.entries(@work_dir).select do |f| packed_dbs << f if f.include? '.sql.gz' end...
require 'journey' describe Journey do describe '#initialization' do it "should store entry station when created" do station = double(:station) journey = Journey.new(station) expect(journey.entry_station).to eq(station) end end describe '#fare' do it "should give penalty fare if n...
require 'spec_helper' describe Webmachine::Dispatcher::Route do let(:method) { "GET" } let(:uri) { URI.parse("http://localhost:8080/") } let(:request){ Webmachine::Request.new(method, uri, Webmachine::Headers.new, "") } let(:resource){ Class.new(Webmachine::Resource) } context "building URLs" do context...
class JoinViewController < UIViewController attr_accessor :hintLabel def viewDidLoad super self.view.backgroundColor = UIColor.blackColor self.hintLabel = UILabel.alloc.initWithFrame(CGRectMake(0, 0, 0, 0)).tap do |label| label.text = "Scan QR-Code (this is ...
class CreateStudents < ActiveRecord::Migration def change create_table :students do |t| t.string :student_first_name t.string :student_last_name t.string :parent1_email t.string :parent2_email t.integer :classroom_id t.timestamps end end end
class Launch::Component::Tabs < Launch::Component def nested_attributes [ { component: :tab, type: :has_many } ] end def html content_tag tag, class: css_class do nested_content end end def css_classes ["tabs--menu"] end def default_tab :ul end end
class Coursecontent < ApplicationRecord validates :course_id, :content_name, :content_description, presence: true belongs_to :course end
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html #routes namespace :api do namespace :v1 do resources :users, only: [:index] resources :games, only: [:index] resources :likes, only: [:index] resourc...
# from: # https://edruder.com/blog/2017/12/19/add-markdown-to-rails-5.html # modified very slightly to work with Rails 6 require 'redcarpet' module ActionView module Template::Handlers class Markdown class_attribute :default_format self.default_format = Mime[:html] class << self def c...
# frozen_string_literal: true require 'spec_helper' describe 'mellon::config' do let(:title) { 'mysite' } let(:params) do { sp_metadata: 'foobar', idp_metadata: 'foobar', sp_private_key: 'foobar', sp_cert: 'foobar', melloncond: :undef, mellonsetenvnoprefix: :undef, ignore_l...
module GetAllIds extend ActiveSupport::Concern def self.ids all.collect { |record| record.id } end end
class Movie attr_writer :name, :date, :genre @@all = [] def self.all @@all end def self.most_actors most_actors = self.all.map {|movie| [movie, movie.actors.count]}.sort_by {|movie_and_characters| movie_and_characters[1]}.last puts "#{most_actors[0].name} has the most actors at #{most_actors[1]...
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__))) module TwitterFu autoload :Client, 'twitter_fu/client' autoload :ContentSanitizer, 'twitter_fu/content_sanitizer' def self.updates( username, *args ) Client.new( username ).updates( *args ) end def self.existing?( username ) Client...
class Site < ActiveRecord::Base belongs_to :trial #TODO? City is not populating in the database. geocoded_by :address after_validation :geocode def address [city, state, country, zip_code].compact.join(', ') end end
#!/usr/bin/env ruby require './spydus_scraper' require 'ostruct' card = OpenStruct.new( host: ENV.fetch('CARD_HOST'), number: ENV.fetch('CARD_NUMBER'), pin: ENV.fetch('CARD_PIN') ) def show_availabilites(location_availabilities) require 'terminal-table' puts Terminal::Table.new(rows: location_availabilities...
class SessionsController < ApplicationController skip_before_action :require_login, only: [:age, :home, :new, :create, :logout] def home render :home end def age render layout: false end def new end def create user = User.find_by(username: params[:username]) ...
require 'rails/generators/active_record' require 'securerandom' module Coalla module Cms class InitGenerator < ActiveRecord::Generators::Base argument :name, type: :string source_root File.expand_path("../templates", __FILE__) def setup_names @name = name.underscore end d...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.define "docker" do |docker| docker.vm.box = "geerlingguy/centos7" docker.vm.network "private_network", type: "dhcp" docker.vm.hostname = "docker" docker.vm.provider "virtualbox" do |v| v.name = "docker" ...
class Product < ApplicationRecord belongs_to :store before_create :set_slug validates :title, presence:true validates :description, presence:true #gererate default slug before create record def set_slug o = [('a'..'z'), ('A'..'Z'),(0..9)].map(&:to_a).flatten str = (0..5).map { o[rand(o.length)] }.join if s...
require_relative './metadata' def pretty_print_expression(expression, opts = { client: GoodData.connection, project: GoodData.project }) temp = expression.dup pairs = get_uris(expression).pmap do |uri| if uri =~ /elements/ begin #sample = GoodData::Attribute.find_element_value(uri, opts) ...
json.array!(@veterinarians) do |veterinarian| json.extract! veterinarian, :clinic_name, :address1, :address2, :city, :state, :zip, :phone, :email json.url veterinarian_url(veterinarian, format: :json) end
Rails.application.routes.draw do resources :products do post :import, on: :collection end root to: 'products#index' end
class State < ActiveRecord::Base include AlphabeticalOrder has_many :municipalities has_many :towns, through: :municipalities validates :code, presence: true, uniqueness: true validates :name, presence: true end
class Api::V1::ArticlesController < ApplicationController respond_to :json before_filter :get_friend def index respond_with @friend.articles end def create binding.pry friend = @friend.articles.create(article_params) respond_with friend end private def get_friend binding.pry @fr...
class Group < ActiveRecord::Base self.table_name = "VcsGroups" has_many :products, :class_name => "Product", :foreign_key => "group_id" end
class Background < ApplicationRecord has_many :background_items belongs_to :user, optional: true end
=begin * Modelo de la tabla Client de la base de datos * @author rails * @version 14-10-2017 =end class Client < ApplicationRecord has_many :quotations validates :first_name, format: {with: /\A[a-zA-Z ]+\p{Latin}+\z/, message: "El nombre solo puede contener letras"}, length: { maximum: 20 }, presence: true va...
# Simulate rolling of die. class Die def initialize(sides) @sides = sides end def generate_die_roll rand(@sides) + 1 end def roll(number=1) roll_array = [] number.times do roll_array.push(generate_die_roll) end total = 0 roll_array.each do |roll| ne...
module Cultivation class QueryBatchPhases prepend SimpleCommand PhaseInfo = Struct.new(:id, :name, :phase, :start_date, :end_date, :duration) attr_reader :staying_schedu...
module Admin class JobsController < AdminController def index @jobs = Job.all.order(:start_date).reverse end def new @job = Job.new end def create @job = Job.new(job_params) if @job.save redirect_to admin_jobs_path end end def edit @job = Job...
#! /usr/bin/env ruby require 'pnglitch' def sub(input, output) #side scan lines input = input output = output PNGlitch.open(input) do |png| png.each_scanline do |scanline| scanline.change_filter 1 end png.glitch do |data| data.gsub /\d/, 'x' end png.save output end e...
# frozen_string_literal: true class User::QuizzesSerializer < ApplicationSerializer property(:quizzes) def quizzes model.map do |quiz| { id: quiz.id, title: quiz.title, description: quiz.description } end end end
class OpenSSL < DebianSourceFormula url 'http://backports.debian.org/debian-backports/pool/main/o/openssl/openssl_0.9.8o-4~bpo50+1.dsc' md5 '0ce765777672340889a9cad03ee50fe6' end
class User < ActiveRecord::Base validates_presence_of :first_name, :last_name, :email, :password, :password_confirmation validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } validates :email, uniqueness: {case_sensitive: false} has_many :itineraries has_secure_password end
class ProgressBar module Components class ElapsedTimer include Timer def to_s "Time: #{elapsed_time}" end private def elapsed_time return '--:--:--' unless started? hours, minutes, seconds = divide_seconds(elapsed_whole_seconds) sprintf TIME_FORMAT, ...
class QuestionComment < ApplicationRecord validates :username, presence: true validates :body, presence: true belongs_to :question end
class CLI def start puts "-" * 25 puts "Welcome to Tic Tac Toe!" @row_size = get_board_size @board = Board.new(@row_size) @game = set_up_game until @game.over? turn end end_game_message play_another? end def set_up_game puts "How many players would you like to have?...
require '01_open_classes' describe "Open Classes" do before :each do @precision = 0.001 @currencies = %w(dollar euro rupee yen) end describe "Currency:" do it "should convert to euros (1.292)" do 6.euros.should be_within(@precision).of 7.752 end it "should convert to rupees (0.019)" ...
FactoryGirl.define do factory :album do name "MyString" release_date "2016-03-24" artist_id 1 end end
ActiveAdmin.register PlaceAllowList do # permit_params :enable,:group_category_id,:place permit_params do params = [:enable] params.concat [:group_category_id, :place_id] if current_user.role_id==1 params end index do id_column column :group_category_id do |order| order.group_cate...
class AddIndexToPurchases < ActiveRecord::Migration def change add_index :purchases, [:link_id,:user_id] end end
# frozen_string_literal: true # Write a function called that takes a string # of parentheses, and determines if the order of the # parentheses is valid. The function should return true # if the string is valid, and false if it's invalid. def valid_parentheses(string) if string.empty? == true true else ...
class Customer < ApplicationRecord has_many :addresses has_many :carts has_many :orders validates_presence_of :first_name, :last_name validates_uniqueness_of :email validates_presence_of :email validates_format_of :email, with: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i end
require 'singleton' require 'fileutils' require 'shellwords' module Specinfra module Backend class Exec < Base def run_command(cmd, opts={}) cmd = build_command(cmd) cmd = add_pre_command(cmd) stdout = with_env do `#{build_command(cmd)} 2>&1` end # In ruby ...
module ApplicationHelper def lookup_mlog_entry(col_id, m_id) MlogEntry.where("collection_id = ? and media_id =?", col_id, m_id) end def display_in_terabytes(bytes) bytes.nil? ? '' : ((((bytes / 1024.0) / 1024.0) / 1024.0) / 1024.0).round(2) end def display_in_gigabytes(bytes) bytes.nil? ? ...
class Expense < ActiveRecord::Base validates_presence_of :particular, :amount, :created_at has_one :BalanceBook end
require 'pry' class Triangle attr_accessor :a, :b, :c def initialize(a, b, c) @a = a @b = b @c = c @triangle_sides = [@a, @b, @c] end def equilateral if @a == @b && @a == @c true end end def isosceles if (@a == @b && @a != @c) || (@a == @c && @a != @b) || ...
require 'chronic' require 'cgi' # current day of week event day of week # SU MO TU WE TH FR SA DAY_OF_WEEK_MAP =[ [ 0, 6, 5, 4, 3, 2, 1 ], # SU [ 1, 0, 6, 5, 4, 3, 2 ], # MO [ 2, 1, 0, 6, 5, 4, 3 ], # TU [ 3, 2, 1, 0, 6, 5, 4 ], # WE [ 4, 3, 2, 1, 0, 6, 5 ]...
class AddCategoryRefToPage < ActiveRecord::Migration def change add_reference :pages, :category end end
class ImageUploader < Uploader if CloudinaryReady.up? cloudinary_transformation transformation: [ { width: 1920, height: 1080, crop: :limit } ] end end
class CurrentFullForecastMock def self.forecast {:latitude=>39.7392358, :longitude=>-104.990251, :timezone=>"America/Denver", :currently=> {:time=>1579114217, :summary=>"Clear", :icon=>"clear-day", :nearestStormDistance=>322, :nearestStormBearing=>157, :precipIntensity=>0, :precipProbabilit...
class Relation < ActiveRecord::Base belongs_to :person, :class_name => "Person", :foreign_key => "base_person_id" belongs_to :related_person, :class_name => "Person", :foreign_key => "related_person_id" def relative_person(person) if self.person == person self.related_person else self...
require 'bundler' Bundler.setup require 'cloudapp' require 'sinatra' require 'tempfile' class S3itchApp < Sinatra::Base helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Restricted Area") throw :halt, [ 401, 'Not authorized\n' ] end end ...
require 'puppet-lint/tasks/puppet-lint' require 'puppetlabs_spec_helper/rake_tasks' require 'puppet-syntax/tasks/puppet-syntax' Rake::Task[:lint].clear PuppetLint::RakeTask.new :lint do |config| config.ignore_paths = ['modules/**/**/*.pp','pkg/**/**/*.pp','spec/fixtures/modules/**/**/*.pp'] config.log_format = '%{...
class Product < ApplicationRecord has_many :imgs has_many :reviews end
posts = [] dump_file = 'articles.yml' unless ARGV.include?('load_dump') # Step 1, dump mephisto articles ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['migrate_from_mephisto']) ActiveRecord::Migration.rename_column(:contents, :type, :content_type) class Content < ActiveRecord::Bas...
class Player attr_accessor :scoreboard_index, :current_score def initialize(name:, scoreboard_index:, current_score:) @name = name @scoreboard_index = scoreboard_index.to_i @current_score = current_score.to_i end def moves current_score + 1 end def scoreboard_coords @scoreboard_index....
# frozen_string_literal: true require "dry/monads/result" require "dry/monads/do/all" RSpec.describe(Dry::Monads::Do::All) do result_mixin = Dry::Monads::Result::Mixin include result_mixin before { stub_const("VisibilityLeak", Class.new(StandardError)) } shared_examples_for "Do::All" do context "include...
class IncreaseDefaultChapterXp < ActiveRecord::Migration[5.0] def change change_column_default :chapters, :default_xp, from: 0, to: 31 end end
class Settings::SecuritiesController < ApplicationController layout 'settings' def show authorize [:settings, :security] set_meta_tags title: "Security overview | Settings", description: "Personal security overview and action audits", noindex: true, nof...
module ApplicationHelper module MassAssignment def initialize(attributes = {}) self.attributes = attributes end def attributes=(attributes = {}) self.class.attributes.keys.each do |attr| value = attributes.is_a?(Hash) ? attributes[attr] : (attributes.send(attr) if attributes.respond_t...
module Sumac module Messages # Representes a _Sumac_ message (and not a message component). # @api private class Message < Base # Calculates the maximum possible depth of a json data structure representing a message. # Uses the assigned object nesting depth to find the json depth of the deep...
class AddPayloadCiphertextToPassword < ActiveRecord::Migration[6.1] def change # Column for new lockbox encryption add_column :passwords, :payload_ciphertext, :text # Rename legacy encryption column rename_column :passwords, :payload, :payload_legacy end end