text
stringlengths
10
2.61M
class Species < ActiveRecord::Base #sighting has one species and belongs to a region; a region has many sightings validates :name, :presence => true #a species has many sightings; a sighting has one species belongs_to :regions #todo whats the difference has_many :sightings end
require 'spec_helper' module Refinery module Testimonials describe Testimonial, type: :model do let(:good_testimonial) { FactoryBot.create(:testimonial)} let(:no_name_testimonial) { FactoryBot.create(:testimonial, name: "") } let(:no_quote_testimonial) { FactoryBot.create(:testimonial, qu...
#!/usr/bin/env ruby require 'csv' require 'rally_rest_api' require 'ostruct' require 'optparse' require 'yaml' require 'gruff' options = OpenStruct.new options.csvoutput = false options.pdfouput = false options.iteration = "" options.user = nil options.password = nil opts = OptionParser.new opts.banner = "Usage: tas...
Rails.application.routes.draw do resources :articles, only: [:index, :create, :show] do resources :comments end root "articles#index" end
module QuotientCube module Tree module Query class Point < Base def process(selected = {}) node_id = tree.nodes.root tree.dimensions.each_with_index do |dimension, index| value = conditions[dimension] if value != nil and value != '*' ...
class ApplicationController < ActionController::API include ActionController::MimeResponds include ActionController::ImplicitRender include ActionController::StrongParameters before_action :cors_set_access_control_headers ################### # ERROR RESPONSES # ################### # Generic fallbac...
class MenuItem < ActiveRecord::Base before_save :linkit belongs_to :menu #acts_as_nested_set attr_accessor :page attr_accessor :url def published? self.published == 1 end private def linkit self.link = ( self.page == 0 ) ? self.url : self.page end end
FactoryGirl.define do factory :start_time do day_of_week 1 time '2014-12-14 00:44:29' track nil is_repeated true factory :start_time_with_date do day_of_week nil date 2.day.from_now is_repeated false end factory :start_time_with_passed_date do day_of_week nil ...
class ItemApisController < ApplicationController # GET /item_apis # GET /item_apis.xml def index @item_apis = ItemApi.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @item_apis } end end # GET /item_apis/1 # GET /item_apis/1.xml def show @...
module API module V1 class WordsController < ApplicationController def index words = Word.all render json: words, status: 200 end def show word = Word.find(params[:id]) render json: word, status: 200 end def create word = Word.new(word_param...
class Api::Merchant::BaseController < ApplicationController skip_before_filter :verify_authenticity_token before_filter :authenticate_merchant!, :set_headers respond_to :json before_filter :set_headers private def set_headers if request.headers["HTTP_ORIGIN"] #&& /^https?:\/\/(.*)\.some\.site\.co...
module ProductPriceRangeHelper def product_price_range(product) price = number_to_currency(product.min_price, strip_insignificant_zeros: true) price = "#{price} - #{number_to_currency(product.max_price)}" unless product.min_price == product.max_price price end end
Moli::Application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". root 'recipes#index' get '/register', to: 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get...
require 'spec_helper' describe User do before(:each) do @attr = { :name => "Example User", :email => "user@example.com", :password => "changeme", :password_confirmation => "changeme" } end it "creates a new instance given a valid attribute" do User.create!(@attr) end it...
class TasksController < ApplicationController before_filter :signed_in_user, only: [:index, :create, :update, :edit, :destroy] before_filter :correct_user, only: [:destroy, :edit, :update] def index @tasks = Task.where(:complete => false) @tasks_complete = Task.where(:complete => true) @user = current_us...
# 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...
# frozen_string_literal: true class StopSerializer < ActiveModel::Serializer attributes :id, :x, :y end
# -*- ruby -*- #encoding: utf-8 require 'simplecov' if ENV['COVERAGE'] require 'rspec' require 'loggability/spechelpers' require 'arborist' require 'arborist/mixins' require 'arborist/webservice' RSpec::Matchers.define( :match_criteria ) do |criteria| match do |node| criteria = Arborist::HashUtilities.stringify...
module Machsend module RPC class ClientToClient def initialize(base, client) @base, @client = base, client end def sync @client.refresh true end def assets @base.assets end def download(guid) @asset = @base.asset_by_gui...
class AddRangeFieldtoTemplateFields < ActiveRecord::Migration def change add_column :template_fields, :start_of_range, :integer add_column :template_fields, :end_of_range, :integer end end
class Question attr_reader :num1, :num2 attr_accessor :is_right def initialize(current_player) @num1 = 1 + rand(20) @num2 = 1 + rand(20) puts "#{current_player}: What does #{num1} plus #{num2} equal?" print "> " end def ques @num1 + @num2 end def answer users_input = $stdin.gets...
# frozen_string_literal: true class Role < ::ApplicationRecord def table_id = 'rol' has_many :users has_many :allowed_actions, dependent: :destroy class << self def admin = find_by!(name: 'admin') def login = find_by!(name: 'login') def default = find_by!(name: 'default') end end
class SubCategory < ActiveRecord::Base has_many :product_categories has_many :products, through: :product_categories belongs_to :category, inverse_of: :sub_category rails_admin do navigation_label 'Cadastros' list do field :id field :name field :category end edit do field :name ...
class CommentsController < ApplicationController layout false before_filter :authenticate_user! def create @comment = Comment.new(params[:comment]) unless [@comment.bid.bidder, @comment.bid.requestor].include?(current_user) render json: {error: 'Unauthorized'}, status: :unauthorized return ...
# 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 PropertyListingSerializer < ApplicationSerializer include ActionView::Helpers::DateHelper attributes :id, :bhk, :address, :property_type, :buildup_area, :bathrooms, :furnish_type, :rent, :security_deposit, :created_at, :poster_id, :image_url, :is_shortlisted, :is_created has_many ...
class User < ApplicationRecord include Searchable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :omniautha...
class Vote < ActiveRecord::Base belongs_to :movie belongs_to :user enum rating: {disliked: -1, liked: 1, not_voted: 0} scope :likes, ->() { liked } scope :dislikes, ->() { disliked } scope :user, ->(user) { where user: user} scope :movie, ->(movie) { where movie: movie} def liked self.rating = :...
class DownloadsController < ApplicationController def index @title = "Downloads" version_file = (Pathname(__dir__) + "../../../data/bcb-version.txt") @bcb_version = version_file.exist? ? version_file.read.strip : "unknown" version_file = (Pathname(__dir__) + "../../../data/xmage-version.txt") @xma...
# Controller for execution environments class EnvironmentsController < ApplicationController before_action :verify_login before_action :set_environment, only: %i[show update destroy edit] # GET /environments def index respond_to do |format| format.html do # Show all the user's environments ...
class Team < ApplicationRecord belongs_to :game has_many :players end
# === COPYRIGHT: # Copyright (c) Jason Adam Young # === LICENSE: # see LICENSE file class BatterPlayingTime < ApplicationRecord include CleanupTools belongs_to :roster def remaining_starts self.allowed_starts - self.gs end def need_ab need_ab = (self.qualifying_ab - self.ab) (need_ab >= 0) ? (...
# When done, submit this entire file to the autograder. # Part 1 def sum arr arr.reduce(0, :+) end def max_2_sum arr arr.empty? ? 0 : arr.sort.last(2).reduce(:+) end def sum_to_n? arr, n arr.length < 2 ? false : (arr.combination(2).find{|x,y| x + y == n } ? true : false) end # Part 2 def hello(name) "Hell...
class AgentsController < ApplicationController before_action :set_agent, only: [:show, :edit, :update, :destroy] def index if params[:filter] @agents = params[:filter][:on_assignment] ? Agent.on_assignment : Agent.not_on_assignment else @agents = Agent.all end end def show end def...
class AddGoogleVerificationKeyToKuhsaftPages < ActiveRecord::Migration def change add_column :kuhsaft_pages, :google_verification_key, :string end end
# https://docs.hetzner.cloud/#resources-actions-get module Fog module Hetznercloud class Compute class SshKey < Fog::Model identity :id attribute :name attribute :fingerprint attribute :public_key def destroy requires :identity service.delete_ss...
# frozen_string_literal: true require 'uri' RSpec.describe URI do it 'parses the host' do expect(URI.parse('http://foo.com/').host).to eq 'foo.com' end it 'parses the port' do expect(URI.parse('http://example.com:9876').port).to eq 9876 end it 'defaults the port for an http URI to 80' do expect(...
class Api::V1::HealthController < ApplicationController def health render json: {message: "API status ok"}, status: :ok end end
# This migration comes from authentify (originally 20120608223732) class CreateUsers < ActiveRecord::Migration def change create_table :authentify_users do |t| t.string :name t.string :email t.string :login t.string :encrypted_password t.string :salt t.string :status, :default ...
class Event < ActiveRecord::Base validate :date_must_be_valid validates :date, presence: true, format: {with: /....\-..\-../} validates :title, presence: true, uniqueness: true validates :organizer_name, presence: true validates :organizer_email, format: {with: /.+@.+\..+/} def date_must_be_valid if da...
class CreateTeams < ActiveRecord::Migration[5.2] def change create_table :teams do |t| t.string :name t.string :description t.string :twitter t.string :instagram t.string :github t.timestamps end end end
require 'rails_helper' RSpec.describe AdminApplication do describe 'show page' do it 'can approve a Pet for adoption' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) shelter_2 = Shelter.create(name: 'RGV animal shelter', city: 'Harlingen, TX', f...
class User def initialize @fname = "Johnny" @lname = "Designer" @email = "hello@domain.com" @title = "Senior Director of Fun" @experience = 3 @joined = "#{Time.now.month}/#{Time.now.day}/#{Time.now.year}" @admin = false @behance_username = "lexevan" @project_covers = [] end ...
class MeasurementController < ApplicationController before_action :verify_token, only: %i[index create show destroy] before_action :set_measurement, only: %i[show destroy] def index @measurements = current_user.measurements render :all, formats: :json, status: :ok end def create @measurement = c...
class RemoveProviderIdFromLiveVideos < ActiveRecord::Migration def change remove_index :live_videos, :provider_id remove_column :live_videos, :provider_id end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # gender_id :string(255) # created_at :datetime # updated_at :datetime # modelling_agency :string(255) # phone_number ...
require 'rails_helper' RSpec.feature 'Editing price in admin area', settings: false do given!(:price) { create(:effective_price) } background do sign_in_to_admin_area end scenario 'updates price' do visit admin_prices_path open_form submit_form expect(page).to have_text(t('admin.billing....
# How can I show a files modification date with Jekyll? # http://stackoverflow.com/a/18233371/16185 module Jekyll module ModifiedDate def file_date(path) source_dir = @context.registers[:site].source # This doesn't look reliable posts_dir = File.join(source_dir, '_posts') post_path = File.join(...
class NotificationMailer < ActionMailer::Base default from: "from@example.com" def notification_email(report) @report = report mail(to: @report.service.contact.pluck(:email), from: @report.user.email, cc: @report.user.email, subject: 'Systems Emergency: ' + @report.service.name) end end
require('spec_helper') describe(Venue) do it("ensures the presence of a name") do venue = Venue.new({:name => ""}) expect(venue.save()).to(eq(false)) end it("ensures the presence of a location") do venue = Venue.new({:location => ""}) expect(venue.save()).to(eq(false)) end it("properly capi...
class ContactMailer < ActionMailer::Base default from: "from@example.com" def contact_email(contact) @contact = contact mail(to: rstevenson542@gmail.com, subject: "Website Contact Form") end end
class User < ApplicationRecord has_many :comments has_many :images, as: :image_type has_and_belongs_to_many :achievements end
class User < ApplicationRecord before_create :generate_friendly_id has_many :albums, dependent: :destroy has_many :posts, dependent: :destroy validates :name, presence: true validates :friendly_id, uniqueness: { case_sensitive: false }, format: { with: /\A[A-Za-z][\w-]*\z/ }, ...
class EventsController < ApplicationController before_action :set_event, only: [:show, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] # GET /events def index @events = Event.all render json: @events end # GET /events/1 def show @event.view_count += 1 @even...
class Wiki < ApplicationRecord belongs_to :user validates :user, presence: true has_many :collaborators, dependent: :destroy has_many :users, through: :collaborators validates :title, presence: true validates :body, presence: true end
require_relative 'acceptance_helper' feature 'Make new search', %q{ As some user I want to be able to update username} do given!(:user) { create(:user, name: 'SomeUser', email: 'some@email.test') } given!(:other_user) { create(:user, name: 'SomeOtherUser', email: 'someother@email.test') } given!(:one_commit) { c...
module Pyrite module Assertions # Assert some text appears somewhere on the page def assert_text(text, msg=nil) assert browser.text?(text), msg || "Text '#{text}' not found on page" end # Assert some text does not appear somewhere on the page def assert_no_text(text, msg=nil) assert ...
class AddDraftPlayers < ActiveRecord::Migration[5.2] def change create_table "draft_players", id: :integer, force: :cascade do |t| t.integer "season" t.references :player t.references :roster t.string "firstname", default: "", null: false t.string "lastname", default: "", null: false...
class AnimalsController < ApplicationController def index @zoo = params[:zoo_id] @zoo_animals = Zoo.find_by_id(@zoo) @animals = @zoo_animals.animals end def new @animal = Animal.new @zoo = Zoo.find params[:zoo_id] end def create @zoo = Zoo.find params[:zoo_id] @animal = @zoo.animals....
class Technician < ActiveRecord::Base belongs_to :account, class_name: Account belongs_to :group, class_name: Group validate :is_technician_account def is_technician_account account = Account.find(account_id) unless account.technician? errors.add(:technician, 'cannot add non-technician to Techn...
# == Schema Information # # Table name: path_subscriptions # # id :integer not null, primary key # path_id :integer # user_id :integer # # Indexes # # index_path_subscriptions_on_path_id (path_id) # index_path_subscriptions_on_user_id (user_id) # class PathSubscription < ApplicationRecord belong...
module Archangel class Post < ApplicationRecord acts_as_paranoid # Callbacks before_validation :parameterize_slug before_save :stringify_meta_keywords before_save :build_path_before_save after_destroy :column_reset # Uploader mount_uploader :feature, Archangel::FeatureUploader #...
class PeopleController < ApplicationController before_action :set_person, only: [:show, :edit, :update] # GET /people/1 # GET /people/1.json def show end # GET /people/new def new @person = Person.new end # GET /people/1/edit def edit @symptoms = Symptom.all end # POST /people # PO...
# Specification: health insurance contribution class InsuranceHealthTag < PayrollTag def initialize super(PayTagGateway::REF_INSURANCE_HEALTH, PayConceptGateway::REFCON_INSURANCE_HEALTH) end def deduction_netto? true end end
require 'rubygems' require 'zlib' class MultipartSitemap # to speed things up, this uses the permalink columns directly. If we ever # change how to create the canonical links for categories, products, reviews # or profile pages, this will need to be updated. PRIORITIES = { :home => 0....
# A loyalty currency such as miles or points which a user can spend on flights # (and other rewards) # # An specific user's balance in a specific currency (if they have one) is # stored in the `balances` table. # # Attributes: # - name: # the currency's name. This will be seen by users; i.e. it's not just for # ...
module EmSpecHelper # This is designed to work like EM.connect -- # it mixes the module into StubConnection below instead of EM::Connection. # It does *not* run within an EM reactor. # The block passed it should set any expectations, and # then call the callbacks being tested. # These will ...
class Admin::InventoryController < ApplicationController before_action :set_garments, :set_categorys def index authorize! :edit, Category end private def set_garments @garments = Garment.all end def set_categorys @categories = Category.all end end
Capistrano::Configuration.instance(:must_exist).load do desc "Setup configuration variables for deploying in a "\ "production environment" task :staging do # Population of roles requires setting up of environment # variables for the different roles. The expected syntax # is a simple csv. ...
class UsersController < ApplicationController before_action :authenticate, except: :show before_action :user_self?, except: :show def show @user = User.find_by_id(params[:id]) @symptoms = Symptom.where(:user_id => @user.id).reverse_order end def destroy @user = current_user @user.destroy! ...
module Amorail # AmoCRM lead entity class Unsorted < Amorail::Entity attr_accessor :contacts, :leads, :pipeline_id, :form_id, :form_page validates :form_id, :form_page, presence: true def initialize(*args) super self.contacts ||= [] self.leads ||= [] end protected def c...
# frozen_string_literal: true class UserPresenter < ApplicationPresenter def roles Enums.user_roles end end
# @param {Integer[]} nums # @param {Integer} target # @return {Integer[]} def two_sum(nums, target) hash_nums = {} (0...nums.length).each do |i| another = target - nums[i] return [hash_nums[another], i] if hash_nums.has_key?(another) hash_nums[nums[i]] = i end end
require 'spec_helper' describe 'visit games#show' do subject { page } before :each do create_and_sign_in_user click_button('Play as X') end it { should have_selector('h1') } it { should have_selector('div.gameboard') } it { should have_selector('div.square', count: 9) } it { should have_selecto...
require "rails_helper" RSpec.describe Tag, type: :model do it "is invalid with missing attributes" do tag = Tag.new(name: nil) expect(tag).to_not be_valid end it "is valid with all attributes" do tag = Tag.new(name: "Moon") expect(tag).to be_valid end end
class CreateDemandResponses < ActiveRecord::Migration def change create_table :demand_responses do |t| t.references :interval, index: true, foreign_key: true t.timestamps null: false end end end
class UserTwoFactorAuthenticationMutation < Mutations::BaseMutation graphql_name "UserTwoFactorAuthentication" argument :id, GraphQL::Types::Int, required: true argument :password, GraphQL::Types::String, required: true argument :qrcode, GraphQL::Types::String, required: false argument :otp_required, GraphQL...
# 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 Picture < ActiveRecord::Base validates :title, :artist, :url, presence: true validates :title, length: { in: 3..20 } validates :url, uniqueness: true end
#!/usr/bin/env ruby -rubygems -wKU require 'rdiscount' require 'time' require 'index' require 'erb' require 'page' INTRAY_DIR = "InTray" OUTTRAY_DIR = "OutTray" MAIN_STYLESHEET_FILENAME = "styles/main.css" MAIN_DOCUMENT_TEMPLATE = "main_page_template.erb.txt" INDEX_STYLESHEET = MAIN_STYLESHEET_FILENAME CREATION_TIM...
class CreateLtiDeployments < ActiveRecord::Migration[5.1] def change create_table :lti_deployments do |t| t.bigint :application_instance_id t.string :deployment_id t.timestamps end add_index :lti_deployments, :application_instance_id add_index :lti_deployments, :deployment_id add...
class AddPriorityToUsers < ActiveRecord::Migration def change add_column :users, :priority_level, :int end end
# Run me with `rails runner db/data/20230718131711_import_ukri_level_d_budgets.rb` # Script to add budgets to activities when those budgets cannot be added via bulk upload (for example they are for a # level not currently handled by bulk upload). # Re-usable if you replace `file_name` with the path to your chosen csv...
#!/run/nodectl/nodectl script # Compare datasets/snapshots between DB and on-disk states # # This script does not take any locks, so some mismatches may be due to changes # being done while this script is running. require 'nodectld/standalone' include OsCtl::Lib::Utils::Log include NodeCtld::Utils::System class Data...
require 'test_helper' class CommentsControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do @comment = comments(:one) @lecture = lectures(:one) end test "should get edit" do sign_in users(:one) get edit_lecture_comment_url(@lecture,@comment) asser...
class CreateProfiles < ActiveRecord::Migration def self.up create_table :profiles do |t| t.integer :user_id t.string :first_name t.string :last_name t.string :city t.string :state t.string :country t.string :postal_code t.string :job_title t.string :website ...
module TheCityAdmin FactoryGirl.define do factory :user_process_answer, :class => TheCityAdmin::UserProcessAnswer do question_id 316 question "Do you like foo?" answer "bar" answered_at Date.today required true end end end
module ApplicationHelper def formatted_price(price, currency = nil) currency = (currency || current_currency) if CoingateService::CRYPTO_CURRENCIES.include? currency "#{price} #{currency}" else number_with_precision(price, precision: 2).to_s + ' ' + currency end end def currency_ico...
class MapFacade attr_reader :location def initialize(location) @location = location end def closest_electric_station service = NrelService.new nearest_station_data ||= service.fetch_electric_stations(@location) Station.new(nearest_station_data) end end
class AddTwitterScreenNameToUsers < ActiveRecord::Migration def self.up add_column :photos, :migrated, :string add_column :users, :twitter_screen_name, :string add_column :users, :twitter_oauth_token, :string add_column :users, :twitter_oauth_secret, :string add_column :users, :twitter_avata...
class Api::CourseLevelsController < Api::ApplicationController def mass_update_order level_ids = params[:ids] levels = Course::Level.find(level_ids) level_ids.map!(&:to_i); levels.each do |level| order = level_ids.index(level.id) level.update_attribute :order_at, order end head ...
#!/usr/bin/env ruby ## BrianWGray ## Carnegie Mellon University ## Initial Creation date: 10.05.2016 ## = Description: ## == The script performs the following: # 1. load fingerprint file # 2. Apply the fingerprint file to a provided uri # 3. Return data as filtered by the finger print. # # Examples: # - "ruby de...
require_relative "pseudo_db/version" require_relative "pseudo_db/database" module PseudoDb DEFAULTS = { adapter: 'mysql', user: nil, password: nil, host: 'localhost', database: 'test', dry_run: false, custom_dictionary: nil } def anonymize(options = {}) options = D...
require 'rails_helper' describe MeasureSelection do it { is_expected.to validate_presence_of(:measure_id) } it { is_expected.to validate_presence_of(:audit_report_id) } it { is_expected.to belong_to(:measure) } it { is_expected.to belong_to(:audit_report) } it { is_expected.to have_many(:field_values) } ...
FactoryGirl.define do factory :user, class: 'Authentify::User' do name "Test User" login 'testuser' email "test@test.com" password "password1" password_confirmation {password} status "active" last_updated_by_id...
# frozen_string_literal: true require 'socket' module Dynflow class Config include Algebrick::TypeCheck def self.config_attr(name, *types, &default) self.send(:define_method, "validate_#{ name }!") do |value| Type! value, *types unless types.empty? end self.send(:define_method, nam...
require 'test_helper' class HomeControllerTest < ActionController::TestCase test "html updates" do end test "iphone version" do end test "rjs updates" do end test "should success access home" do get :index assert :success end test "should get last tags" do get :index assert_not_nil assigns(...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, authentication_keys: [:email, :team_name]...
class Component < ApplicationRecord belongs_to :text has_many :component_citations accepts_nested_attributes_for :component_citations, reject_if: :all_blank, :allow_destroy => true def translators unless @translators load_citations_by_role end @translators end def load_citations_by_role...
json.articles @articles do |article| json.published_at article.published_at json.title article.title end