text
stringlengths
10
2.61M
class CreateActivities < ActiveRecord::Migration[5.1] def change create_table :activities do |t| t.string :ip_address t.decimal :lat t.decimal :long t.string :user_agent t.references :short_url, foreign_key: true t.timestamps end end end
class Slider < ApplicationRecord before_save :default_cta mount_uploader :image, ImageUploader validates :image, presence: true include RailsSortable::Model set_sortable :sort private def default_cta self.cta = "ENTER" if self.cta.blank? end end
module SupplyTeachers class Supplier < ApplicationRecord has_many :branches, foreign_key: :supply_teachers_supplier_id, inverse_of: :supplier, dependent: :destroy has_many :rates, foreign_key: :supply_teachers_supplier_id, inverse_of: :supplier,...
module Shanty # Small mixin that gives the receiver class a logger method. This method simply wraps the Ruby Logger class with a # nice consistent logging format. module Logger module_function def logger @logger ||= ::Logger.new($stdout).tap do |logger| logger.formatter = proc do |_, dateti...
# frozen_string_literal: true module GeoPattern class Color private attr_accessor :color public def initialize(html_color) @color = ::Color::RGB.from_html html_color end def to_svg r = (color.r * 255).round g = (color.g * 255).round b = (color.b * 255).round ...
class GuildInvitation < ApplicationRecord belongs_to :guild belongs_to :user belongs_to :invited_user, class_name: "User" validates_with GuildInvitationValidator, field: [ :user_id, :invited_user_id, :guild_id ] scope :for_user_index, -> (user_id) do where(invited_user_id: user_id).order(created_at: :de...
#encoding: utf-8 ActiveAdmin.register Wine do config.sort_order = 'updated_at_desc' controller do def update @wine = Wine.find(params[:id]) region_tree_id = params[:region].values.delete_if{|a| a == ''}.pop @wine.region_tree_id = region_tree_id if region_tree_id if @wine.update_attributes...
require "spec_helper" describe Refunge::Stack do attr_reader :stack context "when creating a new stack" do it "should accept arguments to put in the stack first" do @stack = Refunge::Stack.new(1, 2) expect(stack.pop).to eq(2) expect(stack.pop).to eq(1) end end context "when appendin...
class User < ActiveRecord::Base DEFAULT_START_RATING = 1600.0 # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable...
class Comment include Mongoid::Document include Mongoid::Timestamps include Mongoid::Votable field :body, type: String field :abusive, type: Boolean, default: false belongs_to :user belongs_to :post has_many :votes def has_voted? user votes.map(&:user_id).include?(user_id) end end
class Vga < ApplicationRecord belongs_to :company belongs_to :brand,optional:true end
class Cart < ApplicationRecord def item_count 0 end end
class Album < ApplicationRecord acts_as_paranoid belongs_to :artist belongs_to :album_type belongs_to :record_company belongs_to :recording_type validates_presence_of :release_year validates_numericality_of :release_year, greater_than: 1900 end
require "singleton" require "bunny" require_relative "rabbit" require "pry" class Worker include Singleton attr_accessor :rabbit attr_accessor :graceful_exit def connect! @rabbit = Rabbit.new @graceful_exit = false end def subscribe while true if graceful_exit? puts "[#{Proces...
class Estimate < ActiveRecord::Base after_initialize :default_values after_save :accept_lines before_validation :default_values has_many :line_items, :dependent => :destroy, :order => "position" has_many :negotiate_lines, :through => :line_items has_one :invoice_schedule, :dependent => :destroy belongs_to...
json.array!(@device_models) do |device_model| json.extract! device_model, :model, :description, :numberOfPort json.url device_model_url(device_model, format: :json) end
require "asciidoctor" require "asciidoctor/nist" require "asciidoctor/standoc/converter" require "isodoc/nist/html_convert" require "isodoc/nist/word_convert" require_relative "front" require_relative "boilerplate" require_relative "validate" require_relative "cleanup" require "fileutils" module Asciidoctor module N...
class Log < ActiveRecord::Base symbolize :severity, :in => [:information, :error, :warning] validates_presence_of :description, :severity, :schedule belongs_to :schedule end
module Discovery class CareerRecommendation < ActiveRecord::Base attr_accessible :category_id, :career_id belongs_to :career belongs_to :category validates :career_id, presence: true end end
class CreateGroups < ActiveRecord::Migration def change create_table :groups do |t| t.integer :organizer_id, null: false t.string :name, null: false t.string :background_image_url t.string :profile_image_url, null: false t.string :who, null: false, default: "Friends" t.string :...
module Cloudfuji class CustomerObserver < EventObserver # "customer_created" # :account_balance => 0 # :object => "customer" # :email => "s+cfdemo@cloudfuji.com" # :created => 1332269951 # :id => "cus_cpkg4h0KfLD3lp" # :livemode => true # ...
require "bundler/setup" require "pry" require "sentry" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.exp...
class Comment < ApplicationRecord belongs_to :user belongs_to :recipe has_many :comment_reports validates :body, presence: true, length: { minimum: 3 } def mark_as_deleted! update_attribute :deleted, true end end
Pod::Spec.new do |s| s.name = "GeoFire" s.version = "5.0.0" s.summary = "Realtime location queries with Firebase." s.homepage = "https://github.com/firebase/geofire-objc" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = "Firebase" s.source = { :git => "h...
require_relative 'InvalidTaskException.rb' require_relative 'SaveFileError.rb' require_relative 'OpenFileError.rb' require_relative 'InvalidIndexError.rb' require_relative 'TaskCompletedError.rb' class TaskList attr_reader :task_list, :autonumeric def initialize @task_list=SortedSet.new @autonumeri...
require 'spec_helper' describe SessionsController do let(:member) { FactoryBot.create(:member, password: 'mala', password_confirmation: 'mala') } let(:valid_sessions) { { member_id: member.id } } describe "GET 'new'" do context "when member doesn't exist" do it do get 'new' ...
module Showboat module Generators class InstallGenerator < Rails::Generators::Base desc 'Install the base assets for setting up a showboat presentation.' source_root File.expand_path('../../../../../spec/dummy', __FILE__) def cleanup_rails remove_file "README.rdoc" remove_dir "a...
module Endpoints # The base class for all Sinatra-based endpoints. Use sparingly. class Base < Sinatra::Base register Pliny::Extensions::Instruments register Sinatra::Namespace configure :development do register Sinatra::Reloader end not_found do content_type :json status 404...
require "spec_helper" describe CellSkedsController do describe "routing" do it "routes to #index" do get("/cell_skeds").should route_to("cell_skeds#index") end it "routes to #new" do get("/cell_skeds/new").should route_to("cell_skeds#new") end it "routes to #show" do get("/ce...
module IndepthOverrides module IndepthFinanceSettingsController def self.included (base) base.instance_eval do alias_method_chain :index, :tmpl end end def index_with_tmpl config_keys = [ 'MultiReceiptNumberSetEnabled', # multiple receipt number set enabled = 1 'M...
module OpinionsHelper def display_form render 'form' if user_signed_in? end def user_owner?(opinion) render 'opinion_owner', opinion: opinion if user_signed_in? && current_user.id == opinion.user_id end end
class Membership < ActiveRecord::Base belongs_to :member, :class_name => "User", :foreign_key => "member_id" belongs_to :scenario belongs_to :group validates_presence_of :member, :scenario before_create :set_member_role scope :non_admin, includes(:member).where("users.role_code != #{User::ROLES[:ad...
module SemanticExtraction module Yahoo include SemanticExtraction::UtilityMethods STARTER = "http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction" def self.find_keywords(text) prefix = 'context' raw = SemanticExtraction.post(STARTER, text, prefix, :appid) self.outp...
# encoding: utf-8 require 'spec_helper' describe IdRandomico do describe '#novo' do it 'gera id composto de letras e números' do id_rand = IdRandomico.new(5, 15) 50.times do id = id_rand.novo id.should match /^[[:alnum:]]+$/ end end it 'mantém o tamanho do id no interva...
class AddCharactersToUsers < ActiveRecord::Migration def change add_column :players, :user_id, :integer add_column :players, :character_id, :integer end end
# Problem 335: Gathering the beans # http://projecteuler.net/problem=335 # Whenever Peter feels bored, he places some bowls, containing one bean each, in a circle. After this, he takes all the beans out of a certain bowl and drops them one by one in the bowls going clockwise. He repeats this, starting from the bowl he...
class SoundDocumentsController < ApplicationController # GET /sound_documents # GET /sound_documents.xml def index @sound_documents = ((((SoundDocument.author_filter params[:author_id] ).director_filter params[:director_id] )....
class Movie < ApplicationRecord has_many :movie_tags has_many :tags, through: :movie_tags belongs_to :user attr_accessor :tags_ids end
module Refinery module Sites module Admin class SitesController < ::Refinery::AdminController crudify :'refinery/sites/site', :title_attribute => 'name', :xhr_paging => true # before_filter :reset_current_site_id, :except => [:create, :update] before_...
require "test_helper" require "date" require 'pry' describe Customer do describe "validations" do before do @customer = customers(:customer_one) end it "can be created" do expect(@customer.valid?).must_equal true end it "requires name, postal_cost, registered_at" do r...
if Rails.env.development? || Rails.env.test? namespace :brakeman do desc 'Run Brakeman' task run: :environment do require 'brakeman' Brakeman.run( app_path: '.', quiet: true, pager: false, print_report: true ) end end end
require 'uri' require 'net/http' module AgilysysSdk class AgilysysApiClient # Your code goes here... def initialize(url, client_id, auth_code) @url = url @client_id = client_id @auth_code = auth_code url = URI(url) @http = Net::HTTP.new(url.host, url.port) ...
require 'brew_sparkling/action/xcode/base' require 'brew_sparkling/action/xcode/discover' require 'brew_sparkling/action/xcode/devices' require 'brew_sparkling/action/xcode/accounts' require 'brew_sparkling/action/xcode/certificates' # Show xcode info module BrewSparkling module Handler # show xcode info cla...
module CDI module V1 module PageStructure class BaseSerializer < ActiveModel::Serializer root false attributes :page_structure_name def page_structure_name self.class.name.to_s.underscore.split('/').last.sub('_page_serializer', '') end end end end end
Dir[File.dirname(__FILE__) + '/actions/*.rb'].each(&method(:require)) class Screenplay # Actions provides methods to all types of classes included in the # Screenplay::Actions module. It defines a method based on the class name. # Include this into any class to gain access to the commands. module Actions ...
class AddRawHtmlFieldToLetters < ActiveRecord::Migration def change add_column :letters, :raw_html, :string end end
class ApplicationController < ActionController::Base protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' } before_filter :configure_permitted_parameters, if: :devise_controller? before_filter :set_csrf_cookie_for_ng after_filter :track_visit protected def...
class EnableFuzzyMatch < ActiveRecord::Migration[6.1] def change enable_extension "fuzzystrmatch" end end
class WorksController < ApplicationController def index @works = Work.all end def new @work = Work.new end def create work = Work.create( work_params ) if work.save redirect_to "/works/#{work.id}" else render :new end end def edit @work = Work.find(params[:id]) ...
class Post < ActiveRecord::Base extend FriendlyId friendly_id :title, use: [:slugged, :history] has_many :comments, :dependent => :destroy belongs_to :user validates_presence_of :content, :user_id, :title attr_accessible :content, :title, :user_id end
class Export < ActiveRecord::Base serialize :structure serialize :associated_columns serialize :join_columns default_scope :order => "created_at DESC" MODELS = [["Employee Admission", "Employee"], ["Student Admission", "Student"], ["Guardian Addition", "Guardian"], ["Student Attendance", "Attendance"], ["St...
class CreateJadwals < ActiveRecord::Migration[5.0] def change create_table :jadwals do |t| t.string :kode_mk t.integer :nip t.string :kode_ruang t.string :waktu t.timestamps end end end
require 'json' module Uploader class LoopholesParser < BaseParser def parse grouped_routes = group_routes( merge_node_pairs_routes( extract_data('node_pairs'), extract_data('routes') ) ) grouped_routes.values.select { |routes| routes.length > 1 }.map do |rou...
class AdvisorHasSubject < ApplicationRecord belongs_to :advisor belongs_to :subject end
describe :varchar do # ================================================ it "raises RuntimeError if allow :null and :min = 0" do should.raise(RuntimeError) { Class.new { include Datoki field(:name) { varchar nil, 0, 50 } def create clean :name end } }.mes...
require './test/test_helper' class IterativeLinkedListTest < Minitest::Test def setup @list = IterativeLinkedList.new end def test_it_has_a_head assert_nil @list.head end def test_it_appends_a_node_to_an_empty_list @list.append(Node.new(:blue)) assert_equal :blue, @list.head.data asser...
class TympanogramsController < ApplicationController before_action :set_tympanogram, only: [:show, :edit, :update, :destroy] # GET /tympanograms def index @tympanograms = Tympanogram.all end # GET /tympanograms/1 def show end # GET /tympanograms/new def new @tympanogram = Tympanogram.new ...
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :exception add_flash_types :success, :danger, :warning, :info rescue_from ActionController::RoutingError do render file: "#{Rails.root}/public/404", layout: false, status: :not_found end end
class CategoriesController < ApplicationController before_filter :fetch_group before_filter :authenticate_user! def new @category = @group.categories.new respond_to do |f| f.html end end def create @category = @group.categories.new params[:category] @group.add_category(@category) ...
class CountryMovie < ActiveRecord::Base belongs_to :country belongs_to :movie attr_accessor :association_should_exist end
=begin #=============================================================================== Title: Utils - Change Equip Author: Hime Date: Sep 26, 2014 URL: http://www.himeworks.com/utils-change-equips/ -------------------------------------------------------------------------------- ** Change log Sep 26, 2014 - eq...
require_relative "lib/safely/version" Gem::Specification.new do |spec| spec.name = "safely_block" spec.version = Safely::VERSION spec.summary = "Rescue and report exceptions in non-critical code" spec.homepage = "https://github.com/ankane/safely" spec.license = "MIT" spec.a...
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! $install_salt_master = <<SCRIPT curl -L https://bootstrap.saltstack.com | sudo sh -s -- -M SCRIPT $install_salt_slave = <<SCRIPT curl -L https://bootstrap.saltstack.com | sudo sh SCR...
class PrenotationsController < ApplicationController before_action :set_prenotation, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! # GET /prenotations # GET /prenotations.json def index @property = Property.find(params[:property_id]) @prenotations = @property.prenotations ...
require 'spec_helper' require 'appdirect_log_record' describe AppdirectLogRecord do subject { described_class.new(line) } context 'valid line' do let(:line) do <<-EOS 10.10.32.10 -- [2013-07-03 05:24:11.251382] appdirect_gateway - pid=1502 tid=dd3d fid=b3df DEBUG -- Reply status:200, headers:{"Content-...
# Group 1 def check_return_with_proc my_proc = proc { return } my_proc.call puts "This will never output to screen." end # check_return_with_proc # returning from a proc amounts to returning from the method invocation that called the proc (?) # Group 2 my_proc = proc { return } def check_return_with_proc_2(my...
module WellFormed class NullModel attr_reader :attribute_names def initialize(attribute_names) @attribute_names = attribute_names end def present? false end def valid? true end def invalid? !valid? end def save! true end def save; end...
# # Cookbook Name:: pg_bouncer # Recipe:: default # # The MIT License (MIT) # # Copyright (c) 2015 Jeffrey Hulten # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, includ...
class OrderSummaryMailer < ActionMailer::Base default from: "sales@goverlan.com" def order_summary_email(order_summary) @order_summary = order_summary mail(to: order_summary.email, cc: order_summary.reseller, subject: 'Goverlan Order Summary') end end
module Lita module Handlers class Anonymous < Handler route(/anonymous to #(\w*): (.*)/, command: true, help: { 'anonymous to #ROOM: YOUR_TEXT' => 'Send an anonymous message to a room' }) do |response| room_name = response.matches.flatten.first room = Lita::Room.find_by_name(room_name) ...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root "creatures#index" # base route localhost:3000 get "/creatures", to: "creatures#index" get "/creatures/new" => "creatures#new", as: 'new_creature' post "/creatures" => "cr...
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' # Find a way to accumulate the :worldwide_grosses and return that Integer # using director_data as input def gross_for_director(director_data) pp director_data movies_index=0 total=0 movies=director_data[:movies] while movies_index<movies.c...
module API class Root < Grape::API include API::Helpers::ErrorHandler prefix 'api/' format :json before do header['Access-Control-Allow-Origin'] = '*' header['Access-Control-Request-Method'] = '*' end mount API::V1::Root route :any, '*path' do error!({ code: ...
require 'spec_helper' require 'app/models/config/base' require 'app/models/config/java_script' require 'app/models/config/parser_error' describe Config::JavaScript do describe '#content' do context 'with a modern javascript config' do it 'returns the content from GitHub as a hash' do commit = stubb...
class AddIndexToMissionName < ActiveRecord::Migration[5.2] def change add_index :mission_names, :mission_id add_index :mission_names, :name end end
# # Copyright 2013, Seth Vargo <sethvargo@gmail.com> # Copyright 2013, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
gem 'minitest', '~> 5.2' require 'minitest/autorun' require 'minitest/pride' require './lib/node' class NodeTest < Minitest::Test def test_node_exists node = Node.new("Burke") assert_instance_of Node , node end def test_node_has_surname node = Node.new("Burke") assert_equal "Burke", node.sur...
module FTPPROXY class App < EM::FTPD::App def start(config_path) config_data = File.read(config_path) config = EM::FTPD::Configurator.new config.instance_eval(config_data) config.check! update_procline(config.name) EventMachine.epoll EventMachine::run do puts "...
class ReactionsController < ApplicationController before_action :authenticate_user! def create reaction = Reaction.find_or_initialize_by(photographer_id: params[:photographer_id], user_id: current_user.id) reaction.update_attributes( status: params[:reaction] ) end end
require 'spec_helper' describe PrimeNumberCalc do context 'calculate_prime_numbers_from_max(max)' do it 'should throw an exception when max is not an integer' do expect { PrimeNumberCalc.new.calculate_prime_numbers_from_max(nil) }.to raise_error(PrimeNumberCalcException, 'invalid max') en...
class Category < ActiveRecord::Base has_many :category_ships has_many :posts , :through => :category_ships end
module SupplyTeachers class BranchesController < SupplyTeachers::FrameworkController before_action :set_end_of_journey SEARCH_RADIUSES = [50, 25, 10, 5, 1].freeze helper :telephone_number def index @journey = Journey.new(params[:slug], params) @back_path = @journey.previous_step_path ...
class CreateEventos < ActiveRecord::Migration def change create_table :eventos do |t| t.references :artista t.references :lugar t.timestamps end add_index :eventos, :artista_id add_index :eventos, :lugar_id end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'singleton' module TwitterCldr module Segmentation class NullSuppressions include Singleton def should_break?(_cursor) true end end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string # username :string # password :text # email :string # phone :string # birthdate :date # bio :text # url :string # level :integer # created_at :datetime ...
require 'spec_helper' describe 'docker::cgroups' do context 'when running on oracle 6.5' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'oracle', version: '6.5').converge(described_recipe) end it 'installs the libcgroup package' do expect(chef_run).to install_package('libcgroup') ...
require 'minitest_helper' class TestZulu < MiniTest::Test def setup Zulu.options = nil end def test_it_has_version_number refute_nil ::Zulu::VERSION end # # Zulu.parse_options # def test_it_has_default_option_for_port assert_equal 9292, Zulu.options[:port] end def test_it_...
Vagrant.configure(2) do |config| config.vm.box = "freebsd/FreeBSD-11.0-STABLE" config.vm.synced_folder ENV['STACK_BUILD_DIR'], "/vagrant-build", type: "rsync", rsync__verbose: true, rsync__exclude: [".stack-work/", "_release/", ".cabal-sandbox/", "cabal.sandbox.config", "dist/", ".#*#", "*.vdi", "*.vmdk", "*.raw"],...
class CreateKinds < ActiveRecord::Migration[5.0] def change create_table :kinds do |t| t.string :nome t.string :sigla t.text :obs t.timestamps end end end
require 'rghost' require 'rghost_barcode' require 'pp' class BoxesController < ApplicationController include BiobankHelper include QueryConditionHelper CATEGORY = "biobank" SUBCATEG ="boxes" before_filter :set_current_scope layout "home" protect_from_forgery :except => [:autocomplete_box_name...
# This code is free software; you can redistribute it and/or modify it under # the terms of the new BSD License. # # Copyright (c) 2013-2017, Sebastian Staudt class RBzip2::Java::Decompressor def initialize(io) @io = io @is = RBzip2::Java::BZip2CompressorInputStream.new io.to_inputstream end def close ...
# code -> noIdentificacion # name -> Descripcion # measure_unit -> Unidad # quantity -> Cantidad # price -> Precio Unitario # importe -> Importe # module MCFDI # Concepts Class class Concept < Base attr_accessor :code, :name, :measure_unit, :quantity, :price, :import def initialize(args = {}) args.e...
require 'byebug/state' module Byebug # # Controls state of Byebug's REPL when in control mode # class ControlState < State def proceed end extend Forwardable def_delegators :@interface, :errmsg, :puts def confirm(*_args) 'y' end def context nil end def file ...
# Namespace for a set of helper methods and classes available within the admin # section of the application. # @since 0.6.0 module Admin # A base controller, inherited by all Admin controllers. # Ensures the correct layout is used and that a user is authenticated. # # @author Matthew Rayner # @since 0.1 cla...
require_relative 'minitest_helper' class TestTarIntegration < MiniTest::Unit::TestCase def tar(path = "#{samples_path}/tar_with_directory.tar") @tar ||= Swathe::Tar.open(path) end def test_is_a_tar assert tar.tar? end def test_file_count assert_equal 1, tar.files.count end def test_file_l...
require 'rubygems' # super_crud require File.dirname(__FILE__) + '/metajp/shared/super_crud/controller.rb' require File.dirname(__FILE__) + '/metajp/shared/super_crud/model.rb' require File.dirname(__FILE__) + '/metajp/shared/super_crud/helper.rb' # acts_as_invitable require File.dirname(__FILE__) + '/metajp/shared/a...
require 'spec_helper' describe EventsController do describe "trying to access protected resources when not logged in" do it "should block access to GET 'index'" do get :index, :format => :json response.response_code.should == 403 end end describe "accessing resources with a logged in user"...
class AddLovesToSightseeings < ActiveRecord::Migration[6.0] def change add_column :sightseeings, :loves, :integer end end
require 'formula' class Libscarab < Formula homepage 'https://hcrypt.com/scarab-library/' url 'https://hcrypt.com/downloads/libScarab-1.0.0.zip' sha1 '3d33e04b50298187861eaf598dac3698a391424a' depends_on 'gmp' depends_on 'flint1' def patches # build shared and static objects DATA end def ins...
# Source: https://launchschool.com/exercises/29ffd590 def print_boundary(len) p "+#{'-' * (len + 2)}+" end def print_middle(len) p "|#{' ' * (len + 2)}|" end def print_in_box(str) len = str.size if len > 78 print_boundary(76) print_middle(76) str.scan(/.{1,76}/).each do |chunk| buffer = (7...