text
stringlengths
10
2.61M
class Blog < ActiveRecord::Base validates :title, presence: true validates :account_name, presence: true, uniqueness: true belongs_to :maid has_many :posts def self.import_info(maid, url) if url info = HomePageCrawler.blog_detail(url) self.create(maid_id: maid.id, title: info[:title], accoun...
class ApplicationController < ActionController::Base helper :all # include all helpers, all the time helper_method :can_create_accounts? #, :has_permission? helper_method :home_path, :in_epr? protect_from_forgery #:secret => 'b3fbefe926ee038a7584a15aaefcf762' filter_parameter_logging :password # Filters th...
class AddNameColumnToDocuments < ActiveRecord::Migration def change add_column :documents, :name, :string add_column :documents, :class, :string add_column :documents, :s3_key, :string add_column :documents, :s3_bucket, :string add_column :documents, :url, :string end end
# encoding: utf-8 require 'net/http' require './config/environments' require './models/tickerSymbol' require './models/dataPayload' desc 'Gather TickerSymbols, ping Yahoo Finance APi, temporarily store response' task :refreshPayload do def assemble_symbols(type) if type == 'All' || type.nil? @ticker_list =...
class PostingApplicationsController < ApplicationController def all @posting_applications = PostingApplication.where(student: current_account.student) end def create @posting_application = current_account.student .posting_applications.build(posting_id: params[:posting_id]) ...
class AddStatusToTask < ActiveRecord::Migration[5.1] def change add_column :tasks, :status, :integer, :null => false, :default => 0 add_column :tasks, :locale, :integer, :null => false, :default => 0 end end
require_relative 'stock' class Portfolio attr_accessor :name, :stocks def initialize(name) @name = name @stocks = {} end def add_stock(name, quantity) @stocks[name] = Stock.new(name, quantity) end def remove_stock(name) @stocks[name] = nil end def get_stock_balance total = 0 ...
Then /^I should see "([^\"]*)" followed by "([^\"]*)"$/ do |string1, string2| regexp = Regexp.new("#{Regexp.escape string1}.*#{Regexp.escape string2}", Regexp::MULTILINE) if defined?(Spec::Rails::Matchers) response.should contain(regexp) else assert_contain regexp end end Then /^the response should be ...
class River attr_reader :name, :fish def initialize(name, fish) @name = name @fish = fish end def fish_count return @fish.count() end end
# frozen_string_literal: true FactoryBot.define do factory :item do name { SecureRandom.uuid } visibility { :publicly_visible } lifetime_amount { nil } lifetime_unit { :month } valid_from { nil } valid_until { nil } organization Item.kinds.each do |key, _value| trait key.to_sym...
require_relative '../../environment' require 'minitest/spec' require 'minitest/autorun' require 'classes/race' require 'classes/body_part' require 'classes/effect' describe Race do before do @name = "Dwarf" attributes = { :strength => 30, :dexterity => 20, :agility => 20, :endurance =...
json.array!(@board_studies) do |board_study| json.extract! board_study, json.url board_study_url(board_study, format: :json) end
class AddOsVirtualProcessorCountToNode < ActiveRecord::Migration def self.up add_column :nodes, :os_virtual_processor_count, :integer add_index :nodes, :os_virtual_processor_count end def self.down remove_column :nodes, :os_virtual_processor_count end end
God.watch do |w| w.name = "appscale-controller-17443" w.group = "controller" w.interval = 30.seconds # default w.start = "ruby /root/appscale/AppController/djinnServer.rb" w.stop = "ruby /root/appscale/AppController/terminate.rb" w.log = "/var/log/appscale/controller-17443.log" w.pid_file = "/var/appscal...
require 'test_helper' class PersonCocoonsControllerTest < ActionDispatch::IntegrationTest setup do @person_cocoon = person_cocoons(:one) end test "should get index" do get person_cocoons_url assert_response :success end test "should get new" do get new_person_cocoon_url assert_response ...
#!/usr/bin/ruby class Animal attr_reader :legs, :sound attr_writer :type attr_accessor :name def initialize(legs = 4, sound = "MmmmKROOOOOOOO", type = "Platypus", name = "Martin") @legs = legs @sound = sound @type = type @name = name end def speak() puts @sound end end
class AddPictureToCharities < ActiveRecord::Migration def change add_column :charities, :picture, :string end end
class Article < ActiveRecord::Base attr_accessible :teacher, :recorded, :sound, :image, :title, :content, :tag_list has_many :taggings has_many :tags, through: :taggings def self.tagged_with(name) Tag.find_by_name!(name).articles end def self.tag_counts Tag.select("tags.*, count(taggings.tag_id) as co...
module Concerns::BoardComment::Method extend ActiveSupport::Concern included do before_save :normalize_newlines scope :publishes, -> {where(public: true)} scope :unpublishes, -> {where(public: false)} scope :nil_publics, -> {where(public: nil)} end module ClassMethods end private #==...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception around_filter :set_time_zone protected def grab_user auth_token = params[:auth_token] raise SlyErrors::...
ActiveAdmin.register User do index do column :company_name column :last_name column :first_name column :position column :email column :address column :phone column :country column :city default_actions end form do |f| f.inputs do f.input :company_name f.inp...
Rails.application.routes.draw do get 'card/new' get 'card/show' devise_for :users, controllers: { registrations: 'users/registrations', sessions: 'users/sessions', } devise_scope :user do get 'addresses', to: 'users/registrations#new_address' post 'addresses', to: 'users/registrations#create_a...
class CreateContentTopicsValues < ActiveRecord::Migration def change create_table :content_topics_content_values do |t| t.references :content_topic t.references :content_value end end end
class Api::CartItemsController < Api::BaseController include AnonymousController skip_before_action :authenticate_user! def index current_cart = current_anonymous_or_user.cart render json: {items_count: current_cart.items_count} end def create current_cart = current_anonymous_or_user.cart ...
# This migration comes from maestrano_connector_rails_engine (originally 20160205132857) class AddSyncEnabledToOrganizations < ActiveRecord::Migration def change add_column :organizations, :sync_enabled, :boolean, default: false end end
class AddStepTypeIdToDealStep < ActiveRecord::Migration def self.up add_column :deal_steps, :step_type_id, :integer end def self.down remove_column :deal_steps, :step_type_id end end
require 'spec_helper' describe Category do let(:category) { FactoryGirl.build(:category) } it "has a valid factory" do expect(category).to be_valid end describe "validation" do it "validates category has a name" do category.name = nil expect(category).not_to be_valid end it "val...
class Answer < ApplicationRecord belongs_to :question validates :body, presence: true validate :has_answers scope :correct, -> { where(correct: true) } private def has_answers errors.add(:base, "Question have many answers") if (question && question.answers.size > 4) end end
# encoding: UTF-8 require "bigdecimal" # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 [Integer, Float, BigDecimal].each do |klass| TwitterCldr::Localized::LocalizedNumber.localize(klass) end [Array, Date, DateTime, String, Symbol, Time, Hash].each do |klass| TwitterCldr::Localized::co...
require 'open3' class Emulator def initialize(emulator_path) self.emulator_path = emulator_path end def run(script_path) _, error, status = Open3.capture3(*interpreter, emulator_path, script_path) [error, status] end private attr_accessor :emulator_path def interpreter shebang_line.sl...
module Domain class Root class BoardNotFound < StandardError end class BoardAlreadyExists < StandardError end def create_board(id:, title:) raise BoardAlreadyExists if @boards.any?(&by(id)) @boards << (Board.new(id:, title:)) Events::Board::Created.new(id:, title:) end ...
class Actor < ApplicationRecord has_many :actors_films has_many :films, through: :actors_films end
require 'spec_helper' describe Banker::LloydsTSBUK do TEST_FIELD = { username: 'frmLogin:strCustomerLogin_userID', password: 'frmLogin:strCustomerLogin_pwd', memorable_word: [ 'frmentermemorableinformation1:strEnterMemorableInformation_memInfo1', 'frmentermemorableinformation1:strEnterMemorab...
class Author < ActiveRecord::Base has_and_belongs_to_many :books validates :first_name, :last_name, :presence => true end
Rails.application.routes.draw do scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do root to: 'tasks#index' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :tasks resources :users end resources :account_a...
class AddFieldsToLawyers < ActiveRecord::Migration def change add_reference :lawyers, :state, index: true, foreign_key: true add_reference :lawyers, :city, index: true, foreign_key: true end end
module Notification::Handles class WebHandle < Base def self.deliver(event, users) users.each do |user| notification = find_or_create_notification(event, user) # Notification::WebNotification.create(notification: notification) end end end end
class DemandedProductSerializer include FastJsonapi::ObjectSerializer attributes :product_id, :amount end
require_relative "logging" require 'json' module Crawler module Api class Tokens class EmptyTokensFile < RuntimeError end include Logging attr_accessor :source def initialize(args={}) @source=args[:source] || "" @data=[] @timestamp=Time.now end ...
class Room attr_reader :id, :capacity, :occupants, :playlist, :entry_fee def initialize(id, capacity, occupants, entry_fee) @id = id # Room number @capacity = capacity # Total number of people each room can hold @occupants = occupants # Array of guests who are in the room @pla...
class EventsController < ApplicationController before_action :authenticate, only: [:new, :create] def index @upcoming_events = Event.upcoming_events @previous_events = Event.previous_events end def new @event = Event.new end def create @event = @current_user.events.new(event_params) if @...
# Copyright 2013 Ride Connection # # 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...
pg_dba = input('pg_dba') pg_dba_password = input('pg_dba_password') pg_db = input('pg_db') pg_host = input('pg_host') control "V-72895" do title "PostgreSQL must maintain the confidentiality and integrity of information during reception." desc "Information can be either unintentionally or maliciously disclos...
Gem::Specification.new do |s| s.name = "activestorage-office-previewer" s.version = "0.1.2" s.authors = "George Claghorn" s.email = "george@basecamp.com" s.summary = "Active Storage previewer for Microsoft Office files based on LibreOffice" s.homepage = "https://github.com/basecamp/activestorage-o...
Spree::Core::Engine.routes.draw do # Add your extension routes here namespace :admin do resources :news end resources :news, only: [:index, :show]#, path: :news end
class Song attr_accessor :artist, :author, :post, :title def initialize @artist = Artist.new end end
require "ex48/parser.rb" require "test/unit" class TestParser < Test::Unit::TestCase def test_peek assert_equal(Parser.peek([['stop', 'the']]), 'stop') assert_equal(Parser.peek(nil), nil) result = Parser.peek([['stop', 'the'], ['noun', 'bear'], ['verb', 'eat']]) assert_...
require 'data_mapper' unless defined?DataMapper require 'ysd_md_yito' unless defined?Yito::Model::Finder module Yito module Model module Booking # # It represents a rental storage or campa # class RentalStorage include DataMapper::Resource extend Yito::Model::Finder ...
# frozen_string_literal: true require 'spec_helper' require 'bolt/inventory' require 'bolt/result' require 'bolt/result_set' describe 'canary::skip' do let(:inventory) { Bolt::Inventory.empty } let(:target) { inventory.get_target("target1") } let(:result) do Bolt::Result.new(target, error: { ...
# -*- encoding : utf-8 -*- require 'rails_helper' RSpec.describe GroupsController, type: :controller do let(:valid_attributes) { {name: 'Test', description: 'test'} } let(:members) { 'test@example.com; test2@example.com' } let(:user) { FactoryGirl.create(:user) } let!(:group) { FactoryGirl.create(:group, user...
class Quote attr_accessor :body, :author def initialize(body, author) @body = body @author = author end end a = Quote.new("A reader lives a thousand lives before he dies. The man who never reads lives only one.", "George R.R. Martin") b = Quote.new("The more that you read, the more things you will know...
class TradesEntryDateMonthly < ActiveRecord::Base self.table_name = 'trades_entry_date_monthly' self.primary_key = 'entry_date' def as_json(options = {}) super(options).merge(attributes: { entry_date: entry_date }) end end
class EmergencyDetailsController < ApplicationController before_action :set_emergency_detail, only: [:show, :update, :destroy] # GET /emergency_details def index @emergency_details = EmergencyDetail.where(user_id: current_user.id) cg_ids = UserAssociation.where(patient_id: current_user.id).pluck(:caregiv...
class Admin::SettingsController < ApplicationController def index if Preference.first @preference = Preference.first else @preference = Preference.create end end def update Preference.first.update(settings_params) redirect_to admin_settings_index_path end private def sett...
Rails.application.routes.draw do namespace :api do resources :trips, only: [:create] get 'stats/weekly', to: 'stats#weekly' get 'stats/monthly', to: 'stats#monthly' end end
class FavoritesController < ApplicationController def index @favorites = Favorite.where(user_id: current_user.id) @cart_item = CartItem.new @favorites = Favorite.page(params[:page]).per(12) end def create @item = Item.find(params[:item_id]) @favorite = Favorite.ne...
require 'celluloid' require_relative './aggregated_message.rb' class ClearMessageHandler include Celluloid def initialize(notifier, clearing_interval, timesrc) @notifier = notifier @timesrc = timesrc @msgs = [] @clearing_interval = clearing_interval end def handle(msg) @msgs << msg end ...
require 'spec_helper' vpc = { name: 'testvpc1', offering: "Default VPC offering", cidr: "10.10.0.0/22" } describe vpc(vpc) do it { should be_created } it { should exist } it { should be_ready } it { should be_reachable } its(:enable_remote_vpn) { should be_set } its(:remote_vpn_enabled?) { sh...
require 'csv' require_relative '../lib/customer' class CustomerRepository attr_reader :all, :parent def initialize(file_path, parent) contents = CSV.open(file_path, headers: true, header_converters: :symbol) @all = contents.map do |row| Customer.new({:id => row[:id], ...
module Hatchet # Hatchet apps are useful after the tests run for debugging purposes # the reaper is designed to allow the most recent apps to stay alive # while keeping the total number of apps under the global Heroku limit. # Any time you're worried about hitting the limit call @reaper.cycle # class Reaper...
require 'rxp' require 'schemastron' require 'tempfile' #require 'spec_helper' # SIP a TIPR package describe RXP do before :all do @rxp = RXP.new(File.join(File.dirname(__FILE__), '..', '..', 'RXPs', 'FDA0666002'), 'FDA0666002') end # in the future, this could change it "sh...
require_relative '../spec_helper.rb' describe 'ab' do let(:charaters) { [('0'..'9'),('a'..'z'),('A'..'Z')].map(&:to_a).flatten } it 'can encrypt with a set of random passwords' do for i in 0..100 length = 6 + rand(9) password = '' for j in 0..length password += charaters[rand(62)] ...
FactoryBot.define do factory :course do state { 'GA' } city { 'Atlanta' } sequence(:name) { |n| "Course #{n}" } country { 'USA' } association :submitter, factory: :user end end
json.array!(@modulos) do |modulo| json.extract! modulo, :id json.url modulo_url(modulo, format: :json) end
module Axon module WriterTests def test_writes_something @mod.write(@image, @io_out) refute @io_out.string.empty? end def test_returns_bytes_written ret = @mod.write(@image, @io_out) assert_equal @io_out.size, ret end def test_invalid_numeric_height [0, -100, 0.0001...
module BrewSparkling module Action module Install class Build < Base def call logger.start "Build to: #{recipe.archive_path}" at_build_path { recipe.build } end end end end end
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::Validator do let(:validator) { GraphQL::StaticValidation::Validator.new(schema: Dummy::Schema) } let(:query) { GraphQL::Query.new(Dummy::Schema, query_string) } let(:validate) { true } let(:errors) { validator.validate(quer...
require 'rails_helper' require 'spec_helper' RSpec.describe Devise::RegistrationsController, type: :controller do let(:email) { 'email@email.ru' } let(:password) { 'password' } before :each do request.env['devise.mapping'] = Devise.mappings[:user] end describe '#create' do it "sign up and redirect ...
# Copyright 2019 The inspec-gcp-cis-benchmark Authors # # 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...
# frozen_string_literal: true require "rack" # Stub connection socket class TestSocket attr_reader :transmissions, :streams def initialize(coder: LiteCable::Coders::JSON, env: {}) @transmissions = [] @streams = {} @coder = coder @env = env end def transmit(websocket_message) @transmission...
require 'spec_helper' describe "Supplier-related pages" do subject {page} describe "Supplier index" do before(:each) do FactoryGirl.create(:supplier) some_tag = FactoryGirl.create(:tag, tag_group: FactoryGirl.create(:tag_group)) FactoryGirl.create(:filter, name: "unitedstates-3dprinting"...
class Api::FoxesController < ApiController def show @fox = Fox.find(params[:id]) render json: @fox, root: false end end
class EARMMS::UserSettingsController < EARMMS::ApplicationController before do @user = current_user @profile = EARMMS::Profile.for_user(@user) @status = @profile.decrypt(:membership_status) @fields = [ {name: "full_name", friendly: t(:full_name), type: "text", required: true}, {name: "bir...
require 'time' class Tweet attr_reader :user_id, :id, :created_at, :status def initialize(id:, user_id:, status:, timer: Time) @user_id = user_id @id = id @created_at = timer.now @status = status end def to_s "#{@status}\n- #{@created_at}" end end
class Parent < Profile has_many :children has_many :cases has_many :ratings, through: :cases has_many :items, through: :ratings belongs_to :user end
module DefaultPageContent extend ActiveSupport::Concern included do before_action :set_page_defaults end def set_page_defaults @page_title = "My Portfolio" end end
Vedeu.interface :test_interface do background '#000066' foreground '#ffffff' border do title "Width: #{Vedeu.width} Height: #{Vedeu.height}" end end
require 'rails_helper' RSpec.describe ImagesController, type: :controller do render_views include Devise::TestHelpers before(:each) do @user = FactoryGirl.create(:user) @user_bad = FactoryGirl.create(:user) end context 'Если заходит гость' do describe "#index" do it "должен возвращать ст...
class InvalidMoveError < RuntimeError end class Board attr_accessor :grid def initialize(fill_board = true) @grid = Array.new (8) { Array.new (8) } setup_board if fill_board end def move(color, from, to) raise InvalidMoveError.new("No piece to move there.\n") if self[from].nil? raise...
class GuardianshipsController < ApplicationController before_action :authenticate_user! def index @guardianships = Guardianship.all end def show @guardianship = Guardianship.find(params[:id]) @descripion = @guardianship.description end def new @guardianship = Guardianship.new end d...
#!/usr/bin/env ruby require 'optparse' require 'methadone' require_relative '../lib/cg_scout' class App include Methadone::Main include Methadone::CLILogging main do CgScout::CLI.run(options) end on("-e ENV", "--environment", "Specific environment to check") version CgScout::VERSION description...
module Quicken class Error < StandardError def error_name self.class.name end end end
class DemoWarpScene < SKScene def initWithSize(size) super self.anchorPoint = CGPointMake(0.5, 0.5) self.name = "Scene" self end def didMoveToView(view) prepare_demo # Set warpGeometry to base before the first warp action or it will delay and lurch. @leaf.warpGeometry = @warps[:base] end ...
# represent an event where backoffice has released payout class AdminCanceledEvent < WorkspaceStatusEvent CNAME = 'admin_canceled_event' belongs_to :user field :reason field :subtitute_freelancer def display I18n.t("workspaces.events.#{CNAME}", :email => StaticDataLancer::TEAM_EMAIL) end def awai...
require 'command_line_reporter' class Example include CommandLineReporter def run header(:title => 'TABLE EXAMPLES - Borders, Wrapping, Alignment and Padding', :align => 'center', :width => 70) 2.times do |j| header(:title => "Table #{j}", :align => 'center', :width => 65) table(:border => j...
# frozen_string_literal: true require 'test_helper' module Vedeu describe 'Bindings' do it { Vedeu.bound?(:_refresh_group_).must_equal(true) } end module Groups describe Refresh do let(:described) { Vedeu::Groups::Refresh } let(:instance) { described.new(_name) } let(:_name) {...
#require 'model/website/site/constants' #require 'model/website/site/actions' module Website class Site #include Model::Website::Site::Constants #include Model::Website::Site::Actions attr_accessor :url def initialize @url ||= set_url end def set_url return "http://www.tesco.com" end # Pr...
class G1Controller < ApplicationController def show @homeworks = Homework.limit(10) end end
require 'rails_helper' RSpec.describe BidNewspaper, type: :model do it 'has a valid factory' do expect(create :bid_newspaper).to be_valid end describe 'Validations' do it { should validate_presence_of :name } it { should validate_presence_of :client_id } it { should validate_presence_of :user_id } it { s...
class UrlStatisticsController < ApplicationController before_action :find_url # Show all statistics for a given URL def index @statistics = @url.url_statistics end private def find_url @url = UserUrl.find(params[:user_url_id]) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe UpdateRecurrencesJob, type: :job do include ActiveJob::TestHelper before(:each) do f = FactoryGirl.create( :transaction, recurrence: FactoryGirl.create(:recurrence) ) CreateRecurrencesJob.perform_now(f.class.to_s, f.id.to...
class CartsController < ApplicationController protect_from_forgery :except => [:update] before_action :authenticate_user! def index carts_user = current_user.carts @carts = carts_user.where(deleted_flag: "false") if @carts == [] flash[:noticean] = "カートの中身はありません" redirect_to root_path ...
class AddParticipationsGoalCountAtProjects < ActiveRecord::Migration[5.0] def change add_column :projects, :participations_goal_count, :integer, default: 1000 end end
require 'spec_helper' RSpec.describe 'Fund::Arithmetic' do it 'must add two same currency funds' do f1 = Fund.new(100) f2 = Fund.new(200) f3 = f1 + f2 expect(f3.to_s).to eql '300 $' end it 'must add two different currency funds' do f1 = Fund.new(0.91, :eur) f2 = Fund.new(110, :pkr) ...
class CreateUserScenarios < ActiveRecord::Migration def self.up create_table :user_scenarios do |t| t.integer :user_id t.integer :scenario_id t.timestamps end add_index :user_scenarios, :user_id add_index :user_scenarios, :scenario_id end def self.down remove_index :us...
class Resource < ActiveRecord::Base has_and_belongs_to_many :tunes before_save :init_data def init_data self.entryDate ||= Date.today if new_record? end RESOURCE_TYPE_SHEETMUSIC = 1 RESOURCE_TYPE_VIDEO = 2 RESOURCE_TYPE_AUDIO = 3 RESOURCE_TYPE_LINK_VIDEO = 10 RESOURCE_TYPE_LINK_YOUTUBE = 11 RESOURCE_T...
class PropertyDrop < Liquid::Rails::Drop attributes :id, :name, :summary, :unit_type, :prop_type, :exterior, :created_at, :updated_at def exterior_template "exterior_#{object.exterior}" end end
=begin Handy Commands Rails Console: bundle exec rails console Mysql DB: bundle exec rails db =end class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def require_use...
# frozen_string_literal: true Gem::Specification.new do |s| s.name = 'model-mapper' s.version = '0.1.0' s.licenses = ['MIT'] s.summary = 'Map data between models' s.description = 'Easy way to configure what data is mapped between models' s.authors = ['Doug Youch'] s.email = 'd...
require 'dotiw' module Widgets module Page # General-purpose timestamp; displays elapsed time since base time in words, # and the timestamp value as a fortmatted string in a tooltip class Timestamp < Views::Base needs :timestamp, base_time: Time.zone.now, wrapper_class: 'updated-at' include...