text
stringlengths
10
2.61M
module GemName class AuthenticationError < StandardError; end class InvalidUsername < AuthenticationError; end end raise Exceptions::InvalidUsername # lib/app_name/error/base.rb module AppName module Error class BadStuff < ::AppName::Error::Base; end end end
class Passenger < ApplicationRecord has_many :bookings belongs_to :booking end
#!/usr/bin/env ruby require 'optparse' require 'ostruct' # Set up default values for command line arguments options = OpenStruct.new options.amount = 1024 options.dump = false options.lookback = 3 options.tokenize = :character options.verbose = FALSE # parse command line options OptionParser.new do |opts| o...
FactoryGirl.define do factory :order do total_price {rand(1..100)} completed_date "2015-07-11 10:45:04" billing_address {FactoryGirl.create :address} shipping_address {FactoryGirl.create :address} credit_card {FactoryGirl.create :credit_card} user # after(:build) do |ord...
class AddClickcountToBaner < ActiveRecord::Migration def change add_column :baners, :clickcount, :integer end end
require 'spec_helper' describe 'Post' do it 'displays posts' do post1 = FactoryGirl.create(:post) visit posts_path expect(page).to have_content post1.title expect(page).to have_content post1.body end end
class ChangeFeebackColumnConflict < ActiveRecord::Migration def change rename_column :feedbacks, :type, :feedback_type end end
require 'rails_helper' RSpec.describe "seat_prices/new", type: :view do before(:each) do assign(:seat_price, SeatPrice.new( :theater => nil, :weekdays => "", :weekdays => "", :weekends => "", :weekends => "", :is_deleted => false )) end it "renders new seat_price form...
class RestaurantSerializer < ActiveModel::Serializer attributes :id, :name, :city, :state, :postal_code, :street_address, :latitude, :longitude, :price_rating, :media_image, :logo has_many :dishes end
class Rate < ActiveHash::Base include ActiveHash::Associations has_many :games self.data = [ { id: 1, name: 'ノーレート', num: 0 }, { id: 2, name: 1, num: 10 }, { id: 3, name: 3, num: 30 }, { id: 4, name: 5, num: 50 }, { id: 5, name: 10, num: 100 }, { id: 6, name: 20, num: 200 }, { id: 7, n...
class ContactMailer < ApplicationMailer default from: 'server@weteling.com' def confirm_mail(contact_form) @contact_form = contact_form mail(to: @contact_form.email, subject: 'Copy of your email to Rene Weteling') end def contact_mail(contact_form) @contact_form = contact_form mail(to: 'rene...
class Specialty attr_reader :name, :id def initialize (attributes) @name = attributes[:name] @id = attributes[:id] end def self.all results = DB.exec("SELECT * FROM specialty ORDER BY id;") specialties = [] results.each do |result| name = result['name'] id = result['id'].to_i ...
# == Schema Information # # Table name: tags # # id :integer not null, primary key # content :string # created_at :datetime not null # updated_at :datetime not null # class Tag < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks has_ma...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebo...
class ChoiceSerializer include FastJsonapi::ObjectSerializer attributes :id, :choice, :question_id, :updated_at, :created_at end
json.array!(@movies) do |movie| json.extract! movie, :id, :name, :director, :starring, :released_on, :rating, :description, :duration, :screening_count, :is_delete json.url movie_url(movie, format: :json) end
# frozen_string_literal: true require 'bundler' require 'bundler/gem_tasks' require 'bundler/setup' require 'rspec/core/rake_task' require 'rubocop/rake_task' task default: :test desc 'Run unit tests only' RSpec::Core::RakeTask.new(:spec) do |spec| require 'pry-byebug' spec.pattern = 'spec/**/*_spec.rb' spec.r...
module Rails module Sequel class Database class Mysql def initialize (env) @env = env @config = Database.configurations[@env] end def connect (options = {}) ::Sequel.connect(@config.merge(options)) end def create_database (optio...
class AddPartnersCodesToCountriesAndShowplaces < ActiveRecord::Migration def change add_column :countries, :hotels_code, :text add_column :showplaces, :hotels_code, :text add_column :countries, :flights_code, :text add_column :showplaces, :flights_code, :text add_column :countries, :car_rental_cod...
require 'tent-client/version' require 'faraday' require 'tent-client/faraday/utils' require 'tent-client/multipart-post/parts' require 'tent-client/faraday/chunked_adapter' require 'tent-client/tent_type' require 'tent-client/middleware/content_type_header' require 'tent-client/middleware/encode_json' require 'tent-cli...
require 'spec_helper' describe Mongoid::History::Attributes::Base do before :each do class ModelOne include Mongoid::Document include Mongoid::History::Trackable field :foo field :b, as: :bar end class ModelTwo include Mongoid::Document field :foo field :goo ...
class StudentsController < ApplicationController # before_filter :authenticate_user! before_action :set_student, only: [:show, :edit, :update, :destroy] before_filter :prepare_exception_notifier respond_to :html def index if current_user.present? @students = current_user.students.where('student_type ...
class Car < ActiveRecord::Base belongs_to :driver def full_car "#{self.year} #{self.color} #{self.make} #{self.model}" end end
class Permutate attr_accessor :data, :criteria def initialize(data) raise 'Data set is not contained in an Enumerable object' unless data.respond_to? :each @data = data @criteria = Array.new end def add_criteria(lamb) raise 'Criteria is not a Proc or Lambda' unless lamb.respond_to? :call @...
class FilmType < ApplicationRecord has_many :films end
class Page < ActiveRecord::Base include Concerns::Page::Association include Concerns::Page::Validation include Concerns::Page::Method attr_accessor :blog_top_genre_id before_validation :generate_blog_folder_and_set_genre_id_and_name, if: lambda { self.blog_top_genre_id && self.blog_date...
class Role < ActiveRecord::Base has_many :roles_user has_many :users, :through => :roles_user end
module Songkick module Transport module Serialization extend self SANITIZED_VALUE = '[REMOVED]' def build_url(verb, host, path, params, scrub=false) url = host + path return url if USE_BODY.include?(verb) qs = build_query_string(params, true, scrub) url + (qs ...
require_relative "errors" require 'colorize' module Listable def format_description description, type "#{type}: #{description}".ljust(35) end def format_completion_status status status ? "X" : "" end def format_priority priority priority = priority ? priority.downcase : nil case priority...
require "test_helper" class GraphQLLoaderTest < Minitest::Spec include GraphQLServer::SchemaTestHelper before do StatsDClient.reset! end def test_single_loader_with_valid_uid query(%({ loaderWithUid(uid: "Widget:23") { id } })) assert_result({ "loaderWithUid"=>{"id"...
module KeyRotator class AttributeEncryption def initialize(user) @user = user self.new_cost = Figaro.env.attribute_cost self.encryptor = Pii::PasswordEncryptor.new end # rubocop:disable Rails/SkipsModelValidations def rotate user.update_columns(encrypted_attributes) end ...
require "rails_helper" RSpec.describe TreinosController, :type => :routing do describe "routing" do it "routes to #index" do expect(:get => "/treinos").to route_to("treinos#index") end it "routes to #new" do expect(:get => "/treinos/new").to route_to("treinos#new") end it "routes t...
class Web::Admin::EventsController < Web::Admin::ProtectedApplicationController authorize_actions_for ::Event def index @events = Event.admin_order.page(params[:id]) end def show @event = Event.find(params[:id]) end def new @event = EventType.new end def create @event = EventType.new...
require 'spec_helper' describe "gameplans/edit.html.erb" do before(:each) do @gameplan = assign(:gameplan, stub_model(Gameplan, :organisation_id => 1, :name => "MyString", :desription => "MyText" )) end it "renders the edit gameplan form" do render # Run the generator again wi...
require 'rails_helper' RSpec.describe 'CommandPages', type: :request do let!(:command) { create(:command) } let(:download) { get download_command_pages_path command.id } describe 'download' do it do download expect(response).to have_http_status(200) expect(response.header['Content-Type'])....
def prompt(message) puts "=> " + message end # Add two strings together that, when concatenated, # return your first and last name as your full name # in one string. prompt "1. Abhi " + "Reddy" puts # Use the modulo operator, division, # or a combination of both to take a 4 digit number # and find the digit in t...
# frozen_string_literal: true module Blacklight class FacetFieldNoLayoutComponent < ::ViewComponent::Base with_content_areas :label, :body def initialize(**); end def call body end end end
class CartItem < ActiveRecord::Base belongs_to :cart belongs_to :product monetize :unitary_price_cents validates_presence_of :cart, :amount, :product validates_uniqueness_of :product, scope: :cart_id validates :amount, numericality: { greater_or_equal_than: 0 } before_validation :set_initial_amount b...
class DeliverytypesController < ApplicationController def index @deliverytypes = Deliverytypes.all render json: @deliverytypes end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
# == Schema Information # # Table name: reviews # # id :integer not null, primary key # serie_id :integer not null # user_id :integer not null # rating :integer not null # created_at :datetime not null # updated_at :datetime not null # body ...
class Kubediff < Formula desc "A tool for Kubernetes to show differences between running state and version controlled configuration." homepage "https://github.com/weaveworks/kubediff" url "https://github.com/rstuven/kubediff/archive/current-context-namespace.zip" sha256 "937146ffee30768edbdd68aa24ec4b8a539f67dc...
# 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 ChapterSerializer < ActiveModel::Serializer attributes :book_id, :title, :is_paid, :contents attribute :slug, key: :id attribute :chapter_tag_list, if: :tags? belongs_to :book, if: :book? has_many :chapter_tag_list, if: :tags? def book? @instance_options[:render_params].present? && @instance_...
# frozen_string_literal: true require 'spec_helper' describe Projects::AfterRenameService do let(:rugged_config) { rugged_repo(project.repository).config } describe '#execute' do context 'using legacy storage' do let(:project) { create(:project, :repository, :legacy_storage) } let(:gitlab_shell) ...
#============================================================================== # ** NAMKCOR's Random Battle Transition #------------------------------------------------------------------------------ # Override to the standard Scene_Map to allow for random selection of # multiple battle transition graphics. # # Conf...
class Countdown OPS = [:+, :-, :*, :/] class Term # New(INT) or new(:op, Term, Term) def initialize(op, x=nil, y=nil) if x #obj is Op @op, @x, @y, x, y = op, x, y, x.val, y.val #validate / evaluate @val = case @op when :+ (x < y) ? false : x + y when :- (x > y) ?...
require_relative '../lib/get_deputy_urls' describe "the crypto_scrapper function" do tester = get_deputy_urls it "return an Hash" do expect(tester.class).to eq(Hash) end it "return at least 500 deputies" do expect(tester.length > 500).to eq(true) end it "verify that M. Joachim Son-Forget exist an...
require 'test_helper' class VendedorClientesControllerTest < ActionController::TestCase setup do @vendedor_cliente = vendedor_clientes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:vendedor_clientes) end test "should get new" do get :ne...
require 'rails_helper' RSpec.describe "employees/show.html.erb", type: :view do # pending "add some examples to (or delete) #{__FILE__}" before(:each) do @employee = assign(:employee, Employee.create!( :name => "Name", :email => "Email", :phone => "1234567890" )) end it "renders attributes in <...
module Projects module Workers class ProcessProject class ProcessProjectError < StandardError; end include Sidekiq::Worker sidekiq_options queue: 'projects', retry: true def perform(project_id) project = Project.find(project_id) result = Projects::Interactors::GetFileAndCr...
json.classrooms @classrooms do |classroom| json.(classroom, :id, :name) json.building(classroom.building, :id, :name) json.temperature classroom.try(:device).try(:temperature) json.options classroom.options do |option| json.(option, :id, :name) end end
class Group < ActiveRecord::Base # TODO Implement Group associations. See group_spec.rb for specification. has_many :subscriptions has_many :users, through: :subscriptions belongs_to :user # TODO Implement Group validations. See group_spec.rb for specification. validates :name, presence: true, uniqueness: t...
class CreateNewsletters < ActiveRecord::Migration def self.up create_table :newsletters do |t| t.string :name t.string :artist_name t.text :artist_caption t.string :party_name t.string :party_cost t.text :party_adress t.text :party_description t.timestamps end ...
class AddReturnedToLoans < ActiveRecord::Migration[6.0] def change add_column :loans, :returned, :boolean, default: false end end
module FacilitiesManagement class RegionalAvailability < ApplicationRecord belongs_to :supplier, foreign_key: :facilities_management_supplier_id, inverse_of: :regional_availabilities validates :lot_number, presence: true, uniqueness: { scope: %i[suppli...
require File.expand_path('../concerns/swagger.rb', __FILE__) class ApidocsController < ActionController::Base include Swagger::Blocks swagger_root do key :swagger, '2.0' info do key :version, '1.0.0' key :title, 'FLPPD backend api doc' key :description, 'api doc' key :termsOfServic...
class AddIntroductionPaper < ActiveRecord::Migration def self.up add_column :papers, :introduction, :text, :limit => 10000 end def self.down end end
# == Schema Information # # Table name: events # # id :integer(4) not null, primary key # name :string(255) # date :datetime # description :string(255) # created_at :datetime # updated_at :datetime # flyer_file_name :string(255) # flyer_...
class Student < ActiveRecord::Base # INITIALIZE IS GONE def full_name "#{first_name} #{last_name}" end def self.all_names Student.all.map do |student| student.full_name end end end
class CreateGroups < ActiveRecord::Migration def change create_table :groups do |t| t.string :nombre t.integer :sexo t.integer :quota t.integer :extended_quota t.integer :initial_age t.integer :maximun_age t.timestamps null: false end end end
module Charts class QueryWorkerWorkingHour prepend SimpleCommand def initialize(current_user, args = {}) @current_user = current_user @args = args range = args[:range] if range == 'daily' @st_date = Time.current.beginning_of_week @ed_date = Time.current.end_of_week ...
class GossipController < ApplicationController # before_action :authenticate_user, only: [:index] def index @gossip_new = Gossip.new puts flash[:alert] end def show @user = User.find(session[:user_id]) @gossip = Gossip.find(params['id']) @comments = Comment.where(gossip_id: @gossip).order("created_at ...
class AlbumsController < ApplicationController before_action :find_artist before_action :find_album, only: [:show, :update, :destroy] def index render json: @artist.albums end def show render json: @album end def create @artist.albums.create!(album_params) render json: @artist, status: ...
def times(number) counter = 0 while counter < number do yield(counter) counter += 1 end number # return the original method argument to match behavior of `Integer#times` end p times(5) { |num| puts num }
require 'spec_helper' describe TwitterAccount do let :user do Factory(:user) end let :account do Factory(:twitter_account, :user_id => user.id) end it "is valid with valid attributes" do account.should be_valid end it "is not valid without an access token" do account.access_token = nil...
# Write a method that takes an Array of Integers between 0 and 19, and returns an Array of those Integers sorted based on the English words for each number: NUMBER_WORDS = %w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fift...
#blackjack.rb # A way to deal cards with the four suits and 13 in each suit # Gameplay: # Deal player first, then deal a card to dealer # Deal 2nd card to player and to dealer, 1st card of dealer face up # Hit or Stay for the player # Once Player stay, Dealer opens second card. Hit until total is at least 1...
class UsersController < ApplicationController def update # プロフィール情報更新 @user = User.find(params[:id]) if @user.update(user_params) redirect_to root_path else redirect_to profile_mypage_path(current_user) end end private def user_params params.require(:user).permit( ...
class SynonymsAndAntonymsTestsController < ApplicationController before_filter :authenticate_user! def new @synonyms_and_antonyms_test = SynonymsAndAntonymsTest.setup_for(current_user) @synonyms_and_antonyms_chart = SynonymsAndAntonymsTest.chart_for(current_user) end def create @synonyms_and_anton...
class AddTotalTimeToTimeCounts < ActiveRecord::Migration[6.1] def change add_column :time_counts, :total_time, :integer end end
class Photo < ApplicationRecord mount_uploader :name, GalleryUploader belongs_to :project, inverse_of: :photos end
class V1::BaseDecorator < Draper::Decorator def dom_id h.dom_id(model) end private ###################################################################### def spanish? I18n.locale == :es end end
class ImportByPortalLogWorker < SidekiqWorker::Base sidekiq_options queue: :import_by_portal_log def execute(args) import_by_portal_log = ImportByPortalLog.find(args['id']) import_by_portal_log.process_status = :processed import_by_portal_log.save end end
TodoApp::Application.routes.draw do match '/', :to => 'todos#index' resources :todos root :to => 'todos#index' end
require 'chemistry/element' Chemistry::Element.define "Boron" do symbol "B" atomic_number 5 atomic_weight 10.811 melting_point '2573K' end
require 'migration_helper' class AddPermissionsAndLocationsToUsersTable < ActiveRecord::Migration extend MigrationHelper def self.up add_column :users, :permission_id, :integer, :null => false add_foreign_key 'users', 'permission_id', 'permissions' email = EmailAddress.new(:email => 'admin@eventhub.com...
require 'nyaplot' unless defined? Nyaplot module Mikon class Series def plot(args={}) args = { :type => :histogram }.merge(args) plot = Nyaplot::Plot.new case args[:type] when :histogram plot.add(:histogram, @data.to_a) when :line plot.add(:line, @ind...
target 'Example-macOS' do platform :osx, '10.10' # AppAuth Pod # In production, just use `pod 'AppAuth'` without the path reference. pod 'AppAuth', :path => '../../' end
class OldWayTag < ActiveRecord::Base set_table_name 'way_tags' belongs_to :old_way, :foreign_key => [:id, :version] validates_presence_of :id validates_length_of :k, :v, :maximum => 255, :allow_blank => true validates_uniqueness_of :id, :scope => [:k, :version] validates_numericality_of :id, :version, :on...
# Be sure to restart your server when you modify this file. #Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: ActiveSupport::Inflector.inflections(:en) do |inflect|...
class FoldersController < ApplicationController before_filter :authenticate_user!, :except => [ :index, :get ] @public_view = false def index if user_signed_in? @being_shared_folders = current_user.shared_folders_by_others @folders = current_user.folders.roots @assets = current_user.assets.where("fol...
class IphoneAppPlistParser class NullElement def inner_text; nil; end def /(xpath); []; end end def initialize(plist_element) @plist_element = plist_element end def attributes dict = @plist_element/'dict' purchaseDate = value_for_key(dict, 'purchaseDate') downloadInfo = elemen...
json.array!(@tweets) do |tweet| json.extract! tweet, :id, :title, :body json.url tweet_url(tweet, format: :json) end
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def all Rails.logger.debug(request.env['omniauth.auth']) @auth = Authentication.find_for_provider_oauth(request.env['omniauth.auth'], current_user) if @auth.persisted? sign_in @auth.user Collaborations.create_after...
class AddEncryptedUserProfileFields < ActiveRecord::Migration[5.0] def change add_column :user_profiles, :encrypted_preferred_units, :string add_column :user_profiles, :encrypted_preferred_units_iv, :string add_column :user_profiles, :encrypted_height, :string add_column :user_prof...
require 'rails_helper' feature 'User sets Procedure performer', js: true do scenario 'completing without selecting a Performer from the Performer dropdown' do given_i_have_added_a_procedure_to_an_appointment when_i_complete_the_procedure then_i_should_see_that_i_am_the_procedure_performer end scena...
require 'rails_helper' RSpec.describe '/users', :type => :request do let(:params) { {} } let(:url) { '/users' } describe 'POST' do let(:request) { post url, params: params } describe "/" do describe 'sending user credentials' do let(:params) do { email: 'robert.schae...
class Destination < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :prefecture belongs_to :user, optional: true with_options presence: true do validates :post_code, format: { with: /\A\d{7}\z/, message: "は半角数字7桁で入力してください", allow_blank: true} #ハイフンなし7桁 v...
module SetLocale def self.included(base) base.class_eval do before_filter :set_locale def set_locale @locales = AppConfig[:locales].map(&:to_sym) locale = params[:locale].to_sym rescue nil I18n.locale = locale if @locales.include?(locale) I18n.locale ||= @locales.fir...
class AddMapOptionsToLeague < ActiveRecord::Migration def change add_column :leagues, :coordinate_lat, :string add_column :leagues, :coordinate_long, :string add_column :leagues, :zoom_level, :integer, :default => 5 add_column :leagues, :show_map, :boolean, :default => false end end
# frozen_string_literal: true # # CONSUL # default['consul']['version'] = '0.9.2' default['consul']['config']['domain'] = 'consulverse' # This is not a consul server node default['consul']['config']['server'] = false # For the time being don't verify incoming and outgoing TLS signatures default['consul...
require 'statement' describe Statement do before(:each) do deposit1 = double('Transaction', credit: 10, debit: nil, balance: 10, date: Time.now) deposit2 = double('Transaction', credit: 20, debit: nil, balance: 30, date: Time.now) activity = [] activity.push(deposit1, deposit2) @statement = State...
class ClientsController < ApplicationController #before_filter :authentication_required , :only => :temp before_filter :login_required , :except => [:callback] before_filter :client_authentication_required , :only => [:show, :edit, :update, :destroy] before_filter :http_get, :only => [:index, :show, :temp, :edi...
class Tracepoint < ActiveRecord::Base include GeoRecord set_table_name 'gps_points' validates_numericality_of :trackid, :only_integer => true validates_numericality_of :latitude, :only_integer => true validates_numericality_of :longitude, :only_integer => true validates_associated :trace validates_prese...
class CreateProblemFilms < ActiveRecord::Migration def change create_table :problem_films do |t| t.string :title t.boolean :no_response t.boolean :no_match t.boolean :multiple_results t.timestamps end end end
class PatientSearch < SitePrism::Page set_url '/#patient-search-screen' set_url_matcher /\/#patient-search-screen$/ # ***************** All_Form_Elements ******************* # # ***************** All_Container_Elements ******************* # element :ctn_fluid, "div[class='container-fluid']" # *****...
class RemovePhotoFromSpaces < ActiveRecord::Migration def change remove_attachment :spaces, :photo end end
class UserMailer < ApplicationMailer def confirmation_email(user, order) @user = user @order = order @url = 'no-reply@jungle.com' mail(to: @user.email, subject:"Order # #{@order.id}") end end
require 'rails_helper' describe "tournament test" do # it "overlapped_schedule test" do # time = Time.zone.now.change(hour: 17) # (1..15).each do |n| # tournament_1 = create(:tournament, start_date: 5.days.after.midnight, tournament_time: time, max_user_count: 32) # expect(tournament_1.persisted...