text
stringlengths
10
2.61M
class ApplicationController < ActionController::Base protect_from_forgery before_filter :authorize before_filter :set_var helper :all # include all helpers, all the time config.encoding = "utf-8" helper_method :order_limit private def set_var @day0 = Time.now.strftime("%a, %b #{Time.now.day.or...
class LeaveGroupEmployee < ActiveRecord::Base attr_accessor :selected, :name, :department, :position, :grade belongs_to :employee, :polymorphic => true belongs_to :leave_group validates_presence_of :employee_id def self.leave_group_employees(leave_type) LeaveGroupEmployee.all(:select => "emplo...
class AddGrossVehicleWeightToVehicles < ActiveRecord::Migration def change change_table :vehicles do |t| t.integer :gross_vehicle_weight, limit: 8 end end end
require 'rails_helper' RSpec.describe "Users", type: :request do describe "GET /users" do it "responds with JSON" do user = User.create! nickname: 'nickname1' get users_path # expect the result to be json expect(response.content_type).to eq('application/vnd.api+json') end end end
# 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class CommentsController < ApplicationController def index @comments = Comment.paginate(page: params[:page], per_page: 5) end def new @comment = Comment.new end def create #render plain: params[:article].inspect @article = Article.find(params[:article_id]) @comment = @article.comments....
class Sighting < ActiveRecord::Base geocoded_by :address # auto-fetch coordinates and the condition is for preventing fetching the same address more than once after_validation :geocode, if: :address_changed? end
require_relative "../../../../spec_helper" describe "govuk_jenkins::config", :type => :class do let(:default_params) do { github_client_id: "bar", github_client_secret_encrypted: "baz" } end describe "manage config" do context "false (default)" do let (:params) { default_params.merge(manage_config...
# -*- mode: ruby -*- # vi: set ft=ruby : # To use this, install Vagrant from http://vagrantup.com/ and VirtualBox # then run 'vagrant up' # It should automatically download an Ubuntu 10.04 virtual machine, # install WeasyPrint with PyGTK in it and run the test suite. # The point is to test that everything works fine ...
class Location < ActiveRecord::Base has_many :lists has_many :beers, through: :lists end
require 'active_support/core_ext' require 'active_support/inflector' require 'active_model' require 'rest_client' require 'hmac-sha2' require 'bitstamp/net' require 'bitstamp/helper' require 'bitstamp/collection' require 'bitstamp/model' require 'bitstamp/orders' require 'bitstamp/transactions' require 'bitstamp/tick...
require 'spec_helper' describe Pet, type: :model do describe 'validations' do it { should validate_presence_of(:name) } it { should validate_presence_of(:breed) } it { should validate_presence_of(:gender) } it { should validate_presence_of(:description) } it { should validate_presence_of(:avatar) } ...
require "test_helper" describe Art do describe 'validations' do before do #Arrange @art = arts(:one) end it 'is valid when it has a category and title' do #Act result = @art.valid? #Assert result.must_equal true end it 'is invalid when it has no title' do ...
class AccountGroupAuthzAssignment < ActiveRecord::Base acts_as_authorizable validates_presence_of :authz_id validates_presence_of :account_group_id validates_uniqueness_of :authz_id, :scope => :account_group_id acts_as_audited acts_as_reportable belongs_to :authz, :class_name => 'Account', :foreign_key...
module OpenMensa class Api include HTTParty require 'httparty' base_uri 'openmensa.org/api/v2' def initialize @id = 289 # OpenMensa ID @options = { } # parameters end def hs_mannheim self.class.get("/canteens/#{@id}") end def meal_list @data = self.class.ge...
# == Informacion de la tabla # # Nombre de la tabla: *dbm_descriptor_especifico* # # idDescriptorEspecifico :integer(11) not null, primary key # idDescriptorGenerico :integer(11) not null # descriptorEspecifico :string(100) default(""), not null # # Se valida que se registre un Descriptor Especifico ...
class ProductsController < ApplicationController before_action :authenticate_administrator!, except: [:index, :search, :show, :recommend] ## ユーザー ## USER_PER = 12 SEARCH_PER = 20 #カテゴリー別商品一覧 def index @greed = Greed.find(params[:id]) @greeds = Greed.all @products = @greed.products.order(params[:so...
require 'rails_helper' RSpec.describe 'As an authenticated user' do context 'when I click favorites' do xit "shows a list of starred companies" do user_logs_in user = User.first companies = create_list(:company, 1) new_company = create(:company) companies << new_company user...
class Post < ActiveRecord::Base validates :title , presence: true validates :content, length: {minimum: 250} validates :summary, length: {maximum: 250} validates :category, inclusion: { in: %w(Fiction Non-Fiction) } validate :clickbait? def clickbait? if title != nil && !title.start_with?('Won\'t Beli...
require "rails_helper" describe ::ExternalEvents::EnrollmentEventNotification do let(:m_tag) { double('m_tag') } let(:t_stamp) { double('t_stamp') } let(:e_xml) { double('e_xml') } let(:headers) { double('headers') } let(:responder) { instance_double('::ExternalEvents::EventResponder') } let :enrollment_e...
module Players class Computer < Player def move(board) valid_move_possibilities = ["", " "] computer_array = board.cells.map.with_index do |a, index| if valid_move_possibilities.include?(a) input = index + 1 input.to_s end end if computer_array.sample...
class FeedbacksController < ApplicationController before_action :authenticate_user! def new @feedback = Feedback.new end def create @feedback = Feedback.new(feedback_params) if @feedback.save redirect_to thankyou_path, notice: 'Feedback submitted successfully.' else render :new ...
json.array!(@muas) do |mua| json.extract! mua, :id, :style, :education, :experience, :clients, :equipment, :rate, :user_id json.url mua_url(mua, format: :json) end
# This benchmark solves the testBoard. require 'benchmark/ips' require_relative '../lib/lee' board = Lee.read_board(File.expand_path('../inputs/testBoard.txt', __dir__)) def expand(board, obstructed, depth, route) start_point = route.a end_point = route.b # From benchmarking - we're better of allocating a ne...
class CreateTarifCalculations < ActiveRecord::Migration def self.up create_table :tarif_calculations do |t| t.date :from t.date :to t.boolean :active t.string :notes t.integer :port_id t.timestamps end end def self.down drop_table :tarif_calculations end ...
require 'fipeapi/version' require 'httparty' require 'active_support/inflector' require_relative './core_ext/myparty' require_relative 'fipeapi/objeto_com_construtor' require_relative 'fipeapi/marca' require_relative 'fipeapi/modelo' require_relative 'fipeapi/ano' require_relative 'fipeapi/valor' module FipeApi API...
class CreateExpensesTable < ActiveRecord::Migration[6.0] def change create_table :expenses do |t| t.belongs_to :user t.belongs_to :theme # precision is the total number of digits # scale is the number of digits to the right of the decimal point t.decimal :amount, :precision => 8, :sc...
require "open-uri" require "json" class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :strip_www before_action :check_for_redirection before_action :strip_file_extension before_action :set_social_links before_action :set_new_subscriber before_action :...
require 'spec_helper' RSpec.describe FdaEventService do it "should return 10 results for a wide-scoped search" do expect( FdaEventService.search("viagra")['results'].length ).to eq 10 end describe "search on brand/term" do before :each do @brand_name = "Lipitor" @term = "DIZZI...
class Station DEFAULT_ZONE = 'z' attr_accessor :zone attr_reader :name def initialize(name) @name = name @zone = DEFAULT_ZONE end end
Rails.application.routes.draw do devise_for :users resources :reports do resources :comments end root 'reports#index' end
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 helper_method :current_user, :flash_class, :check_id before_filter :require_login private def require_login ...
class CreateBiddingsAccreditationPresentials < ActiveRecord::Migration def change create_table :biddings_accreditation_presentials do |t| t.belongs_to :bidding t.belongs_to :accreditation_presential t.timestamps end add_index :biddings_accreditation_presentials, :bidding_id, name: "bidding_id" add_in...
# frozen_string_literal: true class FeedWithArticles < SimpleDelegator attr_reader :articles, :paginated_articles, :category_id, :subscription_id def initialize(feed, articles, cid, sid) super(feed) @articles = articles.map { |a| ArticleWithFeedURL.new(a, feed) } @category_id = cid @subscription_i...
module Lolita module Configuration module Tab class Content < Lolita::Configuration::Tab::Base def initialize(*args,&block) super set_default_fields end private def set_default_fields default_fields if @fields.empty? end def validate(...
require "pry" # David Lin # Search diagonally to range the matrix to 2*2 matrix in O(log(m/2)+log(n/2)) time. # and then search the 2*2 matrix in O(1). # @param {Integer[][]} matrix # @param {Integer} target # @return {Boolean} def search_matrix(matrix, target) return false if matrix == [] return false if mat...
module Guard # The UI class helps to format messages for the user. Everything that is logged # through this class is considered either as an error message or a diagnostic # message and is written to standard error (STDERR). # # If your Guard does some output that is piped into another process for further #...
class Board < ActiveRecord::Base attr_accessible :category, :name, :pin_id, :user_id, :fav, :foll validates_presence_of :user_id belongs_to :user has_many :board_pins has_many :pins, :through => :board_pins #allows for polymorphic comments has_many :comments, :as => :commentable has_many :follows ...
class CreateOrders < ActiveRecord::Migration def up create_table :orders do |t| t.integer :client_id, null: false t.float :summa, default: 0 t.text :address t.timestamps null: false end add_index :orders, :client_id end def down remove_index :orders, :client_id drop_t...
class FontCrimsonText < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/crimsontext" desc "Crimson Text" homepage "https://fonts.google.com/specimen/Crimson+Text" def install (share/"fonts").install "CrimsonText-Bold.ttf" (share/"f...
require 'spec_helper' describe "tax_withholdings/index" do before(:each) do assign(:tax_withholdings, [ stub_model(TaxWithholding, :working_days => 1, :working_hours => 2, :holiday_working_hours => 3, :night_working_hours => 4, :extra_working_hours => 5, :bas...
class ReviewQuestion < ActiveRecord::Base has_many :answers end
class Api::V1::OrdersController < ApplicationController before_action :set_user before_action :set_order, only: [:show, :update, :destroy] # GET /orders def index @orders = Order.where(user_id: params[:user_id]) render json: @orders end # GET /orders/1 def show render json: @order end #...
class ShotRecordsController < ApplicationController before_action :set_animal def create @shot_record = @animal.shot_records.build(record_params) if @shot_record.save respond_to do |format| format.html {redirect_to user_animals_path(current_user.id)} format.js end end end ...
ENV['SCREENSHOTS'] ||= 'false' require 'page-object' Before do @employee = { first_name: 'Test', last_name: 'User', title: 'Software Consultant', supervisor: 'Manager-Test User', project: 'WatchDogs2', location: 'Greensboro' } end After do # make sure the browser is logged out before beg...
class UsersController < ApplicationController include PrivilegeHelper include UsersHelper include PmailHelper before_action :require_user, except: [:new, :create, :list, :search_user_name, :add_user_favorite, :delete_user_favorite] before_action :require_login, except: [:new, :create] before_action :require...
require 'spec_helper' describe UpdatePolicy do subject { described_class } let(:policy) { described_class.new(user, update) } let(:user) { nil } let(:update) { create(:update) } shared_examples_for 'create permissions' do it 'should deny access if user is nil' do expect(subject).not_to permit(nil...
require 'test_helper' class WallRaportsControllerTest < ActionController::TestCase setup do @wall_raport = wall_raports(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:wall_raports) end test "should get new" do get :new assert_respons...
class Departments::EditSerializer < ApplicationSerializer object_as :department attributes( :id, :name, :slug, :location_id, :notes, ) belongs_to :location, serializer: Locations::OptionsSerializer, optional: true end
require 'colorize' class WaterfallHell DELTA = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] } def initialize(file: nil, display: false, verbose: false, start: nil, stop: nil, center: nil, fast: nil, follow: nil, height: nil, width: nil, output: false) @file = fi...
ActiveAdmin.register Client do menu false config.sort_order = 'last_name_asc' permit_params :first_name, :last_name, :phone_number, :next_court_date_at, :id_number, :notes, :active, :client_status_id, user_ids: [] show do panel 'Client Details' do attributes_table_for client do row :first_n...
class CreateJoinTableCharactersUsers < ActiveRecord::Migration def change create_table :characters_users, id: false do |t| t.belongs_to :character, index: true t.integer :fb_user_id, limit: 8, index: true t.timestamps end add_index :characters_users, [ :character_id, :fb_user_id ], unique: true end end
# frozen_string_literal: true require 'fileutils' require 'json' require 'colorize' # Provides a way to update iOS Assets with new ones class IOSAssetUpdater # Copies image files (.jpg, .png) from a source, and update corresponding # assets in an iOS project folder. # Names have to match exactly for the update ...
class CreatePortfoliosTable < ActiveRecord::Migration def up create_table :portfolios do |t| t.integer :placement t.timestamps end end def down drop_table :portfolios end end
require_relative 'linked_list_item' class LinkedList attr_reader :first_item attr_reader :size def initialize *args @size = 0 end def add_item(payload) @size += 1 if @first_item.nil? @first_item = LinkedListItem.new(payload) else last_item = @first_item while !last_item.la...
class TemplateLesson < ActiveRecord::Base belongs_to :course belongs_to :day_template default_scope :order=>"strftime('%H:%M', start_time)" end
set :application, 'cpt-style-guide' set :repo_url, 'git@github.com:OffBase/cpt-style-guide.git' set :user, 'cpt' set :deploy_to, "/home/#{fetch(:user)}/#{fetch(:application)}" set :releases_directory, "/home/#{fetch(:user)}/#{fetch(:application)}/releases" set :deploy_via, :remote_cache set :use_sudo, false set :keep_r...
# frozen_string_literal: true require 'dry-monads' require_relative 'assertions/maybe' require_relative 'assertions/either' module Minitest module Dry module Monads # Assertions for dry-rb monads module Assertions M = ::Dry::Monads include Maybe include Either end end...
class ApplicationController < ActionController::Base before_action :set_locale private def set_locale cookies[:locale] || :en I18n.locale = cookies[:locale].to_sym || :en end end
class LocationDescription < ActiveRecord::Base belongs_to :location validates :location_id, :presence => true, :numericality => { :only_integer => true } end
class ApplicationController < ActionController::Base protect_from_forgery rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception.message end around_filter :set_time_zone #Dynamically set time zone based on user.time_zone private def set_time_zone old_time_zone ...
FactoryGirl.define do # lists sequence sequence (:list_name) do |n| "List #{n}" end factory :list do family family_user name { generate(:list_name) } end end
ActiveAdmin.register Lesson do permit_params :name, :content, :video_link end
class Api::V1::CountriesController < ApplicationController def index render json: ISO3166::Country.countries.sort.map{|i| { label: i.name, value: i.alpha2 }} end def show states = [] country = ISO3166::Country.find_country_by_alpha2(params[:id]) if country.present? country.states.each do |k, v...
RSpec.describe Slim::Jets do it "has a version number" do expect(Slim::Jets::VERSION).not_to be nil end end
require 'em-xmpp/namespaces' require 'em-xmpp/nodes' require 'em-xmpp/conversation' require 'fiber' module EM::Xmpp module Helpers include EM::Xmpp::Namespaces def get_roster f = Fiber.current roster = iq_stanza(x('query',:xmlns => Roster)) send_stanza(roster) do |response| f.res...
class Api::V1::ArticlesController < Api::V1::ApiApplicationController # skip_before_action :authenticate_user!, :only => [:index,:show] def index if index_params[:category].present? && index_params[:category].downcase == "phrase" selector_query = Content.shared.phrases elsif index_params[:ca...
class Team < ApplicationRecord belongs_to :trainer belongs_to :pokemon end
require "#{Rails.root}/db/chores/csv_user_importer" describe CsvUserImporter do around (:each) do |test| @temp_file = Tempfile.new("temp_file.csv") test.run @temp_file.close unless @temp_file.closed? @temp_file.unlink end describe 'header guessing' do it 'makes reasonable guesses when column...
module People class QueryJobRole prepend SimpleCommand def initialize(current_user, args = {}) @current_user = current_user @args = args end def call f_ids = @args[:facility_id].split(',').map { |x| x.to_bson_id } main = [] months = I18n.t('date.abbr_month_names').compa...
shared_examples 'idv account creation' do |sp| it 'redirects to SP after IdV is complete', email: true do allow(Figaro.env).to receive(:enable_agency_based_uuids).and_return('true') allow(Figaro.env).to receive(:agencies_with_agency_based_uuids).and_return('1,2,3') email = 'test@test.com' visit_idp_f...
module Admin class RawHooksController < AdminController expose(:raw_hooks) { RawHook.order(created_at: :desc).limit(20) } expose(:raw_hook) { RawHook.find(params[:id]) } end end
# frozen_string_literal: true module StringCheese # Provides constants for identifying actions that take place against # attributes module ActionType # The attr was added ATTR_ADD = 1 # The attr has been changed ATTR_CHANGE = 2 # The attr has been read ATTR_READ = 4 # The attr has bee...
module Enumerable def my_each i = 0 while i< self.size yield(self[i]) i+=1 end end def my_each_with_index i = 0 while i < self.size yield(self[i],i) i+=1 end end def my_select arr = [] self.my_each {|v| arr<<v if yield(v)} arr end def my_all?...
class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters def full_name return "#{self.first_name} #{self.last_name}" end def list_roles #all characters an actor has self.characters.map do |character_info| "#{character_info.name} - #{character_info.show.name}...
class Poblacion < ApplicationRecord belongs_to :municipio end
class BilligEvent < ActiveRecord::Base has_one :samfundet_event, class_name: "Event" has_many :billig_ticket_groups, foreign_key: :event scope :sale_applicable, -> { where("hidden = 'f' AND sale_to > ?", DateTime.current) } self.primary_key = :event attr_accessible :a4_ticket_layout, :dave_id, :dave_time_id...
Rails.application.routes.draw do resources :profiles, only: [:new, :create, :edit, :update, :show] do resources :monecurie, controller: 'profileschevals', only: [:index] resources :mesreservations, controller: 'profilesbookings', only: [:index] resources :mesclients, controller: 'profiles_reservations_cl...
module ApplicationHelper def bootstrap_class_for(type) list = { success: "alert-massage-success", error: "alert-massage-danger", alert: "alert-massage-warning", notice: "alert-massage-info" } list[type.to_sym] end end
require 'rails_helper' RSpec.describe 'User updates Service Components in SPARC', type: :request, delay: false do describe 'full lifecycle' do it 'should update the Protocol', sparc_api: :get_service_components_1 do line_item = create(:line_item, service: create(:service_with_one_time_fee), protocol: cre...
require 'rails_helper' describe 'RegistrationsController', type: :request do describe 'GET#new' do it 'redirects to the sign in page' do get new_user_registration_path expect(response).to redirect_to '/users/sign_in' end end describe 'POST#create' do it 'redirects to the sign in page' do...
# This class is for managing task model # class Task class Task < ApplicationRecord belongs_to :category belongs_to :user validates :title, presence: true, length: { in: 6..60 } validates :description, presence: true, length: { minimum: 60 } validates :company_name, presence: true, length: { in: 6..50 } val...
class CreateExchanges < ActiveRecord::Migration[6.0] def change create_table :exchanges do |t| t.belongs_to :user, null: false, foreign_key: true t.belongs_to :crypto, null: false, foreign_key: true t.float :total t.float :buy_price t.float :sell_price t.float :units t.bo...
class CreateAppearances < ActiveRecord::Migration def change create_table :appearances do |t| t.belongs_to :user t.belongs_to :medium t.datetime :first_appearance t.timestamps end end end
class DropTableCitations < ActiveRecord::Migration[4.2] def change drop_table :citations end end
require 'json' class JSONParser attr_accessor :path def initialize(path) @path = path end def to_arr_of_hash contents = File.read(@path) JSON.parse(contents, symbolize_names: :true) end end
class Trinary def initialize(trinary_number) @trinary_reverse = trinary_number.reverse end def to_decimal return 0 unless @trinary_reverse.chars.all? { |c| c =~ /[0-2]/ } @trinary_reverse.chars.map.with_index { |n, i| n.to_i * 3**i }.reduce(:+) end end module BookKeeping VERSION = 1 end
# frozen_string_literal: true # Asynchronous job used to index EAD Documents class IndexJob < ApplicationJob # Class for capturing the output of the Traject indexer class EADArray < Array # Appends the output of the Traject indexer # (Used by Traject#foo) # @param context [Traject::Context] def put...
class CreateStatements < ActiveRecord::Migration def self.up create_table :statements do |t| t.column :cookie, :string t.column :filename, :string t.column :problem_id, :integer t.column :created_at, :datetime t.column :updated_at, :datetime end end def self.down drop_ta...
# Variable shadowing in Ruby relates specifically to when a *block* parameter of the same name is used. In the below tests, I have initialized two local variables `a` and `b` respectively and these are considered outer scope as opposed to the inner scope within the block further down. We can see the object_ids from the...
module NxtPipeline class Callbacks def initialize(pipeline:) @registry = build_registry @pipeline = pipeline end def register(path, callback) registry.resolve!(*path) << callback end def run(kind_of_callback, type, change_set) callbacks = registry.resolve!(kind_of_callbac...
require 'json' class OJSIssueBuilder attr_reader :json attr_reader :issue def initialize(ojs_json) @json = (ojs_json.is_a? String) ? JSON.parse(ojs_json) : ojs_json @sections = {} end def build build_issue build_articles end def save! @issue.save! end protected def build_i...
class PurchaseOrder < ActiveRecord::Base belongs_to :supplier has_many :item_orders def supplier_name supplier.try :name end def supplier_name=(name) self.supplier = Supplier.find_or_create_by_name(name) if name.present? end def add_phone(phone) supplier.phones << phone end def date c...
require 'helper_frank' module Rdomino describe DatabaseDirectory do subject { DatabaseDirectory.new '',/rdomino\\rspec/ } it 'finds Databases by matchers' do assert subject.all? { |db| db.filepath =~ /^rdomino\\rspec/ } assert (7..12) === subject.count, "#{subject.count} Databases in !!rdomino\...
String.class_eval do # max_len is string size to shorten to if self.size is longer. # Default value is 1/2 the self.size. abbrev_len is the length of # the abbreviation before or after "..." (depending on chop_start_end) # abbrev_len will be coerced up or down if < 0 or exceeds max_len - 3. # shorten_start...
class CreatePunches < ActiveRecord::Migration[6.0] def change create_table :punches do |t| t.integer :client_id t.string :clock_in t.string :clock_out t.string :date end end end
class FontInconsolataLgcNerdFont < Formula version "2.3.3" sha256 "826471e967933f020150430db978a7729927d96bacf3c4e7fbe1e216834f4599" url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/InconsolataLGC.zip" desc "InconsolataLGC Nerd Font (Inconsolata LGC)" desc "Developer targeted fonts w...
module ContactsHelper def contact_columns { id: 'ID', first_name: 'First', last_name: 'Last', birthdate: 'DOB', age: 'Age', gender: 'Gender', ethnicity: 'Ethnicity', description: 'Description' } end def contact_id( cont...
class Admin::EventsController < Admin::AdminController include Admin::S3UploaderHelper include Admin::CalendarHelper before_action :set_event, only: [:edit, :update, :show, :destroy, :recurring_exception] before_action :parse_time, only: [:create, :update] before_action :set_s3_direct_post, only: [:new, :create, :...
# == Schema Information # Schema version: 20101210013325 # # Table name: ratings # # id :integer not null, primary key # beer_id :integer # user_id :integer # score :decimal(, ) # notes :string(255) # created_at :datetime # updated_at :datetime # class Rating < ActiveRecord::Base...