text
stringlengths
10
2.61M
class ProductArticle < ApplicationRecord alias_attribute :article_name, :name alias_attribute :article_sku, :sku has_many :product_sizes has_many :sizes, through: :product_sizes has_many :product_photos has_many :related_sku, class_name: 'ProductArticle', foreign_key: 'related_sku_id' belongs_to :produc...
# frozen_string_literal: true module SolidusGraphqlApi module Types class Mutation < Base::Object field :sign_in, mutation: Mutations::User::SignIn field :save_in_address_book, mutation: Mutations::User::SaveInAddressBook field :remove_from_address_book, mutation: Mutations::User::RemoveFromAdd...
class Api::IngredientsController < Api::ApplicationController before_filter :require_user, except: [:show, :index] def index @recipe = Recipe.find(params[:recipe_id]) @ingredients = @recipe.ingredients render json: @ingredients, status: :ok end def create @recipe = @current_user.recipes.find(p...
class CategoriesController < ApplicationController def index @categories = Category.order('name asc').all end def new @category = Category.new @subcategories = Subcategory.all end def create @category = Category.new(category_params) if @category.save redirect_to category_path(@cat...
class SumOfMultiples def initialize(*n) @factors = n end def to(limit) return 0 if limit == 1 @factors.map do |f| (1...limit).each_with_object([]) do |r, result| result << ((r % f).zero? ? r : 0) end end.flatten.uniq.reduce(:+) end end
load "math_util.rb" class LatLng def initialize(lat, lng) # Instance variables @lat = lat @lng = lng end def lat @lat end def lng @lng end def to_s "{lat: #{@lat}, lng: #{@lng}}," end end def compute_angle_between(from, to) ...
# encoding: UTF-8 class AcceptReviewersController < ApplicationController before_filter :load_reviewer, :load_audience_levels def show if @reviewer.preferences.empty? @conference.tracks.each do |track| @reviewer.preferences.build(track_id: track.id) end end end def update if ac...
require 'formula' class Aiger < Formula homepage 'http://fmv.jku.at/aiger/' url 'http://fmv.jku.at/aiger/aiger-1.9.9.tar.gz' sha256 '1e50d3db36f5dc5ed0e57aa4c448b9bcf82865f01736dde1f32f390b780350c7' depends_on 'picosat' def patches DATA end def install system "./configure.sh" system "make"...
class PostsController < ApplicationController before_action :do_sort, only: [:index] before_action :do_search, only: [:index] # GET /posts # GET /posts.json def index if !params[:dir].present? && !params[:q].present? && !params[:startdate] && !params[:enddate] @posts = Post.all end end # G...
# Veritrans API methods require 'uri' module Veritrans module Api # POST /v2/charge { payment_type: "vtlink" } # Docs http://docs.veritrans.co.id/vtdirect/integration_cc.html#step2 # Docs http://docs.veritrans.co.id/sandbox/charge.html # # Example: # Veritrans.charge( # payment_type: ...
class LibView::LibraryFindsController < ApplicationController # Injected actions # GET /lib_view/library_finds/:cond/:val # Examples # /lib_view/library_finds/lib_code_eq/B410 def find_where params[:q] = { params[:cond] => params[:val] } search end def search @find = LibraryFind.new @q...
module Result class AbstractResult attr_reader :source_entity def initialize(entity) @source_entity = entity end end end
class Contact < ActiveRecord::Base attr_accessible :name, :Phone_Number, :Email, :language, :can_text, :student_ids validates_presence_of :name, :message => "can't be blank" validates_length_of :Phone_Number, :is => 10, :allow_blank => true, :message => 'does not work' validates_format_of :Email, :with =>/\A([...
class CreateProjects < ActiveRecord::Migration[5.0] def change create_table :projects, id: :uuid do |t| t.string :name t.string :project_status t.string :intake_path t.string :project_type t.decimal :estimated_annual_production t.decimal :estimated_annual_savings t.decima...
class CreateVisits < ActiveRecord::Migration[5.2] def change create_table :visits do |t| t.integer :visitor_type t.integer :visitor_id t.string :person_name t.date :on_date t.time :tentative_time t.belongs_to :device, foreign_key: true t.belongs_to :company, foreign_key: ...
class Apartment attr_reader :unit, :renter def initialize(unit) @unit = unit @renter = nil end def add_renter(renter) @renter = renter end end
class Article < ApplicationRecord belongs_to :column has_and_belongs_to_many :topics has_many :comments validates :title, presence: true, length: { maximum: 100 } validates :content, presence: true validates :views, presence: true, numericality: { greater_than_or_equal_to: 0 } validate :thumbnail_size ...
class AddReservationFormFields < ActiveRecord::Migration[5.2] def change remove_column :reservations, :from, :time remove_column :reservations, :till, :time add_column :reservations, :from, :datetime add_column :reservations, :till, :datetime end end
require "bundler/gem_tasks" require "rake/testtask" Rake::TestTask.new(:test) do |t| t.libs << "test" t.libs << "lib" t.test_files = FileList["test/**/*_test.rb"] end task default: :test namespace :docker do task :build do require_relative "lib/dexter/version" system "docker build --pull --no-cache ...
class ChangeDateTypeJob < ActiveRecord::Migration def change change_column :jobs, :date, :date end end
class Partner class Profile < ApplicationRecord self.table_name = 'partner_profiles' serialize :unread_notifications, Array after_initialize :init belongs_to :partner, class_name: 'Partner' private def init return unless has_attribute?(:rating) self.rating ||= 0.0 self.num...
class Command def self.help return "The base command class" end def self.run(nick, channel, msg) return "#{nick} said #{msg} in #{channel}" end end
class StatisticsController < DocumentsController enable_request_formats index: %i[json atom] before_action :inject_statistics_publication_filter_option_param, only: :index before_action :expire_cache_when_next_publication_published def index @filter = build_document_filter @filter.publications_search ...
require 'cloudformation_mapper/resource' class CloudformationMapper::Resource::AwsResourceLogsLoggroup < CloudformationMapper::Resource register_type 'AWS::Logs::LogGroup' type 'Template' parameter do type 'Template' name :Properties parameter do type 'Integer' name :RetentionInDays ...
require 'spec_helper' describe Feed2Email do it 'has a VERSION constant' do expect { Feed2Email::VERSION }.not_to raise_error expect(Feed2Email::VERSION).to match /\A\d+\.\d+\.\d+\z/ end end
class CompaniesController < ApplicationController expose :companies, -> { Company.includes(servers: [:server_users]) } expose :company before_action :save_and_render_on_error!, only: [:create, :update] before_action :push_company_contact_if_empty!, only: [:new, :edit] def index; end def show; end; def n...
#Copyright 2010 Foradian Technologies Private Limited #This product includes software developed at #Project Fedena - http://www.projectfedena.org/ # #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...
FactoryGirl.define do factory :notification do sequence(:title) { |i| "Notification #{i}" } message "This longer message for the notification." association :user association :notable, factory: :order end end
class Apple include Comparable attr_accessor :weight def initialize(weight) self.weight = weight end def <=>(other) self.weight <=> other.weight end end small_apple = Apple.new(0.1) medium_apple = Apple.new(0.2) big_apple = Apple.new(0.3) puts small_apple > medium_apple p...
class GamesController < ApplicationController def index @games = Game.order(year: :desc, title: :asc).page(params[:page]) end end
#! /usr/bin/env ruby require 'json' # This script just counts how many manifests exist in a module and their maximum directory depth manifests = Dir.glob('manifests/**/*.pp') maxdepth = manifests.map {|item| item.count('/') }.max count = manifests.count puts JSON.pretty_generate( [[ "#{ENV['mvp_owner']}-#{ENV...
require 'open-uri' require 'nokogiri' require 'pry' class Scraper def self.scrape_index_page(index_url) students = [] html = File.read(index_url) profile_index = Nokogiri::HTML(html) profile_index.css("div.student-card").each do |thumbnail| student_hash = {} name = thumbnail.css("h4.student...
class CommentsController < ApplicationController def create newComment = Comment.new(comment_params) if newComment.save render status: 200, json: newComment else render status: 304 end end def destroy comment = Comment.find(params[:id]) comment.destroy render json: comment...
class MakeDefaultNameEmptyStringForProfile < ActiveRecord::Migration def change change_column :profiles, :first, :string, :default => '', :null => false change_column :profiles, :last, :string, :default => '', :null => false end end
class ApplicationController < ActionController::Base respond_to :json, :html protect_from_forgery helper_method :current_user before_filter :check_for_mobile before_filter :check_browser before_filter :check_for_app_user before_filter :clear_obselete_caches after_filter :set_last_logged_in priva...
class IndexForeignKeysInBankTransactions < ActiveRecord::Migration def change add_index :bank_transactions, :from_account_id add_index :bank_transactions, :to_account_id end end
require 'rails_helper' describe Address do describe '#create' do it "is invalid without a postal_code" do address = build(:address, postal_code: nil) address.valid? expect(address.errors[:postal_code]).to include("を入力してください") end it "is invalid without a city" do address = build(:a...
class CreateStations < ActiveRecord::Migration[5.0] def change create_table :stations do |t| t.references :user, foreign_key: true t.string :sname t.integer :country t.integer :city t.integer :province t.string :address t.string :pnumber t.string :hpage t.stri...
class AddEmailRecipientsToForms < ActiveRecord::Migration[5.0] def change add_column :forms, :email_recipients, :text end end
# frozen_string_literal: true module EventTypes module Refresh # rubocop:disable Rails/OutputSafety # html_safe: Text is sanitized before display def refresh @new_event_types = <<~HTML.html_safe "<option value=\\"\\">#{refresh_prompt}</option>" + "<option value=\\"\\"></option>" + ...
class CreateDetails < ActiveRecord::Migration[6.0] def change create_table :details do |t| t.timestamps t.string :title t.integer :number t.integer :probability t.references :count, foreign_key: true end end end
require 'test_helper' class UsersIndexTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) @user_admin = users(:gui) end test "should see pagination in the users index" do log_in_as @user get users_path assert_template 'users/index' assert_select 'div.pagination' ...
class AddDaoToCategories < ActiveRecord::Migration def change add_column :categories, :dao, :string end end
class RankingShelvesController < ApplicationController before_filter :require_sign_in, :except => [:show] before_filter :load_ranking_shelf, :only => [:show, :destroy] before_filter :require_owner, :only => [:destroy] def show redirect_to @ranking_shelf.shelf end def create @ranking_shelf = Ra...
class Post < ApplicationRecord has_many :shared_users, dependent: :destroy belongs_to :user validates :title, :body, :presence => true end
require 'rails_helper' describe OpeningsController do describe '#index' do before do Opening.create(room: 'Foo', open_date: Date.today+3, discovered_open: Date.today) Opening.create(room: 'Foo', open_date: Date.today-2, discovered_open: Date.today) Opening.create(room: 'Bar', open_date: Date.to...
class AddUserToSkillCategory < ActiveRecord::Migration def change add_reference :skill_categories, :user, index: true, foreign_key: true end end
class AddStatusToClimbs < ActiveRecord::Migration[5.2] def change add_column :climbs, :status, :string, default: 'Status Unknown' end end
class AddIsMultipostingToEmail < ActiveRecord::Migration def self.up add_column :emails, :is_multiposting, :boolean, :default => 0 end def self.down remove_column :emails, :is_multiposting end end
cask "devhub" do version "0.102.0" sha256 "d6f348fbebbd9acb2f0a4554ffab635479ab3f2105c0a94b6c1d75ddcf92d4c2" url "https://github.com/devhubapp/devhub/releases/download/v#{version}/DevHub-#{version}.dmg" appcast "https://github.com/devhubapp/devhub/releases.atom" name "DevHub" desc "TweetDeck for GitHub" ...
require 'test_helper' class EndOfGameTest < ActionDispatch::IntegrationTest test "user wins and can restart game" do create_start_of_game ApplicationController.any_instance.stubs(:status).returns("true") visit restart_game_path assert page.has_content?("You Won") click_button "Play Again" ...
json.array!(@coaches) do |coach| json.extract! coach, :id, :capacity, :Train_id, :Staff_id json.url coach_url(coach, format: :json) end
class AddDesignerToAssignments < ActiveRecord::Migration def change add_column :assignments, :designer, :integer end end
class User < ActiveRecord::Base after_save :send_email def send_email UserMailer.welcome_email(self.email).deliver end end
FactoryGirl.define do factory :user do first_name "Wonky" last_name "McWonkerson" email "wonky@wonky.com" end end
class AddIndexToGetCard < ActiveRecord::Migration[5.2] def change add_index :get_cards, [:e_no, :result_no, :generate_no], :unique => false, :name => 'resultno_and_eno' add_index :get_cards, :name add_index :get_cards, :card_id add_index :get_cards, :get_type end end
class Api::GroupsController < Api::ApiController def show @group = Group.find_by_canonicalized_name!(params[:id]) render :json => @group.to_json({:include => [:members, :transactions]}) end end
require 'spec_helper' describe "31292053 If has_sage_flow_transitions is called more than once, the transitions are added to the list of possible transitions" do describe "within the same class definition" do before(:each) do class Foo < Sample has_sage_flow_states :new, :open, :saved, :locked ...
require "helper" module Neovim RSpec.describe LineRange do let(:client) { Support.persistent_client } let(:buffer) { client.current.buffer } let(:line_range) { LineRange.new(buffer) } before do buffer.set_lines(0, -1, true, ["1", "2", "3", "4"]) end describe "#each" do it "yield...
class CreateProxyParams < ActiveRecord::Migration[6.0] def change create_table :proxy_params, id: :uuid do |t| t.uuid :proxy_id, null: false t.string :param_from t.string :param_to t.timestamps end end end
require 'casclient' require 'casclient/frameworks/rails/filter' class SessionsController < ApplicationController before_action CASClient::Frameworks::Rails::Filter, :except => [:create, :new] def new end def admin_new @email = session[:cas_user] + "@tamu.edu" admin = Admin.where(:email => @email).fir...
class AddUsersToProperties < ActiveRecord::Migration self.up do change_table :properties do |t| t.references :user_id end end end
# 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...
require 'digest/sha1' require 'net/http' require 'cgi' require 'iconv' require 'set' require 'rubygems' require 'xml/libxml' require 'json' require 'curb' $KCODE = "UTF8" require 'jcode' $:.unshift File.expand_path(File.dirname(__FILE__)) + '/calais' require 'client' require 'response' require 'error' module Calai...
Pod::Spec.new do |s| s.name = 'Testlib' s.version = '1.0.5' s.license = 'BSD' s.summary = 'Test statis lib' s.description = 'Pod to test static library as dependency' s.homepage = 'https://maliwan.net' s.author = 'Ross' s.source = { :git => 'https://github.com/Rostyk/Testlib.git', :tag =...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one :buyer_profile has_one :dressmaker_profile ...
class Artist < ActiveRecord::Base has_and_belongs_to_many :events has_and_belongs_to_many :arts validates :name, presence: true, uniqueness: {case_sensitive: false} end
class AddOverrideCostToRegistrations < ActiveRecord::Migration[5.2] def change add_column :registrations, :override_cost, :integer end end
require 'rails_helper' RSpec.describe SupplyTeachers::Journey::WorkerType, type: :model do subject(:step) { described_class.new(worker_type: 'nominated') } let(:model_key) { 'activemodel.errors.models.supply_teachers/journey/worker_type' } it { is_expected.to be_valid } context 'when worker_type is not vali...
class AddPeriodoLetivoToAtividades < ActiveRecord::Migration def self.up add_column :atividades, :periodo_letivo, :string end def self.down remove_column :atividades, :periodo_letivo end end
class CreateSportsUsersJoinTable < ActiveRecord::Migration def change create_table :sports_users, :id => false do |t| t.integer :user_id t.integer :sport_id end add_index :sports_users, [:user_id, :sport_id] end end
require 'spec_helper' describe QML::JSArray do let(:array_script) do <<-JS [1, 2, 3] JS end let(:array) { QML.engine.evaluate(array_script) } describe '#each' do it 'enumerates each values' do expect(array.each.to_a).to eq [1,2,3] end end describe '#to_a' do it 'converts ...
module Nokogiri module XML module SAX ### # PushParser can parse a document that is fed to it manually. It # must be given a SAX::Document object which will be called with # SAX events as the document is being parsed. # # Calling PushParser#<< writes XML to the parser, calling...
class AddSectionIdAndSectionOrderToTasks < ActiveRecord::Migration[5.2] def change add_column :tasks, :section_id, :integer add_column :tasks, :section_order, :integer add_index :tasks, :section_id end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook,...
class CreateUnitTypes < ActiveRecord::Migration[5.2] def change create_table :unit_types do |t| t.string :value, null:false t.boolean :active, null: false, default: true t.integer :order, null: false, default: 0 t.string :updated_by t.timestamps end end end
require 'rails_helper' RSpec.describe User, :type => :model do it { is_expected.to validate_presence_of :email } it { is_expected.to validate_presence_of :password } it { is_expected.to have_one :profile } it { is_expected.to have_many :questions } it { is_expected.to have_many :answers } it { is_expected.to hav...
module Rocket class Rocket def initialize(avg_burn_rate, engine) @avg_burn_rate = avg_burn_rate @engine = engine end def calculate_rates_for(elapsed_time) speed = @engine.speed_at(elapsed_time) burn_rate = (speed.to_f / @engine.avg_speed) * @avg_burn_rate [speed, burn_rate]...
# ScheduleOccurrence class ScheduleOccurrence < ActiveRecord::Base outpost_model has_secretary include Concern::Associations::PolymorphicProgramAssociation include Concern::Callbacks::TouchCallback ############################ scope :after, ->(time) { where("starts_at > ?", time).order("starts_at") } s...
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def link_toggle(id, name, speed = "slow") # "<a href='#' onclick=\"Element.toggle('%s'); return false;\">%s</a>" % [id, name] link_to_function name, "$('##{id}').slideToggle('#{speed}')" # link_...
require 'spec_helper' describe Specialty do it 'is initialized with a name' do test_specialty = Specialty.new({:name => 'hand'}) expect(test_specialty).to be_an_instance_of Specialty end it 'sets the specialty id when it is saved' do test_specialty = Specialty.new({:name => 'Hand'}) test_specia...
require 'rails_helper' include AdminHelpers RSpec.feature 'Creating employee by H.R' do before do @hr = create(:hr) login_as(@hr, scope: :hr) assign_permission(@hr, :read, Employee) assign_permission(@hr, :create, Employee) visit new_admin_employee_path end scenario 'with valid data' do ...
class PinterestDatum < ActiveRecord::Base include Datum belongs_to :social_network set_type :pinterest_data comparable_metrics :total_followers, :liked, :repin, :comments, :community_boards def total_investment (investment_agency + investment_ads + investment_actions) end def coste_fan (tota...
class ImportWorker include Sidekiq::Worker def perform(class_name) class_name.constantize.new.import end end
require 'rails_helper' describe "Navigating signup/signin Users" do context "logged in" do let(:user) { create :user } it "unknown user goes to root" do logout visit root_url expect(page).to have_text "Log In" end it "after sigin go to 'days#index'" do login_as user ...
class BooksController < ApplicationController load_and_authorize_resource # GET /books # GET /books.json def index case when params[:tag] @books = Book.tagged_with(params[:tag], :on => :tags, :any => true) when params[:author] @books = Book.tagged_with(params[:author], :on => :authors, :...
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] # sort words, iterature through hash, if hash does not exist, give it the value of 1 # sort out the values and print them to console hash = {} words.each do |...
1234 1_234 # underscores can be used anywhere in a number for readability purposes --> 1234 == 1_234
class CLI def initialize @commands = {} @help = {} @error = nil @thread = nil end attr_accessor :commands, :help, :error def defn name, help_msg, &block @commands[name] = block @help[name] = help_msg end def main_loop print '- ' STDIN.each_line do |line| command,...
class Api::V1::RestaurantsController < ApplicationController before_action :authorized def index if params[:user_id].present? count = params[:count].present? ? params[:count].to_i : 0 per_page = params[:per_page].present? ? params[:per_page].to_i : 20 blocked_users = BlockedUser.where({user_id: params[:us...
#!/usr/bin/env ruby require 'optparse' require 'yaml' CONFIG_FILE = "rdft.txt" def read_config(filename) YAML.load_file(filename) end def read_params() options = {} optparse = OptionParser.new do |opts| opts.banner = "Usage: rdft.rb [options] filename" options[:verbose] = false opts.on('-v',...
CarrierWave.configure do |config| # These permissions will make dir and files available only to the user running # the servers config.permissions = 0755 config.directory_permissions = 0755 config.storage = :file end
class AddColumnEmailToTrackings < ActiveRecord::Migration def change add_column :trackings, :txn_date, :date add_column :trackings, :emailed, :boolean end end
require 'spec_helper' describe RunsController do let(:user) { FactoryGirl.create(:user) } let(:run) { FactoryGirl.create(:run) } describe "GET #index" do it "should assign the current user's runs to @runs" do login(run.user) get :index, user_id: run.user.id expect(assigns(:runs)).to include run end ...
class ProofsController < ApplicationController # protect_from_forgery except: :new before_action :set_proof, only: [:show, :edit, :update, :destroy] def index @proofs = policy_scope(Proof) @proof = Proof.new end def show @user = User.find(params[:user_id]) authorize @proof end def new ...
# Advent of Code 2019 Day 12 Part One https://adventofcode.com/2019/day/12 # The N-Body Problem # What is the total energy in the system after simulating the moons given in your scan for 1000 steps? Axes = [0, 1, 2] # X, Y, Z class Body attr_accessor :position, :velocity def initialize(input_text) @position =...
class Post < ActiveRecord::Base validates :title, presence: true belongs_to :user end
class AddNameColumnToUser < ActiveRecord::Migration[5.0] def change add_column :users, :first_name, :string add_column :users, :last_name, :string add_column :users, :sex, :integer add_column :users, :birth, :date end end
# frozen_string_literal: true module Slack class Client HOST = $app_config.call(:slack_host) CHANNELS_IDS = { support_operations: "C58EJNB6D" }.freeze attr_reader :access_token, :adapter def initialize(client_params = {}) @adapter = client_params[:adapter] ||= RestClient init_access_tok...
#encoding: utf-8 class Cpanel::OrdersController < Cpanel::ApplicationController set :views, ENV["VIEW_PATH"] + "/cpanel/orders" #set :haml, layout: :"../layouts/layout" # list # GET /cpanel/orders get "/" do @orders = Order.normals haml :index, layout: :"../layouts/layout" end # create # POS...