text
stringlengths
10
2.61M
# Constructs a normalised list of parameters, with non-recognised params # removed. # # Array parameters are sorted for caching purposes. class Trade::SandboxSearchParams < Hash def initialize(params) sanitized_params = { :annual_report_upload_id => params[:annual_report_upload_id], :sandbox_shipments...
class ComponentsController < ApplicationController def index components = Rails.cache.fetch('components') do Oj.dump(Component.all) end render json: components end end
namespace :scraper do # be rake scraper:cloud_provider[aws] desc "Scrape cloud provider prices" task :cloud_provider, [:name] => [:environment] do |t, args| Delayed::Job.enqueue(Scraper::Job.new(args[:name] || '')) end desc "Empty all cloud related tables, DON'T RUN THIS UNLESS YOU KNOW WHAT YOU ARE DOIN...
class InstanceAccountMigrator < AbstractMigrator class << self def prerequisites GpdbInstanceMigrator.migrate HadoopInstanceMigrator.migrate end def classes_to_validate [InstanceAccount] end def migrate prerequisites # Make sure gpdb_instances are flagged as shared...
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program 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 Foundation; either version 2 of the License. # # This program ...
require 'spec_helper' require 'support/test_classes' describe 'associations with other objects' do let(:user) { User.new('Flump') } let(:topic) { Topic.new('Title', user) } let(:user_mapper) { Perpetuity[User] } let(:topic_mapper) { Perpetuity[Topic] } before do user_mapper.insert user topic_mapper....
Pod::Spec.new do |s| s.name = 'TGCircularTimerView' s.version = '1.0.0' s.summary = 'A timer with a circular progress indicator.' s.description = <<-DESC An easy-to-use iOS timer view with a customizable circular progress indicator similar to the native Clock.app's timer. ...
class Carpetmaterial < ApplicationRecord belongs_to :carpet_datum belongs_to :raw_material_warehouse end
class Post < ActiveRecord::Base validates :title, :onid, :location, presence: true validate :order? def self.today where("meeting_time >= ? AND meeting_time < ?", Time.current.midnight, Time.current.tomorrow.midnight) end def self.future where("meeting_time >= ? OR meeting_time IS NULL", Time.curr...
class User < ActiveRecord::Base validates :name, presence: true validates :email, presence: true, uniqueness: true, format: { with:/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i} validates :password, :length => {:within => 6..20} has_secure_password has_many :statuses, dependent: :destroy has_many :likes, de...
class MergeArchiveFieldsInOneArchiverAnnotation < ActiveRecord::Migration[4.2] def change Rails.cache.write('check:merge_archive_fields_in_one_archiver_annotation:progress', nil) end end
class ExerciseSetLogSerializer < ActiveModel::Serializer include Pundit attributes :id, :duration, :repetition, :rest, :exercise_logs, :can_update, :can_delete def exercise_logs object.exercise_logs.map do |set_log| ExerciseL...
class Settings::IndexController < ApplicationController before_action :set_new_settings, :set_settings, only: [:index] def index authorize! :index, :settings respond_to do |format| format.html # index.html.erb end end private def set_settings @types = Type.order name: :asc @manuf...
module DateRange extend ActiveSupport::Concern private def date_range @date_range ||= begin date_range = params[:date_range] if date_range.present? from, till = date_range.split('..').map(&:to_datetime) (from..till) else date_range_from_params end end e...
desc "Create a bunch of seed data for artists and songs" task :seed_artists_and_songs => [:environment, :clear_artists_and_songs] do # Build Song Off Artist # Given a Song called R.E.S.P.E.C.T # build the Aretha Franklin Artist respect = Song.create(:name => "R.E.S.P.E.C.T") puts "Just created song #{respect...
class ChangeIntegerLimitInClients < ActiveRecord::Migration def change change_column :clients, :mobile, :integer,limit: 8 end end
# == Schema Information # # Table name: albums # # id :integer not null, primary key # name :string not null # band_id :integer not null # live_recording :boolean default(FALSE), not null # created_at :datetime # updated_at :datetime # cla...
# frozen_string_literal: true require 'singleton' require_relative './query_helper.rb' require_relative './validation' module Departments module Archive module Services ## # Consumes the model {CodeInjection::SqlInjectionReport}. class SqlInjectionReport include Singleton # Co...
## # Data object that represents a Template # class Template ## # Memoizes the input data Hash # attr_accessor :data ## # Memoizes the input data Hash # # @param [Hash] data The template's data # def initialize(data) @data = data end ## # Returns the template's name # # @return [Stri...
class Castle::Piece::Rook < Castle::Piece def name 'rook' end end
Rails.application.routes.draw do get 'sessions/new' #root 'static_pages#home' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/signup', to: 'users#new' resources :users get '/records/new', to: 'records#new' post '...
Sequel.migration do up do create_table :update_audit_secure do foreign_key :secure_form_id, :secure_forms DateTime :timestamp, :null => false String :type, :size => 8 integer :form_size end end down do drop_table :update_audit_secure end end
require "minitest/autorun" require_relative "../../src/revlog" class RevlogTest < Minitest::Test def setup end def test_init r = Revlog.new("ifile", "dfile") assert_equal "ifile", r.indexfile assert_equal "dfile", r.datafile end def test_addrevision r = Revlog.ne...
class AddAdditionalInfoToPoster < ActiveRecord::Migration[5.2] def change add_column :posters, :additional_info, :string add_column :posters, :message_id, :integer end end
module Pincers::Support class Cookie < Struct.new(:name, :value, :domain, :path, :expires, :secure); end end
# frozen_string_literal: true class CommentAccountsController < ApplicationController before_action :set_comment_account, only: %i[show edit update destroy] respond_to :html def index @comment_accounts = CommentAccount.all respond_with(@comment_accounts) end def show respond_with(@comment_acco...
# Alternative Augeas-based provider for mailalias type (Puppet builtin) # # Copyright (c) 2012 Dominic Cleal # Licensed under the Apache License, Version 2.0 raise("Missing augeasproviders_core dependency") if Puppet::Type.type(:augeasprovider).nil? Puppet::Type.type(:mailalias).provide(:augeas, :parent => Puppet::Typ...
# frozen_string_literal: true require 'rakuten_web_service/string_support' module RakutenWebService class Configuration attr_accessor :application_id, :affiliate_id, :max_retries, :debug def initialize @application_id = ENV['RWS_APPLICATION_ID'] @affiliate_id = ENV['RWS_AFFILIATE_ID'] @ma...
#!/usr/bin/env ruby # frozen_string_literal: true require_relative './lib/game' if $PROGRAM_NAME == __FILE__ marks = ARGV.first unless marks warn 'Usage: ./bowling.rb 6,3,9,0,0,3,8,2,7,3,X,9,1,8,0,X,6,4,5' abort end game = Bowling::Game.new(marks) puts game.score end
class Content < ApplicationRecord before_destroy :delete_files validates :title, presence: true validates_uniqueness_of :source_id, scope: :tube_id has_many :thumbs, dependent: :destroy has_many :content_stats, dependent: :destroy belongs_to :tube, counter_cache: true def delete_files content = se...
require File.dirname(__FILE__) + '/../test_helper' require 'profiles_controller' # Re-raise errors caught by the controller. class ProfilesController; def rescue_action(e) raise e end; end class ProfilesControllerTest < Test::Unit::TestCase fixtures :profiles def setup @controller = ProfilesController.new ...
module ApplicationHelper def messages_about_actions messages = "" flash.each do |key, message| css_class = generate_css_class(key.to_s) messages << content_tag(:div, (message + link_to_close).html_safe, :class => css_class) end messages.html_safe end def generate_css_class(key) css_class = 'alert-box...
require File.expand_path('../../spec_helper', __FILE__) describe JobQueue do before do @q = JobQueue.new 2 $job_queue_results = Set.new $job_queue_runs = 0 $job_queue_data_mutex = Mutex.new end class TestWorker def perform(item, delay) sleep delay $job_queue_data_mutex.synchroniz...
module SuperCardValidator class Validator # Validates number against Luhn algorithm class Luhn attr_reader :number def initialize(number) @number = number end def valid? checksum % 10 == 0 end # Returns checksum number calculated by Luhn algorithm d...
require 'minitest/autorun' require 'minitest/rg' require_relative '../bus' require_relative '../person' require_relative '../bus_stop' class BusTest < Minitest::Test def setup @bus = Bus.new(25,"Riccarton") @person1 = Person.new("Andris", 29) @person2 = Person.new("Jaime", 29) @bus_stop1 = BusStop....
class AddStatusToTasks < ActiveRecord::Migration[5.2] def change add_column :tasks, :status, :string, inclusion: { in: %w(todo doing done) } end end
class CreateShaadiTypes < ActiveRecord::Migration def change create_table :shaadi_types do |t| t.column :name, :string, :limit => 30, :null => false t.timestamps :null => false end end end
class AddNumSharesToTickerTable < ActiveRecord::Migration[5.2] def change add_column :tickers, :num_shares, :integer end end
require 'base64' require 'sinatra/base' require 'jwt' module OpenBEL module JWTMiddleware def self.encode(payload, secret) ::JWT.encode(payload, secret, 'HS256') end def self.decode(token, secret, verify, options) ::JWT.decode(token, secret, verify, options) end def self.check_token...
#!/usr/bin/ruby -KU require 'rubygems' $LOAD_PATH << "#{File.dirname(__FILE__)}/../lib" require 'idcbatch' require 'logger' unless ARGV.length == 1 or ARGV.length == 0 puts "Usage: #{$0} [config_file]" exit 1 else if ARGV.length == 1 config_file = ARGV.shift else config_file = "/etc/idc...
require 'test_helper' class JournalEntriesControllerTest < ActionDispatch::IntegrationTest setup do @journal_entry = journal_entries(:one) end test "should get index" do get journal_entries_url assert_response :success end test "should get new" do get new_journal_entry_url assert_respon...
class AddTokenToUpload < ActiveRecord::Migration def up add_column :uploads, :token, :string end def down remove_column :uploads, :token end end
class ChangeAttributeTypeToEmailId < ActiveRecord::Migration def update update_column :institutions, :email_id, :string end end
class ChangeCallsActive < ActiveRecord::Migration def self.up execute "DROP VIEW IF EXISTS calls_active" if ActiveRecord::Base.connection_config[:adapter] != 'sqlite3' execute <<-SQL CREATE VIEW calls_active AS SELECT a.uuid AS uuid, a.direction AS direction, a.crea...
class VendorAdmin::EventsController < ApplicationController def new @event = Event.new end def create @event = Event.new(event_params) @event.parse_date_time(params[:event][:date_time]) if @event.save flash[:notice]= "Your event has been created." redirect_to new_vendor_ticket_path(ev...
require 'spec_helper' describe Store do it 'has a valid factory' do expect(FactoryGirl.build(:store)).to be_valid end it 'is not valid without a name' do store = FactoryGirl.build(:store, name: '') expect(store.valid?).to be_false end it 'is not valid without a path' do store = FactoryGirl....
class Node < ActiveRecord::Base attr_accessible :name, :parent_id, :size, :type belongs_to :parent, :class_name => 'Node', :foreign_key => 'parent_id' has_many :children, :class_name => 'Node', :foreign_key => 'parent_id' validates :name, :presence => true, :uniqueness => {:scope => :parent_id} validates :t...
require 'generator_spec' require 'generators/light/decorator/install/install_generator' RSpec.describe Light::Decorator::Generators::InstallGenerator, type: :generator do destination File.expand_path('../../../../tmp', __FILE__) before(:all) do prepare_destination run_generator end it 'creates applic...
class Order < ActiveRecord::Base belongs_to :user has_many :orderlists has_many :products, through: :orderlists validates :email, presence: true end
class AddReviewerToAppStatus < ActiveRecord::Migration def change add_reference :app_statuses, :reviewer, index: true add_foreign_key :app_statuses, :reviewers end end
class AddViewCountToLiveVideos < ActiveRecord::Migration def change add_column :live_videos, :view_count, :integer, default: 0 end end
class BookingsController < ApplicationController # skip_before_action :authenticate_user # testing # skip_before_filter :verify_authenticity_token # skip_before_filter :authenticate_user!, :raise => false def index @bookings = current_user.bookings skip_policy_scope end def create @swimming_po...
# Use spray_paint to clearly specify what we want to perform class MyCar attr_accessor :color attr_reader :speed, :year def initialize(year, color, model) @year = year @color = color @model = model @speed = 0 end def speed_up @speed += 10 end def brake @speed -= 5 end def...
class User < ActiveRecord::Base has_and_belongs_to_many :roles, :join_table => :users_roles # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable # Instead of using :authentication_keys here, we could put it in the # Devise initializer under config....
class Team < ActiveRecord::Base belongs_to :Association has_many :players has_many :coaches end
class Post < ApplicationRecord validates :title, length: {minimum: 3, maximum: 64} validates :html, presence: true validates :css, presence: true end
#!/usr/bin/env ruby # Load the simple_fuzzer binary and execute it repeatedly # with an ever-growing first command-line argument. Exit # when we receive a signal (don't care which one but it's # likely to be SIGSEGV!) and show the stack trace. require 'rubug/gdb' require 'pp' EXE = 'simple_fuzzer' def handle_signal...
module PrintfulAPI class APIResource attr_accessor :raw_data class << self; attr_accessor :api_attribute_list end def self.api_attributes( *args ) self.api_attribute_list = (self.api_attribute_list || []).concat(args) attr_accessor *args end def self.has_many( attribute_name, args = {} ) args[...
# frozen_string_literal: true # == Schema Information # # Table name: users # # id :bigint not null, primary key # email :string # first_name :string # last_name :string # password_digest :string # created_at :datetime not null # updated_at :datetime...
require "formula" class Clucene < Formula homepage "http://clucene.sourceforge.net" url "https://downloads.sourceforge.net/project/clucene/clucene-core-unstable/2.3/clucene-core-2.3.3.4.tar.gz" sha1 "76d6788e747e78abb5abf8eaad78d3342da5f2a4" bottle do cellar :any sha1 "80b58c05e8acc9b2848a57da7e052bf1...
class Charity < ActiveRecord::Base validates :name, presence: true DEFAULT_CURRENCY = 'THB' def credit_amount(amount) self.with_lock { update_column :total, total + amount } end def self.random_charity Charity.order(Arel.sql("RANDOM()")).first end end
json.array!(@members) do |member| json.extract! member, :id, :profile_id, :group_id, :relationship json.url member_url(member, format: :json) end
class UserSearch include ActiveModel::Model attr_accessor :search_name, :search_age def execute User.ransack(name_eq: @search_name, age_eq: @search_age).result end end
class SpFieldTypeSet < ActiveRecord::Base has_one :service_provider has_one :field_type end
# Реализуйте класс Dessert c геттерами и сеттерами # для полей класса name и calories, конструктором, # принимающим на вход name и calories, # а также двумя методами healthy? # (возвращает true при условии калорийности десерта менее 200) # и delicious? (возвращает true для всех десертов). class Dessert attr_...
require 'rails_helper' describe 'Professor::update', type: :feature do let(:responsible) { create(:responsible) } let(:resource_name) { professor.model_name.human } before do login_as(responsible, scope: :professor) end describe '#update' do let(:professor) { create(:professor) } before do ...
require_relative "test_helper" class CUDATest < Minitest::Test def test_works assert !Torch::CUDA.available?.nil? assert Torch::CUDA.device_count end def test_device device = Torch.device("cpu") assert_equal "cpu", device.type assert !device.index? end end
class UserController < ApplicationController protect_from_forgery before_filter :authenticate_user! # Make the social links available everywhere, so they can be used in the footer before_filter do |controller| @footer_data = Content.get_hash_by_slug(%w(facebook_url twitter_url linkedin_url google_plus_url ...
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Monitoring::Event::Cmap::ConnectionCheckedOut do describe '#summary' do let(:address) do Mongo::Address.new('127.0.0.1:27017') end let(:id) do 1 end declare_topology_double let(:pool) do ...
require 'puppet/parameter/boolean' Puppet::Type.newtype(:oneandone_server) do @doc = 'Type representing a 1&1 Cloud server.' newproperty(:ensure) do newvalue(:present) do provider.create(:present) unless provider.running? end newvalue(:absent) do provider.destroy if provider.exists? e...
require 'test_helper' class TodoTest < ActiveSupport::TestCase should_validate_presence_of :body context "A new Todo with no due time" do setup do @todo = Todo.create!(:body => "Buy Milk") end should "be created as incomplete" do assert_equal false, @todo.complete? end ...
class AccountsController < ApplicationController before_filter :login_required skip_before_filter :find_cart, :only => [:new, :create] # GET /accounts # GET /accounts.xml #Changing this to be the hub for the member account. To view and edit accounts, use admin/accounts - coming soon :) def index @cur...
describe 'space.txt file' do it 'contains correctly formated data' do file = File.open("data/space.txt") contents = file.read expect(contents).to_not include(", ") expect(contents).to_not include(" | ") end end describe 'pipe.txt file' do it 'contains correctly formated data' do file = File.o...
class User < ApplicationRecord after_create :create_booking # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable has_one_attached :picture has_many :orders has_many :bookings has_many :packages belongs_to :team, optional: true de...
# coding: utf-8 # frozen_string_literal: true require 'fakefs/spec_helpers' require 'rspec' require 'aruba/rspec' Aruba.configure do |config| config.allow_absolute_paths = true end # Given the output of sass-spec, # return the number of tests in # each state (success, failed, etc) def test_results(output) result...
require 'rails_helper' feature 'User can look a question with answers', %q{ In order to search for an answer As User I'd like to see a question with all the answers } do given(:user) { create(:user) } given(:question) { create(:question_with_answers, answers_count: 2) } scenario 'Unauthenticated user tri...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_action :set_locale def default_url_options(options = {}) { locale: I18n.lo...
object @order attributes :id, :total_tip, :tip_percent, :total_tax, :receipt_no, :store_no, :is_paid, :sub_price, :total_price, :payment_type, :fee attribute :get_order_date => "order_date" attribute :get_paid_date => "paid_date" child @order_items => "order_items" do attributes :id, :item_name, :item_id...
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get root" do get root_path assert_template 'static_pages/top' assert_select "title", "Awesome Penguins" assert_response :success end end
require 'rest_client' require 'json' require 'digest/sha1' require 'base64' module DoceboRuby class API def initialize @url = DoceboRuby.config.api_url @key = DoceboRuby.config.api_key @secret = DoceboRuby.config.api_secret end def send_request(api, method, params, &block) raise ...
class PigLatinizer(string) words = string.split(' ') vowels = ['a', 'e', 'i', 'o', 'u'] words.map each do |word| # For words that begin with vowel sounds, one just adds "way" if vowels.include?(word[0].downcase) word + 'way' else # When words begin with consonant clusters (multiple cons...
class CoatsController < ApplicationController before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] before_action :set_coat, only: [:show, :edit, :update, :destroy] before_action :move_to_index, only: [:edit, :destroy] def index @coats = Coat.order('created_at DESC') end de...
class League class Match class PickBanPresenter < BasePresenter presents :pick_ban def team present(if pick_ban.home_team? pick_ban.match.home_team else pick_ban.match.away_team end) end def picked_by @pi...
module Models class Field < ActiveRecord::Base self.inheritance_column = :_type_disabled belongs_to :collection validates :name, presence: true, uniqueness: { scope: :collection } validates :type, presence: true validates_exclusion_of :name, in: %w(type) def internal false e...
require "administrate/base_dashboard" class BusinessDetailDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages ...
require './test/test_helper' require './lib/game' require './lib/board' require 'pry' class GameTest < Minitest::Test # def test_instance_of_game # player_board = Board.new(4) # comp_board = Board.new(4) # game = Game.new(player_board, comp_board, "b") # assert_instance_of Game, game # end def t...
class Tron::Trc10tokenController < NetworkController layout 'tabs' before_action :token, :breadcrumb QUERY = BitqueryGraphql::Client.parse <<-'GRAPHQL' query ( $token: String!){ tron{ transfers( currency: {is: $token} )...
class MeetingRoom < ApplicationRecord has_many :users, foreign_key: :meeting_id, class_name: :User validates :name, presence: true, uniqueness: true end
class CreateInstrumentos < ActiveRecord::Migration[6.1] def change create_table :instrumentos do |t| t.integer :idCategoria t.string :tipo t.string :nombre t.string :detalles t.string :img t.timestamps t.column :deleted_at, :datetime, :limit => 6 end end end
Rails.application.routes.draw do mount RailsAdmin::Engine => '/admin', as: 'rails_admin' mount Commontator::Engine => '/commontator' devise_for :users root 'statuses#index' resources :users, constraints: { id: /.*/ } resources :groups do member do post :join get :can_join get :memb...
class Customer attr_reader :id, :first_name, :last_name, :created_at, :updated_at, :customer_repository def initialize(data, customer_repository=nil) @id = data[:id] @first_name = data[:first_name] @...
class Work < ApplicationRecord has_many :votes validates :title, presence: true, uniqueness: true def total_votes votes = self.votes.count return votes end # similar but opposite of the user model. def user_voters votes = self.votes.order(created_at: :desc) user_ids = [] votes.each...
class ShortVisitSerializer include JSONAPI::Serializer attributes :visitor_ip, :visitor_city, :visitor_state, :visitor_country_iso2 end
class Boat < ApplicationRecord geocoded_by :address after_validation :geocode, :if => :address_changed? validates_presence_of :boat_name, :style, :description, :price, :image has_many :bookings belongs_to :user has_attached_file :image, styles: { large: "600x600>", ...
require 'rails/railtie' module ToSpreadsheet class Railtie < ::Rails::Railtie config.to_spreadsheet = ActiveSupport::OrderedOptions.new config.to_spreadsheet.renderer = ToSpreadsheet.renderer config.after_initialize do |app| ToSpreadsheet.instance_variable_set("@renderer", app.config.to_spreadsheet...
require 'rails_helper' describe SocialProfile do describe '#create' do before do @user = create(:user) end it "すべてのデータがあり正常に登録できる" do socialprofile = SocialProfile.new(uid: "1", provider: "facebook", access_toke...
class LessonsController < ApplicationController skip_before_action :authenticate_cookie def index @lessons = set_course_id && set_unit_id ? set_course_unit_lessons : set_unit_id ? set_unit_lessons : Lesson.all if set_course_id && set_unit_id render ({ json: { ...
require "hpricot" require 'open-uri' class Spot < ActiveRecord::Base validates_presence_of :geolocation_x validates_presence_of :geolocation_y validates_presence_of :name has_many :claims, :order => "created_at DESC", :dependent => :destroy has_many :stuffs, :dependent => :destroy belongs_to :city va...
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string not null # password_digest :string not null # session_token :string not null # is_admin :boolean not null # created_at :datetime ...
# namespace :mgmt do # bundle_cmd = :'/home/isucon/local/ruby/bin/bundle' # # desc "Bundle install" # task :install do # on roles(:mgmt) do |host| # within "#{release_path}/mgmt" do # execute bundle_cmd, :install, :'--path', :'vendor/bundle', :'-j2' # end # end # end # # desc "re...