text
stringlengths
10
2.61M
class GenerateRawPlaneObservation include Sidekiq::Worker sidekiq_options queue: :generate_rpo def perform(id) RawPlaneObservation.generate_from_raw_plane(RawPlane.find(id)) end end
require 'spec_helper' describe Gollum::Git::Repo do before(:each) do @repo = Gollum::Git::Repo.new(fixture('dot_bare_git'), :is_bare => true) end it "should have a Gollum::Git::Repo::init_bare method" do Gollum::Git::Repo.should respond_to(:init_bare) end it "should have a path method" do ...
# frozen_string_literal: true require_relative "boot" require "sprockets/railtie" require "rails/all" Bundler.require(*Rails.groups) require "renalware/diaverum" module Dummy class Application < Rails::Application # config.load_defaults 6.0 config.autoloader = :zeitwerk # Initialize configuration defa...
module Structural class InvalidDefaultTypeError < StandardError end end
class Route attr_reader :stations, :name def initialize(from, to, name) @stations = [from, to] @name = name end def add_midway(name) @stations.insert(-2, name) end def last? self.stations == stations.last end def first? self.stations == stations.first? end def d...
class CreateKeychains < ActiveRecord::Migration def self.up create_table :keychains do |t| t.integer :user_id t.text :crypted_details t.timestamps end end def self.down drop_table :keychains end end
module Seed class CartmanJokesService def self.build self.new end def initialize end def call Rails.logger.info("- Start #{self.class.name}") jokes = [ {:joke_type => 1, :sequence => 1, :uuid => 101, :joke => "How come everything today has involved things eit...
require 'bundler' Bundler.setup require 'nokogiri' require 'algorithms' class Song include Comparable attr_reader :name, :duration def initialize(name, duration) @name = name @clean_name = clean_name(name) @duration = duration end def clean_name(name) name = name.upcase name = name.st...
# frozen_string_literal: true module Ability::Roles::User extend ActiveSupport::Concern included do def user can [:index], User, id: @user.id end end end
class CreateHistorials < ActiveRecord::Migration[6.0] def change create_table :historials do |t| t.string :owner_name t.numeric :owner_phone t.string :owner_address t.string :owner_document t.string :pet_name t.string :pet_breed t.string :pet_species t.string :pet_c...
require 'spec_helper' require 'aker' require 'vcr' describe NcsNavigator::Authorization::Core::Authority do before do @ncs_navigator_authority = NcsNavigator::Authorization::Core::Authority.new @user = mock(:username => "lee", :cas_proxy_ticket => "PT-cas-ticket") end describe '.initialize' do it 'a...
FactoryGirl.define do factory :mission do name "Scopes" end end
ActiveAdmin.register Client do permit_params :name, :description menu :parent => "Tablas",:label => "Clientes" config.sort_order = "name_asc" breadcrumb do params[:action]=='index' ? [] : [] end action_item :only => :show do link_to "Volver", admin_clients_path end # sidebar 'Prod...
module RSpec module Mocks # @private class ObjectReference # Returns an appropriate Object or Module reference based # on the given argument. def self.for(object_module_or_name, allow_direct_object_refs=false) case object_module_or_name when Module if anonymous_modu...
# # Cookbook Name:: odi-cert-deployer # Recipe:: default # # Copyright 2013, The Open Data Institute # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without...
module Adminpanel module Sitemap extend ActiveSupport::Concern included do after_create :ping_engines after_update :ping_engines after_destroy :ping_engines end private def ping_urls { google: "http://www.google.com/webmasters/tools/ping?sitemap=%s", bing: "...
class AddFields2ToHouses < ActiveRecord::Migration def change add_column :houses, :offer_type, :integer add_column :houses, :owner_connection, :integer add_column :houses, :house_connection, :integer add_column :houses, :reference_pois, :boolean, default: false add_column :houses, :description_hou...
class Person < ApplicationRecord validates :first_name,:last_name, :age ,presence: true validates :first_name, :last_name, length: { minimum: 3, too_short:"must have at least %{count} words" } validates :age, numericality: { only_integer: true } end
# Write a cat class # > A cat is initialized with its name # > A cat is happy, if and only if its fed, rested, entertained, and adopted # > It is possible to play with a cat in order to entertain it, # but when you play with a cat, it becomes tired # > It is possible to pet a cat. When you pet a cat, it will either ...
require 'spec_helper' describe HairsHelper do it { should have_defined_method :user_hairs } it { should_not have_defined_method :user_genders } it { should_not have_defined_method :user_nationalities } context "should include method" do subject { Class.new { include HairsHelper }.new } its(:user_hair...
class AffordancesController < ApplicationController before_action :set_affordance, only: [:show, :edit, :update, :destroy] # GET /affordances # GET /affordances.json def index @affordances = Affordance.all end # GET /affordances/1 # GET /affordances/1.json def show end # GET /affordances/new ...
class CreateUserPoints < ActiveRecord::Migration[5.0] def change create_table :user_points do |t| t.references :user, foreign_key: true, null: false t.integer :amount, null: false, default: 0 end end end
# encoding: utf-8 # validate_equality # validates_in [true, false, nil] # it can work as validate_length (0..10) as well module Formidable module Validations class ValidateEquality < Validation register(:validate_equality) def initialize(element, *values) @values = values super(eleme...
class ProductContent < ActiveRecord::Base attr_accessible :category_id, :flavor_name, :product_id, :quantity, :type_id, :name belongs_to :product belongs_to :category, :class_name => "ProductCategory" belongs_to :type, :class_name => "ProductType" validates :category_id, :flavor_name, :product_id, :quantity,...
class YelpSearch attr_reader :businesses def initialize(query, paramas) response = Yelp.client.search(query, paramas) @businesses = response.businesses end end
module Rubot module Message class Base attr_accessor :sender_id def initialize (sender_id) @sender_id = sender_id end end end end
class AddPaperclipToSectionAndProduct < ActiveRecord::Migration def self.up add_column :products, :cover_file_name, :string add_column :products, :cover_file_size, :integer add_column :products, :cover_content_type, :string add_column :products, :cover_updated_at, :datetime add_column :sections, :cover...
class Enemy < ActiveRecord::Base has_many :fights has_many :players, through: :fights end
class ContractorFeaturesController < ApplicationController # GET /contractor_features # GET /contractor_features.json def index @contractor_features = ContractorFeature.all respond_to do |format| format.html # index.html.erb format.json { render json: @contractor_features } end end #...
module CSSPool module CSS class MediaQuery < CSSPool::Node attr_accessor :only_or_not, :media_expr, :and_exprs attr_accessor :parse_location def self.empty new(nil, nil, []) end def initialize(only_or_not, media_expr, and_exprs, parse_location = {}) @only_or_not = o...
class ClientIndAr < ActiveRecord::Base attr_accessible :id, :client_id, :imie, :nazwisko, :client validates_presence_of :imie, :nazwisko belongs_to :client end
class TestIssue < ActiveRecord::Base belongs_to :build attr_accessible :dirty, :category, :subtype, :scenario_id, :description, :step_order def scenario @scenario ||= build.find_scenario_by_id(scenario_id) end def wip? scenario.wip? end def problem_step # if category == ScenarioCategories:...
class Messaging::Twilio::Error < Messaging::Error # https://www.twilio.com/docs/api/errors ERROR_CODE_REASONS = {21211 => :invalid_phone_number, 21614 => :invalid_phone_number} def initialize(message, error_code) @message = "Error while calling Twilio API: #{message}" @reason = ER...
class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: # #user ||= User.new # guest user (not logged in) if user.has_role? :admin can :manage, :all else can :create, Task can :show, Task do |task| ...
#!/usr/bin/env ruby require 'nokogiri' require 'open-uri' CACHE_FILE='full-emoji-list.html' FULL_EMOJI_LIST='https://unicode.org/emoji/charts/full-emoji-list.html' unless File.exists?(CACHE_FILE) $stderr.puts "#{CACHE_FILE} doesn't exist, downloading" File.open(CACHE_FILE, 'w') do |file| open(FULL_EMOJI_LIST...
# frozen_string_literal: true class NewRecordService attr_writer :app, :via, :ga_client, :page_category attr_reader :record def initialize(user, record) @user = user @record = record end def save! @record.user = @user @record.work = @record.episode.work @record.detect_locale!(:comment) ...
class PigLatinizer attr_reader :text def initialize end def piglatinize(text) vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] words = text.split words.map do |word| if vowels.include?(word[0]) word + "way" else i = 0 ...
module PowerAPI module Data class Student def initialize(soap_url, soap_session, populate = true) @soap_url = soap_url @soap_session = soap_session self.populate if populate end def populate transcript = fetch_transcript parse_transcript(transcript) ...
class AddLessonIdToWords < ActiveRecord::Migration def change add_column :words, :lesson_id, :integer end end
# frozen_string_literal: true require 'stannum/constraints' module Stannum::Constraints # An Equality constraint uses #== to compare the actual and expected objects. # # @example Using an Equality constraint # string = 'Greetings, programs!' # constraint = Stannum::Constraints::Equality.new(string) ...
class Individuals::RegistrationsController < Devise::RegistrationsController before_action :configure_sign_up_params, only: [:create] before_action :configure_account_update_params, only: [:update] def new super end def create super end def edit super end def update super end ...
RSpec.describe TeamsController do describe "GET index" do it "blocks unauthenticated access" do get :index, format: :json expect(response.body).to eq({user: :invalid}.to_json) end context 'with login' do before do @user = create(:user) @team = create(:team, user: @user) ...
class AddColumnsToJobs < ActiveRecord::Migration[5.0] def change add_column :jobs, :name, :string add_column :jobs, :cost, :decimal add_column :jobs, :origin, :string add_column :jobs, :destination, :string end end
module Admin::DashboardHelper def devise_error_messages alert_types = { notice: :olive, alert: :red } close_button_options = { class: "close icon" } close_button = content_tag(:i, "", close_button_options) alerts = flash.map do |type, message| alert_content = close_button + content_tag(:div, message, {class: "...
module ClientUser def get_users @users = User.all end def update_user_list(client) puts "Updating user list." get_users api_members = client.web_client.users_list.members save_user_on_update_list(api_members, @users) s = Rufus::Scheduler.new(:max_work_threads => 200) s.every '10m' do...
require 'test_helper' class Admin::ProducerControllerTest < ActionController::TestCase fixtures :producers test "new" do get :new assert_response :success end test "create" do num_producers = Producer.count post :create, :producer => { :name => 'The Monopoly Publishing Company' } assert_r...
require "rails_helper" RSpec.describe Seed::Config do before do # We need to clear this, otherwise tests that depend on them will have weird side # effects hanging around from previous tests ENV.delete("SEED_TEST_MODE") end after do # We want to make sure other tests have the correct test ENV va...
require 'scripts/ui/passage_panel' module UI # UI component for editing passage flags # The flag is disabled as: # U # LAR # D # Where U=UP, L=LEFT, A=ABOVE, R=RIGHT, D=DOWN # Left clicking on any of the blocks will flip the flag and trigger a # {PassageEditor::PassageChanged} (passage_changed)...
require 'spotify_web/resource' module SpotifyWeb # Represents a country-based restriction on Spotify data class Restriction < Resource CATALOGUE_IDS = { Schema::Metadata::Restriction::Catalogue::AD => [:free], Schema::Metadata::Restriction::Catalogue::SUBSCRIPTION => [:premium, :unlimited] } ...
require 'term_extraction' require_dependency 'photo' class Status EXTRAS = %w[description url_m url_s url_sq url_t].join(',') attr_reader :id def initialize(options = {}) @record ||= options[:record] @user ||= options[:user] @id = @record ? @record.id : options[:id] raise ArgumentError("id not ...
class Admin::DisplayTaxonomyItemsController < Admin::BaseController permit "superuser" layout "admin/base" helper_method :all_items def all_items @items = DisplayTaxonomyItem.find_all_roots end # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html) verify :method => :...
require 'test_helper' class PostTest < ActionDispatch::IntegrationTest test 'creates appt' do post '/appointments', { appointment: { first_name: 'Jon', last_name: 'Rose', start_time: '0011-01-2017T11:00:00.000Z', end_time: '0011-01-2017T12:00:00.000Z' } }.to_json, { 'Accept' => Mime::JSON, 'C...
class AddTrashcanToNote < ActiveRecord::Migration def self.up add_column :notes, :trashcan, :boolean end def self.down remove_column :notes, :trashcan end end
require 'ssq_machines/transition' class SsqMachines::Frame < SsqMachines::Transition ############### # # # Constructor # # # ############### def initialize(*) super raise NoBehaviorError unless @behavior @state ||= behavior.initial_state end ##########...
require 'spec_helper' describe "static_contents/index" do before(:each) do assign(:static_contents, [ stub_model(StaticContent), stub_model(StaticContent) ]) end it "renders a list of static_contents" do render # Run the generator again with the --webrat flag if you want to use webra...
##= $:.unshift(File.expand_path(File.dirname(__FILE__))) ##= require 'app/lib/three_scale/api/sour' ##= ##= namespace 'CMS API' ##= resourcePath '/admin/api/cms/files' ##= swaggerVersion "1.1" ##= apiVersion "1.0" ##= ##= module Threescale::Api::Sour::Operation ##= def file_model_params ##= param 'path', 'URI o...
class MetaController < AdminController before_action :require_meta private def require_meta redirect_to root_path unless user_can_meta? end end
class Bag attr_reader :candies def initialize @candies = [] end def empty? @candies.empty? end def count @candies.count end def <<(candy) @candies << candy end def contains?(type) # check each candy see if it matches type candies.find do |candy| candy.type == type ...
class Invitation < ApplicationRecord has_many :guests validates :rsvp_code, :addressee, :address_line_1, :city, :zip, presence: true validates :rsvp_code, uniqueness: true validates :accepted_at, absence: true, if: -> { declined_at.present? } validates :declined_at, absence: true, if: -> { accepted_at.prese...
require 'helper' require 'media/filter/argument' module Media class Filter class TestArgument < MiniTest::Unit::TestCase def subject Argument end def test_option assert_equal 'foo=bar', subject.new(key: 'foo', value: 'bar').to_s end def test_true_flag ...
require File.dirname(__FILE__) + '/../test_helper' context "A user" do use_controller LoginController fixtures :users, :companies, :customers setup do use_controller LoginController @request.host = 'cit.local.host' end specify "is required to log in" do use_controller ActivitiesController...
# frozen_string_literal: true # stock_quotes.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that provides Yahoo! Finanance stock quotes for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT...
require 'json' require 'pry' module Society class Matrix attr_reader :nodes def initialize(nodes) @nodes = nodes end def to_hash { nodes: node_names.map{ |name| {name: name, group: 1} }, links: self.nodes.map do |node| node.edges.map do |edge| nex...
class Drop1ColsLnparams < ActiveRecord::Migration[5.0] def change remove_column :lnparams, :mark, :string end end
class AddFinalEvaluationTimeToResult < ActiveRecord::Migration[5.0] def change add_column :results, :final_evaluation_time, :datetime end end
class CreatePromotionCadres < ActiveRecord::Migration[5.2] def change create_table :promotion_cadres do |t| t.string :rank t.date :date t.integer :promotion_id t.timestamps end end end
namespace :movie_utils do desc "This rake file will print a list of all movies." task :movie_print => :environment do Movie.all.each do |movie| puts "#{movie.title} | #{movie.stock}" end end end
class CargoWagon < Wagon def wagon_type "Cargo" end end
#!/usr/bin/env ruby # Define a task library for performing code coverage analysis of unit tests # using rcov. require 'rake' require 'rake/tasklib' module RcovRails # A variant of Rcov::RcovTask # which lets me switch off descriptions on auto-generated tasks # # Example: # # require 'rcov_rails/rcovta...
# == Schema Information # # Table name: payrolls # # id :integer not null, primary key # user_id :integer # payroll_number :integer # start_date :datetime # end_date :datetime # draft :boolean default(TRUE) # total_...
class Auto def initialize(marca, modelo, año, placa) @marca = marca @modelo = modelo @año = año @placa = placa end def encender "El auto de marca: #{@marca} está encendiendo..." end def avanzar "Estoy avanzando..." end def parar "Voy a parar..." end end auto1 = Auto....
class Course < ApplicationRecord has_many :user_courses, dependent: :destroy has_many :users, through: :user_courses has_many :course_subjects, dependent: :destroy has_many :subjects, through: :course_subjects scope :latest, ->{order created_at: :desc} validates :title, presence: true, length: {maximu...
module MongoDoc module Associations class DocumentProxy include ProxyBase attr_reader :document delegate :to_bson, :id, :to => :document %w(_modifier_path _selector_path).each do |setter| class_eval(<<-RUBY, __FILE__, __LINE__) def #{setter}=(path) super ...
require 'hpricot' class ExplanatoryNotesFile < ActiveRecord::Base belongs_to :bill has_many :explanatory_notes, :dependent => :destroy validates_presence_of :name, :path, :bill_id validates_uniqueness_of :path before_validation_on_create :set_name, :set_bill after_create :load_notes class << self ...
class ChangeColumnsInConversations < ActiveRecord::Migration[6.0] def change add_column :conversations, :selected, :boolean, default: false, null: false add_reference :conversations, :request, foreign_key: { to_table: :requests}, null: false change_column_null :conversations, :title, false change_col...
class WordFrequencyValidator def self.from_request_params(params, cookies = nil) self.new(params['text'], params['exclude'], params['answer'], cookies) end def initialize(text, exclusion, freq, cookies = nil) # Clean out punctuation that shouldn't be counted @text = text @exclusion = exclusion ...
class User < ActiveRecord::Base enum status: { active: 0 } has_many :raw_images has_many :mockups has_many :invitations has_and_belongs_to_many :projects validates_presence_of :username, :pin validates_associated :raw_images, :mockups, :invitations, :projects validates :pin, numericality: true, lengt...
# 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 Location < ActiveRecord::Base # Relationships belongs_to :event has_many :assignments scope :for_event, ->(event_id) { joins(:event).where('event_id = ?', event_id) } end
class AddAccountIdKeysToCampaignsAndContent < ActiveRecord::Migration def self.up add_index :contents, :account_id end def self.down end end
require 'rails_helper' describe ContactsController do describe 'GET #new' do before { get :new } it 'renders the contact template' do expect(response).to render_template('new') end it 'responds successfully with an HTTP 200 status code' do expect_successfull_response end it 'loads...
class User < ApplicationRecord before_save :reset_due_time_seconds EMAIL_REGEX = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/.freeze enum send_due_date_reminder: {on_due_date: 0, one_day_before: 1} validates_format_of :email, with: EMAIL_REGEX private def reset_due_time_seconds self.due_date_reminder_time = ...
require 'rails_helper' RSpec.describe 'Potepan::Products', type: :system do let(:taxonomy) { create(:taxonomy) } let(:taxon) { create(:taxon, taxonomy: taxonomy) } let(:product) { create(:product, taxons: [taxon]) } let(:other_taxon) { create(:taxon, taxonomy: taxonomy) } let!(:related_product) { create(:prod...
# MessageProcessor handles an incoming responce and parses to the required responder object class NewsFeed < MessageProcessor def initialize(message, user) @message = message end def call prepare_response end private #this is messy, but I'm running low on time def prepare_response feed = g...
require "heroku_status/version" require "faraday" require "json" # https://devcenter.heroku.com/articles/heroku-status#heroku-status-api-v3 module HerokuStatus module_function # Retrieve the current issue status from Heroku # @return {hash} def current_status response = Faraday.get("https://status.heroku....
############################### # # contrib/inifile.rb # # These modules/classes are contributed by Yukimi_Sake-san. # Distributed at http://vruby.sourceforge.net/index.html # ############################### class Inifile < Hash =begin ===Inifile It makes inifile like Window's in working directory or abs...
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'version' Gem::Specification.new do |spec| spec.name = "tictactoe_core" spec.version = TicTacToe::VERSION spec.authors = ["Cedric Kisema"] spec.email = ["github@c_nak"] spe...
Rails.application.routes.draw do devise_for :user, controllers: { omniauth_callbacks: 'authentication' } devise_scope :user do delete '/logout', to: 'authentication#logout' end root 'home#index' end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :logged_in, except: [:denied] private def logged_in ''' Filter that denies users if they are not in the database. Redirects them to a 403 page if they are not logged in. ''' user = s...
class CreateAssets < ActiveRecord::Migration def self.up create_table :assets do |t| t.string :title, :type t.text :content end add_index :assets, [:title, :type], :unique => true end def self.down remove_index :assets, :column => [:title, :type] drop_table :assets end end
ScrabbleDojo::Application.routes.draw do root 'dojo#home' resources :sessions, only: [:new, :create, :destroy] get '/login' => 'sessions#new' delete '/logout' => 'sessions#destroy' resources :users get '/signup' => 'users#new' resources :word_entries, only: [:new, :create, :destroy, :index, :sh...
class Administrativo::PassagemServico < ApplicationRecord attr_accessor :user_saiu_senha, :user_entrou_senha # CONSTANTES LISTA_TIPO_DATA = [ { key: :created_at, label: 'Criado em', selected: "selected" }, { key: :updated_at, label: 'Passado em' } ] OBJ_DEFAULT = { q: "", data_inicio: Time.zon...
class AddCommentAndSupervisorHourToWorkhours < ActiveRecord::Migration def change add_column :workhours, :comment, :text add_column :workhours, :supervisor_hour, :integer end end
class User < ActiveRecord::Base has_secure_password has_many :orders has_many :meals, through: :orders validates :name, presence: true validates :password, length: { in:1...30 } def self.from_omniauth(auth) where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| user.provider = aut...
module Ristretta class Configuration attr_accessor :redis_client, :namespace, :subject_id_method, :version def initialize @version = "1" @namespace = "ristretta" @subject_id_method = :id end def client @client ||= redis_c...
class CreateDictionaries < ActiveRecord::Migration def change create_table :dictionaries do |t| t.string :title t.string :long_title t.string :URI t.string :current_editor t.string :contact t.string :organisation t.timestamps end end end
# frozen_string_literal: true require 'rib' module Rib; module LastValue extend Plugin Shell.use(self) attr_reader :last_value, :last_exception def print_result result return super if LastValue.disabled? @last_value = result super end def print_eval_error err return super if LastValue.d...
class Cli attr_reader :cli_interface, :list def initialize(list) @cli_interface = HighLine.new @list = list create_new_ask end #Asks user what kind of task they want #Throws InvalidItemType if type does not exist def create_new_ask types = ["todo","link","ev...
class CreateProductPhotos < ActiveRecord::Migration def change create_table :product_photos do |t| t.references :product, index: true t.string :src t.integer :position, index: true end add_foreign_key :product_photos, :products end end
require_relative "article" #Describes diving gear kit in the rental store. Extends Article. See article.rb for #further documentation. class DivingGear < Article def initialize(name, id) @rented = false @name = name @id = id end #Products whose string representation shouldn't be identical to the ...