text
stringlengths
10
2.61M
class MembersController < ApplicationController before_action :authenticate_user # POST /ideas/12/members def create member = Member.new idea = Idea.find params[:idea_id] redirect_to idea_path(idea), alert: "Access denied." and return if can? :edit, idea member.idea = idea membe...
Rails.application.routes.draw do resources :url_shorts, only: [:index, :create, :new] get '/:short_url', to: 'url_shorts#to_original' root 'url_shorts#new' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class EmailAFriendMessage < ActiveRecord::Base # Validates that the domain exists validate :emails_are_valid? validates_presence_of :recipient_email_address validates_presence_of :sender_email_address # Validate that both email fields are correct. def emails_are_valid? EmailValidationHelper.valida...
class RemovePwdigestFromUsers < ActiveRecord::Migration def change remove_column :users, :password_digest, :string, limit: 255 end end
class Public::HomesController < ApplicationController def top @items = Item.all @items = Item.all.order(:id) @items = Item.page(params[:page]).per(4) end def about end private def item_params params.require(:item).permit(:image_id, :name, :description, :genre_id, :price, :is_active) ...
# ----- # Input # ----- # just do a simple XOR if binary string arguments passed if ARGV.size >= 2 width = ARGV.map(&:size).max # work out the longest binary string (for display purposes) system "clear" ARGV.each do |binary| puts binary.rjust(width, " ") end puts "-" * width puts ARGV.map{|x| x.to_i(2)}.reduce(...
class CreateDonationCashes < ActiveRecord::Migration def change create_table :donation_cashes do |t| t.references :user t.float :amount t.references :pot t.timestamps end end end
class KptBoard < ActiveRecord::Base unloadable belongs_to :project has_many :entries, :class_name => 'KptEntry', :dependent => :destroy, :include => :user, :order => KptEntry.arel_table[:created_at].asc validates :title, :presence => true, :length => { :within => 2..80 } attr_accessible :title d...
require 'test_helper' class CategoriesControllerTest < ActionDispatch::IntegrationTest def setup @category = Category.create(name: "sports") @user = User.create(username: "john", email: "john@gmail.com", password: "password", admin: true) end test "should get categories index" do get categories_path as...
class AddCondateToLnparams < ActiveRecord::Migration[5.0] def change add_column :lnparams, :condate, :date end end
class RailsPowergrid::Railtie < Rails::Railtie railtie_name :rails_powergrid config.rails_powergrid = ActiveSupport::OrderedHash.new initializer "rails_powergrid.initialize" do |app| app.config.rails_powergrid[:grid_path] = %w( app/grids ) app.config.rails_powergrid[:fetch_user_method] = :current_user ...
require 'pry' SUITS = %w(H D S C) VALUES = %w(2 3 4 5 6 7 8 9 10 J Q K A) PLAYER_LIMIT = 21 COMPUTER_LIMIT = 17 WINNING_SCORE = 3 player_cards = [] dealer_cards = [] def prompt(message) puts "=> #{message}" end def clear_system system('clear') end def initialize_deck SUITS.product(VALUES).shuffle end def ...
class CreateSplits < ActiveRecord::Migration def self.up create_table :splits do |t| t.integer :entry_id t.integer :ledger_id t.integer :amount # OFX field FITID (Financial Institution Transaction ID) # See OFX spec sect 3.2.1 t.string :fit t.timestamps end end ...
class ContactsController < ApplicationController def create @form = ContactForm.new(contact_params) service = ContactService.new(@form) if service.call redirect_to root_path, notice: _('Message sent successfully') else redirect_to contact_path, alert: _('Something went ...
require "rails_helper" describe "Send Participant To Voicemail Mutation API", :graphql do describe "sendParticipantToVoicemail" do let(:query) do <<~'GRAPHQL' mutation($input: SendParticipantToVoicemailInput!) { sendParticipantToVoicemail(input: $input) { success } ...
#!/usr/bin/ruby require "optparse" ARGV.push "-h" if ARGV.empty? options = {} OptionParser.new do |opts| opts.banner = "Usage: stacks [options] AMOUNT [STACK SIZE=64]" opts.on("-d", "--dye", "prints amount of dye needed for stained glass or concrete") do |o| options[:dye] = o end end.parse! unl...
#!/usr/bin/env ruby $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'minecraft_query' require 'optparse' require 'ostruct' require 'json' options = OpenStruct.new options.port = 25565 options.host = 'localhost' options.timeout = 5 options.pretty = false OptionParser.new do |opts| opts.ba...
require "./lib/ims/DJTable.rb" require 'yaml/store' class Main def initialize(test=false) if !test @store = YAML::Store.new('./data/data.yml') else @store = YAML::Store.new('./data/test_store.yml') end @table = @store.transaction{@store[:table]} @table = DJTable.new if @table == nil...
require 'spec_helper' describe "opendata_dataset_groups", type: :feature, dbscope: :example do let(:site) { cms_site } let(:node) { create_once :opendata_node_dataset, name: "opendata_dataset" } let(:index_path) { opendata_dataset_groups_path site.host, node } let(:new_path) { new_opendata_dataset_group_path s...
class Product < ActiveRecord::Base validates :name, :description, :image, presence: true has_attached_file :image, styles: { large: "400x400>", medium: "200x200>", thumb: "100x100>" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end
class Product < ActiveRecord::Base belongs_to :category has_many :line_items before_destroy :ensure_not_referenced_by_any_line_item has_attached_file :photo validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/ extend FriendlyId friendly_id :name, :use=>[:slugged,:finders] def ens...
# Public: Takes an integer and decides if it's negative or not # # number - The integer that is decided if it's negative or not # # Examples # # is_negative(-1) # # => True # # is_negative(1) # # => False # Returns True if the integer is negative # Returns False if the integer is not negative def is_ne...
module Seed class PrescriptionDrugSeeder def self.call(*args) new(*args).call end attr_reader :config attr_reader :counts attr_reader :facility attr_reader :logger attr_reader :user_ids attr_reader :raw_to_clean_medicines delegate :scale_factor, to: :config def initiali...
class AuthorSerializer < ActiveModel::Serializer attributes :id, :name, :version has_many :posts def version '0.10.0' end end
# frozen_string_literal: true class Pet < ApplicationRecord belongs_to :shelter has_many :pet_applications, dependent: :destroy has_many :applications, through: :pet_applications validates :image, :name, :age, :sex, :description, :status, presence: t...
ApiPagination.configure do |config| # If you have both gems included, you can choose a paginator. config.paginator = :pagy end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB 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 # # U...
# frozen_string_literal: true require "attr_extras" module Renalware module Diaverum class PatientPresenter < SimpleDelegator def height_in_cm return if last_clinic_visit.blank? || last_clinic_visit.height.blank? last_clinic_visit.height.to_f * 100.0 end private def cl...
#!/usr/bin/ruby require_relative 'worldcat_api_interaction' def stringify_author(tagdict_author, bibl, do_viaf) if tagdict_author.include? " / " authors = tagdict_author.split(' / ') elsif tagdict_author.include? ' and ' # case: multiple authors authors = tagdict_author.split(' and ') else # case: one a...
json.array!(@children) do |child| json.extract! child, :id, :name, :lastname, :gender, :birthdate, :image_id, :allergies, :notes json.url child_url(child, format: :json) end
class AddOnPathToClues < ActiveRecord::Migration def self.up add_column :clues, :on_path, :boolean, :default => true, :null => false end def self.down remove_column :clues, :on_path end end
module VW class HTTPResult attr_accessor :object, :error, :response, :request_url, :request_params, :request_method def initialize(response, response_object, error) @response = response @object = response_object @error = error end def status_code @response.statusCode if @resp...
#!/usr/bin/env ruby # Circular Linked list - ADT class Node attr_accessor :value, :nxt def initialize(value=nil,nxt=nil) @value = value @nxt = nxt end end class CircularLinkedList def initialize(i) # last_node will always point to the most recent node added. @last_node = Node.new(i) # to ge...
class PlaylistsController < ApplicationController before_action :set_playlist, only: [:show, :update, :edit, :destroy] before_action :set_p_movie_id, only: [:add_movie_to_playlist] before_action :set_account def index @playlists = Playlist.all end def add_movie @movies = Movie.all @playlist...
class MainController < ApplicationController def index @last_notes = if params[:by_tag] Note.tagged_with(params[:by_tag]) else Note end @last_notes = @last_notes.where(hide: false).order(created_at: :desc).limit(9).includes(:taggings)...
# frozen_string_literal: true class EnumInput < ApplicationInput delegate :ta, to: :template def custom_text_field @builder.select(custom_attribute_name, select_choices, select_options, new_html_options) end def select_choices input_options[...
describe "Signing Up" do it "signs in the user immediately after the sign-up process is successful" do # Arrange - N/A # Action visit root_url click_link "Sign Up" fill_in "Name", with: "Joe Doe" fill_in "Username", with: "joedoe" fill_in "Email", with: "joedoe@example.com" fill_in "P...
class TasksController < ApplicationController def fmt(datetime) if datetime fmt = "%Y-%m-%dT%H:%M:%S.%3N" datetime.strftime(fmt) end end def completed tasks = current_user.tasks.completed json = CollectionJSON.generate_for('/tasks/completed') do |builder| tasks.each do |task| ...
require 'libxml' module ROXML module XML # ::nodoc:: Document = LibXML::XML::Document Node = LibXML::XML::Node Parser = LibXML::XML::Parser module NamespacedSearch def search(xpath) if default_namespace && !xpath.include?(':') find(namespaced(xpath), in_default...
class ArticleToTagsController < ApplicationController before_action :set_article_to_tag, only: [:show, :edit, :update, :destroy] # GET /article_to_tags # GET /article_to_tags.json def index @article_to_tags = ArticleToTag.all end # GET /article_to_tags/1 # GET /article_to_tags/1.json def show en...
class Task < ApplicationRecord belongs_to :movement, optional:true enum task_type: [:instruction, :copyable, :url, :phone_num, :email, :appointment] VALID_NAME = /\A[a-zA-Z]+[a-zA-Z0-9\-\ \_]*\z/i validates :name, presence: true, length: {minimum: 5, maximum: 200}, format: { with: VALID_NAME, mess...
require 'sqlite3' require 'sqlbuilder' require_relative 'results/sqlite_result' require_relative '../logger' module EasyMapper module Adapters class SqliteAdapter def initialize( host: nil, port: nil, database:, user: nil, password: nil ) @d...
# encoding: utf-8 require "open-uri" require 'gender_detector' class Politician < ActiveRecord::Base CollectingAndShowing = 1 CollectingNotShowing = 2 NotCollectingOrShowing = 3 NotCollectingButShowing = 4 has_attached_file :avatar, { :path => ':base_path/avatars/:filename', :...
class Admin::PairsController < ApplicationController before_action :require_login before_action :authorized? skip_before_action :verify_authenticity_token def index @pairs = Pair.order(date: :desc) end def new @pair = Pair.new end def create Pair.removeTeams(params[:date]) Pair.tea...
class RenameDates < ActiveRecord::Migration[5.0] def change rename_table :dates, :entries end end
class Api::V1::ConferencesController < ApplicationController def index @conferences = Conference.all.order(:id) render '/conferences/index.json.jbuilder', conferences: @conferences end end
# A Coach Assignment is the relationship between a participant # and which coach he/she is assigned to. However, please keep # in mind that only one coach is tied to each participant # However, a coach could have many participants class CoachAssignment < ActiveRecord::Base belongs_to :coach, class_name: "User" bel...
module Harvest module HTTP module Server module Resources class JavaScriptFileResource < Resource # Interim step, we need to remove knowledge of web files SOURCE_DIR = PROJECT_DIR + '/web_client/www/lib' def trace? false end def content...
# Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {Integer[]} nums # @return {TreeNode} def sorted_array_to_bst(nums) if nums.empty? nil ...
class Api::V1::AddressesController < ApiController before_action :authenticate_consumer_from_token! before_action :authenticate_consumer! def index @addresses = current_consumer.addresses.where(deleted: false) end def create current_consumer.addresses.each {|address| address.update(is_default: false...
module ApplicationHelper def show_advice temperature case temperature when 5..15 then I18n.t('weather.autumn') when 15..35 then I18n.t('weather.summer') when -40..5 then I18n.t('weather.winter') else '' end end end
require 'spec_helper' describe User do it 'sets the singleton name to the model_name.element' do expect(described_class.singleton_name).to eq 'user' end it { should respond_to :email } it { should respond_to :github_access_token_present } it { should respond_to :subscribe } describe '#repositories' d...
class UsersController < ApplicationController clear_respond_to respond_to :json before_action :admin_required before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.all end # GET /users/new def new new_user end # POST /u...
class SubcategoriesController < ApplicationController def index @subcategory = Subcategory.find(params[:id]) @products = @subcategory.products end end
# User prompt puts "Enter Name:" # GETS will wait for a response # The CHOMP method will get rid of the new line # from hitting the 'enter' key name = gets.chomp() puts "Enter Age:" age = gets.chomp() # Store the data into variables and print greeting puts "Hello, #{name}, you are #{age}!" # Example output without ...
class ChangePrecisionAdvertisersTable < ActiveRecord::Migration def up change_column :advertisers, :spend, :decimal, :precision => 5, :scale => 2 end def down change_column :advertisers, :spend, :decimal, :precision => 4, :scale => 2 end end
# == Schema Information # # Table name: pages # # id :integer not null, primary key # survey_id :integer # sequence :integer # title :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_pages_on_survey_id (survey_id) # # Foreign K...
module IGMarkets # Contains details on an IG Markets application configuration. Returned by {DealingPlatform#applications}. class Application < Model attribute :allow_equities, Boolean attribute :allow_quote_orders, Boolean attribute :allowance_account_historical_data, Fixnum attribute :allowance_ac...
# frozen_string_literal: true require 'spec_helper' describe 'RuboCop' do it 'should conform' do expect(system('rubocop')).to be true end end
class AdditionalBlock < ActiveRecord::Base belongs_to :additional_row, counter_cache: true has_one :additional_title, dependent: :destroy has_one :additional_paragraph, dependent: :destroy has_many :additional_buttons, -> { displayed }, dependent: :destroy has_one :additional_animation, dependent: :destroy ...
require 'test_helper' class ProductTest < ActiveSupport::TestCase test ("product attributes must not be blank") do product = Product.new assert product.invalid?, "ok" assert product.errors[:title].any? assert product.errors[:description].any? assert product.errors[:image_url].any? assert product.errors...
module DbAdmin class Api::BaseController < ActionController::API before_action :fetch_db_connection_info def fetch_db_connection_info # TODO: 方便调试,固定参数 params[:conn] = "postgres://postgres:@localhost:5432/postgres" RequestStore.store[:db_connection] ||= Connection.establish_connection(param...
class Api::V1::QuestionsController < Api::V1::BaseController before_action :set_question, only: [:show, :destroy, :update] authorize_resource def index @questions = Question.all render json: @questions, each_serializer: QuestionsCollectionSerializer end def show render json: @question end...
# frozen_string_literal: true module RequestMacros def login before(:each) do create(:user) unless User.first get '/auth/twitter' get '/auth/twitter/callback' end end end
class PlayersController < ApplicationController before_action :set_player, only: [:show, :edit, :update] before_action :require_same_player, only: [:edit, :update] def set_player @player = Player.find(params[:id]) end def index @player = Player.new end def new @player = Player.new end ...
class Room < ApplicationRecord validates :room_number, uniqueness: { message: "Room number should be unique" } end
class ConditionColorExpr < ConditionSimple def initialize(a, op, b) @a = a.downcase @op = op @b = (b.downcase.chars & %W[w u b r g]).to_set end def match?(card) if @a == "c" a = card.colors.chars.to_set elsif @a == "ind" a = card.color_indicator_set return false unless a ...
#!/opt/rightscale/sandbox/bin/ruby # # Cookbook Name:: snapshot_timer # # Copyright (C) 2013 Ryan Cragun # # 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/...
class Indocker::ContainerDeployer attr_reader :server_pool def initialize(configuration:, logger:) @configuration = configuration @logger = logger @server_pool = Indocker::ServerPools::DeployServerPool.new( configuration: @configuration, logger: logger ) @deployed_containers = Has...
require 'luego' module Kernel def future(*args, &block) Luego::Future.new(*args, &block) end end
class AddDescriptionToGiftlist < ActiveRecord::Migration def self.up add_column :giftlists, :description, :text end def self.down remove_column :giftlists, :description end end
class TweetsController < ApplicationController layout 'ft' before_action :confirm_logged_in, :except => [:show] def index current_user = User.find(session[:user_id]) followed_users = current_user.followeds.pluck(:id) followed_users << current_user.id @myself = current_user @tweets = Twee...
require 'spec_helper_acceptance' describe 'chronograf' do context 'default server' do describe package('chronograf') do it { should be_installed } end describe service('chronograf') do it { should be_running } end end end
# frozen_string_literal: true module Mutations module Destroy class Base < ::Mutations::Base def destroy_generic(record, ctx) ctx[:pundit].authorize record, :destroy? record.destroy end end end end
#You learned about the Enumerable module that gets mixed in to the Array and Hash classes (among others) and provides you with lots of handy it#erator methods. To prove that there's no magic to it, you're going to rebuild those methods. module Enumerable def my_each for i in self yield i end end #end of my_each ...
class Werewolf attr_reader :name, :location attr_accessor :human, :wolf, :hungry def initialize(name, location = nil) @name = name @location = location @human = true @wolf = false @hungry = false end def human? @human end def wolf? ...
# rubocop: disable Metrics/ModuleLength # rubocop: disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity module Enumerable def my_each if is_a? Range min = self.min max = self.max while min <= max puts min min += 1 end elsif block_given? min = 0 ...
module GapIntelligence class Merchant < Record attribute :name attribute :merchant_type attribute :channel attribute :country_code end end
require 'spec_helper' describe Post do describe 'associations' do it { should belong_to(:standup) } it { should have_many(:items) } it { should have_many(:public_items) } end describe "validations" do it { should validate_presence_of(:standup) } it { should validate_presence_of(:title) } ...
require 'disk/modules/MiqLargeFile' require 'metadata/util/md5deep' require 'minitest/unit' require 'tmpdir' module DiskTestCommon class TestMiqLargeFile < Minitest::Test FILE_1MB = smartstate_images_root.join("containers/raw/DiskTestCommon_MiqLargeFile_1MB").to_s FILE_1GB = smartstate_images_root.join("cont...
class FixScrambleId < ActiveRecord::Migration def change add_column :milestones, :scramble_id, :integer end end
class Material < ActiveRecord::Base has_attached_file :file do_not_validate_attachment_file_type :file validates :description, presence: true validates :file, attachment_presence: true end
require 'test_helper' class TeamsControllerTest < ActionController::TestCase def test_should_get_index get :index, {}, { :user_id => users(:fred).id } assert_response :success end def test_should_get_new get :new, {}, { :user_id => users(:fred).id } assert_response :success end def test_s...
require "test/unit" require_relative "../Hangman.rb" class Hangman_tests < Test::Unit::TestCase def setup_guess @hm.original_word = "pie" @hm.word = "pie" @hm.slate = ["_", "_", "_"] end def setup @hm = Hangman.new @word = @hm.random_word end def test_random_word_is_a_strin...
require 'rails_helper' describe "Factories", :factories do FactoryGirl.factories.map(&:name).each do |factory_name| it "#{factory_name} is valid" do instance = FactoryGirl.build(factory_name) expect(instance.valid?).to be(true), instance.errors.full_messages.to_sentence end end end
class CreateStargateManualOverrides < ActiveRecord::Migration[6.1] def change create_table :stargate_manual_overrides do |t| t.integer :original_start_id t.integer :original_end_id t.integer :start_id t.integer :end_id t.boolean :bloacking t.datetime :start_date t.datetim...
class Marmiton def initialize @recipes = [] end def search(keyword) url = "http://www.marmiton.org/recettes/recherche.aspx?s=#{keyword}" # parse le html pour recuperer les infos doc = Nokogiri::HTML(open(url), nil, 'utf-8') doc.search('.m_contenu_resultat').each do |element| if element.a...
module Twirloc class LocationGuesser attr_reader :username, :client #@profile_location = user_profile_location(username) X #@geolocations_of_tweets = user_tweet_geolocations(username) #@geolocations_of_followers_tweets = follower_tweet_geolocations(username) #@geolocations_of_followings_tweets = f...
class AddKwkOrderToPaypalNotifications < ActiveRecord::Migration def change add_reference :paypal_notifications, :kwk_order, index: true, foreign_key: true end end
require 'slack-ruby-bot' require 'slack-ruby-client' # require 'slackbot-pingity/commands/ping' require 'slackbot-pingity/routing/ping' require 'slackbot-pingity/bot' require 'slack-notifier' require 'pingity' notifier = Slack::Notifier.new( ENV['SLACK_WEBHOOK_URL'] ) Slack.configure do |config| config.token = EN...
class CoursesSubject < ActiveRecord::Base acts_as_paranoid enum status: [:created, :started, :finished] attr_accessor :update_status belongs_to :course belongs_to :subject has_many :users_subjects, dependent: :destroy has_many :users, through: :users_subjects has_many :courses_subjects_tasks, depende...
class AddUuidToPhoneModels < ActiveRecord::Migration def change add_column :phone_models, :uuid, :string rescue puts "column already added" end end
json.array! @recipes do |recipe| json.(recipe, :id, :name, :instructions) json.user recipe.user.try(:name) json.categories recipe.categories.map(&:name) end
require 'spec_helper' describe TmuxStatus::Segments::MusicPlayer do subject { described_class.new(options) } let(:options) do { max_length: 8, playing_symbol: 'p', stopped_symbol: 's', } end let(:max_length) { options[:max_length] } let(:wrapper) { subject.wrapper } it { should b...
#!/usr/bin/ruby def services(services_list) puts("#--- enabling services ---#") system("arch-chroot /mnt systemctl enable #{services_list}") end
class ManageIQ::Providers::Amazon::Inventory::HashCollection attr_reader :collection def initialize(collection) @collection = collection end def each collection.each { |item| yield(transform(item)) } end def all collection.each_with_object([]) { |item, obj| obj << transform(item) } end d...
# encoding: utf-8 class TipoDocumento < ActiveRecord::Base # metodo que por defecto presenta el string has_many :documentos # metodo que por defecto presenta el string def to_s tipo_doc end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Because all controllers extend from this class, you're pretty much saying that before loading any page, fetch the user etc. before_action :fetch_user private def fetch_user # Find the user and store it in an ins...
class Manager::TasksController < Manager::ManagerController before_action :set_lists def new @task = Task.new @task.badge_id = params[:badge_id] if params[:badge_id] end def create @task = Task.new params[:task].permit! authorize! :create, @task params[:task].delete( :video_id ) if para...
class Admin::DeviseOverrides::SessionsController < Devise::SessionsController layout 'admin' def after_sign_in_path_for(resource) admin_path end def after_sign_out_path_for(resource) new_admin_user_session_path end end