text
stringlengths
10
2.61M
class RenameQueryTableToTable < ActiveRecord::Migration def change rename_table :query_tables, :tables end end
feature 'Peeps' do scenario 'expect profile page to display all peeps' do visit('/') submit_peep expect(page.current_path).to eq '/profile' expect(page).to have_content 'My first test peep!' end scenario 'expect homepage to have display peeps when logged out' do visit('/') submit_peep ...
#!/usr/bin/env ruby # # Created by nwind on 2008-1-4. Name = File.basename(__FILE__) def usage "USAGE: #{Name} file_path " end def px2em(file) unless FileTest.exists?(file) puts '#{ARGV[0]} doen\'t exist' exit end styles = IO.read(file).gsub(/\s*-?\d*px/) do |px| sprintf(" %.1fem", px[0..-...
class MenusRole < ApplicationRecord belongs_to :menu belongs_to :role end
require 'rails_helper' RSpec.describe 'Cycle#create', :ledgers, type: :system do before { log_in admin_attributes } context 'when Term' do it 'adds due date', js: true do cycle_page = CyclePage.new type: :term cycle_create id: 1, due_ons: [DueOn.new(month: 3, day: 25)] expect(Cycle.first.due...
require 'eventmachine' require 'cairo' module MiW autoload :KeySym, "miw/keysym" autoload :Layout, "miw/layout" autoload :Menu, "miw/menu" autoload :MenuBar, "miw/menu_bar" autoload :MenuItem, "miw/menu_item" autoload :MenuWindow, "miw/menu_window" autoloa...
module Sales class Sale < ApplicationRecord self.table_name = "sales" belongs_to :sales_person belongs_to :company end end
class AddTopicIdToReasons < ActiveRecord::Migration[5.0] def change create_table :procedures do |p| p.belongs_to :topic, null: false p.belongs_to :patient, null: false p.belongs_to :clinician p.integer :visit_id p.timestamps null: false end create_table :complications do |c|...
json.topic do json.extract! @topic, :name, :id end
class ChangeUrlTypeToText < ActiveRecord::Migration def up change_column :hyperlinks, :url, :text, null: false end def down change_column :hyperlinks, :url, :string, null: false end end
class Theme class Template < File class << self def valid?(path) @@template_types.keys.include?(extname(path)) end def subdirs %w(templates) end end def text? true end def valid? self.class.valid?(localpath) && valid_path? end def val...
# хелпер # по большей части используются просто обертки для бутстраповых элементов, # которые используются повсеместно module Admin::AdminHelper delegate :url_helpers, to: 'Rails.application.routes' def empty_list content_tag :div, 'Пусто', class: 'well' end # все языки def get_languages Language.a...
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) Gem::Specification.new 'require_pattern', '1.1.2' do |s| s.summary = 'Requires files based on a pattern in a robust and optimistic manner.' s.authors = ['Tom Wardrop'] s.email = 'tom@tomwardrop.com' s.homepage = 'h...
#--- # Excerpted from "Rails 4 Test Prescriptions", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit ...
# The controller for schedule related pages and actions, such as the schedule page # as well as creating and editing categories # TODO: Most requests should enforce user being signed in, as data can't be made anonymously class SchedulesController < ApplicationController # Only admins can access the beta scheduler ...
class CreatePieces < ActiveRecord::Migration def change create_table :pieces do |t| t.string :type t.string :subtype t.string :color t.string :brand t.string :size t.date :date_purchased t.decimal :price t.string :source t.attachment :picture t.text :not...
# frozen_string_literal: true class UserPolicy < ApplicationPolicy ADMIN_ATTRIBUTES = %i[ email password password_confirmation admin first_name last_name company phone address_id coordinator_id status profession printer_ids tag_ids printers_attributes a...
require 'spec_helper' describe 'sensu::server', :type => :class do let(:title) { 'sensu::server' } context 'defaults' do let(:facts) { { :fqdn => 'testhost.domain.com' } } it { should contain_sensu_redis_config('testhost.domain.com').with_ensure('absent') } it { should contain_sensu_api_config('testho...
class CreateLunch < ActiveRecord::Migration def change create_table :lunches do |t| t.string :price t.references :lunchable, polymorphic: true end end end
class MyTradeShipProfitObject attr_accessor :view_context, :show_profit def initialize(view_context, show_profit: ) self.view_context = view_context self.show_profit = show_profit end def table_first_header view_context.content_tag('th', colspan: (show_profit ? 3 : 2)) do if !show_profit ...
class Api::V1::BaseController < ApplicationController before_action :doorkeeper_authorize! protect_from_forgery with: :null_session rescue_from CanCan::AccessDenied do |e| head :forbidden end private def current_user current_resource_owner end def current_resource_owner @current_...
FactoryGirl.define do factory :role do sequence(:name) { |i| "Role #{i + 1}" } event_id { Event.first.id } end end
class CreateExport < ActiveRecord::Migration def up create_table :exports do |t| t.references :user, index: true t.string :export_type t.string :prefix t.boolean :active, default: true t.datetime :started_at t.datetime :finished_at t.string :error_msg t.timestamps ...
class AddRecordactionToActionlogs < ActiveRecord::Migration def change add_column :actionlogs, :recordaction_id, :integer add_index :actionlogs, :recordaction_id end end
class AddOrderIdToReservation < ActiveRecord::Migration[5.0] def change add_column :reservations, :order_id, :string, :default => "11111111" end end
#!/usr/bin/env ruby require 'marc' require 'ostruct' abort "Usage: ruby yrb.rb <MARC_FILE>" unless ARGV.size == 1 MAX_EACH_FILE = 20 reader = MARC::Reader.new ARGV[0], extenal_encoding: "UTF-8" accounts = { '175009': 'US Approvals', '175010': 'US Firms', '175059': 'UK Approvals', '175060': 'UK Firms', '1...
# 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...
class ProjectsController < ApplicationController before_action :fetch_project, only: [:show, :update, :destroy] before_action :handle_already_enabled, only: [:create] before_action :authenticate_user!, raise: false def new @organization_names = [current_user.github_id].concat(github_service.organization_n...
class ItemOptionAddon < ActiveRecord::Base attr_accessible :item_option_id, :name, :price, :is_selected, :is_deleted belongs_to :item_option has_many :order_item_options validates :name , length:{minimum: 1, message:"^Addon Name can't be blank"} validates :price ,:presence =>true default_scope :order => "...
require 'erb' require File.expand_path(File.join(File.dirname(__FILE__), 'dependencies')) class PardotListAddProspectV1 def initialize(input) # Set the input document attribute @input_document = REXML::Document.new(input) # Store the info values in a Hash of info names to values. @info_values = {} ...
%w{dovecot-common dovecot-imapd}.each do |p| package p do action :install end end service "dovecot" do supports :restart => true, :start => true, :stop => true action :nothing end template "/etc/dovecot/passwd" do source "passwd.erb" mode "0640" owner "root" group "root" variables ({ :domains => node[:do...
require 'SimpleCov' SimpleCov.start require_relative '../lib/invoice_item_repository' RSpec.describe InvoiceItemRepository do before :each do @iir = InvoiceItemRepository.new('./spec/fixture_files/invoice_item_fixture.csv') end it 'exists' do expect(@iir).to be_an_instance_of(InvoiceItemRepository) e...
class AdvanceSearch < ActiveRecord::Base def transactions @transactions||=find_transactions end # Start Date getter def start_date_string start_date.strftime("%m/%d/%Y") unless start_date.blank? end #setter def start_date_string=(start_date_str) self.start_date=Date.strptime(start_date_str,...
class User < ActiveRecord::Base has_secure_password has_many :airports has_many :reviews, through: :airports end
class Quote < ApplicationRecord validates :author, presence: true validates :content, presence: true # scope for searching for author and content # where - like ? allows for a little more flexible search query? # need % for the string interpolation for for it to work with the api call? scope :search_author, -> (a...
# frozen_string_literal: true require 'spec_helper' class Example include Capybara::DSL include CapybaraErrorIntel::DSL def has_selector_test? has_selector?(:css, 'h1', text: 'test') end def has_text_test? has_text?('test_text') end def has_title_test? has_title?('test_title') end end ...
require 'spec_helper' describe JobSphere do context 'fields' do it { should have_db_column(:name).of_type(:string) } end context 'mass assignment' do it { should_not allow_mass_assignment_of(:id) } it { should allow_mass_assignment_of(:name) } it { should_not allow_mass_assignment_of(:created_a...
FactoryGirl.define do factory :user do sequence(:username) { |n| "Montblanc#{n}" } sequence(:email) { |n| "iloveinks#{n}@gmail.com" } password 'password' admin false end factory :ink do sequence(:color_name){ |n| "Baystate Blue #{n}" } manufacturer "Noodler's" description 'A pigmented...
require 'test_helper' class PcrInspectionsControllerTest < ActionDispatch::IntegrationTest setup do @pcr_inspection = pcr_inspections(:one) end test "should get index" do get pcr_inspections_url assert_response :success end test "should get new" do get new_pcr_inspection_url assert_resp...
class RemovePhotosCountFromPhotos < ActiveRecord::Migration[5.1] def change remove_column :photos, :photos_count, :decimal end end
class WithoutLayout::PostsBaseController < PostsBaseController def render_json_to_page_changes render 'posts/show.html.erb' response.content_type = "application/json" response.body = { :body => response.body, :title => @post.title, :sharing_head => @sharing_head.to_hash }.to_json e...
class Comment < ActiveRecord::Base attr_accessible :content belongs_to :commentable, :inverse_of => :comments, :polymorphic => true belongs_to :user, :inverse_of => :comments validates_presence_of :user, :user_id validates_presence_of :commentable, :commentable_id, :commentable_type validates_presence_o...
require 'spec_helper' # find all parameters that don't have default values and put in here # ensure validation occurs describe Puppet::Type.type(:certmonger_certificate) do let(:valid_booleans) { [true, false, 'true', 'false'] } context 'with empty name' do let(:name) { '' } it 'raises ArgumentError if n...
class VoteOption < ActiveRecord::Base belongs_to :poll validates :title, presence: true has_many :votes, dependent: :destroy end
require "rails_helper" require "nokogiri" RSpec.describe ApplicationInstance, type: :model do describe "create application" do before :each do @site = create(:site) @name = "An Example application" @key = "example" @application = create(:application, name: @name, key: @key) end i...
class MemberPresenter < BasePresenter presents :member def profile_full_name_field text_field_tag :profile_full_name, [], size: 35, placeholder: "Start typing and profile names will appear...", autofocus: true, class: 'text' end end
TAX = {"北海道" => 0.0685, "東日本" => 0.08, "西日本" => 0.0625, "四国" => 0.04, "九州" => 0.0825} DISCOUNT = {1000 => 0.03, 5000 => 0.05, 7000 => 0.07, 10000 => 0.10, 50000 => 0.15} def discount_rate sum if (sum < 1000) return 0 elsif ( sum < 5000 ) return 0.03 elsif ( sum < 7000 ) return 0.05 elsif ( sum < 10...
class Size < ActiveRecord::Base attr_accessible :atlas_id, :level, :label, :default_radius belongs_to :atlas has_many :tags def self.atlas(index) where(:atlas_id => index) end end
require_relative 'test_helper' class SeasonStatsTest < Minitest::Test def setup game_path = './data/games.csv' team_path = './data/teams.csv' game_teams_path = './data/game_teams.csv' locations = { games: game_path, teams: team_path, game_teams: game_teams_path } @stat_tracke...
class Exchange::Huobi < Exchange::Base attr_reader :user, :currency def initialize(user, currency) @user = user @currency = currency end def id 'huobi' end def balance begin result = client.contract_balance('USDT') balance = result['data'].find {|i| i['valuation_asset'] == 'US...
class CreateLoyalties < ActiveRecord::Migration[5.1] def change create_table :loyalties do |t| t.integer :loyalty_type t.integer :loyalty_points_percentage t.timestamps end end end
# typed: strict # frozen_string_literal: true module Packwerk class Result < T::Struct prop :message, String prop :status, T::Boolean end end
# frozen_string_literal: true Rails.application.routes.draw do devise_for :users, controllers: { registrations: :registrations, omniauth_callbacks: "users/omniauth_callbacks" } root to: 'static_pages#landing_page' get 'static_pages/about' get 'static_pages/contact' get ...
require 'spec_helper' describe WavelabsClientApi::Client::Api::Core::MediaApi do let(:login_user) {UserSignUp.login_user} let (:media_api_obj) { WavelabsClientApi::Client::Api::Core::MediaApi.new} let (:media_api) { WavelabsClientApi::Client::Api::Core::MediaApi} it "#check_connection?" do expect(media_api...
# frozen_string_literal: true class AddTokenToUsers < ActiveRecord::Migration[5.2] def change change_table :users do |u| u.string :api_key end end end
class WordFormatter def initialize(string) @string = string end def camelify @string.split.map(&:capitalize).join end def format_postcode joined_str = @string.split.map(&:upcase).join joined_str.chars.each_slice(3).map(&:join).join(' ') end end
require 'rails_helper' Rails.application.load_seed # Return Type: Record describe "Query: Movie.find(1)" do it "lists one Movie record with all columns" do visit "/" fill_in "Enter a Query", with: "Movie.find(1)" click_on "Execute" movie = Movie.find(1) within "tbody" do expect(...
require "spec_helper" class Search < ActiveRecord::Base; end describe Scenic::SchemaDumper, :db do it "dumps a create_view for a view in the database" do view_definition = "SELECT 'needle'::text AS haystack" Search.connection.create_view :searches, sql_definition: view_definition stream = StringIO.new ...
require "slack-ruby-bot" class Bot < SlackRubyBot::Bot help do title "DJ" desc "Ask me to queue up music" end command "ping" do |client, data, match| client.say(text: "pong", channel: data.channel) end end require "commands"
require 'yaml' require_relative 'src/evie.rb' # Make sure that static files are served from # public which seems to be off by default with Rack run Rack::Directory.new("./public") # https://github.com/hashicorp/vault-ruby if ENV['VAULT_TOKEN'].nil? raise ArgumentError, 'VAULT_TOKEN env is not defined.' end # http...
class ApplicationMailer < ActionMailer::Base default from: "noreply@verifyonline.in" layout 'mailer' end
require "application_system_test_case" class JobsTest < ApplicationSystemTestCase setup do @job = jobs(:one) end test "visiting the index" do visit jobs_url assert_selector "h1", text: "Jobs" end test "creating a Job" do visit jobs_url click_on "New Job" fill_in "Command", with: @j...
class WinesController < ApplicationController before_filter :current_user def index @wines = Wine.paginate(page: params[:page]) end def show @wine = Wine.find(params[:id]) @user = current_user end end
#!/usr/bin/env ruby lib = File.expand_path File.join(__dir__, '../lib') $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'optparse' require 'timelapser' $stdout.sync = true $stdin.sync = true options = { interval: 1.0, save_to: '~/Pictures/timelapses' } OptionParser.new do |opts| opts.banner =...
class AddBenFieldsToUsers < ActiveRecord::Migration def change add_column :users, :empid, :integer add_column :users, :emp_class, :string add_column :users, :emp_home, :string end end
# frozen_string_literal: true require_relative 'views' module Statistics class UniquePageViews < Views attr_reader :page_views_by_ip private # @return [Hash] the resulting hash, e.g. # { "url" => value }, where `value` is the unique views count def analyze! page_views = page_views_stats_...
require 'rails_helper' RSpec.describe Micropost, type: :model do let(:mp) { build :micropost } it '正常系' do expect(mp.save).to be_truthy end it 'messageの存在性チェック' do mp.message = '' expect(mp.valid?).to be_falsy end it 'messageの長さチェック' do mp.message = 'a' * 140 expect(mp.valid...
require 'rails_helper' RSpec.describe Matchmaker do describe "#choose" do let(:matchmaker) { Matchmaker.new(players) } let(:least_recently_played_player) do FactoryGirl.create :player, name: "Least", active: true end subject { matchmaker.choose } context "when there are no players" do ...
require "spree/core" module SpreePos class Configuration < Spree::Preferences::Configuration preference :pos_shipping, :string preference :pos_printing, :string , :default => "/admin/invoice/number/receipt" end end
class Money USD = 'USD'.freeze CHF = 'CHF'.freeze attr_reader :amount, :code def initialize(amount = 0, code) @amount = amount @code = code end def times(value) self.class.new(amount * value, code) end def self.dolar(value) Dolar.new(value, USD) end def self.franc(value) Fran...
require 'rails_helper' RSpec.describe Product, :type => :model do before(:each) do @product = FactoryGirl.build(:product) end describe 'title' do it 'must be present' do @product.title = '' expect { @product.save! }.to raise_exception(ActiveRecord::RecordInvalid) expect(Product...
module Geometry class Rectangle < Struct.new(:x, :y, :width, :height) def area (self.width - self.x).abs*(self.height - self.y).abs rescue 0 end def empty? self.area == 0 end def intersection_with(rect) return Rectangle.new if rect.empty? || self.empty? l1, r...
class CasesController < ApplicationController def new @case = Case.new @atlas = Atlas.find_by_id(params[:atlas_id]) @reports = Report.where(:atlas_id => @atlas.id) end def create if params[:case] @case = Case.new(params[:case]) @case.atlas_id = params[:atlas_id] @case.save @case.add_reports(para...
module CommentMutations MUTATION_TARGET = 'comment'.freeze PARENTS = ['project_media', 'source', 'project', 'task', 'version'].freeze module SharedCreateAndUpdateFields extend ActiveSupport::Concern include Mutations::Inclusions::AnnotationBehaviors included do field :versionEdge, VersionType....
module EasyJournalHelper def easy_journal_render_history(easy_journals, options={}) return if easy_journals.nil? || easy_journals.empty? options ||= {} options[:back_url] = url_for(params) journals = '' easy_journals.each do |journal| details = '' details << content_tag(:h4, content_...
class BidsController < ApplicationController # Bids will go up in one dollar increments, note all amounts are in cents (integers) INCREMENT = 100 def new @bid = Bid.new end # The logic in this method needs to be pulled out and placed into the respective model def create # Set up the new bid @bid = Bid.ne...
class ChangeYearBuiltToInteger < ActiveRecord::Migration[5.0] def change change_column :estates, :year_built, :integer end end
class Cell def initialize(opts) @live = opts[:state] == :live end def live? @live end def next_state false end end
#encoding: utf-8 class Work < ActiveRecord::Base belongs_to :schoolyear belongs_to :student attr_accessible :cycle, :student, :technique, :title, :student_id, :schoolyear_id validates :title, :presence => true validates :technique, :presence => true validates :student, :presence => true validates :sc...
require 'mongo_active_instrumentation/controller_runtime' module MongoActiveInstrumentation class Railtie < Rails::Railtie initializer "mongo_active_instrumentation" do |app| Mongo::Monitoring::Global.subscribe( Mongo::Monitoring::COMMAND, MongoActiveInstrumentation::LogSubscriber.new ...
class Admin::SortController < Admin::AdminController # POST /admin/sort def sort class_name = params[:class_name] sortable = params[class_name.to_sym] sortable.each_with_index do |id, index| class_name.camelize.constantize.where(id: id).update_all(position: index+1) end render noth...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :lockable, :trackable #nameは必ず...
class HousesController < ApplicationController before_action :set_house, only: [:show, :update, :destroy] def index render json: House.all end def create render json: House.create(house_params) end def show render json: @house end def update render json: @house.update(house_params...
require 'spec_helper' describe HomeController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end it "sets title and welcome message" do get 'index' response.should be_success assigns(:title).should eq('Outlaws Softball') ...
module Student class SkillsUsersController < BaseController before_action :set_skill, only: [:show, :destroy] def index @skills = current_user.skills_users end def new @skill = current_user.skills_users.new end def create @skill = current_user.skills_users.new(skill_params...
require 'digest' class Bot::Smooch < BotUser class MessageDeliveryError < StandardError; end class FinalMessageDeliveryError < MessageDeliveryError; end class TurnioMessageDeliveryError < MessageDeliveryError; end class SmoochMessageDeliveryError < MessageDeliveryError; end class CapiMessageDeliveryError < M...
# frozen_string_literal: true require_relative 'lib/monkeylang/version' Gem::Specification.new do |spec| spec.name = 'monkeylang' spec.version = MonkeyLang::VERSION spec.authors = ['Farid Zakaria'] spec.email = ['farid.m.zakaria@gmail.com'] spec.summary = 'A Ruby implemen...
# frozen_string_literal: true module SitePrism module ElementChecker def all_there? elements_to_check.all? { |element| present?(element) } end def elements_present mapped_items.select { |item_name| present?(item_name) } end private def elements_to_check if self.class.expe...
class User < ActiveRecord::Base devise :database_authenticatable, :rememberable has_many :posts has_many :images validates :email, presence: true, format: { with: /.+@.+\..+/i }, uniqueness: true validates :password, presence: true, length: { minimum: 8 }, confirmation: true 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 ...
# frozen_string_literal: true require 'structures/doubly_linked_list' module Structures # +Structures::Queue+ represents a Queue class Queue def initialize @list = Structures::DoublyLinkedList.new end def empty? @list.empty? end def offer(item) @list.add_last(item) end ...
class CreateTaskListService include Auth::JsonWebTokenHelper def call(payload_json) @payload = JSON.parse(payload_json) @task_list = TaskList.new(create_task_params) if @task_list.save task_list_data else unprocessable_entity end end private def task_list_data { h...
class AddAvailabilityIdInMeetings < ActiveRecord::Migration[6.0] def change add_reference :availabilities, :availability, foreign_key: true end end
class ChallengesController < ApplicationController def index @contest = Contest.current @challenges = @contest.challenges end end
#!/usr/bin/env ruby VERSION='1.1.0' $:.unshift File.expand_path('../../lib', __FILE__) require 'hashie' require 'devops_api' require 'pry' require 'awesome_print' class Api include DevopsApi end begin opts = Slop.parse(strict: true, help: true) do banner "Domain Cutover List Hosted Zones, version #{VERSION...
class PhoneNumbersController < ApplicationController def index @phone_numbers = PhoneNumber.all end def edit @phone_number = PhoneNumber.where(id: params['id']).first end def new @phone_number = PhoneNumber.new @person = Person.find_by_id(params[:person_id]) end def create @phone_nu...
class CreateArticles < ActiveRecord::Migration[5.1] def change create_table :articles do |t| t.integer :Articleno, null: false t.string :Regno, foreign_key: true t.text :abstract t.string :Articletype t.string :Language t.text :article t.string :Status t.references ...
module Adornable class Decorators def self.log(method_receiver, method_name, arguments) receiver_name, name_delimiter = if method_receiver.is_a?(Class) [method_receiver.to_s, '::'] else [method_receiver.class.to_s, '#'] end full_name = "`#{receiver_name}#{name_delimiter}#{m...
require 'rails_helper' require 'base64' RSpec.describe Ng::V1::VehiclesController, type: :controller do let(:user) { User.first } let(:user_auth_data) { Base64.strict_encode64("#{user.email}:test@1234") } let(:vehicle) { Vehicle.first } let(:vehicle_2) { Vehicle.last } describe 'GET #index' do context '...
class Word def initialize(word) @word = word end end