text
stringlengths
10
2.61M
class Unit < ActiveRecord::Base include PublicActivity::Model tracked has_many :properties validates :name, presence: true, uniqueness: true validates :title, presence: true, uniqueness: true paginates_per 10 def name_title if name == title name else "#{name}(#{title})" end e...
class Sales::CustomersController < ApplicationController def index @records = QueryCustomer.call.result end def new @record = SaleForm::CustomerForm.new end def create @record = Sales::Customer.new @record.name = record_params[:name] @record.account_no = record_params[:account_no] if...
class AddUniquenessOnFullGithubNameToRepos < ActiveRecord::Migration def change add_index :repos, :full_github_name, unique: true end end
FactoryGirl.define do factory :author do firstname Faker::Name.first_name lastname Faker::Name.last_name biography Faker::Lorem.paragraph end end
#!/usr/bin/env ruby # # net-app-sdk # * Ruby gem for NetApp filer administration via NetApp NMSDK # * https://github.com/azet/NetApp.rb # # LICENSE: # MIT License (http://opensource.org/licenses/MIT) # # AUTHORS: # Todd Pickell @tapickell <todd.pickell@ge.com> # Marion Newman <marion.newman@ge.com> # # require...
class User < ApplicationRecord has_many :lancamentos, dependent: :destroy require 'digest/sha1' #Incluí as validações validates :name, :presence => true, :length => { :in => 3..150 } validates :email, :presence => true, :uniqueness => false, :length => { :in => 3..50 } validates :password, :presence => true, :...
class Enrollment include Mongoid::Document include Mongoid::Timestamps field :active, type: Boolean, default: true field :present, type: Boolean, default: false belongs_to :event, index: true belongs_to :user, index: true validates_uniqueness_of :user, scope: :event scope :actives, -> { where(active...
class CreateJobs < ActiveRecord::Migration[6.0] def change create_table :jobs do |t| t.string :name t.string :saving_throw_profs t.string :skill_profs t.string :hit_die t.integer :proficiencies t.timestamps end end end
require 'rails_helper' feature "User posts a new question" do # As a user # I want to post a question # So that I can receive help from others # # Acceptance Criteria # # - I must provide a title that is at least 40 characters long it "creates invalid question" do # Visit the page containing the new question form...
require 'json' require 'food_search' describe FoodSearch do context'check all values can be read' do before(:each) do @food_search = FoodSearch.new(full_search) end it"Should return the amount of foods found" do expect(@food_search.total).to eq(9) end it "should return the name o...
# encoding: UTF-8 include JenkinsUtils include JenkinsUtils::ConfigFileProvider def whyrun_supported? true end use_inline_resources action :create_if_missing do if @current_resource.exists Chef::Log.info "#{ @new_resource } already exists - nothing to do." else converge_by("Create #{ @new_resource }") ...
class UsersController < ApplicationController def create @user = User.new(user_params) # respond_to do |format| if @user.save cookies[:saved_lead] = true # Sends email to subscriber when he/she is created. Newsletter.sample_email(@user).deliver_now # format.html { redirect_to root...
class Recruit < ApplicationRecord validates :content, {presence:true, length:{maximum:10000}} validates :user_id, {presence:true} belongs_to :prefecture, optional: true validate :start_end_check def start_end_check errors.add(:deadline, "募集期限は開催日前または当日にしてください。") unless self.deadline < self.hold_o...
# frozen_string_literal: true require "dry/logic/predicates" RSpec.describe Dry::Logic::Predicates do describe "#bytesize?" do let(:predicate_name) { :bytesize? } context "when value size is equal to n" do let(:arguments_list) do [ [4, "こa"], [1..8, "こa"] ] e...
namespace :pg do desc "Drop the postgresql connections" task :disconnect do conf = Rails.configuration.database_configuration[Rails.env] return unless conf['adapter'] == 'postgresql' db = conf['database'] cmd = "psql postgres -c \"select pg_terminate_backend(pid) from pg_stat_activity where datna...
class AddArquivoApresentadoToTcc < ActiveRecord::Migration def change add_column :tccs, :nome_arquivo, :string add_column :tccs, :apresentado, :boolean end end
WebiniusCms::Engine.routes.draw do resources :images # resources :users # resources :pages resources :documents, only: :show scope '/admin' do resources :users resources :languages resources :pages, only: [:index, :new, :create, :update, :edit, :destroy] do member do get 'high...
EXPORTS_PATH = "#{Rails.root}/tmp/pdfs" TEMPLATES_PATH = "#{Rails.root}/lib/templates" class Template < ActiveRecord::Base attr_accessor :name attr_accessor :description attr_accessor :path # Given data, build a document from this template. def generate(file, data, user) template_path = "#{ TEMPLATES_P...
class Admin::ProjectsController < ApplicationController layout 'admin.html.erb' before_action :require_login def show @project = Project.find_by(id: params["id"]) @admin = Admin.find_by(id: params["admin_id"]) end def new @admin = Admin.find_by(id: params["admin_id"]) end def create Project.create(nam...
class Business < ActiveRecord::Base validates_presence_of :name has_many :users has_many :clients, :order => 'clients.name' accepts_nested_attributes_for :users end
# note, if you are using Ruby 1.9.2 or earlier you may need to install # the minitest gem and then uncomment the following line. # # gem "minitest" require "minitest/autorun" require_relative "stacker" describe "Stacker::Interpreter" do let(:interpreter) { Stacker::Interpreter.new } it "implements ADD" do e...
class SongsController < ApplicationController def index @songs = Song.all end def show @song = Song.find(params[:id]) end def new @song = Song.new end def create @song = Song.new(song_params) if @song.save redirect_to @song else render :new end end def upl...
require 'net/http' class ScoringService DEFAULT_SCORE = 0.freeze GUIDE = { allow_contact: 45, avatar_file_name: 3, bio: 20, company_name: 1, email: 15, featured: 1000, first_name: 5, gravatar_image_found: 3, ...
class AddWebsiteRatingsToHotels < ActiveRecord::Migration[6.0] def change add_column :hotels, :url, :string add_column :hotels, :website, :string add_column :hotels, :rating, :string end end
module Scenic module Adapters class MySQL # Fetches defined views from the postgres connection. # @api private class Views def initialize(connection) @connection = connection end # All of the views that this connection has defined. # # This will...
class Member < ActiveRecord::Base validates :address, presence: true has_many :people has_many :cards accepts_nested_attributes_for :people, reject_if: proc { |attributes| attributes['name'].blank? }, allow_destroy: true accepts_nested_attributes_for :cards, reject_if: proc { |attri...
FactoryGirl.define do sequence(:email, 1000) {|n| "person#{n}@example.com" } factory :user do name "anshu" password "rubyrails" password_confirmation "rubyrails" email { FactoryGirl.generate(:email) } end end
describe 'Matchers de Igualdade' do it "#equal: testa se dois objetos são iguais" do x = "ruby" y = "ruby" expect(x).not_to equal(y) end it "#be: testa se dois objetos são iguais" do x = "ruby" y = "ruby" expect(x).not_to be(y) expect(x).to be(x) end it "#eql...
class Studio < ApplicationRecord has_many :stays has_many :tenants, through: :stays end
# frozen_string_literal: true require 'spec_helper' RSpec.describe MLBStatsAPI::Schedules do let(:client) { MLBStatsAPI::Client.new } before { stub_requests! } describe '#schedule' do it 'loads a normal schedule' do client.schedule expect(a_get_request('v1/schedule', sportId: '1')).to have_be...
class AddIndexToNewCardUse < ActiveRecord::Migration[5.2] def change add_index :new_card_uses, [:result_no, :generate_no], :unique => false, :name => 'resultno_and_generateno' add_index :new_card_uses, :card_id end end
class Cie10sController < ApplicationController before_action :set_cie10, only: [:show, :edit, :update, :destroy] # GET /cie10s # GET /cie10s.json def index @cie10s = Cie10.all respond_to do |format| format.json { render :json => @cie10s } end end # GET /cie10s/1 # GET /cie10s/1.json ...
require 'test_helper' require 'minitest/autorun' require 'chartup' class ChordTest < MiniTest::Test def test_formatted_chord_name_with_length chord = Chartup::Chord.new('AM7b9#11', 18) assert_equal ' a\breve:maj7.9-.11+ a\breve:maj7.9-.11+ a2:maj7.9-.11+', chord.formatted_chord_name_with_length(:lilypond) ...
class CreateAgentClientTable < ActiveRecord::Migration def change create_table :agent_clients do |t| t.string :name t.string :server_key end end end
require File.dirname(__FILE__) + '/../../../test/test_helper' require File.dirname(__FILE__) + '/../../spec_helper' require 'admin/settings_controller' # Re-raise errors caught by the controller. class Admin::SettingsController; def rescue_action(e) raise e end; end describe Admin::SettingsController do before do ...
# frozen_string_literal: true module Types class Any < Types::BaseScalar description "Represents an unconstrained type. No coercion is performed" def self.coerce_input(input_value, _context) input_value end def self.coerce_result(ruby_value, _context) ruby_value end end end
require 'cpf_faker' FactoryGirl.define do factory :organ do name {Faker::Name.name} cnpj {Faker::CNPJ.numeric} site {Faker::Internet.domain_name} email {Faker::Internet.email} phone {Faker::PhoneNumber.cell_phone} eletronic_portal {Faker::Internet.domain_name} address {Faker::Address.stre...
require "horseman/dom/document" describe Horseman::Dom::Document do include Doubles subject { described_class.new(html) } context "when parsing forms" do it "finds all forms" do expect(subject.forms.count).to eq 3 expect(subject.forms[:form1].id).to eq "form1" expect(subject.forms[:form1].act...
class Application def initialize @current_section = 0 end def run loop do begin case @current_section when 0 main_controller when 1 train_controller when 2 station_controller when 3 route_controller ...
require './shared' input = '123487596' Cup = Struct.new(:label, :next) play = -> (labels, iterations) do min_label = labels.min max_label = labels.max current_cup = Cup.new(labels[0], nil) cups_by_label = { labels[0] => current_cup } last_cup = current_cup labels.drop(1).each do |label| next_cup = ...
class Event < ApplicationRecord include GoogleCalendar belongs_to :calendar scope :tomorrow_events, -> { where('start_at between ? and ?', Time.new.tomorrow.change(hour: 00, min: 00, sec: 00), (Time.new+2.days).change(hour: 00, min: 00, sec: 00)) } def import Calendar.where(notify: true).each do |calenda...
# One of the many strengths of ruby is it's ability for 'reflection'. # This means ruby can read information about a class or object at rubtime # and use any new information to help program itself. This is called metaprogramming. # Some key methods for this are: class(), instance_methods(), # instance_variables(), send...
feature "View a theme" do scenario "a user can view a theme for which he participates" do sign_up create_theme click_button "Budapest Holiday August 2019" expect(page).to have_content "Budapest Holiday August 2019" end end
# frozen_string_literal: true require "characterize/feature_set" module Characterize module Controller def self.included(klass) klass.extend(::Characterize::ControllerMacros) klass.helper_method(:characterize) end private # Apply character modules to the given object. # This will u...
source "https://rubygems.org" version_file = File.expand_path('.rails-version', __dir__) RAILS_VERSION = ENV['RAILS_VERSION'] || (File.exist?(version_file) && File.read(version_file).chomp) || "" gemspec eval_gemfile 'Gemfile-rspec-dependencies' gem 'yard', '~> 0.9.24', require: false group :documentation do gem ...
require "hatetepe/client" require "multi_json" require "json/ld" require "rdf" module Bazapta Vocab = RDF::Vocabulary.new("http://localhost:8080/terms/") class Client def initialize(uri) @uri = URI.parse(uri) @hatetepe = Hatetepe::Client.start(host: @uri.host, port: @uri.port) discover(@uri....
class Review < ActiveRecord::Base belongs_to :reservation belongs_to :guest, :class_name => "User", :foreign_key => "guest_id" #alias_attribute :user, :guest end
class RemoveUserNameToSports < ActiveRecord::Migration[5.1] def change remove_column :sports, :user_name, :string remove_column :sports, :user_image, :text end end
require 'helper' describe Nsqlookupd do before do @cluster = NsqCluster.new(nsqd_count: 1, nsqlookupd_count: 1) @nsqd = @cluster.nsqd.first @nsqlookupd = @cluster.nsqlookupd.first sleep 0.1 end after do @cluster.destroy end describe 'api endpoints' do describe '#ping' do it '...
servers = [ { :name => "master", :type => "master", :box => "debian/stretch64", :box_version => "9.9.1", :eth1 => "192.168.2.2", :mem => "2048", :cpu => "2" }, { :name => "node-1", :type => "node", :box => "debian/stretch64", ...
class Payment attr_reader :authorization_number, :amount, :invoice, :order, :payment_method, :paid_at def initialize(attributes = {}) @authorization_number, @amount = attributes.values_at(:authorization_number, :amount) @invoice, @order = attributes.values_at(:invoice, :order) @payment_method = attribu...
require "test_helper" class BankTest < ActiveSupport::TestCase test "code should be unique" do santander = banks(:santander) itau = banks(:itau) # Tests the uniqueness validation on model assert_raise ActiveRecord::RecordInvalid do santander.update!(code: itau.code) end # Tests the un...
require 'rubygems' require 'yaml' require 'bigdecimal' require 'codecal' require 'active_record' require 'enumerize' require 'paper_trail' require './app/models/application_record' Dir['./app/models/*.rb'].each {|file| require file } Dir['./app/models/transfer_ins/*.rb'].each {|file| require file } Dir['./app/models/t...
# -*- mode: ruby -*- # vi: set ft=ruby : # # Vagrant.configure("2") do |config| config.vm.box = "bento/centos-7.5" #config.vm.network "forwarded_port", guest: 443, host: 9443 config.vm.network "forwarded_port", guest: 8983, host: 8983 config.vm.network "forwarded_port", guest: 8984, host: 8984 config.vm.sy...
class BusinessCardsController < ApplicationController access_control do allow logged_in allow anonymous, :to => [:index, :show] end auto_complete_for :bc_school, :name def search @business_cards = BusinessCard.find(:all, :conditions => [ 'name LIKE ?', "%{params[:search]}%"]) end def ind...
class HomeController < ApplicationController def index if current_user if current_user.candidate redirect_to edit_candidate_path(current_user.candidate) else redirect_to admin_path end end end end
# frozen_string_literal: true module HealthQuest module PatientGeneratedData module Patient ## # A service object for isolating dependencies from any implementing service or controller. # # @!attribute session_service # @return [HealthQuest::SessionService] # @!attribute use...
class Storehouse def initialize column_count @column_count = column_count @columns = [[]]*@column_count end def state state_string = "" @columns.each_with_index do | column, index | column_contents = column.join(" ") if column_contents != "" column_contents = " " + column_co...
class AddCantidadToCotizclomuls < ActiveRecord::Migration[5.1] def change add_column :cotizclomuls, :cantidad, :string end end
=begin Raul Matias REM2174 =end output = "" (1..100).each do |number| if (number % 3 == 0) and (number % 5 == 0) output += "Raul Matias\n" elsif number % 5 == 0 output += "Matias\n" elsif number % 3 == 0 output += "Raul\n" else output += "#{number}\n" end end puts output
class CartItem < ApplicationRecord belongs_to :user belongs_to :item validates :count, presence: true end
require './lib/encryption_key' require './lib/encryption' require './lib/decryption' class Enigma attr_reader :message, :key, :date def initialize(message, key = random_number_generator, date = Time.now.strftime("%d%m%y")) @message = message @key = key @date = date @encryption_key = EncryptionKey....
require "rails_helper" RSpec.feature "User logs out" do context "As a logged in user" do let!(:user) { create(:user) } before(:each) do allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit links_path end describe "on the links page" do it ...
# 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 UserMailer < ApplicationMailer def signup_email(user) @user = user mail( :to => @user.email, :subject => 'Welcome to LiveDiet' ) end def checkin_reminder(user) @user = user mail( :to => @user.email, :subject => "Reminder of upcoming Check In") end end
# Write a code that takes user's input and then prints out "Yes it has C" # if entered input contains the letter "C" (upper or lower case). # And it prints "There is no C" if it doesn't puts "Enter value to check for letter C: " input = gets.chomp.strip.downcase c_count = input.count("c") if c_count > 0 puts "Yes ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or pr...
class HotsGenerate def hero_hashes @artanis_hash = { 'Damage' => 'Seasonded Marksman (4), Templars Zeal (4), Solarite Reaper (2), Purifier Beam (2), Triple Strike (2), Shield Surge (1), Nexus Blades (4)', ...
class CceReportSettingCopy < ActiveRecord::Base class << self def result_as_hash(batch,student_id) records=CceReportSettingCopy.find_all_by_batch_id_and_student_id(batch.id,student_id,:select=>"setting_key,data") if records.present? records=records.inject({}) do |result, element| r...
FactoryBot.define do factory :complex_building do owner {"Me owner"} address {"Me Address"} units { 10 } sqmt { 500 } price { 5400 } end end
Rails.application.routes.draw do root to: "posts#new" resources :posts, only: [:new, :create] end
login = LoginPage.new cliente = LoginClientePage.new Dado("que acesso a pagina de login") do visit "http://www.way2automation.com/angularjs-protractor/banking/#/login" end Quando("efetuo o login com:") do |table| nome = table.rows_hash["nome"] login.botao_login_cliente.click cliente.select_option(cliente.sele...
class FixEducationStatus < ActiveRecord::Migration[5.1] def change rename_column :educations, :graduated?, :status end end
class CreateCommittees < ActiveRecord::Migration def change create_table :committees do |t| t.integer :order_id t.string :committee_name t.string :chair t.string :vice_chair t.string :topic_guide_url t.string :image_url t.references :category t.boolean :is_active, d...
class FolderAssignmentType < ActiveRecord::Base has_and_belongs_to_many :assignable_folder end
class AddFieldsToStudents < ActiveRecord::Migration def change add_column :students, :lastemployer, :string add_column :students, :city, :string add_column :students, :state, :string end end
class JoinersController < ApplicationController before_action :set_joiner, only: [:show, :edit, :update, :destroy] # GET /joiners # GET /joiners.json def index @joiners = Joiner.all end # GET /joiners/1 # GET /joiners/1.json def show end # GET /joiners/new def new @joiner = Joiner.new ...
class RenameIntentToInterpretation < ActiveRecord::Migration[6.0] def change rename_table :intents, :interpretations rename_column :interpretations, :intentname, :interpretation_name rename_column :formulations, :intent_id, :interpretation_id reversible do |direction| direction.up do Fo...
require "helper" RSpec.describe Neovim do let(:client) { Support.persistent_client } let(:stream) do case Support.backend_strategy when /^tcp/, /^unix/ "socket" else "stdio" end end describe ".attach" do it "sets appropriate client info" do chan_info = client.evaluate("n...
class BuscadorAfiliadoTelegram def initialize(repo) @repo = repo end def find(id_telegram) @repo.find_by_telegram_id(id_telegram) end end
# responsible for processing invite request: fetch members with provided emails list, # iterate through this list, and sends invite emails using Sendgrid email service class InviteJob < ApplicationJob queue_as :default def perform(args) email_service = SendgridMailService.new Member.where(email: args).find...
class SubscriptionController < ApplicationController ################################################################ # The subscription controller handles all interaction between # users and their events, since they need to be subscribed to # an event in order to see it on their calendar. The parameters #...
class GoodDog DOG_YEARS = 7 attr_accessor :name, :age def initialize(n, a) self.name = n self.age = a * DOG_YEARS end end sparky = GoodDog.new("Sparky", 4) puts sparky.age
# frozen_string_literal: true gem "ruby-next-parser", ">= 2.8.0.3" gem "unparser", ">= 0.4.7" require "set" require "ruby-next" module RubyNext # Language module contains tools to transpile newer Ruby syntax # into an older one. # # It works the following way: # - Takes a Ruby source code as input # ...
require 'active_record' AVERAGE_WPM = 150 class Post < ActiveRecord::Base # Validation constraints validates :title, length: { minimum: 1, maximum: 400 } validates :content, length: { minimum: 1 } validates :user_id, presence: true # Associations belongs_to :user has_many :comments has_ma...
require 'spec_helper' describe Susanoo::GenresController do describe "フィルタ" do controller do %w(new edit).each do |act| define_method(act) do render text: "ok" end end end let(:top_genre) { create(:top_genre) } describe "reject_event_genre" do let(:event_...
class FontFzshusongZ01 < Formula head "https://cdn1.foundertype.com/Public/Uploads/ttf/FZSSK.TTF" desc "Fangzheng Shusong GBK" homepage "https://www.foundertype.com/index.php/FontInfo/index.html?id=151" def install (share/"fonts").install "FZSSK.ttf" end test do end end
require "rack" require "rack/request" require "rack/response" module Rack class Jekyll def initialize(opts = {}) @path = opts[:path].nil? ? "_site" : opts[:path] @auto_build = opts[:auto].nil? ? false : opts[:auto] @files = Dir[@path + "/**/*"].inspect @mimes = Rack::Mime::MIME_TYPES...
$LOAD_PATH.unshift(File.join(File.split(File.dirname(__FILE__))[0], 'lib')) require "minitest/autorun" require "mocha/mini_test" class TestCase < Minitest::Test class DummyShell def method_missing(method, *args) instance_variable_set(:"@#{method}", [args]) self.class.send(:define_method, method) do...
class Like < ApplicationRecord belongs_to :user belongs_to :likeable, polymorphic: true validates :like_status, :user_id, :likeable_id, :likeable_type, presence: true validates :user_id, uniqueness: {scope: [:likeable_id, :likeable_type]} validates :like_status, numericality: { only_integer: true, greater_...
require 'json' require 'thread' class GemDependencies def initialize(gem_names_and_versions) dependents_hash = {} gem_names_and_versions.each do |name, version| dependents_hash[name] = { :version => read_version(version), :dependents => [] } end @dependents_hash = depende...
class MigrateUpgradesToData2 < ActiveRecord::Migration[5.1] def change add_column :upgrades, :limited, :integer add_column :upgrades, :cost, :integer add_column :upgrades, :hyperspace, :boolean remove_foreign_key :upgrades, :upgrade_types remove_column :upgrades, :image_path, :string remove_co...
require_relative 'player' class HumanPlayer < Player def get_move_sequence input = [nil, nil] puts "What piece did you want to move?" puts "Enter the coordinates as comma separated values" until valid_coords?(input) input = gets.chomp.split(',').map(&:strip) end moves = [...
class BookController < ApplicationController def index @books = Book.get_books end end
ENV['RAILS_ENV'] ||= 'test' require 'active_record' ActiveRecord::Base.logger = Logger.new($stdout) if ENV['DEBUG'] $LOAD_PATH.unshift File.expand_path("#{__dir__}/../app") # load rails/redmine if ENV['REDMINE_PATH'] require File.expand_path('config/environment', ENV['REDMINE_PATH']) else require File.expand_path...
FactoryBot.define do factory :user, class: User do first_name "test" # last_name "hoge" first_name_kana "カナ" last_name "ホゲ" zip_code "123-4567" phone_number '123-4567-8900' email "test@test" password "123456" end factory :admin, class: User do first_name "admin" ...
class Api::LikesController < ApplicationController before_filter :require_signed_in! def create @like = Like.new(like_params) @like.liker_id = current_user.id @like.save! end def destroy @like = Like.find_by(pic_id: params[:id], liker_id: current_user.id) @like.destroy! end private ...
ActiveAdmin.register Driver do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # menu priority: 2 permit_params :name, :grade, :car_id # # or # # permit_params do # permitted = [:permitted, :attributes] # ...
class Proficiency < ActiveRecord::Base # Remember to create a migration! belongs_to :skill belongs_to :user validates_inclusion_of :formal?, :in => [true, false] end
# frozen_string_literal: true describe Zafira::Rspec::Formatter do let(:formatter) { Zafira::Rspec::Formatter.new(nil) } before do allow_any_instance_of(Logger).to receive(:info).and_return(nil) allow_any_instance_of(Logger).to receive(:error).and_return(nil) end before do allow_any_instance_of(Z...