text
stringlengths
10
2.61M
class AddIndexToRelations < ActiveRecord::Migration def change add_index :relations, [:follower_id, :following_id], :unique=> true end end
module VisitorServices class ContactUsForm class << self def send_enquiry_to_admin(enquiry) AdminMailer.contact_us(enquiry).deliver! end end end end
require 'rails_helper' describe Review do describe 'validations' do xit 'is not valid withou a comment' do review = Review.new(comment: nil) expect(review).to have(1).errors_on(:comment) end it 'is not valid if rating is > 5' do review = Review.new(rating: 9 ) expect(review).t...
class Event < ApplicationRecord belongs_to :creator, :class_name => "User" has_many :attendments, :foreign_key => :event_id end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe I18n::Backend::Locale do before(:each) do @valid_attributes = { :code => "en", :name => "English" } end it "should create a new instance given valid attributes" do I18n::Backend::Locale.find_or_create!(@valid_a...
require 'spec_helper' describe RSpec::Matchers::Sequel::ReferTo do before :all do DB.create_table(:users) do primary_key :id column :name, String end DB.create_table(:posts) do column :text, String foreign_key :user_id, :users, on_update: :cascade, key: :id end end afte...
App2::Application.routes.draw do get "/favorites", :controller => "favorites", :action => "index", :as => :favorites get "/greet", :controller => "favorites", :action => "index" root :to => "favorites#index" end
# ruby -r "./regression_tests/download_updated_apps.rb" -e "DownloadUpdatedApps.new.new_apps()" -- downloads only apps that have new versions # # ruby -r "./regression_tests/download_updated_apps.rb" -e "DownloadUpdatedApps.new.all_apps()" -- downloads all apps in the app_store_links.csv require 'webdrivers' require...
class Api::EntriesController < ActionController::API before_action :set_entry, only: [:destroy] before_action -> { @entries = Entry.unread.by_date }, only: [:index, :pods] def index render json: @entries.articles end def destroy @entry.update!(read: true) end def pods render json: @entries....
class ApplicationController < ActionController::Base include Pundit include Roles before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :approved]) end def af...
class Api::V1::InboundController < ApplicationController before_action :get_params, only: [:sms] # Expected API Behavior # - The API should do input validation # - If the ‘to’ parameter is not present in the phone_number table for this specific account you used for the basic authentication, return an error (see Ou...
class BeerSong def verse(left) if left > 2 "#{left} bottles of beer on the wall, #{left} bottles of beer.\n" \ "Take one down and pass it around, #{left - 1} bottles of beer on the wall.\n" elsif left == 2 "2 bottles of beer on the wall, 2 bottles of beer.\n" \ "Take one down and pass ...
require 'rails_helper' require 'different_first_payment_amortization_schedule_creator' RSpec.describe DifferentFirstPaymentAmortizationScheduleCreator do describe 'DifferentFirstPaymentAmortizationScheduleCreator' do let(:dummy_class) { Class.new } before do dummy_class.extend(DifferentFirstPaymentAmor...
class CreateConfirmations < ActiveRecord::Migration def self.up create_table :confirmations do |t| t.references :user t.references :reserve t.boolean :credit_card t.integer :value t.integer :credits t.timestamps end end def self.down drop_table :confirmations end...
require 'rails_helper' RSpec.describe User, type: :model do describe "#Associations" do it { should have_many(:albums) } it { should have_many(:collaborators_albums) } it { should have_many(:images) } end describe "#Validations" do subject { FactoryGirl.build(:user) } it { should validat...
## # Class for searching through tickets # as params hash any of these in official docs could be used: # http://doc.otrs.com/doc/api/otrs/5.0/Perl/Kernel/GenericInterface/Operation/Ticket/TicketSearch.pm.html # module Tessera module Api class TicketSearch def self.call(params = nil) new(params).ca...
class AddCommentToFeed < ActiveRecord::Migration[6.0] def change add_column :feeds, :comment, :text end end
class Twitter < ApplicationRecord has_many :tweets has_many :sent_messages, class_name: "Message" has_and_belongs_to_many :likes, class_name: "Tweet" has_and_belongs_to_many :received_messages, class_name: "Message" has_and_belongs_to_many :followers, class_name: "Twitter", foreign_key: "following_id" ...
require_relative '../../../app/api' require_relative '../../../app/services' require_relative '../../../app/utils' require_relative '../../../app/mappings' RSpec.describe 'GET /complains' do before(:all) do Utils::create_index('complains', Mappings::COMPLAINS) unless Utils::index_exists?('complains') @comp...
module SemanticNavigation module Core class Leaf < NavigationItem attr_accessor :link_classes, :link_html def initialize(options, level) @link_html = {} super options, level end def is_leaf? true end def mark_active if @url @active =...
class ZipCode < ActiveRecord::Base def self.zips_near_zip(source_zip, miles=5, limit=5) latitude = source_zip.latitude longitude = source_zip.longitude sql = <<-SQL SELECT distinct(zip_code),( 2*( asin( sqrt( pow( sin(((:latitude*pi()/180)-(latitude*pi()/180))/2), 2 ...
require "clustering/ai4r_modifications" module ClusteringModule class TargetMatcher attr_accessor :targets attr_accessor :prosumers def initialize(prosumers: Prosumer.all, startDate: DateTime.now - 1.day, endDate: DateTime.now, interval: 1.hour,...
require 'lingua/stemmer' module SadPanda class StatusMessage attr_accessor :message, :verbose attr_reader :stemmer def initialize(message, verbose = false) @message = message @stemmer = Lingua::Stemmer.new(:language => "en") @verbose = verbose end # this method reads a csv file containing 'wo...
class CreateBlocks < ActiveRecord::Migration[5.1] def change create_table :blocks do |t| t.string :name, null: false t.integer :repetitions, null: false t.integer :measures, null: false t.integer :time_signature_over t.integer :time_signature_under t.string :musical_key t...
class User < ActiveRecord::Base has_many :questions has_many :answers has_many :comments has_many :votes validates :username, presence: true, uniqueness: true validates :password, presence: true include BCrypt def password @password ||= Password.new(hashed_password) end def password=(new_pas...
module GroupDocs module Api module Helpers module Accessor # # Allows to easily alias accessors. # # @example # class File < Api::Entity # attr_accessor :fileName # alias_accessor :file_name, :fileName # end # file = File...
# Lecture: Classes and Objects # 1. Given the below usage of the Person class, code the class definition class Person attr_accessor :name def initialize(n) @name = n end end bob = Person.new('bob') bob.name bob.name = 'Robert' bob.name # 2. Modify the class definition from the above to facilitate the fol...
require 'pry' class Calculator def initialize(question) @question = question get_matches() end def get_matches @matches = @question.match(/(-?[0-9]+) (.+) (-?[0-9]+)/) end def operation op = @matches[2] case op when 'plus' then :+ when 'minus' then :- when 'multipl...
class MantaFilesController < ApplicationController before_action :authenticate_user! before_action :set_manta_dir, only: [:index] def index @manta_files = @manta_dir.list_directory end private def set_manta_dir path = params[:manta_path] || "/#{current_manta_account.manta_username}/stor" @ma...
class Role < ActiveRecord::Base validates :name, uniqueness: true, presence: true end
Rails.application.routes.draw do resources :participants root 'participants#new' end
class Category < ApplicationRecord has_many :trashes, dependent: :destroy end
class CreateDailyYardCounts < ActiveRecord::Migration[6.0] def change create_table :daily_yard_counts do |t| t.date :date t.integer :trucks t.integer :transactions t.integer :detained t.time :turntime t.text :note t.references :terminal, null: false, foreign_key: true ...
require 'traject/marc_extractor' require 'traject/translation_map' require 'traject/util' require 'base64' require 'json' require 'marc/fastxmlwriter' module Traject::Macros # Some of these may be generic for any MARC, but we haven't done # the analytical work to think it through, some of this is # def specific ...
json.array!(@profiles) do |profile| json.extract! profile, :id, :name, :picture, :description, :availability, :skills, :projects, :contact json.url profile_url(profile, format: :json) end
Rails.application.routes.draw do root 'public#index' devise_for :users, :skip => [:registrations] authenticate :user do ActiveAdmin.routes(self) end resources :sources, only: [:new, :create] resources :events, only: [:new, :create] scope '/api' do scope '/v1' do resources :events, only:...
class CreateJoinTableTournamentRoundsCourts < ActiveRecord::Migration[6.0] def change create_join_table :tournament_rounds, :courts end end
require 'spec_helper' describe 'Default role-based authorization API' do let(:json) { JSON.parse(response.body) } describe 'GET /posts', :auth_request do subject(:get_posts) { get posts_path, format: :json } let!(:post) { FactoryGirl.create(:post, author: user) } let!(:other_post) { FactoryGirl.creat...
require_relative 'king' require_relative 'queen' require_relative 'knight' require_relative 'bishop' require_relative 'rook' require_relative 'pawn' require_relative 'null_piece' require 'byebug' require_relative 'display' class Board attr_reader :grid def initialize @grid = populate_grid end def play ...
require 'spec_helper_acceptance' require 'erb' test_name 'simp_openldap tiering sssd validation' describe 'simp_openldap with sssd' do let(:hieradata) {{ 'sssd::domains' => ['LDAP'], 'sssd::services' => ['nss', 'pam'], # If you leave purging on, slapd certs will be removed ...
require File.dirname(__FILE__) + '/helper.rb' include GoogleAnalytics::Proxy::ViewHelpers class ViewHelpersTest < Test::Unit::TestCase context "GoogleAnalyticsProxy" do should "embed the analytics proxy js" do assert_equal google_analytics_proxy, '<script type="text/javascript" src="/javascripts/g...
module TemplateBuilder class FromCompose attr_reader :compose_yaml, :options def initialize(options) @compose_yaml = options.delete('compose_yaml') @options = options end def create_template(persisted=true) Template.new(self.options) do |template| template.images = images_...
class OrderServiceExtraCalculation < ActiveRecord::Base self.inheritance_column = nil belongs_to :order_of_service_detail, :touch => true belongs_to :extra_calculation end
require 'entity' # A planet on the game map. # id: The planet ID. # x: The planet x-coordinate. # y: The planet y-coordinate. # radius: The planet radius. # owner: The player ID of the owner, if any. If nil, Planet is not owned. # docking_spots: The max number of ships that can be docked. # health: The planet's healt...
class Car # Our car will have 2 properties: # - color # - make attr_reader :color, :mileage def initialize(color, make) @color = color @make = make @mileage = calculate_mileage(50, 50) end def calculate_mileage(number1, number2) "Mileage blah" + @color end # # attr_reader creates this method # #...
require 'formula' class Pit < Formula homepage 'https://github.com/michaeldv/pit' url 'https://github.com/michaeldv/pit/archive/0.1.0.tar.gz' sha1 '867698a2ef4d01587d81fe89dfd0e549d5b42e49' def install system "make" bin.install "bin/pit" end end
class SpendingInfo < ApplicationRecord # Attributes delegate :couples?, to: :account, prefix: true delegate :monthly_spending_usd, to: :account BusinessType = Types::Strict::String.enum( 'no_business', 'with_ein', 'without_ein', ) def has_business_with_ein? has_business == 'with_ein' en...
Rails.application.routes.draw do root 'pages#index' get 'recipes/index' post 'recipes/create' get '/show/:id', to: 'recipes#show' delete 'destroy/:id', to: 'recipes#destroy' get '/*path', to: 'pages#index' end
# # Be sure to run `pod lib lint Pod.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.swift_version = '5.0' s.name ...
class Article < ActiveRecord::Base validates :title, :presence=>true validates :body, :presence=>true belongs_to :user has_many :comments, :order=>'created_at DESC', :dependent=>:destroy def published? published_at.present? end def owned_by?(owner) return false unless owner.is_a? User user==owner ...
Pod::Spec.new do |s| s.name = "SelfieCocoapod" s.version = "1.0.0" s.summary = "Testing sdk with the cocoapods abcdefghijklmnop" s.description = "validation of the cards for the given image abc" s.homepage = "https://github.com/KrishnaMohan454/SelfieCapture.git" s.license = "MIT" s.author ...
require 'fs/ReiserFS/utils' module ReiserFS class FileData attr_reader :pos # Initialization def initialize(dirEntry, superblock) raise "Nil dirEntry object" if dirEntry.nil? raise "Nil superblock" if superblock.nil? @sb = superblock @de = dirEntry @key = @de.key...
require 'ptools' module DownloadTestHelper def assert_downloaded(expected_filesize, source) download = Downloads::File.new(source) tempfile = download.download! assert_equal(expected_filesize, tempfile.size, "Tested source URL: #{source}") end def assert_rewritten(expected_source, test_source) d...
class Categorization < ActiveRecord::Base belongs_to :job belongs_to :group validates_presence_of :job validates_presence_of :group end
class AddBelongsToFlowerToComments < ActiveRecord::Migration def change add_column :comments, :flower_id, :integer add_index :comments, :flower_id end end
# Grouping of records class GroupingsController < ApplicationController before_action :set_grouping, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! def index @groupings = Grouping.all @grouping_records = ["name"] end def show @grouping = Grouping.find(params[:id]) ...
class Recipe < ApplicationRecord validates :title, presence: true validates :image, presence: true validates :description, presence: true validates :chef_name, presence: true has_many :recipe_tags has_many :tags, through: :recipe_tags end
FactoryBot.define do factory :contest_nomination do caption {Faker::Company.name} availible_for_registration {Faker::Boolean.boolean} end end
module ActiveSesame class Base ActiveSesame::MonkeyPatches #Run The monkey Patches def Base.inherited(subClass) ############################################ ####### Generic Attribute Handling ######## ############################################ #Create class variables that are independant of t...
#Required Modules require 'VMTConn' require 'nokogiri' require 'active_support/core_ext/hash/conversions' require 'yaml' require 'cgi' class Market attr_accessor :vmt_userid, :vmt_password, :vmt_url, :query_builder #Initalize Entity Object def initialize(vmt_userid, vmt_password, vmt_url) #Ins...
class GivenOffersController < ApplicationController layout 'template' def index @given_offers = Offer.where(buyer: current_user.email) @received_counteroffers = Counteroffer.where(buyer: current_user.email) end end
class ZipcodeSearcher require 'correios-cep' extend ActiveModel::Naming extend ActiveModel::Translation include ActiveModel::Validations include ActiveModel::Conversion validates_presence_of :zip_code validates_length_of :zip_code, length: 8, allow_blank: false attr_accessor :zip_code def initiali...
# frozen_string_literal: true class EncryptionService SALT = Rails.application.credentials.salt KEY = ActiveSupport::KeyGenerator.new('password').generate_key(SALT, 32).freeze private_constant :KEY def encrypt(value) encryptor.encrypt_and_sign(value) end def decrypt(value) encryptor.decrypt_and...
module EnumeratorEx module Generators #Intersperse several iterables, until all are exhausted def weave(*enumerators) enums = enumerators.map{|e| e.to_enum} result = Enumerator.new do |y| while !enums.empty? loop_enum = enums.dup loop_enum.each_with_index...
class User < ApplicationRecord has_many :favorite_songs has_many :songs, through: :favorite_songs validates :user_name, :user_pass, :email, presence: true validates :email, uniqueness: true end
class Cat < ActiveRecord::Base attr_accessible :age, :birth_date, :color, :name, :sex validates :age, :birth_date, :color, :name, :sex, presence: true validates :color, inclusion: { in: %w(brown red black calico orange striped), message: "%{value} is not a valid color" } has_many :cat_rental_requests, dep...
class OrdersController < ApplicationController before_action :authenticate_user! before_action :set_order, :only => [:update, :index, :order_validation] #after_rollback :custom_error, on: :update def index @items = @order.order_items end def update @order = Order.update params[:id], order_params.m...
class ItemCollection attr_reader :all def initialize(items) @all = items end def find(id) @all.select{|item| item.merchant_id == id} end end
send respond_to? try # only in rails instance_eval class_eval Singleton define_method Module.const_get instance_variable_get settr and gettr -------------------------------------------------- eval extend included struct How to process with a new task. class A def t "Hello" end def g "Bye" end end x =...
#This method should take an undefined number of arguments, #using the splat operator, and return an array with every key from #the hash whose value matches the value(s) given as an argument. class Hash def keys_of(*arguments) # code goes here arr = [] self.each do |key, value| arguments.each do |i| ...
require 'rails_helper' describe EventPrice do let(:event_price) { build_stubbed :event_price } describe 'ActiveModel validations' do it 'has valid factory' do expect(event_price).to be_valid end it 'is not valid without price' do event_price.price = nil expect(event_price).not_to be...
class FixStateSchoolyears < ActiveRecord::Migration def change remove_column :schoolyears, :active remove_column :schoolyears, :next add_column :schoolyears, :state, :string end end
module AttachmentList def self.extended(base) base.instance_eval do permit_params :file, :title, :link_url, :category actions :all, except: :show index do selectable_column column :title column :link_url column :file_uploaded? column :category act...
class InstanceDatabasesController < GpdbController def index gpdb_instance = GpdbInstance.find(params[:gpdb_instance_id]) databases = GpdbDatabase.visible_to(authorized_gpdb_account(gpdb_instance)) present paginate databases end def show database = GpdbDatabase.find(params[:id]) authorize_gp...
class Song @@count = 0 @@artists = [] @@genres = [] attr_accessor :name, :artist, :genre def initialize(name, artist, genre) @@count += 1 @@artists << artist @@genres << genre @artist = artist @genre = genre @name = name end def Song.count @@count end def So...
# Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
class RecipesController < ApplicationController before_action :set_recipe, only: [:show, :edit, :update, :destroy] respond_to :html def index @recipes = User.find(current_user.id).recipes respond_with(@recipes) end def show respond_with(@recipe) end def new if user_signed_in? @s...
class StoreOrderWorker include Sidekiq::Worker def perform(store_order_id) store_order = StoreOrder.where(id: store_order_id).first if store_order.present? && store_order.status != 'success' store_order.charge if store_order.status == 'success' StoreOrderMailer.send_success_to_a...
require_relative 'station' class OysterCard MAX_LIMIT = 90 MIN_FARE = 1 attr_reader :balance, :journey_history, :journey, :entry_station, :exit_station def initialize @balance = 0 @entry_station = nil @exit_station = nil @journey_history = [] end def top_up(amount) fail "Top up is abo...
module ApplicationHelper SOCIAL_SHARE_SERVICE_URLS = { twitter: 'https://twitter.com/intent/tweet', googleplus: 'https://plus.google.com/share', facebook: 'https://www.facebook.com/sharer/sharer.php' } def page_title title return 'Christian Rolle' if title.blank? title end def page_descr...
class ReviewCreator def initialize(reviewable) @reviewable = reviewable end def create return false unless @reviewable.sha @reviewable.create_review(patches: get_patches) unless @reviewable.review @review = @reviewable.review end def review @review end private def get_p...
require 'rubygems' require 'packetfu' require 'arpspoof.rb' require 'bolocookie.rb' #get active interface begin PacketFu::Utils.whoami?(:iface=>ARGV[0]) rescue Exception => e puts "Invalid interface or improper permissions, try being root" exit(1) end interface = ARGV[0] #verbose output? if ARGV[1] =~ /[tT]/ ...
class Bracket < ActiveRecord::Base belongs_to :bracket_group has_and_belongs_to_many :bowlers validates :bracket_group, presence: true end
class Food < ActiveRecord::Base belongs_to :category scope :not_deleted, where(:deleted => false) def deleted? self.deleted end end
require 'spec_helper' module Rockauth RSpec.describe 'Session Creation', type: :request do include ::Warden::Test::Helpers after { ::Warden.test_reset! } let(:class_name_params) do { resource_owner_class_name: "Rockauth::User" } end describe 'POST create' do let(:authentication_para...
# **************************************************************************** # # 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 ...
require "attr_typecastable/version" require "attr_typecastable/types" require "attr_typecastable/initialize_hook" require "attr_typecastable/reflection" require "active_support/concern" require "active_support/core_ext/class" require "active_support/core_ext/hash" module AttrTypecastable extend ActiveSupport::Conce...
# frozen_string_literal: true module SolidusYotpo module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, type: :boolean, default: false source_root File.expand_path('templates', __dir__) def copy_initializer template 'initializer.rb', 'con...
class Stack #クラス名は大文字で def initialize @index = 0 @s = [] end def push(e) @s[@index] = e @index += 1 end def pop @index -= 1 return @s[@index] end end i = 0 s = Stack.new while i < ARGV.size do s.push(ARGV[i]) i += 1 end i = 0 while i < ARGV.size do puts s.pop i += 1 end...
# == Schema Information # # Table name: levels # # id :integer not null, primary key # name :string # required_points :integer # image_url :string # created_at :datetime not null # updated_at :datetime not null # FactoryGirl.define do factory :le...
require "./lib/takeaway.rb" describe Takeaway do let (:salad) {Dish.new(:Salad, 2.5)} let (:rice) {Dish.new(:Rice, 4.4)} let (:beef) {Dish.new(:Beef, 10.1)} let (:veal) {Dish.new(:Veal, 5.5)} let (:takeaway) {Takeaway.new} let (:customer) {Customer.new("Nadav", "+447503671785")} it "can add a customer to the ...
class ClimbsController < ApplicationController include DateRange before_action :set_climbs, only: [:index] before_action :set_climb, only: [:show, :update, :destroy] # GET /climbs def index render json: @climbs end # GET /climbs/1 def show render json: @climb end # POST /climbs def cre...
#!/usr/bin/env ruby require 'lib/selenium_viewpointsbase' class IdeasTests < Selenium::ViewpointsBase def test_searching_an_idea return unless @@SITE =~ /mysears/ @sel.open('/') @sel.click("link=ideas") @sel.wait_for_page_to_load(3000) assert(@sel.title =~ /Ideas/) @sel.type("i...
class AddDeliveryAreaIdToStationService < ActiveRecord::Migration def change add_column :station_services, :delivery_area_id, :integer end end
ActiveAdmin.register Specialist do decorate_with SpecialistDecorator controller do has_scope :by_order, as: 'order', only: [:index] def permitted_params params.permit() end end show do render partial: 'specialist' end end
require 'rails_helper' RSpec.describe AuthenticationController, type: :request do let!(:user) { create(:user) } describe '#login' do it 'error password invalid and return error' do post '/auth/login', params: { email: user.email, password: 'as21sd' } expect(response).to have_http_status(:unauthori...
class LocationPeopleController < ApplicationController before_action :set_location_person, only: [:show, :update, :destroy] # GET /location_people def index @location_people = LocationPerson.all render json: @location_people end # GET /location_people/1 def show render json: @location_person ...
# -*- coding: utf-8 -*- require 'doozer_hook_listener' Redmine::Plugin.register :redmine_doozer do name 'Doozer plugin' author 'Andreas Öman' description 'Integration of doozer autobuild system with redmine' version '0.0.1' url 'https://github.com/andoma/doozer2' author_url 'http://www.lonelycoder.com/' ...
class AddToJob < ActiveRecord::Migration[6.0] def change add_column :jobs, :title, :string add_column :jobs, :description, :text add_reference :jobs, :company, foreign_key: true end end
# Modelo Configuracion # Tabla configuraciones # Campos id:integer # nombre:string # valor:integer # created_at:datetime # updated_at:datetime class Configuracion < ActiveRecord::Base validates :nombre, presence: true, uniqueness: true validates :valor, presence: true end