text
stringlengths
10
2.61M
class Play < ApplicationRecord belongs_to :user belongs_to :category has_many :reviews # attr_accessor :name, :play_img include ImageUploader::Attachment(:image) # adds an `image` virtual attribute has_one_attached :image # has_one_attached :play_img end
# frozen_string_literal: true require './card.rb' require './hand.rb' RSpec.describe Hand do before do @hand = Hand.new end it 'responds to dealt_cards' do expect(@hand).to respond_to(:dealt_cards) end describe '#add_card' do it 'responds to add_card' do expect(@hand).to respond_to(:add_...
get '/' do @posts = Post.order(created_at: :desc) erb(:index) end
class ChangeTypeToCategoriesInDietaryRequirement < ActiveRecord::Migration[5.2] def change rename_column :dietary_requirements, :type, :categories end end
class AddDoneToExperiences < ActiveRecord::Migration def change add_column :experiences, :done, :boolean, null: false, default: false Experience.reset_column_information Experience.find_each do |exp| exp.update_attributes(done: true) if exp.status == 'Done!' end end end
Fabricator(:destination) do name {Faker::Name.name} zip {Faker::Address.zip} description {Faker::Hipster.words} end
class Dice < ActiveRecord::Base scope :character_sheet, -> { where('number > ? and plus < ?', 3, 5) } def self.d3 find_by(number: 3) end def self.d4 find_by(number: 4) end def self.d6 find_by(number: 6) end def self.d8 find_by(number: 8) end def self.d10 find_by(number: 10) ...
class Admin::ExperiencesController < AdminController respond_to :json def toggle @experience = Experience.find(params[:experience_id]) if params[:done] == 'true' @experience.mark_done else @experience.update_attributes(done: false) end render json: { success: true } end def de...
class Expense < ApplicationRecord belongs_to :user belongs_to :label belongs_to :day monetize :amount_cents end
class EmailListsAddAccount < ActiveRecord::Migration def self.up add_column :email_lists, :account, :string, :default => nil end def self.down remove_column :email_lists, :account end end
class Success < Response attr_reader :data def initialize(data) @data = data end def success? true end end
require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) index_page = Nokogiri::HTML(open(index_url)) student_info = index_page.css("div.student-card") students = [] student_info.each do |student| name = student.css("h4.student-name").text l...
require 'net/http' require 'net/https' require 'uri' require 'json' class ApiModel API_KEY = 'demo' class << self def get_offers_json(params, no_json = false) response_data = {} http = Net::HTTP.new('development.adilitydemo.com', 443) query = '' if params[:zip] && !params[:zi...
#!/usr/bin/ruby # require 'rubygems' require 'net/http' require 'cgi' require 'json' def get_response(query, output_type, entity_type) domain ='http://10.17.208.221:6860' path = '/get_entity' params = {:query => query, :output_type => output_type, :entity_type => entity_type} path = "#{path}?".concat(params.co...
require 'rails_helper' describe User do describe "#liked(bookmark)" do before do @user = create(:user) @bookmark_like = create(:bookmark, user: @user) @bookmark_unlike = create(:bookmark, user: @user) @like = @user.likes.create(bookmark: @bookmark_like) end describe "#liked(b...
require 'aws-sdk-apigateway' module Stax module Aws class APIGateway < Sdk class << self def client @_client ||= ::Aws::APIGateway::Client.new end def api(id) client.get_rest_api(rest_api_id: id) end def stages(id, deployment = nil) ...
class ActiveRecord::Base before_validation :populate_uuid, :on => :create before_validation :populate_gs_node_id, :on => :create # Set a UUID. # def populate_uuid if self.attribute_names.include?('uuid') && self.uuid.blank? uuid = UUID.new self.uuid = uuid.generate end end # Set the...
class Location < ActiveRecord::Base geocoded_by :full_street_address # can also be an IP address after_validation :geocode end
class List < ActiveRecord::Base as_enum :category, doing: 0, in_qa: 1, qa_pass: 2, accepted: 3 CATEGORY_DISPLAY_NAME = { "doing" => "Doing", "in_qa" => "In QA", "qa_pass" => "QA pass", "accepted" => "Accepted" } has_many :cards before_save :reset_previous_category categories.hash.each do...
FactoryBot.define do factory :docin_import_content, class: 'Docin::Content::Import' do site_id { 1 } concept_id { 1 } name { "記事取込" } code { "docin_import_test" } model { "Docin::Import" } trait :with_related_contents do after(:create) do |item| gp_article_content = FactoryBot.c...
class SendWelcomeEmailJob < ApplicationJob queue_as :default def perform(user_id) user = User.find(user_id) WelcomeMailer.welcome_email(user: user).deliver_now end end
Given(/^the user is logged in, navigates to edit manage account nickname page CAN_DT$/) do DataMagic.load("ducttape_canada.yml") visit LoginPage on(LoginPage) do |page| logindata = page.data_for(:can_login_dt_smoke_test) username = logindata['username'] password = logindata['password'] ssoid = log...
class HomeController < ApplicationController def index @title = "Welcome to Blggr using Ember JS" end end
def consolidate_cart(cart) new_hash = {} cart.each do |element| element.each do |item, item_info| if !new_hash.has_key?(item) new_hash[item] = item_info end if new_hash[item].has_key?(:count) new_hash[item][:count] += 1 else new_hash[item][:count] = 1 end ...
class AddComponentsPosition < ActiveRecord::Migration def self.up add_column :components, :position, :integer @components = Component.find(:all) @components.each do | c | c.position = 0; c.save end end def self.down remove_column :components, :position end end
require 'test_helper' class AddressPolicyTest < ActiveSupport::TestCase setup do setup_context @address = addresses(:one) @other_address = addresses(:two) end test 'should index all addresses for super user' do addresses = Pundit.policy_scope(@context, Address) assert addresses.map(&:user).u...
class DeveloperLead < ApplicationRecord belongs_to :team_lead belongs_to :developerz end
require 'rails_helper' describe UsersController do let(:user) { create(:user)} before do sign_in user end let(:valid_attributes) { { email: Faker::Internet.email, password: "abcd1234", password_confirmation: "abcd1234" } } let(:invalid_attributes) { { email: "inval...
require_relative 'db_connection' require 'byebug' require 'active_support/inflector' # NB: the attr_accessor we wrote in phase 0 is NOT used in the rest # of this project. It was only a warm up. class SQLObject def self.columns query = DBConnection.execute2(<<-SQL) SELECT * FROM #{tab...
class HomeController < ApplicationController before_action :authenticate_user!, except: %i[ index privacy free_acct terms get_started ] def index if current_user redirect_to action: 'dash' else render layout: 'front-page' end end def privacy; end def terms; end...
# Creates a withdrawal for the user, pulling from their cash account balance. # Controls the process to guaruntee its security, and creates a withdrawal # accounting entry in order to adjust the user's cash account balance after # it has been completed. # # The cash payment is sent through Paypal to the user's `paypal_...
require 'spec_helper' describe Phony::LocalSplitters::Regex do describe 'instance_for' do it 'does not cache' do described_class.instance_for({}).should_not equal(described_class.instance_for({})) end end describe 'split' do before(:each) do # Norway as example. # @split...
module V1 class JobsController < ApplicationController skip_before_action :verify_authenticity_token def create location = Location.find_by_name(params[:localizacao]) return render json: {success: false, message: "localização inválida"}, :status => 400 if location.nil? @job = Job.new(job_p...
# frozen_string_literal: true class RemoveStringFromGasSimulation < ActiveRecord::Migration[5.2] def change remove_column :gas_simulations, :string, :string end end
require_relative 'client_proxy' # Implements Campaign-related calls for Marketo. # # === Sources # # Campaigns have a source, which the Marketo SOAP API provides as +MKTOWS+ # and +SALES+. MarketoAPI provides these values as the friendlier values # +marketo+ and +sales+, but accepts the standard Maketo SOAP API # enum...
require 'spec_helper' describe TopicsController do before(:each) do @user = Factory(:user) end describe "GET tag" do def do_request(params = {}) get :tag, params.merge(:tag => "foo") end before(:each) do @topics = Topic.scoped @topics.stub_chain(:tagged_with, :in_groups_of).a...
class ProfileAddress < ActiveRecord::Base validates_presence_of :label belongs_to :profile belongs_to :address, :dependent => :destroy end
require File.dirname(__FILE__) + '/../spec_helper' describe User do describe '#authentication' do before(:each) do @user = create_active_user @user.should be_valid end describe 'on active account' do it 'should succeed given correct password' do @user.authenticate('p...
class Photo < ApplicationRecord belongs_to :event mount_uploader :image, ImageUploader validates :image, presence: true validates :event, presence: true end
require 'spec_helper' require 'kintone/api' require 'kintone/api/guest' require 'kintone/command/record' require 'kintone/command/records' describe Kintone::Api do let(:target) { Kintone::Api.new(domain, user, password) } let(:domain) { "www.example.com" } let(:user) { "Administrator" } let(:password) { "cyboz...
# 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 "rails_helper" describe "user creates a store", type: :feature do before :each do @user = User.create(role: 0, username: "guy", password: "pass", full_name: "DJ G", email: "example@example.com",) visit login_path within "#login" do fill_in "session[username]", with: "guy" fill_in "sess...
# -*- ruby -*- require 'rubygems' require 'hoe' require './lib/couchdiff.rb' require './lib/copier.rb' Hoe.plugin :bundler Hoe.spec('couchdiff') do |p| p.version = "0.0.3" p.developer('Jens Schmidt (Mu Dynamics)', 'jens@mudynamics.com') p.rubyforge_name = 'couchdiff' p.summary = 'Diff/Merge utility to compare...
class FoundationsController < ApplicationController # Presentar lista general de fundaciones def index @Foundation = Foundation.all end # Presentar un articulo especifico def show @Foundation = Foundation.find(params[:id]) end #Crear un articulo def new @Foundation = Foundation.new ...
require 'spec_helper' describe Solid::Template do let(:liquid) { %{first_string{% comment %} {% if foo %}ifcontent{% endif %} {% if foo %}ifsecondcontent{% endif %} {% endcomment %} {% unless foo %}unlesscontent{% endunless %} } } let(:template) { Solid::Template.parse(liquid) } spe...
AdminCanteen::Engine.routes.draw do root to: 'home#index' devise_for :administrators, controllers: { registrations: 'admin_canteen/registrations', sessions: 'admin_canteen/sessions' } get '/archived', to: 'orders#archived' get '/incidents', to: 'orders#incidents' ...
class NewArrivalWidget < ActiveRecord::Base #attr_accessible :element_count, :folder_id, :title include Widget MAX_ELEMENT_COUNT = 20 belongs_to :folder before_validation :set_default! validates_numericality_of :element_count, :greater_than_or_equal_to => 1, ...
class UserPictureUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick # storage :file version :middle do process resize_to_fill: [ 200, 200 ] end version :mini, from: :middle do process resize_to_fill: [ 28, 28 ] end def store_dir "uploads/user/picture/#{model.id}" end ...
class TasksController < ApplicationController def show @task = Task.find(params[:task_id]) @tags = @task.tags end def new @list = List.find(params[:list_id]) @task = Task.new end def create @list = List.find(params[:list_id]) @task = Task.new(task_params) if @task.save flas...
# Write a method that returns a list of all of the divisors of the positive # integer passed in as an argument. The return value can be an in any sequence # you wish. # Examples def divisors(number) (1..number).select { |n| number % n == 0 } end # or def divisors(number) 1.upto(number).select do |candidate| ...
class Personalcharge < ActiveRecord::Base STATE_TYPES = ["pending", "denied", "submitted", "approved"] validates :hours, numericality: true validates :service_fee, numericality: true validates :reimbursement, numericality: true validates :meal_allowance, numericality: true validates...
require 'action_view' require 'tzinfo' class Offer class DateHelper include ActionView::Helpers::DateHelper end def self.helper @h ||= DateHelper.new end include Mongoid::Document include Mongoid::Timestamps field :status, :type => String field :short_details, :type => Array field :created_tim...
class Upsell < ApplicationRecord belongs_to :first_customization, class_name: 'Customization' belongs_to :second_customization, class_name: 'Customization' end
class Estado < ActiveRecord::Base establish_connection(:snib) self.primary_key = 'entid' scope :campos_min, -> { select('entid AS region_id, entidad AS nombre_region').order(entidad: :asc) } scope :centroide, -> { select('st_x(st_centroid(the_geom)) AS long, st_y(st_centroid(the_geom)) AS lat') } scope :geoj...
@convert = { "celsius_fahrenheit" => ->(t) {(t*9.0/5.0) + 32}, "fahrenheit_celsius" => ->(t) {(t-32) * 5.0/9.0}, "celsius_kelvin" => ->(t) {t + 273.15}, "kelvin_celsius" => ->(t) {t - 273.15}, "kelvin_fahrenheit" => ->(t) {(t - 273.15) * 9.0/5.0 + 32}, "fahrenheit_kelvin" => ->(t) {(t - 32) * 5.0/9.0 + 27...
class PortalController < ApplicationController def show @categories = Category.all end end
class AddProductDetailsToItem < ActiveRecord::Migration def change add_column :items, :product_details, :text end end
class AddProductIdToCartItem < ActiveRecord::Migration def change add_column :cart_items, :product_id, :integer add_index :cart_items, :product_id end end
module Mirrors # A class to reflect on instance, class, and class instance variables, # as well as constants. The uniting theme here is items indexable off of a # +Class+ or other +Object+ with a +String+ key but without abundant extra # metadata like classes and methods. # # A FieldMirror is basically an o...
ChoreTracker::Application.routes.draw do # Generated routes for models resources :chores resources :tasks resources :children # Routes for authentication resources :users resources :sessions match 'user/edit' => 'users#edit', :as => :edit_current_user match 'signup' => 'users#new', :as => :signup ...
class Publication < ActiveRecord::Base attr_accessible :title belongs_to :author validates :author, presence: true end
class VotesController < ApplicationController def up_vote set_up update_vote(1) redirect_to word_path(@word) end def down_vote set_up update_vote(-1) redirect_to word_path(@word) end def current_ip request.remote_ip.to_s end def user User.find_or_create_by ip: current_...
module YACCL module Model class Repository attr_reader :id attr_reader :name attr_reader :description attr_reader :root_folder_id attr_reader :capabilities attr_reader :url attr_reader :latest_change_log_token attr_reader :vendor_name attr_reader :cmis_version...
# == Schema Information # # Table name: blog_entries # # id :integer not null, primary key # title :string # author :string # content :text # created_at :datetime not null # updated_at :datetime not null # image_file_nam...
#!/usr/bin/env ruby require_relative "./mini/Parser" require_relative "./mini/Helpers" require "pp" # TODO: This is a list of things that I want to implement in this language # 1. DETAILS # - Add string formatting # - Pass arrays by reference!!! # 2. CLASSES - Implement a class syntax to allow for object orient...
class Note < ActiveRecord::Base belongs_to :transaction attr_accessible :transaction, :content validates :transaction, presence: true validates :content, presence: true end
module Terminus module Connector autoload :Server, ROOT + '/terminus/connector/server' autoload :SocketHandler, ROOT + '/terminus/connector/socket_handler' end end
class AddHonorificToContacts < ActiveRecord::Migration def self.up add_column :contacts, :honorific_prefix, :string, :limit => 50 add_column :contacts, :honorific_suffix, :string, :limit => 50 end def self.down remove_column :contacts, :honorific_suffix remove_column :contacts, :honorific_prefix ...
require 'pry' STDOUT.sync = true def show_abbreviations `gedit language.json` end def escape_double_quotes(string) string.gsub('"', '\\"') end def error(message) `notify-send --hint=int:transient:1 --hint=string:sound-name:bell "#{escape_double_quotes(message)}"` end def capitalize(sentence) sentence.spli...
require_relative "../builder" require_relative "../statements/postgres/insert" require_relative "../statements/postgres/sequence" require_relative "../utils/postgres" module Sqlbuilder module Builders class PostgresBuilder < Sqlbuilder::Builder def initialize @utils = Utils::Postgres.new end...
class CurriculumVitae < ApplicationRecord acts_as_taggable belongs_to :user has_many :curriculum_vitae_details, dependent: :destroy has_many :curriculum_vitae_jobs, dependent: :destroy has_many :jobs, through: :curriculum_vitae_jobs, dependent: :destroy has_attached_file :cv_upload accepts_nested_at...
# Contains all parsers used to convert clients' data strings to ruby hashes. module ChainReactor::Parsers # Error raised if there's an error parsing a string. class ParseError < StandardError end # Error raised if a required key is missing class RequiredKeyError < StandardError end # Base class for a...
module HandRules class Straight < BaseRule def match_rule?(hand) hand.sort_by!{ |card| card.face.face_value } (0..hand.length-2).each do |time| return false unless hand[time+1].sequence_of(hand[time]) end true end def value 5 end def to_s 'straight' ...
class AwsJobsController < ApplicationController before_filter :require_login def index gajs = GetAwsJobsStatus.for(user_id: current_user.id) if gajs.errors? flash[:alert] = "There were errors trying to retrieve AWS jobs status: #{gajs.errors.join(' ')}" @jobs = [] else @jobs = gajs.jo...
# Add your code here class Dog @@all = [] attr_accessor :name def initialize(name) @name = name save end def self.all @@all end def self.clear_all @@all.clear end def self.print_all self.all.each{|dog| puts "#{dog.name}"} end def save @@all << self end end
require 'rails_helper' module Annotable RSpec.describe User, type: :model do let(:user) { described_class.new(attributes) } context 'valid_attributes' do let(:valid_attributes) do Fabricate.attributes_for(:user) end let(:attributes) { valid_attributes } it { expect(user).to b...
set :stages, %w( production staging ) set :default_stage, 'staging' require "capistrano/ext/multistage" set :application, 'womble' set :scm, :git set :repository, "git@github.com:sparksp/#{application}.git" set :ssh_options, { forward_agent: true } # set :scm_username, '' set(:deploy_to) ...
class ChangeKnoteDefaultDifficulty < ActiveRecord::Migration def self.up change_column_default :knotes, :difficulty, 37.5 end def self.down change_column_default :knotes, :difficulty, 12.5 end end
class DosesController < ApplicationController def new @cocktail = Cocktail.find(params[:cocktail_id]) @dose = Dose.new kind ingredients end def create @dose = Dose.new(dose_params) if @dose.ingredient_id @dose.ingredient_id = Ingredient.where(name: dose_params['ingredient_id'])[0].i...
module SponsorsHelper def cache_key_for_sponsors count = Sponsor.count max_updated_at = Sponsor.maximum(:updated_at).try(:utc).try(:to_s, :number) "sponsors/all-#{count}-#{max_updated_at}" end def sponsor_plans_collection Sponsor.plans.map do |key, plan| ["#{plan[:name]} #{number_t...
class MarkerSerializer < ActiveModel::Serializer attributes *(Marker.attribute_names - []) end
class FavoritesController < ApplicationController before_filter :authenticate_user!, :except => [:create] def index @favorites = current_user.favorites .includes(:show => :artist) .includes(:show => :venue) .paginate(:page => params[:page], :per_page => ...
module Atech module ObjectStore class File ## Raised when a file cannot be found class FileNotFound < Error; end ## Raised if a file cannot be added class ValidationError < Error; end ## Raised if a frozen file is editted class CannotEditFrozenFile < Error; end ## Rai...
class Api::V1::ReportesController < Api::V1::BaseController respond_to :json def index reportes = Reporte.all render json: reportes end def show respond_with Reporte.find(params[:id]) end # Creando reporte def create reporte=Reporte.new(reporte_params) if reporte.save rende...
require "formula" class Ship < Formula homepage "https://github.com/fetchlogic/ship" url "https://github.com/fetchlogic/ship/archive/1.0.0.zip" sha1 "e6d20aa0c9f4b380bf8f3df48a79940bb2944a8e" sha256 "b63c5770bd17ac8593f15b4bfd07b9d393cb7e725c61a60e6ef027abb2a89d1f" def install bin.install 'ship' end ...
require 'capybara' require 'capybara/dsl' require 'capybara/poltergeist' require 'nokogiri' include Capybara::DSL module StockExchangeGrabber module Collectors class Collector @@BASE_URL = "https://www.nyse.com" @@NUM_COMPANIES = 2 def initialize initialize_capybara() end ...
class AddBaseIdToMicroposts < ActiveRecord::Migration def change add_column :microposts, :base_id, :integer add_index :microposts, :base_id end end
class Timer attr_accessor :seconds, :minutes, :hours def initialize(seconds = 0 ) self.seconds = seconds end def seconds=(seconds) @seconds = seconds @minutes = (@seconds / 60).floor @hours = (@minutes / 60).floor end def time_string seconds_display = @seconds % 60 minutes_display = @minutes % 60...
class UsersController < ApplicationController before_action :authenticate_user! def edit @user = current_user end def update user = User.find(current_user.id) if user.update!(update_params) redirect_to "/users/mypage" else render :edit end end def exhibiting @items = ...
class AddCommitteeToCoordinate < ActiveRecord::Migration def change add_reference :coordinates, :committee, index: true, foreign_key: true end end
require 'spec_helper' def mock_api_response(data = {}) Hashie::Rash.new(data) end describe Chef::Knife::DigitalOceanDropletCreate do subject { s = Chef::Knife::DigitalOceanDropletCreate.new s.stub(:client).and_return mock(DigitalOcean::API) s } let(:config) { { :digital_ocean_client_id...
class ProjectManagerController < ApplicationController def index @categories = Category.all @projects = Project.all end end
require 'ruble' command t(:sidebar) do |cmd| cmd.scope = 'source.php' cmd.trigger = 'wpside' cmd.output = :insert_as_snippet cmd.input = :none cmd.invoke do scope = ENV['TM_SCOPE'] if scope.include? 'source.php.embedded.block.html' 'get_sidebar(); ' else '<?php get_sidebar(); ?> ' ...
#============================================================================== # ** Window_Selectable #------------------------------------------------------------------------------ # This window class contains cursor movement and scroll functions. #====================================================================...
module DeepStore module Model module ContentInterface def self.included(base) base.class_eval do extend Forwardable attr_reader :sweeper def_delegators :content, :read, :write, :rewind, :each, :puts, :close, :unlink def reload @content = nil ...
class SiteSetting < ActiveRecord::Base scope :visible, -> { where(visible: true) } def self.get name, default_value = nil where(name: name).first.try(:value) || default_value end def self.set name, value where(name: name).first_or_create.update(value: value) value end end
ActiveAdmin.register Person do permit_params :name, :description, :title, :picture, :slack_id index do selectable_column id_column column :name column :description column :title column :picture column :slack_id actions end filter :name filter :slack_id form do |f| f.in...
FactoryGirl.define do factory :background do consultant citizen false convicted false parole false illegal_drug_use false illegal_purchase false illegal_prescription false information_is_correct '1' end end
class AddTwitterUsertoTweets < ActiveRecord::Migration[5.0] def change add_reference :tweets, :twitter_user, index: true end end
require 'legacy_migration_spec_helper' describe HdfsEntryMigrator do before :all do HdfsEntryMigrator.migrate end describe ".migrate" do it "should migrate the hdfs references found in the edc_comment table to the new database" do count = 0 Legacy.connection.select_all(" SELECT DISTI...