text
stringlengths
10
2.61M
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time helper_method :current_user_session, :current_user, :logged_i...
Before do if Capybara.app_host uri = URI.parse Capybara.app_host host = uri.host if uri.port host += ":#{uri.port}" end host! host end end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| config.vm.box...
class CreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| t.string :username t.string :password_digest t.string :user_type, default: "free" t.integer :score, default: 10 t.string :email, null: false t.timestamps null: false t.integer :profile_...
require 'date_time_precision/patch/1.8.7/date' class Date def self.civil(y=nil, m=nil, d=nil, sg=ITALY) args = [y,m,d] precision = self.precision(args) args = normalize_new_args(args) unless jd = _valid_civil?(*[args, sg].flatten) raise ArgumentError, 'invalid date' end date = ne...
class Dog < ActiveRecord::Base has_one :adoption belongs_to :breed delegate :buyer, :to => :adoption def self.not_special # selects all the dogs that aren't disabled self.all.where(disabled: false) end def self.special # selects all the dogs that are disabled self.all.where(disabled: true) en...
class AddDeletedAtToFolders < ActiveRecord::Migration def change add_column :folders, :deleted_at, :datetime add_index :folders, :deleted_at end end
unless Kernel.respond_to?(:require_relative) module Kernel def require_relative(path) require File.join(File.dirname(caller[0]), path.to_str) end end end require_relative 'helper' class TkPC_Callback def call(tuples) tuples.each do |t| puts t.join(" ") end end end class TestTkParallelCoord...
name "search_helper" maintainer "Kiall Mac Innes" maintainer_email "kiall@hp.com" license "Apache 2.0" description "Chef Search Helper" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.2.0"
get '/users' do @users = User.all #define instance variable for view erb :'users/index' #show all users view (index) end get '/users/new' do erb :'users/new' #show new users view end post '/users' do @user = User.new(params[:user]) p @user.first_name # p "first_name: #{@user.first_name}\n last_name: #{@u...
class TransactionsController < ApplicationController def index if user_signed_in? && !current_user.is_owner? transactions = current_user.transactions.get_unarchived.reverse render json: transactions else head 401 end end end
require 'date' # 日本語形式の日付に変換 # @param [Date] date 日付 # @return [String] 日付を YYYY年MM月DD日 の形式にしたもの # @return [nil] 引数が Date 型以外の場合は nil def convert_jp_date(date) (date.class == Date) ? date.strftime('%Y年%m月%d日') : nil end today = Date::today puts convert_jp_date(today) (データ/型/名前/説明の書き方) # @タグ [型] <名前> <説明> (例) # @par...
class ApplicationController < ActionController::Base helper_method :current_user private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@c...
################################################## # # SubscribePage contains the following pages: # subscribe.aspx # wait.aspx # receipt.aspx # ################################################### class SubscribePage < Page include ScreenshotHelper #include SqlServer def visit(url) @client.open(u...
# 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...
require "aethyr/core/actions/commands/wield" require "aethyr/core/registry" require "aethyr/core/input_handlers/command_handler" module Aethyr module Core module Commands module Wield class WieldHandler < Aethyr::Extend::CommandHandler def self.create_help_entries help_entrie...
# Model for players to a Game (Shouldn't this be "Player"?) class User < ActiveRecord::Base geocoded_by :address after_validation :geocode has_one :profile before_create :build_profile #creates profile at user registration has_many :signedups has_many :games, :through => :appointm...
module Octopus module Migration def self.included(base) base.extend(ClassMethods) end module ClassMethods def using_all_shards return self unless connection.is_a?(Octopus::Proxy) shard_keys = ActiveRecord::Base.connection.shards.keys.map(&:to_sym) self.current_shard =...
# frozen_string_literal: true class CreateJoinTableUserRide < ActiveRecord::Migration[5.2] def change create_join_table :users, :rides do |t| t.index %i[user_id ride_id] t.index %i[ride_id user_id] end end end
# -*- encoding : utf-8 -*- require 'helper' class RedisKeyTest < Test::Unit::TestCase context "Redis key" do setup do RedisModelExtension::Database.redis.flushdb @time = Time.now @args = { "integer" => 12345, :string => "foo", :symbol => :bar, :boolean => true,...
class AddUserRelationshipToAnswers < ActiveRecord::Migration def self.up add_column :qa_answers, :user_id, :integer end def self.down drop_column :qa_answers, :user_id end end
require "product_scoring.rb" class ProductCandidate < ActiveRecord::Base attr_accessible :description, :desired_object_id, :name, :price, :score, :source, :type, :imageUrl before_create :scoreProductCandidate belongs_to :desired_object def scoreProductCandidate desiredObject = DesiredObject.find(self.desi...
class CreateNotes < ActiveRecord::Migration[6.0] def change create_table :notes do |t| t.string :name t.integer :temperature t.string :sport t.string :hour t.string :label t.string :wind_direction t.integer :wind_force t.integer :wind_gust t.integer :wave_heig...
# frozen_string_literal: true class UserHelper include Sinatra::UserHelper end RSpec.describe UserHelper do user_helper = described_class.new describe '.create_user' do context 'when user does not exist' do it 'should create a new user' do email = 'johndoe@gmail.com' user = attributes...
#Exercise - Reading & Writing Object-Oriented Code # => Pair Program! # => Your Ruby program starts here. When you run teddit.rb this file is executed first. # The lib folder contains the RemoteSource class, StoryBoard and Story class. # => The spec folder is a test we added. Don't worry about it, leave as is! # =...
class Api::V1::TechnologiesController < ApplicationController include Concerns::HasPagination def index @technologies = Technology.by_ids(ids). by_query(filter[:q]). page(current_page). per(current_size). order(current_sort) render json: @technologies, meta: meta(@technologi...
require 'spec_helper' describe Bibliografia do before :each do @p1=Bibliografia::Bibliografia.new( ['Dave Thomas', 'Andy Hunt', 'Chad Fowler'],'Programming Ruby 1.9 & 2.0','The Pragmatic Programmers’Guide(The Facets of Ruby)','Pragmatic Bookshelf','4','(2013,7,7)',['ISBN-13: 978-1937...
class ChangeLegacyIdToLegacyShipmentNumberFromTradeShipments < ActiveRecord::Migration def change rename_column :trade_shipments, :legacy_id, :legacy_shipment_number end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception require 'logger' # スタンダードエラーの例外処理_開発時は表示させない。 rescue_from StandardError, with: :render_500 unless Rails.env.development? def render_500(e = nil) if e datetime = DateTime.current Rails.logger.error(da...
class WelcomesController < ApplicationController before_action :set_welcome, only: [:show, :edit, :update, :destroy] # GET /welcomes # GET /welcomes.json def index @users = User.all end end
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module RailsEngineSample class Application < Rails::Application # Initialize configuration defaults for originally generat...
ActiveAdmin.register User do menu label: 'Benutzer' # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters permit_params :email, :encrypted_password, :first_name, ...
Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'activerecord-redshift-adapter-ng' s.version = '0.9.1' s.summary = 'Amazon Redshift adapter for ActiveRecord' s.description = 'Amazon Redshift _makeshift_ adapter for ActiveRecord.' s.license = 'MIT' s.author = ['Minero Aoki', 'Kenne...
module ReadOnlyResource extend ActiveSupport::Concern class ReadOnlyError < StandardError; end included do extend(ClassMethod) alias_method :save, :raise_error alias_method :save!, :raise_error alias_method :update, :raise_error alias_method :update_attri...
require_relative 'boot' require "decidim/rails" require "action_cable/engine" require 'fog/aws' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module DecidimSantCugat class Application < Rails::Application # Setti...
require_relative "../lib/my_select.rb" require_relative "./spec_helper.rb" describe "my_select" do let(:nums) { [1, 2, 3, 4, 5] } it "can handle an empty collection" do empty_array = [] saved_block = Proc.new { my_select(empty_array) do |x| raise "This block should not run!" end } ...
# frozen_string_literal: true require 'stannum/constraints/hashes' require 'stannum/constraints/hashes/extra_keys' module Stannum::Constraints::Hashes # Constraint for validating the keys of an indifferent hash-like object. # # When using this constraint, the keys must be strings or symbols, but it does # not...
module SportsDataApi module Nfl class Standings attr_reader :season, :type, :nfc, :afc def initialize(xml) conferences = xml.xpath('conference') @season = xml[:season].to_i @type = xml[:type] @afc = create_conference(conferences.first) @nfc = create_conference(c...
class DropOnpafpFromWorkers < ActiveRecord::Migration def change remove_column :workers, :onpafp end end
class RemoveHotelFromRoomCategory < ActiveRecord::Migration[5.0] def change remove_column :room_categories, :hotel end end
class CreateBanners < ActiveRecord::Migration def change create_table :banners do |t| t.string :desktop_image t.string :mobile_image t.string :mobile_url t.string :desktop_url t.string :desktop_size t.string :mobile_size t.integer :area, default: 0 t.timestamps nul...
require 'rails_helper' RSpec.describe Mood, type: :model do it { should validate_presence_of :local_date } it { should validate_presence_of :feeling } it { should have_one :team } end
#!/bin/ruby # Check that a version string is formatted correctly. def checkVersion(version) /[0-9]\.[0-9]\.[0-9]\.[0-9]/ =~ version end # Prompt the user for a file-name, re-prompting them in invalid input. def getVersion() print 'new-version> ' version=gets() if checkVersion(version) return ...
class CreateNotifications < ActiveRecord::Migration[5.1] def change create_table :notifications do |t| t.integer :recipient_id, null: false t.integer :actor_id t.datetime :read_at # 노티를 받은 사람이 노티를 언제 확인했는지 t.integer :target_id t.string :target_type t.string ...
class UserInterest < ActiveRecord::Base attr_accessible :subject_id, :user_id belongs_to :subject belongs_to :user end
class AddAgentToPlans < ActiveRecord::Migration[6.0] def change add_reference :plans, :agent, foreign_key: true end end
class Window_SaveConfirm < Window_Command def initialize(x, y, saving = false) @saving = saving super(x, y) @index = 0 self.back_opacity = 255 self.openness = 0 end def make_command_list if @saving add_command(Vocab::SAVE_OVERRIDE_QUESTION, :save_override) else add_command...
require 'app/models/beer' require 'app/models/ingredient' class BeerIngredient < ActiveRecord::Base belongs_to :beer, counter_cache: 'ingredients_count' belongs_to :ingredient, counter_cache: 'beers_count' end
class DatasetsController < ApplicationController before_action :check_date, only: :create # Create and store a csv report def create cc = ClientChannel.find_by(id: params[:channel]) @dataset = Dataset.new(title: file_name(cc), client_channel: cc, status: 'generating') if @dataset.save # Begin...
class ProjectsController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource def index if params[:status] @projects = current_user.projects.where('status = ?', params[:status]) @projects = current_user.is_admin? ? Project.all : current_user.projects else @projects = curren...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'StoreComments', type: :system do let!(:user) { create(:user) } let!(:other_user) { create(:user) } let!(:store) { create(:store) } let!(:store_comment) { create(:store_comment, user_id: user.id, store_id: store.id) } let!(:other_store_comm...
module Map global :width, :height def self.init opts = CONFIG.map_options @width = opts.width @height = opts.height define_tile_types TILES.tile_types, TILES.tile_statuses generate end def self.get_tile x, y tile = @tiles[x][y].to_s.split '_' type = tile[1] ...
# frozen_string_literal: true describe Facts::Macosx::SystemProfiler::ModelIdentifier do describe '#call_the_resolver' do subject(:fact) { Facts::Macosx::SystemProfiler::ModelIdentifier.new } let(:value) { 'MacBookPro11,4' } let(:expected_resolved_fact) do double(Facter::ResolvedFact, name: 'syste...
describe "User accounts" do describe "Sign up & Sign out" do it "a user can sign up" do visit('/signup') fill_in("username", :with => "lorem") fill_in("email", :with => "test@test.com") fill_in("user[password]", :with => "Password1!") fill_in("user...
require "spec_helper" RSpec.describe "does not warn when missing scope but scope inferred from prefix" do specify { expect { Asciidoctor.convert(<<~"INPUT", backend: :gb, header_footer: true) }.not_to output(/GB: no scope supplied, defaulting to National/).to_stderr } = Document title Author :docfile: te...
# frozen_string_literal: true module Quilt class HeaderCsrfStrategy HEADER = "x-shopify-react-xhr" HEADER_VALUE = "1" def initialize(controller) @controller = controller end def handle_unverified_request raise NoSameSiteHeaderError unless same_site? end private def sam...
FactoryGirl.define do factory :announcement do content 'This is a message!' title 'Hello' email true sms false factory :announcement_email do email true end factory :announcement_sms do sms true end factory :announcement_both do sms true email true en...
class Bid < ApplicationRecord belongs_to :round validates_presence_of :round validates :num_tricks, presence: true, numericality: {greater_than_or_equal_to: 6, less_than_or_equal_to: 10} validates :suit, presence: true, numericality: {greater_than_or_equal_to: -2, less_than_or_equal_to: 4} def score if self.su...
# encoding:UTF-8 class RequestNotifier < ActionMailer::Base default from: 'info@sledovani-realit.cz' # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.change_notifier.SearchInfoChangeSummary.subject # def NewRequestInfo(request) @request = request ...
require 'spec_helper' require 'alphabet_calc/alphabet_digit' describe AlphabetCalc::AlphabetDigit do describe 'initialize from alphabet' do it 'return correct value for "a"' do a = AlphabetCalc::AlphabetDigit.new('a') expect(a.to_int).to eq 0 end it 'return correct value for "z"' do z ...
class Bill < ActiveRecord::Base belongs_to :city belongs_to :state belongs_to :district belongs_to :country has_many :links has_many :votes, as: :votable has_many :comments, as: :commentable end
module SampleData # Methods to generate random data def random_string(length = 10) (0...length).map{ (65 + rand(26)).chr }.join end def random_url 'http://' + random_string + '.com' end def random_number(max = 50) rand(max) + 1 end def random_email random_string + '@' + random_strin...
class SessionsController < ApplicationController def new end def create user = User.find_by(username: params[:session][:username]) if user && user.authenticate(params[:session][:password]) session[:user_id] = user.id # flash[:success] = "You are logged in" redirect_to admin_panel_path else # flash...
Pod::Spec.new do |s| s.name = "ILPDFKit" s.version = "0.1.1" s.summary = "A simple toolkit for filling out and saving PDF forms, and extracting PDF data." s.homepage = "http://ilpdfkit.com" s.screenshot = "http://imgur.com/oo5HLUg.png" s.license = "MIT" s.author = { "Derek Blair" => ...
class ContactsController < ApplicationController before_filter :authenticate_user!, except: [:new, :create] before_action :check_admin_user, only: [:index] def index @contacts = Contact.all end def new @contact = Contact.new end def create @contact = Contact.new(contact_params) if @cont...
# encoding: utf-8 #!/usr/bin/env ruby require "bunny" require_relative "../config/rabbitmq" conn = Bunny.new(Config::RabbitMQ::CONF) conn.start ch = conn.create_channel x = ch.fanout("logs") # empty string means connect to a fresh new random queue # exclusive means to create non-durable queue (auto delete once disoc...
# frozen_string_literal: true describe DynVar do let(:default_value) { double(:default_value) } let(:variable) { DynVar.new(default_value) } around do |spec| begin aoe = Thread.abort_on_exception Thread.abort_on_exception = true spec.run ensure Thread.abort_on_exception = aoe ...
require_relative 'cpu_information' require_relative 'memory_information' require_relative 'disk_space_information' require_relative 'entropy_available' require_relative 'os_information' module KPM module SystemProxy module OS def OS.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RbConfig::CONFI...
require 'rails_helper' RSpec.describe "admin/prices/show", :type => :view do before(:each) do @plan = create(:plan_300) @service = create(:basic_service) @price = assign(:price, Price.create!( :plan_id => @plan.id, :app_service_id => @service.id )) end it "renders attributes in <p>" ...
# == Schema Information # # Table name: novels # # id :integer not null, primary key # summary :text(65535) # title :string(255) # created_at :datetime not null # updated_at :datetime not null # user_id :integer # # Indexes # # index_novels_on_user_id (user_id) # # Fo...
require 'rails_helper' RSpec.describe 'quiz/answer', type: :view do let!(:question) { create(:question) } before { assign(:question, question) } it "displays 'Correct'" do render expect(rendered).to include('Correct!') end end
class Role < ActiveRecord::Base include HasUrlSlug has_and_belongs_to_many :users validates :name, presence: true validates_uniqueness_of :name end
# GSPlan - Team commitment planning # # Copyright (C) 2008 Jan Schrage <jan@jschrage.de> # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU # General Public License as published by the Free Software Foundation, either version 3 of the License, # or (at your option) ...
# PEDAC # Write a method that takes a string and returns a boolean indicating # whether this string has a balaced set of parentheses # balancer("hi") == true # balanceer("(hi") == false # balanceer("(hi)") == true # balancer(")hi(") == false # Data Structures # Arrays # Algorithm # initiate an open_paren_counter to ...
module Tracker class Rack require 'benchmark' def initialize(app) @app = app end def call(env) @req = ::Rack::Request.new(env) if @req.path_info =~ /tracker.gif/ result = Services::Params.deploy @req.query_string location = Services::Locations.lookup(@req.ip) ...
require 'minitest/autorun' require 'minitest/pride' require './lib/card_generator' class CardGeneratorTest < MiniTest::Test def test_it_exists card_generator = CardGenerator.new("cards.txt") assert_instance_of CardGenerator, card_generator end def test_it_has_readable_attributes card_generator = Car...
class AddChurchIdToSermon < ActiveRecord::Migration def change add_column :sermons, :church_id, :integer add_index :sermons, :church_id end end
# Class to represent the player class Player attr_accessor :name, :mark, :order ## # Constructor # # Parameters # # name [String] Player's name # mark [String] Player's mark # order [Integer] Player's order # def initialize(name, mark, order) @name = name @mark = mark @order =...
require 'spec_helper' describe 'zookeeper::service' do let(:facts) {{ :operatingsystem => 'Debian', :osfamily => 'Debian', :lsbdistcodename => 'wheezy', }} it { should contain_package('zookeeperd') } it { should contain_service('zookeeper').with( :ensure => 'running', :enable => true )} ...
class TasksController < ApplicationController respond_to :html, :js before_action :set_task, only: [:update, :destroy] def index authorize Task @tasks = current_user.tasks.hide_completed end def new @task = Task.new authorize @task end def create @task = current_user.tasks.new(task_...
module Components module AccordionButton class AccordionButtonComponent < Middleman::Extension helpers do def accordion_button(opts = nil) additional_classes = opts.dig(:html, :class) ? (opts[:html][:class]).to_s : '' link_to link_text(opts[:text]), 'javascript:...
require File.expand_path('../lib/usda/version', __FILE__) Gem::Specification.new do |s| s.name = "usda" s.version = Usda::VERSION s.authors = ["Ian C. Anderson"] s.email = ["anderson.ian.c@gmail.com"] s.summary = "USDA on Rails" s.description = "Provides models to interact with Usda dat...
namespace :db do desc "Inserisco faker data + admin nel db" task populate: :environment do puts "Popolo il database..." make_users make_posts make_relationships make_private_messages end end def make_users admin = User.create!(name: "Marika Pinori", ...
class CreateFeedItems < ActiveRecord::Migration def self.up create_table :feed_items do |t| t.string :feed_type t.references :referenced_model, :polymorphic => true t.belongs_to :user t.timestamps end end def self.down drop_table :feed_items end end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you ...
class AddTimeOfGuessToPlayers < ActiveRecord::Migration def change add_column :players, :time_of_guess, :integer end end
# encoding: utf-8 require "application_responder" class ApplicationController < ActionController::Base helper :all self.responder = ApplicationResponder respond_to :html, :json, :xml WillPaginate.per_page = 10 before_filter :authenticate_user! #before_filter :current_blog, :unless => :devise_controller? ...
namespace :billing do desc 'Remind before account is expired' # $ rake billing:remind task :remind => :environment do puts '*** Reminder for subscriptions about to expire ***' Company.trial.each do |company| if company.trial? && company.notified_trial_will_expire_on.nil? if company.trial_exp...
class Public::ProductsController < ApplicationController PER = 8 def index @genres = Genre.where(status: "1") # urlにgenre_idがある場合 if params[:genre_id] @genre = Genre.find_by(params[:genre_id]) # 降順で表示 @products = Product.where(genre_id: params[:genre_id]).page(params[:page]).per(PER) @products_coun...
class AddMeetingPlaceAndEndingPlaceToPrograms < ActiveRecord::Migration def change add_column :programs, :meeting_place, :text add_column :programs, :ending_place, :text end end
require 'test/unit' require '../../lib/global/globalDef' require '../../lib/js/jsFileReader' module Jabverwock using StringExtension using ArrayExtension class JsFileReaderTest < Test::Unit::TestCase class << self # テスト群の実行前に呼ばれる.変な初期化トリックがいらなくなる def startup p :_startup e...
class ChangeDateFormatInMyTable < ActiveRecord::Migration[5.0] def up change_column :events, :when, :datetime end def down change_column :events, :when, :date end end
module CsvToEmail class Person include Comparable attr_accessor :max_lastname_length, :firstname, :lastname, :email def initialize opts @firstname = opts[:firstname] @lastname = opts[:lastname] if lastname.length < config.default_max_lastname_length @max_lastname_length = lastn...
class ChangeUserRefOnAccounts < ActiveRecord::Migration[5.2] def change rename_column :accounts, :users_id, :user_id end end
class DeleteRelationshipsCreatedByBots < ActiveRecord::Migration def change Rails.cache.write('check:migrate:delete_relationships_created_by_bots:progress', nil) end end
class EntityPositionAdapter # @param [Entity] obj def initialize(obj) @obj = obj @position = Moon::Vector2.new(0, 0) end # @return [Vector2] def position p = @obj[:transform].position @position.set p.x, p.y @position end end
describe Bothan::App do context 'sets the correct visualisation types' do it 'with a single metric type' do Metric.create( name: "simple-metric", time: DateTime.now - 1, value: rand(100) ) get '/metrics/simple-metric' follow_redirect! body = Nokogiri::HTML...
require 'rails_helper' RSpec.describe 'User Profile', :type => :feature do let(:user) { create(:user) } let(:new_email) { 'new@email.com' } let(:new_password) { 'new_password' } describe 'change user data', js: true do before do sign_in user visit edit_user_registration_path end it 'c...
describe Category do subject(:category) { described_class.new } it { is_expected.to respond_to(:name) } end
class Person attr_reader :name, :age def name(value) @name = value self end def age=(value) @age = value self end def books ['Cien años de soledad', 'El coronel no tiene quien le escriba'] end def filter_by(items, name:) puts items puts name items end end one_perso...