text
stringlengths
10
2.61M
require 'oga' require 'xml_patch/diff_document' require 'xml_patch/operations/remove' module XmlPatch class DiffBuilder attr_reader :diff_document def initialize @diff_document = XmlPatch::DiffDocument.new end def remove(xpath) diff_document << XmlPatch::Operations::Remove.new(sel: xpat...
class CreateMatches < ActiveRecord::Migration[5.0] def change create_table :matches do |t| t.references :round, null: false t.references :group t.references :team1, null: false t.references :team2, null: false t.datetime :play_at, null: false t.references :ground t.re...
#!/usr/bin/env ruby # called like: session-reaper 10 /tmp # to cull all ruby sessions older than 10 minutes in /tmp # globals session_prefix = "ruby_sess*" # defaults for command line params fake_delete = false verbose = false session_dir = nil expire_minutes = nil require 'optparse' opts = OptionP...
# encoding: UTF-8 require './spec/spec_helper' describe OmniSearch::Cache do describe 'is a singleton' do it 'responds to instance' do Cache.should respond_to(:instance) end it 'returns the same instance every time' do Cache.instance.should == Cache.instance ...
require 'erb' class String alias :each :each_char end class Controller attr_reader :controller_name, :action_name, :request_parameters attr_accessor :status, :headers, :content def initialize(controller_name, action_name, request_parameters = {}) @controller_name = controller_name @action_name = acti...
# frozen_string_literal: true require 'stannum' require 'support/entities/gadget' module Spec class Factory include Stannum::Entity attribute :address, String attribute :gadget, Spec::Gadget end end
require 'spec_helper' describe 'Product Catalog' do it 'renders the products available' do visit '/products' expect(page).to have_css 'th', text: 'Name' expect(page).to have_css 'tr', text: 'TeddyBear' end end
class AddPublishedToPosts < ActiveRecord::Migration def up add_column :posts, :published, :boolean, default: false, null: false # Make all current posts published by default Post.all.each do |post| post.update_attribute :published, true end end def down remove_column :posts, :published...
class Tables < ActiveRecord::Migration def change create_table "users" do |t| t.string "name" end create_table "stats" do |t| t.integer "player_x_id" t.integer "player_o_id" t.boolean "player_x_won" t.boolean "player_o_won" t.datetime "created_at" end end end
require 'date' require 'json' # Load config config_file = File.read 'config.json' CONFIG = JSON.parse config_file # Put today's date in the intro slide. File.open 'intro/01.md', 'w' do |f| f.puts '!SLIDE' f.puts "# #{CONFIG.fetch 'presentation_title'}" f.puts "## #{Date.today.strftime(CONFIG.fetch 'date_format'...
class PropertiesController < ApplicationController before_filter :authenticate_user!, :only => :show before_filter :is_administrator?, :except => :show def index @properties = Property.order('code, name') end def show @property = Property.find_by_id(params[:id]) end def new @property = Prop...
# frozen_string_literal: true module MachineLearningWorkbench::Tools module Normalization def self.feature_scaling narr, from: nil, to: [0,1] from ||= narr.minmax old_min, old_max = from new_min, new_max = to ( (narr-old_min)*(new_max-new_min)/(old_max-old_min) ) + new_min rescue Zero...
class ReviewsController < ApplicationController def create @product = Product.find(params[:product_id]) @review = @product.reviews.create(review_params) if @review.save flash[:notice] = "Thanks for your review" redirect_to product_path(@product) else render "/products/show" end ...
class Player ROTATION_SPEED = 3 ACCELERATION = 1.2 REVERSE = ACCELERATION * 0.7 FRICTION = 0 attr_accessor :x, :y, :angle, :radius def initialize(window) @x = 600 @y = 400 @angle = 90 @image = Gosu::Image.new('player_tank.png') @velocity_x = 0 @velocity_y = 0 @window ...
class Vote < ApplicationRecord # encoding: UTF-8 belongs_to :user, required: false belongs_to :micropost, required: false end
# == Schema Information # # Table name: transactions # # id :bigint not null, primary key # purchase_shares :integer not null # purchase_price :float not null # user_id :integer not null # ticker_symbol :string not null # created_at :da...
require 'lib/freelancer' require 'rake/rdoctask' require 'rake/gempackagetask' desc 'generate API documentation to doc/rdocs/index.html' spec=Gem::Specification.new do |s| s.name = 'freelancer4r' s.version = Freelancer::VERSION s.platform = Gem::Platform::RUBY s.summary = 'Freelancer API for ruby'...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Profile, type: :model do it { should belong_to :user } it { should have_many :allergies } it { should have_many :contacts } it { should have_many :glucose_measures } it { should have_many :hdls } it { should have_many :heights } it { s...
class ChangeMpointsNulls1 < ActiveRecord::Migration[5.0] def change change_column_null :mpoints, :mesubstation_id, false end end
class Article < Storage belongs_to :user, inverse_of: :articles end
# == Schema Information # # Table name: avatars # # id :integer not null, primary key # user_id :integer # created_at :datetime not null # updated_at :datetime not null # location_x :integer # location_y :integer # timestamp :string # uuid :integer ...
Given(/^user is on the orbitz homepage$/) do visit OrbitHomePage end When(/^user selects the flights tab$/) do on(OrbitHomePage).select_flight_tab_element.click end And(/^user choose round trip option$/) do on(OrbitHomePage).choose_round_trip_element.click end And(/^user search for (.+) city and select (.+) air...
json.array!(@functions) do |function| json.extract! function, :id, :name, :info, :url, :father_id, :rol_id json.url function_url(function, format: :json) end
#参与活动的基类 #配置了活动的时间检查 class Common::JoinActivityBaseController < Common::LoginSystemBaseController before_filter :check_login_time_redirect_user_zone_index helper_method :curr_activity, :leader_login?, :person_info_confirm?, :person_info_review? #检查登录时间 def check_login_time_redirect_user_zone_index redirec...
# 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...
# frozen_string_literal: true module AttributeHelper def display_attribute(resource, attribute) value = resource.public_send(attribute) return value if value th('#not_specified') end def human_attribute_name(object, attr_name, options = {}) return object.human_attribute_name(attr_name, options)...
class UserMailer < ApplicationMailer default from: "do-not-reply@example.com" def contact_email(visitor) @visitor = visitor mail(to: Rails.application.secrets.owner_email, from: @visitor.email, :subject => "Website Contact") end end
class ProjectWeek < ActiveRecord::Base belongs_to :project belongs_to :week end
class Tkadmins::RegistrationsController < Devise::RegistrationsController before_filter :configure_permitted_parameters protected def authenticate_check authenticate_or_request_with_http_basic do |tkusername, tkpassword| tkusername == ENV['tkusername'] && tkpassword == ENV['tkpassword'] end end ...
json.array! VirtualRepository.all do |virtual_repository| json.title virtual_repository.title json.repository_id virtual_repository.repository.id json.repository_uuid virtual_repository.repository.uuid json.collections do json.array! virtual_repository.collections, :id, :uuid end end
# Add a declarative step here for populating the DB with movies. Given /the following movies exist/ do |movies_table| movies_table.hashes.each do |movie| # each returned element will be a hash whose key is the table header. # you should arrange to add that movie to the database here. Movie.create!(movie)...
require 'rails_helper' require_relative '../../../../app/services/statistics/player_statistics.rb' describe 'AverageMissesStatisticTest' do it 'counts average misses correctly' do player = create(:player) create_list(:match_score, 5, player: player, count_miss: 7) expect(PlayerStatistics::AverageMisses...
class Item < ApplicationRecord has_many :reviews, dependent: :destroy has_many :cart_item, dependent: :destroy has_many :item_sizes has_many :sizes, through: :item_sizes has_many :item_images def average_rating return 0 if reviews.empty? (reviews.where.not(rating: nil).reduce(0) { |acc, review| acc...
# == Schema Information # # Table name: locations # # id :integer not null, primary key # department :string # building :string # floor :string # room :integer # created_at :datetime not null # updated_at :datetime not null # event_id :integer # require 'test_hel...
require "rails_helper" describe "Transfer Request Call", :as_twilio, type: :request do describe "#store" do context "with valid params" do it "receives a call and associates it with a transfer request" do user = create(:user_with_number) contact = create(:contact, user: user, phone_number: ...
class User < ApplicationRecord # validation validates :name, presence: true validates :name, uniqueness: true validates_format_of :name, with: /\A[a-zA-Z0-9_\.]*\z/ # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authentic...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'submissions#index' resources :comments, only: %w[create destroy new] resources :communities, only: %w[create destroy new show] resources :submissions, only: %w[create d...
require 'rails_helper' RSpec.describe Book, type: :model do it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_length_of(:title).is_at_least(2) } it { is_expected.to validate_presence_of(:description) } it { is_expected.to validate_length_of(:description).is_at_least(10) } ...
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html get '/other', to: 'mailer#mail_to_other' get '/self', to: 'mailer#mail_to_self' end
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'erb' require 'fileutils' require 'dataMetaDom' require 'dataMetaDom/help' require 'dataMetaDom/pojo' require 'dataMetaDom/record' require 'dataMetaDom/util' require 'ostruct' ...
class Admin::ErrorTracesController < AdminController before_action :require_power_user class Boom < StandardError end def index end def create if error_params.dig(:type) == "job" raise_error = true TracerJob.perform_async(Time.current.iso8601, raise_error) redirect_to admin_error_tr...
=begin rdoc Columbus Dns-sd lookup Server =end module Columbus class Server class << self attr_accessor :name, :description def announce(interface="vmnet8", t="_presence", proto="tcp", port=9419) @interface = interface while true do DNSSD.register(name, "...
# # encoding: utf-8 # Inspec test for recipe apache_tomcat::default # The Inspec reference, with examples and extensive documentation, can be # found at http://inspec.io/docs/reference/resources/ describe group('tomcat') do it { should exist } end describe user('tomcat') do it { should exist } it { should bel...
class AddAreaLevel1ToOffice < ActiveRecord::Migration def change add_reference :offices, :area_level1, index: true, foreign_key: true end end
require 'spec_helper' RSpec.describe Raven::Utils::RealIp do context "when no ip addresses are provided other than REMOTE_ADDR" do subject { Raven::Utils::RealIp.new(:remote_addr => "1.1.1.1") } it "should return the remote_addr" do expect(subject.calculate_ip).to eq("1.1.1.1") end end contex...
module Enocean class Writer def initialize(serial) @serial = serial end def write_packet(packet) Enocean::Esp3::Response.next_expected_response_class = packet.response_class if packet.packet_type == Esp3::CommonCommand.type_id @serial.puts packet.serialize.pack("C*") end end ...
require 'mechanize' namespace :sidekiq do desc "reset notification queue" task reset_notifications_queue: :environment do Sidekiq::Queue.new('notifications').clear Sidekiq::RetrySet.new.clear Sidekiq::ScheduledSet.new.clear end desc "reset updates queue" task reset_updates_queue: :environment...
Rails.application.routes.draw do get 'endpoint/index' scope "/endpoint" do post :get_request, to: "endpoint#get_request" get :index, to: "endpoint#index" end end
class AnswersController < ApplicationController def edit existing_answer = Answer.find_by best_answer: true if existing_answer existing_answer.toggle!(:best_answer)# end Answer.find(params["id"]).toggle!(:best_answer)# @answers = Answer.order("best_answer DESC")# @question = Question....
Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) root :to => "mountains#index" devise_for :skiers # Routes for the Skier resource: # READ get "/skiers", :controller => "skiers", :action => "index" get "/skiers/:id", :controller => "skiers", :a...
class CustomSessionsController < Devise::SessionsController before_filter :before_login, only: :create def before_login user = User.find_by email: params[:user][:email] user.generate_and_save_auth_token! end end
class TasksController < ApplicationController def index @tasks = Task.all render json: @tasks end def create @task = Task.create(task_params) render json: @task end def destroy Task.find(params[:id]).delete end private def task_params params.require(:task).permit(:title, :ready) end end
require 'test_helper' class BudgetTest < ActiveSupport::TestCase def setup @budget = budgets(:one) end test "should be valid" do assert @budget.valid? end test "hours should be present" do @budget.hours = "" assert_not @budget.valid? end test "hours should be greater than 0" do @b...
class TaxSetting < ActiveRecord::Base validates :start_date, presence: true validates :national_rate, :numericality => true, :allow_blank => true validates :local_rate, :numericality => true, :allow_blank => true end
Given /^motto "([^\"]*)"$/ do |motto| Factory :answer, :question => Factory(:question, :question_type=>"motto"), :user => @current_user, :text => motto end
class CreateNodeCategories < ActiveRecord::Migration def change create_table :node_categories do |t| t.text :name t.references :node_type, index: true t.timestamps null: false end add_foreign_key :node_categories, :node_types end end
class EpisodesController < ApplicationController def index respond_to do |format| format.html do @anime = Anime.find(params[:anime_id]) preload_to_ember! @anime, serializer: FullAnimeSerializer, root: 'full_anime' render 'anime/show', layout: 'redesi...
# frozen_string_literal: true require 'rails_helper' RSpec.describe UserBalance, type: :model do it { should belong_to(:user) } it { should belong_to(:payer) } it { should validate_presence_of(:user) } it { should validate_presence_of(:payer) } it 'monetizes balance' do expect(monetize(:balance_cents)).t...
class ChangeColumnnameOfContactGatherings < ActiveRecord::Migration def change remove_column :contacts, :gatherings_mask rename_column :contact_gatherings, :gethering_id, :gathering_id end end
require "rails_helper" RSpec.feature "admin can delete a category" do context "while visiting category index" do it "admin can use delete button to remove category" do admin = User.create(username: "steve", email: "test", password: "pass", role: 1) category = Category.create(name: "...
class VideosController < ApplicationController before_action :authenticate_user!, except: [:index, :show] before_action :set_video, only: [:show, :favorite, :rate] respond_to :html respond_to :json, only: [:favorite, :rate] def index @videos = Video.includes(:user).ordered.censored.page(param...
require 'spec_helper' describe TasksController do context "when signed in" do before(:each) do @current_user = Factory(:user) controller.stub!(:current_user).and_return(@current_user) end # GET /tasks/1 #-------------------------------------------------- describe "responding to GET s...
require 'test_helper' class BankTransactionTest < ActiveSupport::TestCase def test_matches_against_invoice_reference_number invoices(:valid).update!(number: '2222', total: 10, reference_no: '1111') transaction = BankTransaction.new(description: 'invoice #2222', sum: 10, reference_no: '1111') assert_diff...
class AddPlayedByToCharacter < ActiveRecord::Migration def change add_column :characters, :played_by, :string end end
module Treasury module Fields # Public: Модуль добавляет классу метод extract_object, подходит для источников и полей денормализации. # # Deprecated: For extract object use Apress::Sources::ExtractObject module # # Example: # # class Field # extend ::Treasury::Fields::Extractor ...
# Seed data for categories (sample layout) params = {:product_categories => [ { :category => "Skis", :product_subcategories_attributes => [ {:subcategory => "Skate Skis Performance"}, {:subcategory =>...
class Users::InvitationsController < Devise::InvitationsController before_filter :configure_permitted_parameters, if: :devise_controller? def create params[:user][:org_id] = current_user.org_id super end def update params[:user][:org_id] = current_user.org_id super end protected # https://github.com...
# Write a method, compress_str(str), that accepts a string as an arg. # The method should return a new str where streaks of consecutive characters are compressed. # For example "aaabbc" is compressed to "3a2bc". def compress_str(str) counter = 0 compressed_str = "" str.split("").each.with_index do |char, idx| ...
require "test_helper" class SolarSystemsControllerTest < ActionDispatch::IntegrationTest setup do @solar_system = solar_systems(:one) end test "should get index" do get solar_systems_url assert_response :success end test "should get new" do get new_solar_system_url assert_response :succ...
module AdminDashboard class ApplicationController < ::ApplicationController before_action ->{ redirect_to admin_login_path if !signed_in? } end end
class Cocktail < ApplicationRecord before_validation { self.name = name.downcase unless name.nil? } validates :name, uniqueness: true, presence: true, allow_nil: false, allow_blank: false validates :name, presence: true has_many :doses, dependent: :destroy has_many :ingredients, through: :doses has_many :re...
class AddBelongUserProject < ActiveRecord::Migration def change add_column :projects, :project_manager_id, :integer add_column :projects, :project_owner_id, :integer remove_column :projects, :user_id, :integer end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
require 'test_helper' require 'unit/rpx/test_helper' class RPX::ProfileTest < ActiveSupport::TestCase include RPX::TestHelper test "should parse Facebook data" do facebook = profile_from :facebook assert facebook.facebook? assert_equal :male, facebook.gender assert_equal Date.new(1984, 4...
class PetsController < BaseController def index end def create respond_with :api, :v1, Pet.create(pet_params) end def destroy respond_with Pet.destroy(params[:id]) end def update pet = Pet.find(params["id"]) pet.update_attributes(pet_params) respond_with pet, json: pet end pr...
json.array!(@historic_assets) do |historic_asset| json.extract! historic_asset, :id, :description, :historic_asset_type json.url historic_asset_url(historic_asset, format: :json) end
module Page module Post class PostsIndex < Page::Base def visit super posts_path end def view_all click_link 'All posts' end def has_add_post_button? page.has_text? 'New Post' end def has_admin_buttons? page.has_css? '.buttons' end...
module Reviewr class PretendGit < Git attr_reader :output def initialize(output) @output = output end def rebase(base, branch) pretend_execute("git rebase #{base} #{branch}") true end def create_branch(branch_name, base) pretend_execute("git branch #{branch_name} #{b...
require 'bundler' require 'json' Bundler.require class App < Sinatra::Base enable :sessions helpers do def logged_in? session[:login] && session[:password] end def gh_client @gh_client ||= Octokit::Client.new(login: session[:login], password: session[:password]) end end def langs_f...
RSpec.describe Identity, type: :model do it { should belong_to :user } it { should validate_presence_of :uid } it { should validate_presence_of :provider } it { should validate_presence_of :user_id } it 'should be valid' do identity = create :identity expect(identity).to be_valid ...
class Trip < ApplicationRecord has_many :reservations has_many :users, through: :reservations belongs_to :guide_comp end
class PostsController < ApplicationController skip_before_action :verify_authenticity_token, only: [:create] def index @posts = Post.order(created_at: :desc) render json: @posts, include: ['author'] end def show @post = Post.find(params[:id]) render json: @post, include: ['aut...
require 'bacon' require 'tilt' describe Tilt do class MockTemplate attr_reader :args, :block def initialize(*args, &block) @args = args @block = block end end it "registers template implementation classes by file extension" do lambda { Tilt.register('mock', MockTemplate) }.should.not...
$:.push File.expand_path("lib", __dir__) # Maintain your gem's version: require "blacklight/sitemaps/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = "blacklight-sitemaps" spec.version = Blacklight::Sitemaps::VERSION spec.authors = ["Jack Ree...
class Role attr_accessor :owner attr_accessor :team attr_accessor :name def initialize(name, team, description) @name = name @team = team @description = description @owner = nil end def to_s %Q[``` Role: #{@name} Description: #{@description} Team: #{@team} ```] end end
# Copyright (c) 2013 Altiscale, inc. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
json.array!(@captures) do |capture| json.extract! capture, :id, :empleado_id, :incident_id, :fecha_inicial, :fecha_final, :periodo json.url capture_url(capture, format: :json) end
# frozen_string_literal: true require 'base/version' module Base class Error < StandardError; end # Your code goes here... end
class Authentication < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable def changePassword(user_id,old_password,new_password) ...
class SessionsController < ApplicationController def new @user = User.new end def create user = User.find_by(email: params[:email]) if user == nil flash[:error] = "Email does not exist" elsif user.authenticate(params[:password]) session[:user_id] = user.id flash[:message] = "Congratulations, you ...
require File.join(File.dirname(__FILE__), '../..', 'lib', 'helper', 'helper') require "test/unit" include Server::Helper class ServerHelperTest < Test::Unit::TestCase def test_extract_output command_output = 'This is the command output <WS Response Start>{"key": "value"}<WS Response Completed> from the comman...
# == Schema Information # # Table name: articles # # id :bigint(8) not null, primary key # body :text # comments_count :integer default(0), not null # favorites_count :integer default(0), not null # title :string # created_at :datetime not n...
Shindo.tests('Fog#wait_for', 'core') do tests("success") do tests('Fog#wait_for BC').formats(:duration => Integer) do Fog.wait_for(1) { true } end tests("Fog#wait_for with :wait_policy").formats(:duration => Integer) do wait_policy = lambda { |times| times * 0.01 } Fog.wait_for(:wait_po...
class Category < ActiveRecord::Base acts_as_nested_set belongs_to :department #this can be null and is only for hierarchy has_many :sub_categories, class_name: 'Category' belongs_to :category, class_name: 'Category', foreign_key: 'parent_id' has_many :products has_attached_file :attachmen...
# Jon Wu module ApplicationHelper require 'rest_client' def self.thetvdb thetvdb={ api_key: "7FE56AB14EBC6348", endpoint: "http://thetvdb.com" } return thetvdb end def self.themoviedb themoviedb = { api_key: "8dbcc916cb5179dbcc6f9c06145f3085", endpoint: "https://api.themoviedb.org/3", airi...
class CreateMQTRAN < ActiveRecord::Migration[5.1] def change create_table :mqtran do |t| t.references :mqdiag, foreign_key: true t.integer :mqelem_origem_id t.integer :mqelem_destino_id t.string :descricao t.timestamps end end end
require "metacrunch/hash" require "metacrunch/transformator/transformation/step" require_relative "../aleph_mab_normalization" require_relative "./add_erscheinungsform" class Metacrunch::ULBD::Transformations::AlephMabNormalization::AddDescription < Metacrunch::Transformator::Transformation::Step def call target...
class Chat < ApplicationRecord belongs_to :user has_many :messages, dependent: :delete_all def as_json(options={}) super(include: :messages ) end end
class VoteCounter class << self def count_per_bill poll #Groups answers by the title of the poll for each legislation votes = poll.replies.answers.groupby { |answer| answer.question_id.poll.title } { title: "Votes per Bill", data: votes.cou...
if false # modified from an original at https://github.com/carlhuda/bundler/issues/183#issuecomment-1149953 if defined?(::Bundler) ENV['GEM_PATH'].split(':').each do |gemset| gem_paths = Dir.glob("#{gemset}/gems/*") gem_paths.each do |p| gem_path = "#{p}/lib" $LOAD_PATH << gem_path end end e...