text
stringlengths
10
2.61M
class ExpensePolicy < ApplicationPolicy def index? user.role.can_view_expense end def create? user.role.can_create_expense end def update? user.role.can_update_expense end def destroy? user.role.can_destroy_expense end end
class Banking < ActiveRecord::Base has_many :cash_counts def amounts cash_counts.map(&:total_cash_counted) * ' ' end end
=begin Write your code for the 'Difference Of Squares' exercise in this file. Make the tests in `difference_of_squares_test.rb` pass. To get started with TDD, see the `README.md` file in your `ruby/difference-of-squares` directory. =end class Squares def initialize(n) @num = (1..n).to_a end # takes @num, su...
class FriendRequest < ActiveRecord::Base belongs_to :user belongs_to :sender, :class_name => "User" end
# -*- encoding : utf-8 -*- class AddConfigurationToDevices < ActiveRecord::Migration def change add_column :devices, :configuration_id, :int end end
# IMPORTANT: AVAILABILITY_OPTIONS is used for a bitmask field. Once you have data using a bitmask, don’t change the order of the values, remove any values, or insert any new values in the ':as' array anywhere except at the end. You won’t like the results. AVAILABILITY_OPTIONS = [ :local_monday_morning, :local_mon...
# encoding: UTF-8 $: << '../lib' require 'minitest/autorun' require 'ruby-hl7' class ObrSegment < MiniTest::Test def setup @base = "OBR|2|^USSSA|0000000567^USSSA|37956^CT ABDOMEN^LN|||199405021550|||||||||||||0000763|||||P||||||R/O TUMOR|202300&BAKER&MARK&E|||01&LOCHLEAR&JUDY" end def test_read obr = Ru...
class CartesianProduct include Enumerable def initialize(seq1, seq2) @seq1 = seq1 @seq2 = seq2 end def each @seq1.each do |v1| @seq2.each do |v2| yield [v1, v2] end end end end
# Basic implementation of a tagged logger that matches the API of # ActiveSupport::TaggedLogging. require 'delegate' require 'logger' module Kafka class TaggedLogger < SimpleDelegator %i(debug info warn error).each do |method| define_method method do |msg_or_progname, &block| if block_given? ...
class SkillsController < ApplicationController respond_to :json def index if params[:q].blank? head :not_found and return end query_str = params[:q] tags_found = Tag.search_by_name_alike(query_str) if tags_found.empty? head :not_found and return end render json: tags_fou...
require 'spec_helper' describe BatchController, proxy: true do let(:user) { FactoryGirl.create(:user, first_name: "First", middle_name: "Middle", last_name: "Last") } let(:batch) { Batch.create } let(:generic_file) do GenericFile.new.tap do |gf| gf.depositor = user.user_key gf.batch = batch ...
module Sumac class Calls # Manages calls originating from the remote endpoint. # Keeps track of ongoing calls such that: # * a killed connection can wait for them to finish # * the connection can be set to the correct state when it knows all calls have completed # @api private class RemoteCal...
# frozen_string_literal: true module Readapt class Frame attr_reader :location def initialize location, binding_id @location = location @binding = ObjectSpace._id2ref(binding_id) end def evaluate code @binding.eval(code).inspect rescue Exception => e "[#{e.class}] #{e.me...
class Appointment < ActiveRecord::Base default_scope { order(appt_time: :asc) } end
require 'HTTParty' require 'rubygems' require 'nokogiri' require 'open-uri' require 'uri' u1 = "http://techcrunch.com/foo/bar" #=> "techcrunch.com" u2 = "http://www.techcrunch.com/foo/bar" #=> "techcrunch.com" u3 = "www.techcrunch.com/foo/bar" #=> "techcrunch.com" class GetUrl attr_accessor :url, :publisher, :hos...
# frozen_string_literal: true module BeyondApi module Utils extend self def file_content_type(file_path) case File.extname(file_path) when ".png" "image/png" when ".jpg", ".jpeg" "image/jpeg" when ".gif" "image/gif" end end def handle_all_reques...
# -*- coding: utf-8 -*- # # Author:: lnznt # Copyright:: (C) 2011 lnznt. # License:: Ruby's # require 'test/unit' require 'gmrw/extension/string' class TestFields < Test::Unit::TestCase def try_assert_equal(tests) tests.each_with_index do |test, i| actual, expected = test.first assert_equal(expected...
class Hello DATA_PATH = File.join(File.dirname(__FILE__), "..", "data") def self.random(opts = {}) invalid_option_feedback unless valid_options?(opts) hellos = collect_hellos("inoffensive") hellos |= collect_hellos("male") if male?(opts) hellos |= collect_hellos("female") if female?(opts) ...
class KeyFrame include Mongoid::Document field :timestamp, type: Integer field :x, type: Integer field :y, type: Integer field :width, type: Integer field :height, type: Integer field :is_outside, type: Boolean, default: false field :is_occluded, type: Boolean, default: false embedded_in :annotatio...
class CreateRetailslider < ActiveRecord::Migration def change create_table :retailsliders do |t| t.string :image t.string :first_title t.string :second_title t.boolean :show end end end
class NvsDeptUsersController < ApplicationController before_filter :find_project, :prepare_combos before_filter :authorize # GET /nvs_dept_users # GET /nvs_dept_users.json def index @nvs_dept_users = NvsDeptUser.all respond_to do |format| format.html # index.html.erb format.json { rende...
class BlaguesController < ApplicationController load_and_authorize_resource def index unordered = Blague.page(params[:page]).per(10).includes(:user) if params[:order] == "score" @blagues = unordered.order("votes_count DESC") elsif params[:order] == "comments" @blagues = unordered.order("co...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
# frozen_string_literal: true RSpec.describe 'Event Printout Request', type: :request do include_context 'with branch location' include_context 'with user token' include_context 'with json response' include_context 'with event' let(:attendee_one) { build(:event_attendee) } let(:attendee_two) { build(:even...
require 'minitest/autorun' require 'mdml' class LogicUnitTest < Minitest::Test include MDML def test_plain logic = Logic.parse("a == 1") assert_equal ['a == 1'], logic end def test_invalid_condition assert_raises SyntaxError do logic = Logic.parse("a ! 1") end end def test_singl...
#cd c:/Users/renan/Desktop/DBC/Gist_repo/devbootcamp/phase-0-tracks/ruby # ENCRYPT SESSION encrypt = "zed" def encrypt (input) #decelerating method variables index = 0 space = "" #loop to select letters while index < input.length #selecting letter letter = input[index] ...
# frozen_string_literal: true class GenericMailer < ApplicationMailer def generic_message(user, message) @to_list = [user.email] @message = message mail(to: @to_list, subject: "A Message from America's Boating Club - Birmingham Squadron") end end
module ApplicationHelper def nav_item(label, path, current_controller_name) if controller_name == current_controller_name content_tag :li, :class => 'active' do link_to label, path end else content_tag :li do link_to label, path end end end def icon_link(icon,...
require_relative 'helpers/loggable' require_relative '../exports/helpers/actionable' module Susanoo module ServerSync class Worker include ServerSync::Helpers::Loggable include ::Susanoo::Exports::Helpers::Actionable class_attribute :retry_interval self.retry_interval = 10.minutes # 再試行...
class Article < ApplicationRecord belongs_to :user, class_name: 'User', foreign_key: :author_id validates :content, presence: true end
class ProfilesController < ApplicationController before_action :authenticate_user!, only: [:edit, :update] def show @user = User.find_by_username(params[:id]) @user ||= current_user end def edit @user = User.find_by_username(params[:id]) @user ||= current_user end def update @user = User.find_...
class CreateAccountGroups < ActiveRecord::Migration def self.up create_table :account_groups do |t| t.column :name, :string, :null => false t.column :description, :string t.integer :slfgrp t.column :created_at, :datetime t.column :updated_at, :datetime t.timestamps end ...
class SessionsController < ApplicationController skip_before_action :authenticate_user def active render_session_status end def timeout if $user_logged_to_logout user = User.find $user_logged_to_logout.id.to_i user.save_date_logout $user_logged_to_logout = nil end render_session_timeout end ...
#require 'pry' # code goes here ## Pseudocoding: ## 1. Define attributes (owner will have attr_accessor; name will have attr_reader) ## 2. Initialize name and owner args ## 3. Cat starts with a nervous mood ## 4. Need @@all --> class variable of cats that keeps track of all cats class Cat attr_reader :name a...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception rescue_from ActionController::RoutingError do |exception| logger.error 'Routing error occurred' render plain: '404 Not found', status: 404 end end
class CreateCakes < ActiveRecord::Migration def change create_table :cakes do |t| t.references :item, index: true#, foreign_key: true t.integer :hearts_limit t.timestamps null: false end end end
class CreateOperators < ActiveRecord::Migration def change create_table :operators do |t| t.timestamps end add_column :operators, :name, :string add_column :operators, :connection_type, :string end end
=begin #qTest Manager API Version 8.6 - 9.1 #qTest Manager API Version 8.6 - 9.1 OpenAPI spec version: 8.6 - 9.1 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require "uri" module SwaggerClient class TestsuiteApi attr_accessor :api_client def initialize(api_clie...
# frozen_string_literal: true require "cell/partial" module Decidim module Opinions # This cell renders the link to the rejected emendation promoted to opinion. class OpinionLinkToRejectedEmendationCell < OpinionLinkedResourcesCell private def linked_resource @linked_resource ||= model....
class Recipe < ActiveRecord::Base validates :name, presence: true has_many :recipe_ingredients has_many :ingredients, through: :recipe_ingredients # accepts_nested_attributes_for :ingredients def ingredients_attributes=(ingredients_attributes) ingredients_attributes.values.each do |name| ingredient...
class Gallery attr_reader :name, :city @@all = [] def self.all @@all end def initialize(name, city) @name = name @city = city @@all << self end def paintings Painting.all.select{|painting| painting if painting.gallery == self} end def artists self.paintings.map {|painting|...
# frozen_string_literal: true ROM::SQL.migration do change do create_table :tasks do primary_key :id column :name, String, null: false column :project_id, String, null: false column :user_id, String, null: false column :assigned_user_id, String, n...
class EventDetail < ActiveRecord::Base has_many :images, as: :imageable mount_uploader :image, ImageUploader end
require 'test_helper' class LatestDocumentsFilterTest < ActiveSupport::TestCase class FauxFilter < LatestDocumentsFilter private def documents_source subject.published_editions end end test '.for_subject should return an instance of ClassificationFilter for a topic' do topic = create(:topic)...
# This migration comes from phcmembers (originally 20160728231036) class CreatePhcmembersMemberProfiles < ActiveRecord::Migration[5.2] def change create_table :phcmembers_member_profiles do |t| t.string :member_first_name t.string :member_last_name t.string :member_title t.string...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class CreateCurrents < ActiveRecord::Migration[5.2] def change create_table :currents do |t| t.decimal :amount, {precision: 10, scale: 2} t.decimal :balance, {precision: 10, scale: 2} t.string :sort t.string :operation t.integer :date t.references :account t.timestamps ...
class DfTransactionsController < ApplicationController before_filter :authenticate_user! def download_transaction_pdf if params.include? "start_date" and params.include? "end_date" and !params["start_date"][0].blank? and !params["end_date"][0].blank? start_date = Time.parse(params[:start_date]).strftim...
# Die Class 1: Numeric # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # 0. Pseudocode # Input: An integer idicating the number of sides # Output: A count of the sides, a random integer between 1 and the amount of sides # Steps: Create a class # Define a method that accepts an...
class Libssh2 < Utility desc "libssh2 is a client-side C library implementing the SSH2 protocol" homepage 'http://www.libssh2.org/' url 'http://www.libssh2.org/download/libssh2-${version}.tar.gz' release version: '1.8.0', crystax_version: 4 depends_on 'zlib' depends_on 'openssl' def build_for_platform...
# -*- encoding : utf-8 -*- class AddRefreshTokenToLinks < ActiveRecord::Migration def change add_column :links, :refresh_token, :string add_column :links, :token_expires_at, :datetime end end
helpers do def get_snow_data(state, city) w_obj = Wunderground.new hash_info = w_obj.forecast_for(state, city) snow_data_hash = { snow_day: hash_info["forecast"]["simpleforecast"]["forecastday"][0]["snow_day"]["in"], snow_allday: hash_info["forecast"]["simpleforecast"]["forecastday"][0]["snow_...
require 'rails_helper' RSpec.describe DeliveredItem, type: :model do subject { build_stubbed(:delivered_item) } it 'has a correct factor' do expect(subject).to be_valid end # associations it { should belong_to(:delivery) } it { should belong_to(:purchase_order_item) } it { should belong_to(:item) }...
require "active_support" require "active_support/dependencies/autoload" require "thor" module Hubber module Command extend ActiveSupport::Autoload autoload :Base class << self def invoke(full_namespace, args = [], **config) require_relative "commands/application/application_command" ...
FactoryGirl.define do factory :order do amount 1.5 completed_date "2015-01-04 16:22:46" state "in progress" end end
# frozen_string_literal: true describe RollbarApi::Project do describe '.configure' do it 'adds a Project to list' do expect(described_class.find('my-project')).to be_nil described_class.configure('my-project', 'my-token') project = described_class.find('my-project') expect(project).to ...
shared_examples 'display published projects' do def do_action get action_name end context 'when the user is not logged in' do it 'should return success page' do do_action expect(response).to have_http_status(:success) # 200 end it "should display the published projects" do do_ac...
class Category < ActiveRecord::Base include Lolita::Configuration has_many :posts lolita do list do list(:posts) do column :comments do list do column :body end end end end end end
require 'test_helper' class TrkDatatablesActiveRecordWithCalculatedColumnsTest < Minitest::Test class PostsWithCommentsCountDatatable < TrkDatatables::ActiveRecord def columns { 'posts.id': {}, 'string_calculated_in_db.title_and_body': {}, 'integer_calculated_in_db.comments_count': ...
remote_file '/usr/share/applications/nocturn.desktop' do owner 'root' group 'root' mode '644' end
require 'new_relic/recipes' require 'net/http' # -------------- # Variables set :branch, "master" set :rails_env, "production" # -------------- # Roles web1 = "66.226.4.226" web2 = "66.226.4.227" web4 = "66.226.4.240" media = "66.226.4.228" role :app, web2, web4 role :web, web2, web4 role :workers, med...
class ChangeLessonsColumn < ActiveRecord::Migration def change change_column :lessons, :date, :timestamp end end
class AddAccountStatus < ActiveRecord::Migration[5.0] change_table :accounts do |t| t.string "status" end end
class ManageIQ::Consumption::ShowbackPricePlan < ApplicationRecord has_many :showback_rates, :dependent => :destroy, :inverse_of => :showback_price_plan belongs_to :resource, :polymorphic => true validates :name, :presence => true validates :description, :presence => true validates :resource, :presence => tru...
require "application_responder" class ApplicationController < ActionController::Base protect_from_forgery with: :exception self.responder = ApplicationResponder respond_to :html rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, alert: exception.message end before_action :config...
describe Page, :type => :model do describe ".homepage" do context 'with a homepage' do let!(:homepage) { @homepage = Page.create(title: "Home", content: "wonderful homepage", category: Category.new) } it "returns the Home page with the correct slug" do expect(Page.homepage).to eq homepage ...
class ChangeDateType < ActiveRecord::Migration[5.2] def change remove_column :guests, :exp_date add_column :guests, :exp_date, :string end end
module Backup module Configuration module Helpers # A helper method for the config/backup.rb configuration file # Expects a trigger in argument one (STRING) # Expects a block of settings def backup(trigger, &block) backup = Backup::Configuration::Base.new(trigger) ba...
class UserPathBuilder def find_component "something" end end class TestOperations < Test::Unit::TestCase def test_coerce_path assert_path component('text_ctrl') assert_path component(:in => 'text_ctrl') assert_path component(in_('text_ctrl')) assert_path component(Nobbie::Wx::Ele...
class Storyline < ActiveRecord::Base belongs_to :user has_many :segments end
class FontBungeeHairline < Formula head "https://github.com/google/fonts/raw/main/ofl/bungeehairline/BungeeHairline-Regular.ttf", verified: "github.com/google/fonts/" desc "Bungee Hairline" homepage "https://fonts.google.com/specimen/Bungee+Hairline" def install (share/"fonts").install "BungeeHairline-Regul...
module Resourceful module CollectionSorting extend ActiveSupport::Concern included do class_attribute :default_sort_column, instance_reader: true class_attribute :default_sort_direction, instance_reader: true def self.set_default_sort_column(value) self.default_sort_colu...
class Event < ActiveRecord::Base belongs_to :user has_many :consultations, dependent: :destroy #updateしないのでupdate時には評価しない validates_presence_of :planed_start, on: :create #updateしないのでupdate時には評価しない validates :title, length: { in: 1..100 }, on: :create #updateしないのでupdate時には評価しない validate :isconflict, on: :crea...
class CreateUsers < ActiveRecord::Migration[6.1] def change create_table :users do |t| t.string :username t.string :password_digest t.string :name t.integer :age t.string :gender t.string :race t.string :orientation t.string :past_relationship_status ...
# coding: utf-8 module Deploys class Upcoming < ::Deploy self.table_name = :deploys validates :finished_at, absence: true validate :stage_not_locked private def stage_not_locked return unless stage.locked?(branch) errors.add(:base, :stage_locked) end end end
module FixMyTags::Music class TrackNumberMiddle #'./random/folder/artist_d - 354 - title_anem .ext' # attr_reader :name, :artist, :title, :filetype def initialize file @name = file.match(/[^\/]*$/).to_s clean = @name.gsub("_"," ") parts = clean.split /-/ puts parts ...
require "spec_helper" RSpec.describe Abaci::Counter do describe "#decrement" do it "decreases the stat by 1" do expect(Abaci[:testers].get).to eq(0) Abaci[:testers].increment(10) expect(Abaci[:testers].get).to eq(10) Abaci[:testers].decrement Abaci[:testers].decrement expect(...
class AddPhotoToUsers < ActiveRecord::Migration def change add_column :users, :photo_url, :string, default: "https://res.cloudinary.com/dlpclqzwk/image/upload/v1478276712/noPhoto_50_y9zhkk.png" add_column :users, :bio, :string end end
class Note < ApplicationRecord belongs_to :user belongs_to :project validates :content, presence: true def time_created if self.created_at > Time.now.beginning_of_day "#{time_ago_in_words(self.created_at)} ago" else self.created_at.strftime("%b %d, %Y") end end def author User....
def roll_call_dwarves(dwarves) dwarves.each_with_index do |dwarf, index| puts "#{index + 1}. #{dwarf}" end end def summon_captain_planet(calls) calls.map do |call| call += "!" call.capitalize end end def long_planeteer_calls(calls) calls.any? do |call| call.length > 4 end end def find_the...
class LegCut < ActiveEnum::Base value :id => 1, :name => 'Skinny' value :id => 2, :name => 'Straight' value :id => 3, :name => 'Bootcut' value :id => 4, :name => 'Legging' value :id => 5, :name => 'Boyfriend' value :id => 6, :name => 'Flare' end
class ProdutosController < ApplicationController before_action :set_produto, only: [:show, :edit, :update, :destroy] # GET /produtos # GET /produtos.json def index if (params[:department_id]) @produtos = Produto.where(department_id: params[:department_id]) else @produtos = Produto.all en...
# coding: utf-8 class GPURef @@gpu2cores = { "GeForce RTX 2080 Ti" => 4352, "GeForce GTX 1080 Ti" => 3584, "Tesla P100-PCIE-16GB" => 3584, "Tesla V100-PCIE-32GB" => 5120, "Tesla V100-SXM2-32GB" => 5120, "Tesla M2075" => 448, "GeForce GTX TITAN Black" => 2880, "GeForce GTX 980" => 2048...
Praxis::ApiDefinition.define do response_template :other_response do |media_type:| status 200 media_type media_type end response_template :multipart do status 200 media_type 'multipart/form-data' end response_template :bulk_response do |media_type: nil, parts: | status 200 media_typ...
class RenameBidsJobDateTimeToBidsDateTime < ActiveRecord::Migration def change rename_column :bids, :jobdatetime, :date_time end end
class Operator def initialize(_operator) @operator = _operator end def to_s @operator end end
# coding: utf-8 module Fog module Network class SakuraCloud class Real def list_routers(options = {}) request( :headers => { 'Authorization' => "Basic #{@auth_encord}" }, :method => 'GET', :path => "#{Fog::SakuraCloud::SAKURACL...
require_relative 'ui_valet' module AppiumValet class CheckValet < UIValet def is_displayed? result = wait(@after_wait) { driver.exists { target_element } } return false if missed_find_exact_number_of_elements? result end def is_displayed(&block) begin wait_true(@after_wa...
class Transaction < ApplicationRecord belongs_to :user has_many :orders enum status: {NO: 0, YES: 1} end
# encoding: utf-8 # author: Nathan Dines control 'Meltdown and Spectre Vulnerability Check' do impact 1.0 title 'Linux Patch status for Meltdown and Spectre vulnerabilities' desc 'Validates status of infrastructure against Meltdown and Spectre' if os.linux? then describe file('/proc/cpuinfo') do its...
module Batsd # # This is a thin wrapper around the redis client to # handle multistep procedures that could be executed using # Redis scripting # class Redis # Opens a new connection to the redis instance specified # in the configuration or localhost:6379 # def initialize(options) @...
require './spec/support/file_helpers' RSpec.configure do |c| c.include FileHelpers end describe ManageIQ::Providers::Kubevirt::InfraManager::Provision do context "Cloning" do it "calls clone on template" do source = FactoryBot.create(:template_kubevirt) subject.source = source connection = d...
Rails.application.routes.draw do # resources :journals get '/journals', to: 'journals#index' get '/journals/:id', to: 'journals#show' post '/journals', to: 'journals#create' delete '/journals/:id', to: 'journals#delete' # resources :users get '/users', to: 'users#index' get '/users/:id', to: 'users#s...
# # we start with the presumtion that each stundet has an evaluation color based on the interview and test(that got them addmited in the academy) # students =[ # { id: 1,name: "Andrei", eval: "yellow"}, #YELLOW # { id: 2,name: "Laura", eval: "green"}, #GREEN # { id: 3,name: "Ana", eval: "yel...
class Vote < ApplicationRecord belongs_to(:user) belongs_to(:answer) end
class AddSignatureToFoodItem < ActiveRecord::Migration def change add_column :food_items, :if_signature, :boolean, :default => false add_column :food_items, :if_recipe, :boolean, :default => false end end
require 'rails_helper' RSpec.describe Tagging, :type => :model do before(:each) do @user = User.create(username: "test", email:'example@example.com', password: 'password') end it 'connects a photo to a tag' do tag = Tag.create(name: "dogs") photo = Photo.create(owner: @user, title: "test", img...
require 'spec_helper' require_relative 'view_builder_helper' describe TheGrid::Builder::Json do subject{ TheGrid::Builder::Json } include_examples "for Grid View Builder" let(:context) { build_context } let(:records) {[ 1, 2, 3, 4 ]} let(:params) {{ :cmd => [:sort], :field => :name, :order => :desc }} ...
class User < ActiveRecord::Base attr_accessible :dob, :facebook_id, :fact validates :facebook_id, :presence => true, :uniqueness => true validates :fact, :presence => true validates :dob, :timeliness => { :on_or_before => :today, :type => :date } # Goes through all users, checking their data ...
# Provide an interface to read text files from a specified path and return a Ruby hashes of each key value pair module Higo module Transport class Text < Abstract def initialize(*) super @_raw_file = call end # Reads file from path provided by Higo::Transport::Abstract # ...