text
stringlengths
10
2.61M
module Sumac # Wrapper for an object that exists on the remote endpoint (also called a 'stub'). # Calling a method (that is captured by +method_missing+) will call it on the remote endpoint. # They can be forgoten by the application to free up memory. class RemoteObject include ExposedObject extend For...
# == Schema Information # # Table name: projects # # id :integer not null, primary key # code :string(255) default(""), not null # name :string(255) default(""), not null # description :text # created_at :datetim...
class ApplicationController < ActionController::API include Pundit attr_accessor :current_user rescue_from Pundit::NotAuthorizedError do unauthorized! end def authenticate_user! token, options = ActionController::HttpAuthentication::Token.token_and_options(request) user_email = options.blank? ...
class CreateSeens < ActiveRecord::Migration def self.up create_table :seens do |t| t.string :object_type, :default => "episode" t.integer :episode_id t.integer :movie_id t.integer :phile_id t.string :filename t.datetime :seen_at t.datetime :deleted_at t.ti...
class TodoListsController < ApplicationController before_action :authenticate_user! before_action :load_project def create @todo_list = @project.todo_lists.create(todo_list_params) end def show end def update end def destroy @todo_list = @project.todo_lists.find(params[:id]) @todo_li...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user before_action :user_logged_in? before_action :current_user before_action :line_items def orders @orders = Order.all end def line_items @line_items = LineItem.all end ...
require 'rails_helper' describe Sighting do it{ should validate_presence_of :animal_id} it{ should validate_presence_of :region_id} it{ should belong_to :region} it{ should belong_to :animal} end
class CreateSpeeches < ActiveRecord::Migration def change create_table :speeches do |t| t.string :type, :speaker, :timing t.text :additional_info t.integer :reception_id t.timestamps end end end
Rails.application.routes.draw do devise_for :users root to: 'home#index' resources :secret_codes, only: [:index, :create] end
module Msf class Plugin::Pentest < Msf::Plugin # Post Exploitation command class ################################################################################################ class PostautoCommandDispatcher include Msf::Auxiliary::Report include Msf::Ui::Console::CommandDispatcher ...
require "rails_helper" RSpec.describe ProductsController, :type => :controller do describe "GET #index" do it "responds successfully with an HTTP 200 status code" do get :index expect(response).to be_success expect(response).to have_http_status(200) end end describe "GET #show" do ...
source 'https://rubygems.org' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?('/') "https://github.com/#{repo_name}.git" end gem 'rails', '~> 5.0.1' gem 'pg', '0.19.0' gem 'puma', '~> 3.0' gem 'sassc-rails' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2...
# frozen_string_literal: true module Darlingtonia ## # @abstract A null validator; always returns an empty error collection # # Validators are used to ensure the correctness of input to a parser. Each # validator must respond to `#validate` and return a collection of errors # found during validation. If th...
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController # The default OmniAuth forms don't provide CSRF tokens, so we can't verify # them. Trying to verify results in a cleared session. skip_before_action :verify_authenticity_token # rubocop:disable Metrics/AbcSize, Metrics/MethodLength ...
require 'spec_helper' describe "Posts" do it "display sign in when user not authorized" do visit "/posts" expect(page).to have_content('Sign') end it "display Invalid email or password when incorrect login" do visit "/posts" fill_in "login-username", :with => "incorect@incorect.com" fill_in "login-pa...
require 'computer.rb' describe Computer do describe "#choose" do it "sets computer choice variable at random" do computer = Computer.new expect(computer.choose).to be_instance_of(String) end end end
module WP::API module Endpoints def posts(query = {}) resources('posts', query) end def post(id, query = {}) resource('posts', id, query) end def create_post(data = {}) resource_post('posts', data) end def add_post_meta(post_id, data = {}) resource_post("posts/#...
class Question < ActiveRecord::Base belongs_to :game has_many :answers has_many :qapi_answers def right_answer qapi_answers.where(:is_true => "true").first end def answer_of_user(user) answer = Answer.of_question_and_user(self, user) if answer.nil? return nil end answer.answer end def is_right?(...
# Model model: rest_name: cloudroute resource_name: cloudroutes entity_name: CloudRoute package: yeul group: pcn/infrastructure description: Describes a route in a route table. detached: true # Attributes attributes: v1: - name: destinationIPv4CIDR description: The Destination CIDR for the route....
#!usr/bin/env ruby require 'csv' messages, addresses, subjects = [], [], [] email_regex = /(\S+)@(\S+)/ f = CSV.read('index.csv') f.each do |row| subjects.push(row[0]) addresses.push(row[1]) messages.push(row[5]) end messages.each do |email| #strips out header info from message body email.slice!(0...email....
class PersonalsController < ApplicationController def index @personals = User.where('(role = ? AND rang = ? )', 'doctor', 'ะŸะพะบะฐะทะฐั‚ัŒ') @clinics_show = Clinic.where("rang = 'ะŸะพะบะฐะทะฐั‚ัŒ'").first(3) end end
class UpdateNcrOfficeToOrgCode < ActiveRecord::Migration def change rename_column :ncr_work_orders, :office, :org_code end end
class RemoveLatestAt < ActiveRecord::Migration[5.0] def change remove_column :feeds, :latest_at end end
class CreateIronCores < ActiveRecord::Migration def change create_table :BD_TXXL, :id => false do |t| t.primary_key :OBJID t.text :CDID, :limit => 8 t.datetime :AcquisitionTime t.float :TotalCoreCurrent end end end
json.albums do |json| json.array! @albums do |album| json.extract! album, :id, :title json.url album_url(album, format: :json) json.images do |json| json.count album.images.count end end end
class PagesController < ApplicationController before_action :check_page_belongs_to_user, only: [:edit, :update, :destroy] before_action :find_page, only: [:show, :edit, :update, :destroy] before_action :authorize_user, except: [:index, :show, :search] def show @posts = @page.posts @page.views +=1 @...
require 'uri' class Params def initialize(req, route_params) params_hash = route_params || {} [req.query_string, req.body].each do |params| params_hash.merge!(parse_www_encoded_form(params)) unless params.nil? end @params = params_hash end def [](key) @params[key] end def to_s ...
# # Cookbook Name:: jdk # Recipe:: default # # Copyright 2014, Example Com # # 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 # # Unless requir...
module CGL class Trigger attr_reader :cause, :effects def initialize(name, cause, effects) @name = name @cause = cause @effects = effects end def match?(*args) @cause.match?(*args) end end end
require File.dirname(__FILE__) + '/../../../spec_helper' describe 'Fog::AWS::Storage::File' do before(:each) do @directory = AWS[:storage].directories.create(:key => 'fogdirectoryname') end after(:each) do @directory.destroy end describe "#initialize" do it "should remap attributes from parse...
Rails.application.routes.draw do root to: "links#index" resources :links, only: [:new, :create, :show] end
# # Cookbook Name:: supervisor-daemon # Recipe:: install # # Installs the init scripts necessary to run the supervisor daemon on # RHEL derived systems. # # Copyright 2013-2015, Dave Shawley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic...
require "data_source" class Ficha extend ActiveSupport::Memoizable attr_reader :url_foto, :dados_gerais, :notas, :faltas, :ocorrencias, :familiares, :empresa, :periodo_letivo, :url_consulta, :conexao_corpore, :matricula def initialize(empresa_id, matricula) @matricula = matric...
class Entities::SubEntities::Invoice < Maestrano::Connector::Rails::SubEntityBase def self.entity_name 'Invoice' end def self.external? false end def self.object_name_from_external_entity_hash(entity) entity['order_number'] end def self.object_name_from_connec_entity_hash(entity) entit...
# frozen_string_literal: true ## # Bulk object import for Samvera. # # == Importers # # {Importer} is the core class for importing records using {Darlingtonia}. # Importers accept a {Parser} and (optionally) a custom {RecordImporter}, and # process each record in the given parser (see: {Parser#records}). # # @example ...
class Link < ApplicationRecord belongs_to :gossip, optional: true belongs_to :tag, optional: true end
require "../factory/*" module ListFactory class ListFactory include Factory def create_link(caption:, url:) ListLink.new(caption, url) end def create_tray(caption:) ListTray.new(caption) end def create_page(title:, author:) ListPage.new(title, author) end end end
require 'spec_helper' module Naf describe AffinitiesController do it "should respond with the affinity index" do get :index response.should be_success end it "should respond with the affinity show" do id = 5 Affinity.should_receive(:find).with("5").and_return(nil) get :sh...
# frozen_string_literal: true module Boring module FontAwesome module Yarn class InstallGenerator < Rails::Generators::Base source_root File.expand_path("templates", __dir__) desc "Adds fontawesome via rubygems to the application" def add_font_awesome_package say "Adding ...
class FontPottaOne < Formula head "https://github.com/google/fonts/raw/main/ofl/pottaone/PottaOne-Regular.ttf", verified: "github.com/google/fonts/" desc "Potta One" desc "Single style font family featuring letterforms inspired by brush lettering" homepage "https://fonts.google.com/specimen/Potta+One" def ins...
MovieType = GraphQL::ObjectType.define do name "Movie" description "A movie" field :id, types.ID field :title, types.String field :summary, types.String field :year, types.Int field :actors, types[ActorType] end
require 'rails_helper' describe 'Cities API' do describe 'GET /index' do let!(:cities) { create_list(:city, 5) } before { get "/api/v1/cities" } it 'returns 200 status code', :lurker do expect(response).to be_success end it 'included in cities object' do expect(response.body).to ha...
module Libretsy class Session attr_accessor :authorization_headers, :client, :cookie, :nonce_count, :response, :server_info, :urls def initialize(client) @authorization_headers = {} @client = client @nonce_count = 0 end def login @response = Libretsy::LoginRequest.request(cl...
class RemoveCategoryFromTickets < ActiveRecord::Migration def change remove_column :tickets, :category, :string end end
require 'spec_helper' describe "commentaries/edit.html.erb" do before(:each) do @commentary = assign(:commentary, stub_model(Commentary)) end it "renders the edit commentary form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form",...
Rails.application.routes.draw do resources :locations resources :users, except: :new get '/signup', to: 'users#new' get '/login', to: 'logins#new' post '/login', to: 'logins#create' get '/logout', to: 'logins#destroy' resources :friendships, only: [:create, :destroy] root 'pages#home' # For det...
class Order < ApplicationRecord has_many :order_details accepts_nested_attributes_for :order_details belongs_to :customer enum order_status:{ ๅ…ฅ้‡‘ๅพ…ใก: 0, ๅ…ฅ้‡‘็ขบ่ช: 1, made: 2, ็™บ้€ๆบ–ๅ‚™ไธญ: 3, ็™บ้€ๆธˆใฟ: 4 } enum payment_method:{ ใ‚ฏใƒฌใ‚ธใƒƒใƒˆใ‚ซใƒผใƒ‰: 0, ็พ้‡‘ๆŒฏ่พผ: 1 } end
Pod::Spec.new do |s| s.name = "XMLTagView" s.version = "0.0.1" s.summary = "A view for displaying tags with customizable buttons." s.description = <<-DESC XMLTagView is a view for displaying tags, it is based on pureLayout by smileyborg. The tags are customizable buttons. The way to use...
# -*- coding: utf-8 -*- class CollectionsController < ApplicationController include Hydra::CollectionsControllerBehavior include Blacklight::Catalog::SearchContext include Worthwhile::ThemedLayoutController include Hydra::AccessControlsEnforcement include Worthwhile::WithoutNamespace before_filter :filter_d...
xml.instruct! :xml, :version => "1.0" xml.rss :version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom" do xml.channel do xml.title "Startups of Puerto Rico" xml.description "A collection of Startup Events in Puerto Rico" xml.link events_url xml.tag! 'atom:link', :rel => 'self', :type => 'appli...
require "rails_helper" feature "visitor edits loan quantity in cart" do include_context("features") scenario "by increasing loan quantity without being logged in" do visit "/" click_link("Loans") within(".loans") do first(".caption").click_button("Add to Cart") end expect(page).to have...
# -*- encoding : utf-8 -*- class ScientificWorksForPlansController < ApplicationController # GET /scientific_works_for_plans before_filter :check_auth # GET /scientific_works_for_plans.json def index @scientific_works_for_plans = ScientificWorksForPlan.all respond_to do |format| format.h...
class Rental < ApplicationRecord validates :user, :media, presence: true belongs_to :user belongs_to :media end
module Ruhax # Most important parser # Every parser should inherit from it class MasterParser # Constructor def initialize end # Parse the given node def parse_new_node(node, options = {}) content = "" parser = nil case node.type # Any function call when :send ...
class AddFacebookUserNicknameToComments < ActiveRecord::Migration def change add_column :comments, :facebook_user_nickname, :string end end
class DishesController < ApplicationController def index @dishes = Dish.all render json: @dishes end end
class AuthorsBook < ActiveRecord::Base belongs_to :author attr_accessible :book end
require "csv" require_relative "recipe" class Cookbook def initialize(csv_file) @recipes = [] @csv_file = csv_file load_csv end def all @recipes end def add_recipe(recipe) @recipes << recipe write_csv end def remove_recipe(recipe_index) @recipes.delete_at(recipe_index) ...
#-- # Copyright (c) 2009-2010, Jeremy Hinegardner, jeremy@copiousfreetime.org # # 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, including without limitation the rights # ...
# Generic directed-graph implementation # (To add application-specific functionality, subclass Directed::Graph and/or Directed::Node) # Written by Alex Dowad (alexinbeijing@gmail.com) # The original version of this file lives on the Internet at https://github.com/alexdowad/showcase/blob/master/directed_graph.rb # Plea...
# 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...
FactoryGirl.define do factory :comment do comment_content "Word is Life" association :user association :post created_at {Time.now} end end
class ReactionsHelperTest < ActionView::TestCase test "should return the reaction" do assert_dom_equal %{<span class="card-link emoji_happy"><span class="text-muted">๐Ÿ‘</span><span class="count text-muted" id="emoji_happy_count">0</span></span>}, emoji_reaction('happy', '๐Ÿ‘', 0) end end
require 'spec_helper_acceptance' describe 'nexus class' do context 'download folder parameter' do # Using puppet_apply as a helper it 'should work with no errors' do pp = <<-EOS node default { notify { 'Preparing installation of Nexus OSS': } if $::operatingsystem == 'Debi...
class Admin::TopicsController < ApplicationController before_action :set_admin_topic, only: [:show, :edit, :update, :destroy] # GET /admin/topics # GET /admin/topics.json def index @admin_topics = Admin::Topic.all end # GET /admin/topics/1 # GET /admin/topics/1.json def show end # GET /admin/...
class RallyOrgApi::Fundraiser #The fundraiser objects uses many of the same fields as cause objects do, the additions are # cause_id : The unique id for the cause. # user : The user object who started that fan-fundraiser. # name : A string of the name of the user # icon_url : A string of the url for that ...
require File.dirname(__FILE__) + '/spec_base' begin require 'rufus/edo' rescue LoadError puts "'TokyoCabinet' ruby bindings not available on this ruby platform" end if defined?(TokyoCabinet) FileUtils.mkdir('tmp') rescue nil describe 'Rufus::Edo::Cabinet .tcf' do before do @db = Rufus::Edo::Cabi...
module NiceEnumActiveRecordExtension extend ActiveSupport::Concern module ClassMethods private def map_enum(attribute, enum_type) define_method("#{attribute.to_s}=") { |enum_or_string| write_attribute( attribute, enum_or_string.respond_to?(:value) ? enum_or_string.value : ...
module Gateway class Attachments def delete_data_since(time_ago) Attachment.where('created_at < ?', time_ago).destroy_all.count end end end
# == Schema Information # # Table name: deposit_requests # # id :integer not null, primary key # wallet_id :integer # status :integer default(0) # amount :decimal(8, 2) # created_at :datetime not null # updated_at :datetime not null # data :text # uuid ...
class RolesController < ApplicationController include EventSource before_action :authenticate before_action :require_superior before_action :fetch_user def edit @role = ChangeRoleCommand.new(user_id: @user.id, typ: @user.typ) end def update @role = ChangeRoleCommand.new(role_params.merge(user_i...
# frozen_string_literal: true require 'sidekiq' module ClaimsApi class ReportUnsuccessfulSubmissions include Sidekiq::Worker def perform if Settings.claims_api.report_enabled @to = Time.zone.now @from = @to.monday? ? 7.days.ago : 1.day.ago @consumers = ClaimsApi::AutoEstablish...
=begin Problem 14 The following iterative sequence is defined for the set of positive integers: n โ†’ n/2 (n is even) n โ†’ 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 โ†’ 40 โ†’ 20 โ†’ 10 โ†’ 5 โ†’ 16 โ†’ 8 โ†’ 4 โ†’ 2 โ†’ 1 It can be seen that this sequence (starting at 13 and ...
# Write your code here. def line(counter) if counter.length == 0 puts "The line is currently empty." else counter.map! do |name| "#{counter.index(name) + 1}. #{name}" end puts "The line is currently: #{counter.join(" ")}" end end def take_a_number(counter, name) counter.push(name) puts ...
require 'selenium-webdriver' require 'securerandom' require_relative 'helper' class FuckMyLife class Unit < MiniTest::Unit def before_suites # code to run before the first test end def after_suites # code to run after the last test end def _run_suites(suites, type) begin ...
# frozen_string_literal: true require 'securerandom' module SnowplowRubyDuid # Generates a pseudo-unique ID to fingerprint the user # It follows Snowplow Javascript: https://github.com/snowplow/snowplow-javascript-tracker/blob/2.14.0/src/js/tracker.js#L670-L672 class DomainUserid def initialize @domai...
# William Hudgins # 08/01/15 # IterLenSearch.rb # # Implements iterative lengthening search using a graph. # Note: This implementation assumes that a solution exists. If no solution # exists, this implementation fails require_relative 'UndirectedGraph' # This class contains functionaility allowing one to find an op...
class AddPaperclipToPropiedad < ActiveRecord::Migration def change add_attachment :propiedades, :images end end
class IndicationsController < ApplicationController INDICATION_TYPES = %i(event news resource) before_filter :authenticate_user! def create return unless INDICATION_TYPES.include?(params[:type].to_sym) model = params[:type].capitalize.constantize indication = model.find(params[:id]).indications...
class CreateActiveAdminComments < ActiveRecord::Migration[5.0] def change create_table :active_admin_comments do |t| t.string :namespace t.text :body t.references :resource, polymorphic: true t.references :author, polymorphic: true t.timestamps t.index [:namespace] end ...
class CalculateAverageProductPriceJob include Sidekiq::Worker def perform(product_id) Inventory::CalculateAverageProductPrice.call(product_id) end end
require 'spec_helper' describe Blog do it "is valid with a title and body" do blog = Blog.new(title: 'Nice Blog', body: 'Wow so nice') expect(blog).to be_valid end it "is not valid without a title" do blog = Blog.new(body: 'Hey there') expect(blog).to have(1).errors_on(:title) end it "is not valid with ...
module HTTPalooza module Players class CurlPlayer < Base introducing! :curl def response output = `curl -isX #{request.method.to_s.upcase} '#{request.url}'` code = output.scan(/^HTTP[^\s]*\s(\d+)/).first.first.to_i rescue 0 body = output.split(/^\s$/, 2).last.try(:strip) ...
$:.unshift File.expand_path('../lib', __FILE__) require 'medjool' Gem::Specification.new do |s| s.name = 'medjool' s.version = Medjool::VERSION #s.rubyforge_project = 'medjool' s.license = 'MIT' s.summary = 'Date parsing with context' s.description = 'Medjool is a date parser written in pure Ruby, whic...
class CreateTaskRelationRecords < ActiveRecord::Migration def change create_table :task_relations do |t| t.references :subtask t.references :supertask t.string :type t.datetime :added_on t.datetime :removed_on end add_index :task_relations, :subtask_id add_index :task_rel...
class Translation < ApplicationRecord belongs_to :content include ActiveModel::Dirty after_commit :submit_job private def submit_job saved_change = saved_change_to_to_lang? if saved_change TranslateJob.perform_later(content) puts "******* Running translation job! #{saved_change}" en...
class Api::UsersController < Api::BaseController # before_filter :correct_user, only: :show # ^^ To use for verifying the user def index render :json => users end def show render :json => user end def create User.create(user_params) render :json => user end def update User.upda...
class Policy < ApplicationRecord belongs_to :product belongs_to :client belongs_to :sale_executive end
RSpec.describe Peatio::Repme do it "has a version number" do expect(Peatio::Repme::VERSION).not_to be nil end end
class Appointment #attr_accessor :location, :purpose, :hour, :min def initialize (location, purpose, hour, min) @location = location @purpose = purpose @hour = hour @min = min end def location @location end def purpose @purpose end def hour @...
require_relative '../../../../spec_helper' describe 'icinga::timeperiod', :type => :define do let(:title) { 'whenjimisawake' } let(:params) {{ "timeperiod_alias" => "Not Often", "sun" => "00:00-24:00"}} it { is_expected.to contain_file('/etc/icinga/conf.d/timeperiod_whenjimisawake.cfg'). with_content(/timeper...
module Jekyll class Translatel18n < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text end def render(context) site = context.registers[:site] lang = site.active_lang site.data['i18n'][@text.strip!][lang] end end end Liquid::Template.register_tag('...
# <PRO> namespace :redmine do namespace :contacts do desc <<-END_DESC Send reminders about deals due in the next days. Available options: * days => number of days to remind about (defaults to 7) * project => id or identifier of project (defaults to all projects) * users => comma separated list of ...
class AddAttributesToEmployees < ActiveRecord::Migration[5.2] def change add_column :employees, :first_name, :string add_column :employees, :last_name, :string add_column :employees, :gender, :integer, default: 0 add_column :employees, :birthdate, :date add_column :employees, :address, :string ...
class Colour < ActiveRecord::Base has_many :game_players named_scope :random, :order => 'RAND()' end
require 'spec_helper' describe 'ITA Office Locations API V1', type: :request do before(:all) do ItaOfficeLocation.recreate_index fixtures_dir = "#{Rails.root}/spec/fixtures/ita_office_locations" ItaOfficeLocationData.new(["#{fixtures_dir}/odo.xml", "#{fixtures_dir}/oio.xml"]).import end let(:expecte...
class AddEventUsersSumToEvents < ActiveRecord::Migration def self.up add_column :events, :event_users_sum, :integer, :default=>0 end def self.down remove_column :events, :event_users_sum end end
# TODOS: # - remove noomii specific tests and tables # - see if there's a better way to handle transactions NOTIFICATION_ROOT = File.expand_path(__FILE__).split('/')[0..-3].join('/') $: << NOTIFICATION_ROOT require 'active_record' require 'rails_generator' require 'rails_generator/scripts/generate' require 'moch...
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Online Content', type: :feature do let(:doc_id) { 'aoa271aspace_843e8f9f22bac69872d0802d6fffbb04' } before { visit solr_document_path(id: doc_id) } describe 'Viewer' do context 'embedded content' do let(:doc_id) { 'a0011-xmlaspace_r...
require 'rails_helper' require 'gds_api/test_helpers/email_alert_api' RSpec.describe SubscriptionsController do include GdsApi::TestHelpers::EmailAlertApi let(:topic_id) { "GOVUK123" } let(:subscribable_title) { "My exciting list" } let(:subscribable_id) { 10 } let(:subscribable_attributes) do { i...