text
stringlengths
10
2.61M
# frozen_string_literal: true describe Facts::Macosx::SystemProfiler::SerialNumber do describe '#call_the_resolver' do subject(:fact) { Facts::Macosx::SystemProfiler::SerialNumber.new } let(:value) { 'C02WW1LAG8WL' } let(:expected_resolved_fact) { double(Facter::ResolvedFact, name: 'system_profiler.seri...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? # def current_user # @current_user ||= Player.find_by(id: session[:player_id]) if session[:player_id] # end # helper_method :current_user de...
require "capybara" feature "Enter player names" do scenario "players fill out forms" do sign_in_and_play expect(page).to have_text("John vs Duncan") end end
class Office < ActiveRecord::Base has_and_belongs_to_many :addresses belongs_to :listing belongs_to :office def address self.addresses.first end end
class AddMentor < ActiveRecord::Migration def change add_column :users, :isMentor, :boolean, default: false end end
require 'rails_helper' RSpec.describe EmailProcessor, :type => :model do describe "parsing emails" do before do @test_params = { "stripped-text" => "no longer checking the authenticity token when receiving emails", "body-plain" => "no longer checking the authenticity token when receivin...
class CreateLogs < ActiveRecord::Migration[5.1] def change create_table :logs do |t| t.integer :round t.integer :day t.text :content t.integer :status, default: 0 t.integer :motivation, default: 5 t.timestamps end end end
class AccountTransaction < ApplicationRecord belongs_to :origin, class_name: "Account", foreign_key: "origin_account_id" belongs_to :recipient, class_name: "Account", foreign_key: "recipient_account_id", optional: true enum transaction_type: [:withdraw, :deposit, :transfer] validates :amount, presence...
class FootballPlayer < ActiveRecord::Base has_many :fantasy_team_players scope :random, -> { order('RANDOM()') } scope :goalkeepers, -> { where(position: "Goalkeeper") } scope :defenders, -> { where(position: "Defender") } scope :attackers, -> { where(position: "Attacker") } scope :not_in_league, -> (fanta...
class Catalogo < ActiveRecord::Base self.table_name = 'catalogos' self.primary_key = 'id' has_many :especies_catalogos, :class_name => 'EspecieCatalogo' #has_one :especie, :through => :especies_catalogos, :class_name => 'EspecieCatalogo', :foreign_key => 'catalogo_id' IUCN_QUITAR_EN_FICHA = []#['Riesgo baj...
module ApplicationHelper def flash_class(type) case type when "alert" "message--alert" when "notice" "message--success" else "message--warning" end end end # def active_navigation(path) # "navigation__item--active navigation__item__link--active" if params[:cont...
class DeleteRailwayStations < ActiveRecord::Migration[5.1] def change drop_table :railway_stations end end
# OpSpec is the specification of an Operation to be added to a Graph # (using Graph AddOperation). class Tensorflow::OpSpec attr_accessor :type, :name, :input, :attr, :inputlist # @!attribute type # Type of the operation (e.g., "Add", "MatMul"). # @!attribute name # Name by which the added operatio...
require_relative 'import_controller' require_relative 'client' module Budget module PcFinancial class ImportJob def initialize(client_number: nil, password: nil, controller: nil, logger: Budget::NullLogger) @controller = controller @controller ||= PcFinancial::ImportController.new( ...
# @param {String} moves # @return {Boolean} def judge_circle(moves) move_map = { "U" => [0, 1], "D" => [0, -1], "L" => [-1, 0], "R" => [1, 0] } origin = [0, 0] moves.each_char do |item| move_step = move_map[item] origin[0] += move_step[0] origin[1] += move_step[1] end ret...
require 'spec_helper' describe Survey do let(:survey) { build(:survey) } it "is valid" do survey.should be_valid end it {should accept_nested_attributes_for (:questions)} it {should have_many(:users).through(:completed_surveys)} end
class DailyDigestJob < ApplicationJob include Sidetiq::Schedulable queue_as :default recurrence { daily(1) } def perform User.find_each do |user| DailyMailer.digest(user).deliver_later end end end
class AttendancesController < ApplicationController # GET /attendances # GET /attendances.json def index @conference = Conference.find(params[:conference_id]) @attendees = @conference.attendances respond_to do |format| format.html # index.html.erb format.json { render json: @attendees } ...
class AddSaltToUsers < ActiveRecord::Migration[5.1] def up # def change # reversible do |dir| # dir.up add_column :users, :salt, :string rename_column :users, :password, :encrypted_password # end end def down remove_column :users, :salt rename_column :users, :encrypted_password,...
class Activity < ActiveRecord::Base belongs_to :answer validates :name, presence: true, uniqueness: true end
module Refinery module Accommodations class Accommodation < Refinery::Core::BaseModel self.table_name = 'refinery_accommodations' acts_as_indexed :fields => [:name, :rating, :description] after_save :remove_span extend FriendlyId friendly_id :name, :use => [:slugged] ...
Gem::Specification.new {|s| s.name = 'fuse' s.version = '0.0.1' s.author = 'meh.' s.email = 'meh@paranoici.org' s.homepage = 'http://github.com/meh/ruby-fuse' s.platform = Gem::Platform::RUBY s.summary = 'Bindings and wrapper for FUSE' s.files = `git ls-files`.spl...
class PracticeJob < Struct.new(:practice_id, :transition) #Include the faye sender module to send... include CustomFayeSender def perform practica = Practica.find(practice_id) if transition.eql? :open practica.dispositivos.each do |dispositivo| dispositivo.set_ready RemoteIRCGateway....
Rails.application.routes.draw do get 'home/index' root to: 'home#index' get '/tweets', to: 'twitter#tweets' get '/word-cloud', to: 'twitter#word_cloud' get '/sentiment', to: 'twitter#sentiment' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require "google/apis/gmail_v1" require "googleauth" require "json" require_relative "env_token_store" class GoogleMail OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze APPLICATION_NAME = "GovWifi Smoke Tests".freeze SCOPE = [ Google::Apis::GmailV1::AUTH_GMAIL_SEND, Google::Apis::GmailV1::AUTH_GMAIL_MODIFY, ...
class PagesController < ApplicationController def welcome @header= "WELCOME page @header" render :welcome end def about @header = "About page @header" end def contest @header = "Contest page @header" flash[:notice] = "Sorry, contest is finished!" redirect_to welcome_url end def...
class Poll < ApplicationRecord #----------- # Includes #----------- #----------- # Callbacks #----------- # Relationships #----------- has_many :poll_opinions, class_name: 'PollOpinion' has_many :poll_dates, class_name: 'PollDate' belongs_to :owner, class_name:...
class BarPolicy attr_reader :current_user, :bar def initialize(current_user, bar) @current_user = current_user @bar = bar end def destroy? return false if @current_user == @bar.user end end
class CreateTodoItems < ActiveRecord::Migration def self.up create_table :todo_items do |t| t.integer :todo_list_id t.integer :basecamp_id t.datetime :due_at t.string :content t.string :creator_name t.integer :responsible_party_id t.boolean :completed t.string :resp...
class Bowler < ActiveRecord::Base has_many :entries has_and_belongs_to_many :brackets validates :name, presence: true end
class AddSentToCompanies < ActiveRecord::Migration def change add_column :employees, :sent, :boolean, default: false end end
class DivesitesController < ApplicationController # GET /divesites # GET /divesites.xml def index @divesites = Divesite.order('area_id asc', 'pointname asc').paginate(:page => params[:page], :per_page => 20) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @div...
require "test_helper" class HomeControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers test "should get homepage when not signed in" do get :index assert_select "#home-sl1", true, "home should be rendered if not signed in" end test "should get dashboard when signed in" do...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :validatable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :o...
module Kuhsaft module Api class PagesController < ActionController::Base layout :false respond_to :json def index I18n.locale = params[:locale] @pages = Kuhsaft::Page.unscoped.published.content_page.translated.order(position: :asc) render json: @pages.as_json end ...
require 'factories/profiles.rb' describe CreditCardFormatValidator do let(:subject) { CreditCardFormatValidator } let( :attribute ) { :credit_card } let (:object) { Profile.new } invalid_credit_card_numbers = %w[9556494038121161 41128109359983 n396092084242542 535299462783972 1396092084242542] valid_credi...
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Server do fails_on_jruby declare_topology_double let(:cluster) do double('cluster').tap do |cl| allow(cl).to receive(:topology).and_return(topology) allow(cl).to receive(:app_metadata).and_return(app_metadat...
json.array!(@enroll_statuses) do |enroll_status| json.extract! enroll_status, :id, :es_sDescription json.url enroll_status_url(enroll_status, format: :json) end
require_relative '../spec/spec_helper' require_relative '../lib/recommendations' require 'date' require 'benchmark' include Benchmark describe "Recommendations with mongo datamodel" do before(:each) do @db = Mongo::Connection.new.db("recommender") #@preference_collection = @db['items'] #@preference_coll...
# -*- encoding: utf-8 -*- # # Author:: Edmund Haselwanter (<office@iteh.at>) # Copyright:: Copyright (c) 2011 Edmund Haselwanter # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtai...
# frozen_string_literal: true module Queries class AllActionsQuery < ::Queries::BaseQuery description 'アクション一覧取得' type [::Types::Enums::ActionEnum], null: false def query = ::AllowedAction.all_actions end end
module Api module V1 class CheckNonDeliveredController < ApplicationController before_action :restrict_access def index EntriesCheck.deliver_entries() render json: {message: "undelivered entries processed"}, status: :ok end private def restrict_access header...
class AddLocationIdToRefineryAccommodations < ActiveRecord::Migration def change add_column :refinery_accommodations, :location_id, :integer end end
Rails.application.routes.draw do use_doorkeeper namespace :api do namespace :v1 do resources :posts, only: %i(index create show update destroy) end end devise_for :users root to: 'home#index' resources :posts end
class AddSitesToProperties < ActiveRecord::Migration[6.1] def change add_column :properties, :sites, :string end end
class CreateMarketSuppliers < ActiveRecord::Migration[5.0] def change create_table :market_suppliers do |t| t.references :market, foreign_key: true, index: true, null: false t.references :user, foreign_key: true, index: true, null: false t.integer :role t.timestamps end end end
# Instead of using spec_helper, I'm using the twice as fast custom helper # for active record objects. require 'spec_active_record_helper' require 'hydramata/works/predicate_presentation_sequences/storage' module Hydramata module Works module PredicatePresentationSequences describe Storage do subj...
class Group < ActiveRecord::Base has_and_belongs_to_many :users has_many :group_privileges, :dependent => :destroy validates :name, :presence => true def has_privilege?(privilege) !privileges.index(privilege).nil? end def all_users User.find_by_sql <<-SQL select users.* from users, groups_us...
# frozen_string_literal: true # == Schema Information # # Table name: user_achievements # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # achievement_id :bigint not null # photopost_id :integer # user_i...
class SearchForm < ApplicationRecord attribute :posted_at_from, :datetime attribute :posted_at_to, :datetime end
class AddDescriptionFieldToProcedures < ActiveRecord::Migration def up add_column :procedures, :description, :text, default: "" end def down remove_column :procedures, :description end end
module Hydramata module Works module ValueParser module_function def call(options = {}, &block) value = options.fetch(:value) if value.respond_to?(:raw_object) block.call(value: value, raw_object: value.raw_object) else parser = parser_for(options) ...
class AddTotalStatsFlag < ActiveRecord::Migration[5.2] def up add_column(:batting_stats, :eligible_games, :integer, default: 0, null: false) add_column(:batting_stats, :is_total, :boolean, default: true, null: false) BattingStat.reset_column_information BattingStat.fix_total_flags execute "UPDATE ...
Rails.application.routes.draw do resources :projects, only: [:show, :index] resources :posts, only: [:index] mount RailsAdmin::Engine => '/admin', as: 'rails_admin' devise_for :users, :skip => [:registrations] get 'welcome/index' root 'welcome#index' end
require "dotman/messages" module Dotman module Init def show_init_message puts Dotman::Messages::MSG_FIRST_RUN end end end
require File.expand_path(File.dirname(__FILE__) + "/../test_helper") class MessageTest < ActiveSupport::TestCase should "test all_of_hostgroup" should "test count_of_hostgroup" do Host.make(:host => "somehost").save Message.make(:host => "foobar", :message => "bla").save Message.make(:host => "foobar...
class RemoveLocationFromPost < ActiveRecord::Migration[5.0] def change remove_column :posts, :address remove_column :posts, :city remove_column :posts, :state remove_column :posts, :country remove_column :posts, :longitude remove_column :posts, :latitude end end
# frozen_string_literal: true module MachineLearningWorkbench::NeuralNetwork # Feed Forward Neural Network class FeedForward < Base # Calculate the size of each row in a layer's weight matrix. # Includes inputs (or previous-layer activations) and bias. # @return [Array<Integer>] per-layer row sizes ...
module Types class ProjectAttributes < Types::BaseInputObject description 'Attributes for creating or updating projects' argument :title, String, required: true argument :description, String, required: false argument :is_completed, Boolean, required: false end end
class ChangeDatatypeAffiliateAmazonLinkOfMaikingTools < ActiveRecord::Migration[5.2] def change change_column :making_tools, :affiliate_amazon_link, :text end end
# encoding: utf-8 class Topic < ActiveRecord::Base attr_reader :type ## # Relationships belongs_to :user belongs_to :speaker, class_name: 'User' belongs_to :event has_many :comments, as: :commentable, dependent: :destroy, inverse_of: :commentable ## # Validations validates :content, presence: tr...
class Beer < ActiveRecord::Base include AverageRating extend TopRated attr_accessible :brewery_id, :name, :style_id validates_length_of :name, minimum: 1 validates_presence_of :style belongs_to :brewery belongs_to :style has_many :ratings, :dependent => :destroy has_many :raters, through: :ratings,...
json.array!(@transactions) do |transaction| json.extract! transaction, :id, :customer_id, :payment_mode, :actual_total_price, :tax, :vat, :date json.url transaction_url(transaction, format: :json) end
module MeRedis # todo warn in development when gzipped size iz bigger than strict # use prepend for classes module ZipValues module FutureUnzip def set_transformation(&block) return if @transformation_set @transformation_set = true @old_transformation = @transformation @...
require 'factory_girl_rails' FactoryGirl.define do factory :user do sequence(:email) { |n| "user-#{n}@example.com" } password 'testtest' password_confirmation 'testtest' admin true end end
class OmniauthController < ApplicationController skip_before_action :authenticate_user! def callback user = User.from_omniauth(oauth_hash) .assign_credentials(oauth_hash('credentials')) sign_in(user, scope: :users) uri_query = '?success=true' # we'll ask user to complete fields th...
# Displays 3x3 board def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end # Converts user input 1-9 to index 0-8 def input_to_index(user_input) in...
# #1 class Matrix attr_reader :rows, :columns def initialize(matrix) @rows = matrix.each_line.map { |row| row.split.map(&:to_i) } @columns = rows.transpose end end # #2 # class Matrix # def initialize(matrix) # @matrix = matrix # end # def rows # @rows ||= @matrix.each_line.map { |row| ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook] va...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class GemeinschaftSetupsController < ApplicationController # We use the heater rake task to generate this file. # So it loads super fast even on slow machines. # caches_page :new, :gzip => :best_compression skip_before_filter :start_setup_if_new_installation load_and_authorize_resource :gemeinschaft_setup...
class Actor attr_reader :name @@all = [] ###### Instance methods ###### def initialize(name) @name = name @@all << self end #Return the characters the actor has played def characters() Character.all().select() { | char | char.actor == self } end #Assign a...
require_relative 'synchronized_mapper_wrapper' class SynchronizedExpandingMapperWrapper < SynchronizedMapperWrapper def push_value(value) if value.respond_to?(:each) value.each do |item| producing_queue << item end else super end end end
#============================================================================== # ** Game_Battler #------------------------------------------------------------------------------ # A battler class with methods for sprites and actions added. This class # is used as a super class of the Game_Actor class and Game...
class Chat < ActiveRecord::Base has_many :messages, dependent: :destroy has_many :chat_users, dependent: :destroy has_many :users, through: :chat_users validates :name, presence: true, length: { maximum: 50 } end
class Discount attr_reader :code attr_reader :product def initialize(code, product, min_quantity) @code = code @product = product @min_quantity = min_quantity end def valid_discount(quantity) if quantity >= @min_quantity return true end return false end end class TwoForOne <...
require 'rails_helper' RSpec.describe GroupsController, type: :controller do let!(:group){ create(:group) } let!(:user) { create(:user) } let!(:admin) { create(:admin) } context 'when not logged in user' do context 'get show group' do before{ get :show, params: { id: group.id } } it 'redire...
# frozen_string_literal: true require 'json' RSpec.describe 'ReekEnsurance' do it 'does not have reek warnings' do command = 'bin/reek app/* lib/* --config ./.quality/.reek' result = `#{command} --format json` warnings = JSON.parse(result).size message = "Reek #{warnings} warnings, run '#{command}' ...
module Alchemy # Returns alchemys mount point in current rails app. # Pass false to not return a leading slash on empty mount point. def self.mount_point(remove_leading_slash_if_blank = true) alchemy_routes = Rails.application.routes.named_routes[:alchemy] raise "Alchemy not mounted! Please mount Alchemy...
class Product < ApplicationRecord belongs_to :list, primary_key: 'product_id', foreign_key: 'product_id', optional: true require 'open-uri' require 'rakuten_web_service' def self.rakuten_search(user, condition) account = Account.find_by(user: user) search_id = condition[:search_id] if account != n...
module Humidifier # Dumps an object to CFN syntax module Utils # a frozen hash of the given names mapped to their underscored version def self.underscored(names) names.map { |name| [name, underscore(name).to_sym] }.to_h.freeze end end end
module Router class OSMAdapter def initialize(endpoint = 'http://127.0.0.1:5000/route/v1/driving/') @connection = Faraday.new(url: endpoint) end def call(origin, destination) response = @connection.get("#{to_param(origin)};#{to_param(destination)}") JSON.parse(response.body)['routes'].m...
# frozen_string_literal: true RSpec.describe Dry::Types::PrimitiveInferrer, "#[]" do subject(:inferrer) do Dry::Types::PrimitiveInferrer.new end before { stub_const("Types", Dry.Types()) } def type(*args) args.map { |name| Dry::Types[name.to_s] }.reduce(:|) end it "caches results" do expect(...
class Comment < ApplicationRecord belongs_to :user belongs_to :event has_many :reports include Filterable validates :text, presence: true validates :user_id, presence: true validates :event_id, presence: true scope :filter_by_user_id, -> (user_id) { where user_id: user_id } scope :filter_by_event_i...
require 'test_helper' class FotoLojasControllerTest < ActionController::TestCase setup do @foto_loja = foto_lojas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:foto_lojas) end test "should get new" do get :new assert_response :succe...
require 'logger' require 'spec_helper' require 'sneakers' describe Sneakers::Runner do let(:logger) { Logger.new('logtest.log') } describe "with configuration that specifies a logger object" do before do Sneakers.configure(log: logger) @runner = Sneakers::Runner.new([]) end it 'passes the...
module Admin class CategoryAnswersController < ApplicationController before_action :set_category_replay, only: [:show, :edit, :update, :destroy] # GET /category_answers # GET /category_answers.json def index @category_answers = CategoryReplay.all end # GET /category_answers/1 # GET...
require "spec_helper" feature "deleting venues" do let!(:user) { Factory(:confirmed_user, role: 'admin') } let!(:venue) { Factory(:venue) } scenario "deleting a venue as admin" do sign_in_as!(user) visit "/venues" click_link "Wally's" click_button "delete venue information" page.should ha...
class FinderTopicService def self.count criteria.where(topic: nil).count end def self.all criteria.all end def self.find(topic_id) criteria.find(topic_id) end def self.find_by_topic(topic, limit=nil, page=nil) finder = criteria.where(topic: topic) finder = finder.limit(limit) unless...
class CreateQuestions < ActiveRecord::Migration def change create_table :questions do |t| t.string :qtag t.string :qtype t.string :qclass t.timestamps end end end
require 'test/unit' require 'yaml' class Load_tests < Test::Unit::TestCase # def setup # end # def teardown # end def test_dump_string_to_string s = YAML.dump('one') assert(s == "--- one\n") end def test_dump_array s = YAML.dump( ['badger', 'elephant', 'tiger']) expected = "-...
require File.dirname(__FILE__) + '/../../spec_helper' describe Mysears::ProductFactory do BRAND_NAME = "Brand Name" PRODUCT_NAME = "Product Name" describe "product title" do it "should be 'brand_name product_name' when both non-blank" do @product_factory = create_product_factory() @prod...
class Admin::AdminsController < ApplicationController before_filter :authorize def show @admin = Admin.first end def new @admin = Admin.new end def create @admin = Admin.new(admin_params) if @admin.save redirect_to admin_path else render 'new' end end private ...
class EasyAttendance < ActiveRecord::Base include Redmine::SafeAttributes RANGE_FORENOON = 1 RANGE_AFTERNOON = 2 RANGE_FULL_DAY = 3 belongs_to :easy_attendance_activity belongs_to :user belongs_to :edited_by, :class_name => 'User', :foreign_key => 'edited_by_id' belongs_to :time_entry, :class_...
class BookmarkletController < ApplicationController before_filter :find_or_create_link, :only => [ :start, :add ] def index head :ok end def start head :ok end def add head :ok end private def find_or_create_link @link = Link.find_or_create_by_href(params[:url]) end end
require_relative 'wordchain' module Formulator def Formulator.create_sentence(length, subject) iterator = 0 result = [] result << subject.chomp previous_token = subject token = WordChain.bigram_word(previous_token) for _ in 0..length*5 break if token.blank? result << token.chomp ...
require_relative 'mandelbrot' require_relative 'mandelbrot_map' require 'bigdecimal' require 'colorize' class Grid attr_accessor :center_x, :center_y, :precision_index, :precision, :step, :width, :height, :map, :mapfile DEFAULT_MAPFILE = 'mapfile' def initialize(x = 0, y = 0, precision_index = 2, width = 16, ...
class Departments::EmployeesController < ApplicationController # Developer: Marco & Marius # === Callbacks === before_action :set_department, only: [:index, :cut] def index @employees = Employee.where(department_id: @department.id) end def cut set_employees employees_id_array = params[:format...
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.integer :price t.text :body t.string :alias, :unique => true t.belongs_to :subcategory t.timestamps end end end
require 'yaml' MESSAGES = YAML.load_file('loan_calculator_messages.yml') def prompt(message) puts ">> #{message}" end def retrieve_input(input_type, valid_input) input = nil loop do prompt(MESSAGES[input_type]) input = gets.chomp break if valid_input?(input) prompt(MESSAGES["#{input_type}_invali...