text
stringlengths
10
2.61M
class Cocktail attr_accessor :name, :recipe, :category def initialize(name, recipe, category) @name = name @recipe = recipe.split @category = category end end
RSpec.describe Crawler::Db::UrlBuffer, type: :use_db do describe '.fetch_for' do let(:host) { 'rspec.test' } let(:url) { "http://#{host}/path" } subject { described_class.fetch_for(host) } before { described_class.insert(hostname: host, url: url) if url } it 'returns record and removes it from ...
module ESP32 module GPIO include Constants class << self alias :digital_write :digitalWrite alias :digital_read :digitalRead alias :analog_write :analogWrite alias :analog_read :analogRead alias :pin_mode :pinMode alias :hall_read :hallRead ...
module Api class IssuesController < ApiController before_action :authenticate_resource def create issue = Issue.create_by_manual(params, @current_resource) if issue.save render json: issue else status_code = 422 serialize_data = build_serialize_data( Appli...
class Timecard < ActiveRecord::Base belongs_to :location, inverse_of: :timecards belongs_to :user, inverse_of: :timecards belongs_to :activity, inverse_of: :timecard validates :location, presence: true validates :user, presence: true validates :start_time, presence: true validates :stop_time, presence: tr...
class AddBodyToDocumentTemplates < ActiveRecord::Migration[5.0] def change add_column :document_templates, :body, :text, null: false, default: '' change_column_default :document_templates, :body, nil end end
namespace :generators do desc "Generate random questions and answers associated with them" task :question_and_answers => :environment do number_of_questions = ENV['number_of_questions'] ? ENV['number_of_questions'].to_i : 50 number_of_answers = ENV['number_of_answers'] ? ENV['number_of_answers'].to_i ...
require 'rails_helper' RSpec.describe 'As a logged in user' do before(:each) do user_logs_in end context 'when I visit /companies' do VCR.use_cassette('companies_filtering_zip') do xscenario 'I can input a zip and only the companies within distance are shown', :js => true do denver_co = ...
module Poe class KeyboardHandler def self.output(&block) loop do key = Curses.getch unless key.nil? case key when Curses::Key::UP then yield :key_up when Curses::Key::DOWN then yield :key_down when Curses::Key::LEFT then yield :key_left when Curses::Key::RIGHT then yield :key_r...
# == Schema Information # # Table name: schools # # id :integer not null, primary key # name :string(255) # code :string(255) # created_at :datetime # updated_at :datetime # free_trial :boolean default(TRUE) # class School < ActiveRecord::Base has_many :users has_many :cla...
# frozen_string_literal: true module Decidim module Opinions module Metrics class VotesMetricManage < Decidim::MetricManage def metric_name "votes" end def save cumulative.each do |key, cumulative_value| next if cumulative_value.zero? qu...
class GoalSet < ActiveRecord::Base has_many :goals,:dependent => :delete_all attr_accessible :start_time, :daily, :goals_attributes accepts_nested_attributes_for :goals, :allow_destroy => true, :reject_if => :all_blank validates :start_time, :uniqueness=>true def completed_goals goals.complete.count ...
class TweetsController < ApplicationController before_action :authenticate_user! before_action :set_tweet, only: [:show, :edit, :update, :destroy] def index @all_tweets = current_user.tweets @all_users = User.where.not(id: current_user.id) end def show end def edit end def create @twee...
# Evaluate the best possible coordinate for of the next bomb. This is # done via by positioning all remaining enemy ships in all possible # ways over the board. Then the probability of a hit is computed by # counting how many times a particular bomb had hit a possible ship # placement. # # If there are hits on the boar...
require 'machinist/active_record' Road.blueprint(:road1) do user_id { rand(1..1000) } name { Faker::Lorem.sentence(word_count = 4) } description { Faker::Lorem.paragraph(sentence_count = 6) } start_point { "POINT(#{-74.095771} #{41.236122})" } end_point { "POINT(#{-74.065559} #{41.230571})" } g_map_line {...
describe CorrelationChecker do subject { described_class.new(first_dataset: first_dataset, second_dataset: second_dataset) } context 'with invalid params' do context 'with empty datasets' do let(:first_dataset) { [] } let(:second_dataset) { [] } it 'does not generate result' do expec...
class Api::TasksController < Api::ApplicationController before_action :set_task, only: %i[show edit update] def index @tasks = Task.incomplete.where(user_id: current_user.id) end def show end def create tag = Tag.find_or_create_by(name: params[:tags_attributes][:name]) task = Task.new(task_pa...
# write a method that takes a string of digits # and returns the appropiate number as an integer # you may not use String#to_i or Integer() # assume all characters will be numeric # Examples: # # string_to_integer('4321') == 4321 # string_to_integer('570') == 570 # def string_to_integer(string) # string.split("...
require 'rails_helper' describe "the add product process" do it "adds a new product" do visit root_path click_link 'New Product' fill_in 'Name', :with => 'Thingy' fill_in 'Cost', :with => '33.33' fill_in 'Country of origin', :with => 'USA' click_on 'Create Product' expect(page).to have_...
# Use the modulo operator, division, or a combination of both to take a 4 digit number and find the digit in the: # 1) thousands place # 2) hundreds place # 3) tens place # 4) ones place puts 4893 / 1000 puts 4893 % 1000 / 100 puts 4893 % 1000 % 100 / 10 puts 4893 % 1000 % 100 % 10
require_relative '../exceptions.rb' require_relative '../release.rb' require_relative '../formulary.rb' require_relative '../platform.rb' require_relative 'shasum_options.rb' module Crew def self.shasum(args) options, args = ShasumOptions.parse_args(args) Formulary.new.select(args).each do |formula| ...
class AddStartDateToLiability < ActiveRecord::Migration def change add_column :liabilities, :start_date, :date end end
class Tweet < ApplicationRecord validates :message, length:{maximum: 14}, presence: true end
require 'net/http' # I know this is terrible, but it avoids additional dependencies module SimpleCov module Formatter class ShieldFormatter module Generators # TODO: Make configurable class ShieldsIO HOST = 'img.shields.io'.freeze PATH = 'badge'.freeze EXTENSIO...
class Sort attr_accessor :array, :sortarray def initialize(array) @array = array @sortarray = [] end def insert_sort(array) target = [] << array.shift while array.length > 0 do item = array.shift insert(item, target) end return target ...
class CreateSteps < ActiveRecord::Migration def change create_table :steps do |t| t.integer :step_number t.integer :kind t.string :selector t.text :script_code t.text :response t.boolean :store_datalayer t.text :datalayer t.references :case_test, index: true ...
class Obp < ActiveRecord::Base self.table_name = "obp" self.primary_key = "obpid" has_many :sys end
# Preview all emails at http://localhost:3000/rails/mailers/admin_notifier class AdminNotifierPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/admin_notifier/contact_form def contact_form AdminNotifierMailer.contact_form end end
class Backend::AccountController < ApplicationController before_action do if current_admin != nil authenticate_admin! else authenticate_reseller! end end def index @list = Account.order(:created_at) if reseller_signed_in? @list = @list.for_reseller(current_reseller.id) ...
# Given a nonnegative integer, return a hash whose keys are all the odd nonnegative integers up to it # and each key's value is an array containing all the even non negative integers up to it. # # Examples: # staircase 1 # => {1 => []} # staircase 2 # => {1 => []} # staircase 3 # => {1 => [], 3 => [2]} # staircase 4...
class Contestant < ActiveRecord::Base has_many :votes, dependent: :destroy mount_uploader :avatar, AvatarUploader def self.avatar_path(id) "/uploads/#{id}/avatar.png" end def avatar_path self.class.avatar_path id end end
FactoryBot.define do factory :doctor do name { Faker::OnePiece.character } email { "#{Faker::Name.first_name}@hospital.com" } password { 'password' } trait :admin do admin { true } end factory :doctor_with_specialization do before(:create) do |doctor| doctor.specializatio...
class CreateAirportTripPlanePilot < ActiveRecord::Migration[5.2] def change create_table :airports do |t| t.string :name t.float :longitude t.float :latitude end create_table :trips do |t| t.integer :origin_airport_id t.integer :destination_airport_id t.integer :plane_id ...
require_relative "lib/db/postgres/version" Gem::Specification.new do |spec| spec.name = "db-postgres" spec.version = DB::Postgres::VERSION spec.summary = "Ruby FFI bindings for libpq C interface." spec.authors = ["Samuel Williams"] spec.license = "MIT" spec.files = Dir.glob('{lib}/**/*', File::FNM_DOTMATCH,...
class ServiceImporterJob < ImporterJob def perform super { case action when 'create' #create when 'update' update_components(callback_url) when 'destroy' #destroy end } end private def update_components(callback_url) service = RemoteObjectFetc...
# frozen_string_literal: true class RosterController < ApplicationController secure!(:users, :roster) title!('Roster Information') before_action :users, only: %i[new create edit update] before_action :record, only: %i[edit update destroy] def show @collection = model.all end def new @record =...
require('minitest/autorun') require('minitest/rg') require_relative('../guest') require_relative('../room') require_relative('../song') class TestGuest < MiniTest::Test def setup @guest = Guest.new('Ian') @unity = Song.new('Unity','Rick James') end def test_guest_name assert_equal('Ian', @guest.na...
require File.expand_path(File.join(File.dirname(__FILE__), %w[spec_helper])) describe Rhouse::Models::Device do before( :all ) do @lamp = Rhouse::Models::Device.find( 42 ) @lamp.should_not be_nil end it "should have the right template" do @lamp.template.should_not be_nil @lamp.templat...
class AddCoverToGoods < ActiveRecord::Migration[6.0] def change add_column :goods, :cover, :string end end
class AddDateToAcceptedNotification < ActiveRecord::Migration def change add_column :accepted_notifications, :date, :datetime end end
module Eel module CoreExt module SymbolExtensions def attr Arel::Attributes::Attribute.new(nil, self) end def of val relation = case val when Class val.arel_table when Symbol val ...
Rails.application.routes.draw do scope "(:locale)", locale: /en|it/ do resources :active_families, only: [:index] resources :all_families, only: [:index] resources :families resources :inactive_families, only: [:index] resources :schools, only: [:index, :new, :create, :edit, :update, :destroy] ...
class RemoveDaysLeftFromUsers < ActiveRecord::Migration def change remove_column :users, :days_left end end
module Authlogic # This allows you to scope your authentication. For example, let's say all users belong # to an account, you want to make sure only users that belong to that account can # actually login into that account. Simple, just do: # # class Account < ActiveRecord::Base # authenticates_many :u...
# == Schema Information # # Table name: animal_associations # # id :integer not null, primary key # animal_id :integer # service_provider_id :integer # created_at :datetime # updated_at :datetime # checked_in :boolean # class AnimalAssociation < Acti...
class Task attr_reader :date, :group, :description, :state BLANK_SPACE_DATE=" " def initialize(description=nil,date=nil,group=nil) return nil if description.nil? @description=description @date=date @group=group @state=0 #Estado 0 indica pendiente y 1 indica completado...
class AnswersController < ApplicationController def index @questions = Question.order("created_at DESC") @answers = Answer.order("created_at DESC") end def new @question = Question.find(params[:question_id]) @answer = Answer.new @answer.question_id = @question.id @answer.user_id = @qu...
# Third-party dependencies. require 'bindata' module Evtx # The file header provides some basic information about an event log file: # # - the number of chunks # - the chunk current in use # - etc. # # While the header consists of 4096 bytes (1 page), only 128 bytes are # in use. Additionally, th...
class Support::ResponsibleBodiesController < Support::BaseController before_action { authorize ResponsibleBody } def index @responsible_bodies = policy_scope(ResponsibleBody) .select('responsible_bodies.*') .excluding_department_for_education .with_users_who_have_signed_in_at_least_once(priva...
#encoding: UTF-8 class Boleto < ActiveRecord::Base belongs_to :aluno belongs_to :empresa def data_vencimento vencimento = self.data_documento.to_date return nil unless vencimento.kind_of?(Date) && self.dias_vencimento.kind_of?(Numeric) (vencimento + self.dias_vencimento.to_i) end def self.inde...
module Enumerable def my_each self.length.times do |i| yield(self[i]) end end def my_each_with_index i = 0 while i < self.length yield(self[i], i) i += 1 end end def my_select new_array = [] self.my_each do |element| new_array << elemen...
Rails.application.routes.draw do get 'welcome/index' #resource method which is used to declare a REST resource resources :articles #tells the browser where to map the root of project root 'welcome#index' end
# spec/requests/api/v1/cards_spec.rb require 'rails_helper' require 'support/auth_helper' include AuthHelper describe "Cards API" do before(:each) do @user = create(:user) @card = create(:card, user: @user) end it 'provides card data by id' do get "/api/v1/cards/#{@card.id}?#{user_credentials(@use...
module Swow class Client REALM_STATUS_REQUEST = "/wow/realm/status".freeze module Realm def realm_status(locale: @locale) get REALM_STATUS_REQUEST, locale: locale end end end end
require 'rails_helper' RSpec.feature 'Deleting H.R' do before do @admin = create(:admin) login_as(@admin, scope: :admin) @hr = create(:hr) visit admin_hrs_path end scenario 'should has list of H.Rs' do expect(page).to have_content(@hr.full_name) find('.delete-link').click expect(pag...
class OnlineExamOption < ActiveRecord::Base belongs_to :online_exam_question has_many :online_exam_score_details validates_presence_of :option attr_accessor :redactor_to_update, :redactor_to_delete xss_terminate :except => [ :option ] before_update :atleast_one_answer before_update :all_diff_answers...
class Project < ActiveRecord::Base attr_accessible :city, :client_name, :completion_date, :country, :description, :project_name, :project_status, :project_value, :start_date, :state, :client_id, :images_attributes, :address1, :address2, :latitude, :longitude has_many :images, :as => :imageable, :dependent => :de...
module MagicField class ManaButton attr_accessor :button def initialize(color) @value = 'off' @color = color @button = UIView.alloc.initWithFrame [[0, 0], [44, 45]] @bgEmpty = UIImage.imageNamed("#{@color.downcase}-mana-empty.png") @bgFull = UIImage.imageNamed("#{@color.downcas...
class MembersController < ApplicationController def show_detail_members @info = Information.find(params[:information_id]) @member = Member.find_by_information_id(params[:information_id]) end def create member = Member.find_by_information_id(params[:information_id]) if member.nil? new_member ...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::BaseEdge do module NonNullableDummy class NonNullableNode < GraphQL::Schema::Object field :some_field, String end class NonNullableNodeEdgeType < GraphQL::Types::Relay::BaseEdge node_type(NonNullableNode, nul...
require 'bundler/setup' require 'sinatra' require 'roo' #require 'msgpack' #require 'oj' require 'mongoid' require 'mongoid_search' require 'yajl/json_gem' #require 'iconv' require 'open-uri' require "sinatra/reloader" if development? require 'matrix' Mongoid.load!("./mongoid.yml", :development) # class Downloaded_it...
class Post < ActiveRecord::Base acts_as_mappable :default_units => :miles, :default_formula => :sphere, :distance_field_name => :distance, :lat_column_name => :latitude, :lng_column_name => :longitude attr_accessor :current_user_vote, :curr...
class ContactMailer < ActionMailer::Base #layout 'contact' #default from: "from@example.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.contact_mailer.confirmation.subject # def confirmation(email) attachments['rails.png'] = File.read("#{Ra...
require "test_helper" class LessonTest < Test::Unit::TestCase # Replace this with your real tests. context "assignments" do setup do @organization = Factory.create(:organization) @lesson = Factory.create(:lesson) @unassigned_user = Factory.create(:user) @assigned_user = Factory.create(:...
ActiveAdmin.register User do index do column :name column :surname column :email column :created_at actions end form do |f| f.inputs 'User data' do f.input :name f.input :surname f.input :email end f.inputs 'Choose your password' do f.input :password ...
require 'pry' class Startup attr_accessor :domain, :name attr_reader :founder, :funding_rounds @@all = [] def initialize(name,founder, domain) @name = name @founder = founder @domain = domain @funding_rounds = [] @@all << self end def pivot (domai...
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'spec_helper' describe Walrat::ProcParslet do before do @parslet = lambda do |string, options| if string == 'foobar' string else raise Walrat::ParseError.new("expe...
require "spec_helper" RSpec.describe Stringer do it "concatenates undefined number of strings with a space" do expect(Stringer.spacify "Oscar", "Vazquez", "Zweig", "Olasaba", "Hernandez", "Ricardo", "Mendoza").to eq("Oscar Vazquez Zweig Olasaba Hernandez Ricardo Mendoza") end it "shortens the string based o...
require "fog/core/collection" require "fog/brkt/models/compute/workload" module Fog module Compute class Brkt class WorkloadTemplates < Fog::Collection model Fog::Compute::Brkt::WorkloadTemplate # Get workload templates # # @return [Array<WorkloadTemple>] workload templates...
class UsersController < ApplicationController skip_before_action :authorize, only: :create def create @new_user = User.create!(user_params) session[:user_id] = @new_user.id render json: @new_user, status: :created end def show render json: @current_user ...
Rails.application.routes.draw do root to:'iteration_reviews#index' mount Rules::Engine, at: "rules" mount JsModel::Engine, at: 'models' mount ApiDoc::Engine, at:'doc' scope :session do get '/signup' => 'session#signup_page' get '/signout' => 'session#sign_out' post '/signup' => 'session#signu...
class Api::CollegesController < ApplicationController before_action :set_college, only: [:show, :update, :destroy] def index colleges = College.all render json: colleges end def show render json: {college: @college, frats: @college.get_frats_with_event_info, events: @college.events, unassociated_f...
shared_examples 'a commentable' do let!(:user) { create(:user, :paul) } let!(:commentor) { create(:user, :billy) } before do login_as(commentor) visit commentable_path end context 'with valid comment' do it 'on a commentable' do within('.new_comment_form') do fill_in 'comment_body'...
class CommentsController < ApplicationController http_basic_authenticate_with name:"sam", password:"secret", only: :destroy def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_parameters) redirect_to article_path(@article) end def destroy @article = Article...
class AddOptionalContent56ToPosts < ActiveRecord::Migration[6.0] def change add_column :posts, :optional_content_5, :text add_column :posts, :optional_content_6, :text end end
# frozen_string_literal: true module Kafka module Protocol class DeleteTopicsRequest def initialize(topics:, timeout:) @topics, @timeout = topics, timeout end def api_key DELETE_TOPICS_API end def api_version 0 end def response_class P...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive do class MultiWord < GraphQL::Schema::Directive end it "uses a downcased class name" do assert_equal "multiWord", MultiWord.graphql_name end module DirectiveTest class Secret < GraphQL::Schema::Directive a...
class AddExtensionToClassRegistrations < ActiveRecord::Migration def change add_column :class_registrations, :add_extension, :boolean, :default => false end end
class Api::V1::ProjectTaskMappingsController < ApplicationController before_action :authenticate_user! before_action :set_task_mapping, only: [:show, :edit, :update] def index @project_task_mappings = ProjectTaskMapping.page(params[:page]) resp=[] @project_task_mappings.each do |p| if p.activ...
class ExpressionsController < ApplicationController def new @mfe = MonFrenchExpresso.find(params[:mon_french_expresso_id]) @expression = Expression.new end def create @expression = Expression.new(expression_params) @expression.mon_french_expresso = MonFrenchExpresso.find(params[:mon_french_expre...
class SessionsController < ApplicationController skip_before_filter :require_current_user def new end def create email = user = User.find_by_email(params[:email]) if user flash[:notice] = "Logged In!" set_current_user(user.id) redirect_to root_path else flash[:no...
module Pushr module Daemon module ApnsSupport class FeedbackReceiver FEEDBACK_TUPLE_BYTES = 38 def initialize(configuration, _) @configuration = configuration @interruptible_sleep = InterruptibleSleep.new end def start @thread = Thread.new do ...
Given(/^I am on the google site/) do visit 'http://www.google.com' end When(/^I enter "(.*?)" in the search input field$/) do |searchv1| fill_in('gbqfq', :with => 'hello') end And (/^I click google search/) do click_button('gbqfb') end Then(/^I should see message "(.*?)"$/) do |rmessage1| page.has_content?('...
class Coach::AreasController < CoachesController layout "coaches_areas" def show @area = CoachesArea.find params[:id] end end
require 'rails_helper' RSpec.describe Spree::Order do it "generates an order and advances it to the address state" do order = FactoryGirl.create(:order_with_line_items) order.next! expect(order.state).to eq("address") end end
class Driver module Contract class DriverForm < ::Reform::Form ::Driver.attribute_names.each { |col| property col.to_sym } validates :full_name, presence: true end end end
module RedmineRca module ProjectPatch def self.included(base) # :nodoc: base.extend(ClassMethods) base.send(:include, InstanceMethods) # Same as typing in the class base.class_eval do unloadable # Send unloadable so it will not be unloaded in development after_save :update...
class RedeemifyCode < ActiveRecord::Base belongs_to :provider belongs_to :user has_many :vendor_codes #accepts_nested_attributes_for :vendor_codes #validates_presence_of :code validates :code, presence: true, uniqueness: {message: "already registered"}, length: { maximum: 255, message: ...
class BatExtras < Formula desc "Bash scripts that integrate bat with various command-line tools" homepage "https://github.com/eth-p/bat-extras/blob" url "https://github.com/eth-p/bat-extras/archive/v2020.05.01.tar.gz" sha256 "ad6a65570f7dfd49e947eec65b2fae52be59feedf7030de801f7fd5b25193885" head "https://gith...
FactoryGirl.define do sequence :name do |n| "Jennifer #{n}" end sequence :email do |n| "email#{n}@email.com" end factory :user do name email password 'Password123' password_confirmation 'Password123' end end
github_binary 'peco' do repository 'peco/peco' version 'v0.5.1' ext = (node[:platform] == 'darwin' ? 'zip' : 'tar.gz') archive "peco_#{node[:os]}_amd64.#{ext}" binary_path "peco_#{node[:os]}_amd64/peco" end dotfile '.peco'
class Pitchfile include Mongoid::Document include Mongoid::Timestamps belongs_to :user field :file_id, type: Integer field :name, type: String field :visible, type: Boolean, default: false field :parent_id, type: Integer field :is_Folder, type: Boolean validates_presence_of :file_id, :parent_id end
# handles venue reservation from user side module Reservable extend ActiveSupport::Concern def make_reservation unless current_user msg = { status: 'error', message: 'Log in to book!', html: '<b>...</b>' } render json: msg && return end paid = true reservations, errors = make_reservatio...
module FacebookCommands class << self def friends(*args) if args.first == 'help' puts 'list [returns list of your friends]' puts 'list <uid> [returns list of <uid>\'s friends]' return end if args.first == 'list' args.shift person = !args.empty? ? arg...
# frozen_string_literal: true require 'common/client/base' require 'mvi/configuration' require 'mvi/responses/find_profile_response' require 'common/client/concerns/monitoring' require 'common/client/middleware/request/soap_headers' require 'common/client/middleware/response/soap_parser' require 'mvi/errors/errors' re...
# frozen_string_literal: true require_relative 'test_helper' DB.create_table :legacy_humans do primary_key :id column :encrypted_email, :string column :password, :string column :encrypted_credentials, :string column :salt, :string end class LegacyHuman < Sequel::Model(:legacy_humans) self.attr_encrypted_...
class Character < ApplicationRecord belongs_to :user belongs_to :race has_many :comments, dependent: :destroy has_many :users, through: :comments validates :name, presence: true def to_slug name.downcase.parameterize end def to_param slug end def average_rating...
require File.expand_path(File.dirname(__FILE__) + "/../../../spec_helper") describe FreemarkerTemplateEngine do before(:all) do @project_path = "src/vraptor-scaffold" @webapp = "#{@project_path}/#{Configuration::WEB_APP}" @web_inf = "#{@project_path}/#{Configuration::WEB_INF}" @decorators = "#{@web_...
class RailwayStationsRoute < ActiveRecord::Base belongs_to :railway_station belongs_to :route end
# -*- coding: utf-8 -*- require 'spec_helper' describe BooksController, 'GET /find/:query' do before(:each) do @book = Factory(:book) end it "リクエストが成功すること" do get 'find' response.should be_success end it "検索結果に本が含まれること" do get 'find', :query => @book.name ...