text
stringlengths
10
2.61M
class DelayedManageFeeCollectionJob def initialize(obj) @transport_fees = obj end def perform @transport_fees.each do |tf| tf.destroy end end end
require 'rack' class Servatron::Server def self.start application, options={} new(application, options).start end def initialize application, options={} @application = application @port = options[:port] || 3000 @rack = Rack::Builder.new do use Rack::CommonLogger, STDERR use Rack::Sh...
require 'minitest/autorun' require_relative 'test_helper' include FileMover class SuffixTest < MiniTest::Unit::TestCase include TestHelper def test_append_suffix with_source_and_sink do |source, sink| create_file source.dir, 'foo1' , 'foo2', 'bar' filter = Suffix.new append: '.a' assert_...
Gem::Specification.new do |s| s.name = 'pokereval' s.version = '0.0.1' s.date = '2013-07-02' s.summary = "An interface to the poker-eval C library" s.description = "An interface to the very fast poker-eval C library, and various other functions in Ruby." s.authors = ["Mike Cartmell...
require 'net/smtp' module OisNotifier class Gmailer include OisNotifier::Helpers def send_message(message) within_connection do |smtp| smtp.send_message( message, config.gmail.email, defaults.receiver_email ) logger.debug('notification e-mail sent') end end ...
module WebParser module Doc class XPathsNotSet < StandardError; end def self.included base base.extend ClassMethods end module ClassMethods def recipes &block @recipes = Recipes.new(&block) if block_given? @recipes end end # @example # recipes do ...
class CreateBrowsers < ActiveRecord::Migration def up create_table :browsers do |t| t.string :name, limit: 30 t.timestamps null: false end end def down drop_table :browsers end end
class AddStatusToUsers < ActiveRecord::Migration def change change_table(:users) do |t| t.column :status, :string end end end
class Highrise::Person def self.search(term) find(:all, :params => {:term => term}, :from => "/people/search.xml") end def to_ldap_entry { "objectclass" => ["top", "person", "organizationalPerson", "inetOrgPerson", "mozillaOrgPerson"], "uid" => [id.to_s], "sn" => ...
require 'pry' require './lib/card' describe Card, type: :model do let(:card_number) { 'A' } let(:card_suit) { 'Spades' } let(:card) do Card.new(number: card_number, suit: card_suit) end context '#new' do it 'should be a type of Card' do expect(card).to be_a_kind_of(Card) end it 'shou...
class Feedback include ActiveModel::Model attr_accessor( :title, :body ) validates :title, presence: true validates :body, presence: true end
module JobGet class Jobs < Controller map '/job' def read(job_id) @job = job_for(job_id) Stat.log_view(:job_id => @job.id) end def browse @jobs = Job.available pager @jobs end def apply(job_id) acl 'before applying for this job', :applicant @job = job_fo...
require 'api_smith/client' module APISmith # A base class for building api clients (with a specified endpoint and general # shared options) on top of HTTParty, including response unpacking and transformation. # # Used to convert APISmith::Client to a class (versus a mixin), making it useable # in certain oth...
module OpenAgent module Message class SIF_SecureChannel include ROXML xml_name 'SIF_SecureChannel' xml_accessor :sif_authenticationlevel, :from => 'SIF_AuthenticationLevel' xml_accessor :sif_encryptionlevel, :from => 'SIF_EncryptionLevel' end class SIF_Security include ROXML...
# == Schema Information # # Table name: resources # # id :integer not null, primary key # book_id :integer # created_at :datetime not null # updated_at :datetime not null # user_id :integer # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.d...
# == Schema Information # # Table name: articles # # id :integer(4) not null, primary key # title :string(255) # description :text # article_type_id :integer(4) # keywords :string(255) # meta_description :text # permalink :string(255) # created_at :dateti...
require 'faker' FactoryGirl.define do factory :contact do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } email { Faker::Internet.email } landline { Faker::PhoneNumber.phone_number } mobile { Faker::PhoneNumber.cell_phone } company trait :no_name do first_...
class SessionsController < Devise::SessionsController skip_load_and_authorize_resource def create self.resource = warden.authenticate(auth_options) if self.resource.try :active_for_authentication? set_flash_message!(:notice, :signed_in) sign_in(resource_name, self.resource) redirect_back ...
describe Ncr::DashboardController do describe "#index" do it "does not include proposals user did not participate in" do user = create(:user) login_as(user) create(:ncr_work_order) get :index expect(assigns(:rows)).to be_empty end end end
require 'kramdown' module ArticlesHelper def kramdown(content) Kramdown::Document.new(content).to_html.html_safe end end
class SessionsController < ApplicationController def login login = LoginToken.find_or_create_by!(email: login_params[:email]) do |login| login.token = LoginToken.new_token end SessionMailer.login(login).deliver render json: { message: 'ok' } end def authorize login = LoginToken.find_by!...
require 'rely' RSpec.describe 'Dependencies' do let(:abstract_service_class) { Class.new do extend Rely::Dependencies # Initialize the service, optionally setting dependency values. def initialize(dependencies={}) dependencies.each do |attribute, value| send :"#{attribute}=",...
class CommentsController < ApplicationController before_action :set_review, only: [:create] def create if user_signed_in? @comment = @review.comments.new(comment_params) if @comment.save respond_to do |format| format.json format.html { redirect_to review_path(@review) } ...
require 'test_helper' class ActiveFlags::Handler::FlagMappers::AuthorizerTest < ActiveSupport::TestCase test 'should authorize every flags if no authorized_flags passed' do authorized_flags = [] flags_to_check = {hidden: true, magic: false} flags = ::ActiveFlags::Handler::FlagMappers::Authorizer.authoriz...
class AddUserTypeIdToUsers < ActiveRecord::Migration def change add_column :users, :user_type_id, :integer, default: 2, null: false end end
require 'spec_helper' include WebPageParser describe ParserFactory do it "should load parsers in the parsers directory" do ParserFactory.factories.first.to_s.should == "TestPageParserFactory" end it "should provide the right PageParser for the given url" do ParserFactory.parser_for(:url => "http://www....
class Account < ApplicationRecord has_many :rewards, dependent: :destroy has_many :sessions, dependent: :destroy validates :name, presence: true devise :database_authenticatable, :rememberable, :validatable end
FactoryGirl.define do factory :cities do continent_id { rand(1..5) } name { ["Test City 1", "Test City 2", "Test City 3"].sample } population { rand(100..1000)} description { ["This is a great city!", "I never want to visit this place"].sample } end end
class AddActivitiesToCamps < ActiveRecord::Migration def change add_column :camps, :activities, :string end end
class SuppliersController < ApplicationController before_filter :signed_in_user, :only => [:index, :edit, :update, :destroy, :show, :new, :create] before_filter :assignee_user, :only => [:edit, :update, :destroy, :new, :create] helper_method :sort_column, :sort_direction # GET /suppliers # GET /suppl...
class Deed < ApplicationRecord validates :property_id, :game_id, presence: true validates :property_id, uniqueness: { scope: :owner_id }, unless: ->(x) { x.owner_id.nil? } validates :property_id, uniqueness: { scope: :game_id } belongs_to :property belongs_to :game belongs_to :owner, class_name: 'Player', ...
class AddRepostPeopleToMicroposts < ActiveRecord::Migration def change add_column :microposts, :repost_people, :string, :default => "Start" end end
require_relative 'spec_helper' describe ManaSymbols do it "should parse phyexian mana {W/P}" do target = ManaSymbols::parse("{W/P}") target.colors.must_equal Set.new([:white]) end it "should parse dual mana {U/R}" do target = ManaSymbols::parse("{U/R}") target.colors.must_equal Set.new([:blue, :r...
desc "Watch scss files and make me a server." task :watch do c = Process.spawn("compass watch") j = Process.spawn("jekyll --auto --server") Process.waitpid(c) Process.waitpid(j) end
class AddSubjectAndSignatureToCustomMails < ActiveRecord::Migration[6.0] def change add_column :custom_mails, :subject, :string add_column :custom_mails, :signature, :text end end
class CreateServicesWorkers < ActiveRecord::Migration def change create_table :services_workers do |t| t.references :service t.references :worker t.integer :cost t.integer :showing_time t.timestamps end add_index :services_workers, :service_id add_index :services_workers...
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def flash_notices [:notice, :error, :warning].collect do |type| content_tag('div', flash[type], :class=>"message #{type}", :id => "flash_messages") if flash[type] end end end
# RSpec Examples (RSpec Book, The Rails 3 Way, Custom) # http://eggsonbread.com/2010/03/28/my-rspec-best-practices-and-tips/ ################################################################################ # command line # rspec --help (show help) # rake -T spec (list all rspec-rails rake tasks) # rspec spec (run all...
# Connect_board.rb class Board @@cols = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] # each slot will have either a zero, one, or two def player_move(player, last_piece) index = gets.chomp.to_i - 1 # change to zero-based if index >= @@cols.leng...
class Project attr_reader :title def initialize (title) @title = title end def add_backer(backer) ProjectBacker.new(self,backer) end def backers ProjectBacker.all.select do |backer_instance| backer_instance.project == self end.map do |backer_instance...
class UserSerializer < ActiveModel::Serializer attributes :id, :facebook_id, :name def id object._id.to_s end end
class Flight < ApplicationRecord belongs_to :plane has_many :reservations validates :date, :destination, :origin, :plane_id, :presence => true end
class NotificationVolunteer < ActiveRecord::Base belongs_to :volunteer belongs_to :notification validates :volunteer_id, :presence => true, :on => :create validates :notification_id, :presence => true, :on => :create end
json.crime do json.id @crime.id json.name @crime.name json.description @crime.description json.category_id @crime.category_id json.district_id @crime.district_id json.status_id @crime.status_id json.details @crime.details json.address @crime.address json.user_id @cr...
# Validate fields to look like URLs # # A blank URL is considered valid (use presence validator to check for that) # # Examples # validates :url, url_format: true # optional # validates :url, url_format: true, presence: true # required class UrlFormatValidator < ActiveModel::EachValidator def vali...
module LDAP class << self def search(options) admin.search(options) end # def users # admin.users # end # # def get_user(login) # admin.get_user(login) # end # # def get_user_groups(login) # admin.get_user_groups(login) # end def bind(login, passwo...
class Admin::OrdersController < Admin::AdminapplicationsController def index @orders = Order.all.page(params[:page]) end def period_index range = Date.today.beginning_of_day..Date.today.end_of_day @orders = Order.where(created_at: range).page(params[:page]) end def customer_index @orders =...
namespace :category do desc "Load categories from file" task :seed => :environment do CSV.foreach(Rails.root.join("db","data","categories.csv")) do |row| category = Category.find_or_create_by(name: row[0], primary: true) category.children.find_or_create_by(name: row[1], primary: false) end end...
class CreateImageFiles < ActiveRecord::Migration[5.2] def change create_table :image_files do |t| t.string :filename t.string :content_type t.integer :file_size t.boolean :principal_file, default: false t.integer :efemeride_id, null: false, default: -1 t.integer :blob_id, null:...
class AddReceptionNumberToRepairs < ActiveRecord::Migration[5.2] def change add_column :repairs, :reception_number, :integer end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :auth_session helper_method :current_user helper_method :possible_users def auth_session @current_user = Session.new(session, possible_users).find_user redirect_to new_session_path unless @curre...
require "conduit/sureaddress/actions/base" module Conduit::Driver::Sureaddress class VerifyAddress < Base url_route "/SureAddress.asmx/PostRequest" required_attributes :response_type, :match_count optional_attributes :client_tracking, :firm_name, :primary_address_line, :secondar...
class Api::ListsController < ApplicationController def create @movie = Movie.find(params["movie"][:id]) current_user.movies << @movie end def index @list = current_user.movies end def destroy @movie = current_user.lists.find_by(movie_id: params[:id]) @movie.destroy @list = current_u...
class ProjectData < ActiveRecord::Base attr_accessible :id, :name, :project_type, :active, :project_managers_attributes, :actual_work_orders_attributes, :assigned_projects_attributes, :created_at, :updated_at belongs_to :project has_many :assigned_projects has_many :time_tables has_many :actual_work_orders has_...
# frozen_string_literal: true module Types class UserType < Types::BaseObject field :id, ID, null: true, required_permission: :anyone field :username, String, null: true, required_permission: :anyone field :admin, Boolean, null: true end end
class Api::MembershipsController < ApplicationController def index @memberships = Membership.where(group_id: params[:group_id]) end def create @membership = Membership.new(membership_params) @membership.user_id = current_user.id if @membership.save render :show else render json: @...
require 'rails_helper' RSpec.describe "dashboard index" do before do guy = User.create(name: "jim", email: "jim@jim.com", password: "password", role: "admin", course_name: "GBO INC") lady = User.create(name: "jill", email: "jill@jill.com", password: "password", role: "student", course_name: "GBO ...
require File.expand_path(File.join(File.dirname(__FILE__), %w[spec_helper])) require 'ostruct' describe Rhouse::Worker do before( :all ) do end it "should set the worker name correctly" do worker = Rhouse::Worker.new( "test" ) worker.name.should == 'test' end it "should compile the correct confi...
class ApplicationController < ActionController::Base helper :all protect_from_forgery helper_method :current_user private # returns the current logged-in user def current_user @current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token] end # logs the current ...
require_relative 'test_helper' require 'minitest/autorun' require 'minitest/pride' require_relative '../lib/complete_me' require 'pry' class CompleteMeTest < Minitest::Test def test_inserting_word_creates_trie completion = CompleteMe.new completion.insert("hello") assert_instance_of Trie, completion.trie...
require 'test_helper' class UserqTest < ActiveSupport::TestCase test "if modules are available" do assert_kind_of Module, UserQ, "Module UserQ does not exist" assert_kind_of Class, UserQ::Queue, "Class UserQ::Queue does not exist" assert_kind_of Class, UserQ::Entry, "Class UserQ::Entry does not exist" ...
## # $Id: ie_style_getelementsbytagname.rb 7609 2009-11-25 07:25:04Z jduck $ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.c...
module Api module V1 class RentsController < ApiController include Wor::Paginate before_action :authenticate_api_v1_user! def index render_paginated current_api_v1_user.rents end def create @rent = authorize Rent.create(rent_params) if @rent.persisted? ...
class CardBinder < Pakyow::Presenter::Binder binder_for :card def card_link { :href => "/cards/#{bindable.id}" } end def edit_card_link { :href => "/cards/edit/#{bindable.id}" } end def update_card_link { :action => "/cards/#{bindable.id}" } end def date bindable.date.s...
class ReadmesController < ApplicationController before_action :set_owner_and_agent before_action :set_readme, except: [:new, :create] before_action :check_user_rights def new @readme = Readme.new defaut_content = [] defaut_content << I18n.t('views.readme.new.default_prefix') defaut_content << I...
class CareersController < ApplicationController def show @career = Career.find_by(title: params[:id]) @questions = @career.questions @colleagues = @career.active_colleague_relationships @related_questions = @career.related_questions(5) end end
class CreateLexemes < ActiveRecord::Migration def self.up create_table :lexemes do |t| t.string :orthography t.string :analysis t.string :gloss t.string :translation t.timestamps end end def self.down drop_table :lexemes end end
json.array!(@members) do |member| json.extract! member, :id, :name, :title, :joined, :join_reason, :function, :first_computer, :any_other_comments, :gallery_id, :category_id, :order json.url member_url(member, format: :json) end
class SpecializationSkill < ActiveRecord::Base belongs_to :skill belongs_to :specialization validates :specialization, presence: true validates :skill, presence: true 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class CreateUserKids < ActiveRecord::Migration def self.up create_table :user_kids, :force => true do |t| t.string :name,:limit=>50 t.string :logo,:limit=>50 t.string :gender,:limit=>2 t.string :education,:limit=>20 t.string :education_org,:limit=>200 t.string :content,:limit=>...
class QuestionsController < ApplicationController def index @questions = Question.all @new_question = Question.new end def create @question = Question.new(question_params) @question.user = current_user respond_to do |format| if @question.save format.js { render layout: false } ...
require 'digest/md5' namespace :assets do namespace :videos do require 'rffmpeg' desc "Convert videos" task :convert => :environment do puts "DRY RUN!" if ENV["dry_run"] == "true" logger = Logger.new(File.open('log/convert.log', 'a')) logger.info "Starting Conversion (#{Time...
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.admin? # can :manage, :all # else # can :read, :all # end # # The first argume...
#!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/snapshots') module CloudControllers module Ec2 class Volume Fields = [ :type, :id, :undef2, :snap_id, :region, :state, :date, :undef7, :undef8, :undef9, :undef10, :undef11, :undef12, :tag, :tag_value, :undef15, :name, :nam...
Rails.application.routes.draw do # Registration & Authentication mount_devise_token_auth_for 'User', at: 'auth', controllers: { omniauth_callbacks: 'users/omniauth_callbacks', registrations: 'users/registrations', sessions: 'users/sessions', token_validations: 'users/token_va...
class User < ActiveRecord::Base rolify #--------------------------------# # Connections #--------------------------------# belongs_to :position belongs_to :gender belongs_to :team belongs_to :city has_many :shows, dependent: :destroy has_many :games, :through => :shows has_many :participations, dependent: :...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :products with_options presence: true do ...
class CreateLargePosts < ActiveRecord::Migration def self.up create_table :large_posts do |t| t.string :title t.text :content t.timestamps end end def self.down drop_table :large_posts end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe DocidSearch do context "Associations" do it { should belong_to :search } it { should belong_to :doc } end end
Pod::Spec.new do |s| s.name = "Oriole" s.version = "0.5.0" s.summary = "Oriole is a set of protocol extensions that add useful helper methods to Swift collections." s.description = <<-DESC Oriole is a set of protocol extensions that add useful helper meth...
require './app/helpers/tweets_helper' class TweetSection < SitePrism::Section include TweetsHelper element :user_name, '.user-name' element :twitter_user_name, '.twitter-username a' element :tweeted_on, '.reviewed-on' element :rating, '.review-rating' element :review_text, '.tweet-text' element :reply_t...
class AddUserToBatteries < ActiveRecord::Migration def up add_column :batteries, :user_id, :integer end def down remove_column :batteries, :user_id end end
module Yo class Client def initialize(api_token: '') @http = HTTP.new(api_token: api_token) end def yo(username: '') @http.yo(username: username) end def yoall @http.yoall end def subscribers_count @http.subscribers_count end end end
require 'spec_helper' require 'webmock/rspec' module ConsulDo describe Elect do before(:all) { VCR.turn_off! } after(:all) { VCR.turn_on! } before(:each) do stub_request(:any, /localhost:8500/) end context 'with a token' do before(:each) do ConsulDo.config.token = 'foo-bar-b...
require_relative '../../../../spec_helper' describe 'icinga::check::graphite', :type => :define do let(:facts) {{ :fqdn => 'warden.zoo.tld', :fqdn_short => 'warden.zoo', :ipaddress => '10.10.10.10', :aws_environment => 'environment', }} let(:pre_condition) { 'icinga::host { "warden.zoo.t...
require_relative("../ecosystem_bears.rb") require_relative("../ecosystem_fish.rb") require_relative("../ecosystem_river.rb") require("minitest/autorun") require("minitest/rg") class TestBear < MiniTest::Test def setup @bear = Bear.new("Yogi") @river = River.new("Amazon", [@fish]) @fish = Fish.new("Tuna ...
# Encoding: utf-8 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
require 'spec_helper' describe User do before(:each) do user = User.create(:first_name => 'test', :last_name => 'test', :password => 'test', :email => 'test@example.com' ) end it "should require a username" do User.new(:us...
Rails.application.routes.draw do namespace :api, defaults: { format: :json } do namespace :v1 do get '/merchants/random', to: 'random_merchant#show' get '/merchants/find_all', to: 'merchants#index' get '/merchants/find', to: 'merchants#show' get '/merchants/most_revenue', to: 'merchants/to...
class WelcomeController < ApplicationController def index @environments = Environment.order("created_at DESC") @commands = Command.order("created_at DESC") end end
require 'rails_helper' RSpec.feature 'Refreshing permissions' do before do initialize_app_settings end context 'while logged in as H.R' do it 'should return not authorized' do @hr = create(:hr) login_as(@hr, scope: :hr) visit dashboard_admin_settings_path expect(page).to have_co...
# == Informacion de la tabla # # Nombre de la tabla: *dbm_municipios_de_bolivia* # # idMunicipio :integer(11) not null, primary key # idDepartamento :integer(11) not null # municipio :string(100) default(""), not null # class Municipio < ActiveRecord::Base set_table_name('dbm_municipios_de_bol...
FactoryBot.define do factory :group_conversation, class: 'Group::Conversation' do sequence(:name) { |n| "group_#{n}" } association :creator, factory: :user end end
FactoryBot.define do factory :card do customer_id {"cus_ca9d1d98900ec1f2595aebefd9a6"} card_id {"car_a96c76b044d7ae21439d7b9840b7"} user end end
=begin You are given two sorted arrays that both only contain integers. Your task is to find a way to merge them into a single one, sorted in asc order. Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays. You don't need to worry about validation, since arr1 and arr2 must...
class LinkedinDataController < ApplicationController before_filter :authenticate_user! before_filter :has_admin_credentials?, :except => [:index] def index if !get_data_from_range_date? @linkedin_data = LinkedinDatum.where('social_network_id = ?', params[:id_social]).order("start_date ASC") else ...
# (c) Copyright 2017 Ribose Inc. # module Rack class Cleanser VERSION = "0.1.0".freeze end end
# encoding: utf-8 module ActiveRecordUtils #### # simple (generic) database browser - no models required class Browser # also (formerly) known as connection manager # get connection names # def connection_names # ActiveRecord::Base.configurations.keys # end CONNECTS = {} # cache connections de...
require 'test_helper' class ResourceTransactionsControllerTest < ActionController::TestCase setup do @resource_transaction = resource_transactions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:resource_transactions) end test "should get new...