text
stringlengths
10
2.61M
class RemoveFacebookTokenFromUsers < ActiveRecord::Migration def change remove_column :users, :fb_user_uid remove_column :users, :fb_access_token end end
class TransfersController < ApplicationController def index @transfers = Transfer.all render json: @transfers end def create Transfer.create(transfer_params) end private def transfer_params params.require(:transfer).permit(:buyer_id, :seller_id, :item_id, :amo...
class SessionsController < ApplicationController layout "users_sessions" before_action :load_user, only: :create def new return unless logged_in? redirect_to root_path end def create log_in @user redirect_to root_path end def delete log_out redirect_to root_path end private...
class App < Sinatra::Base register Sinatra::Namespace # Begin users namespace namespace '/users' do before do next unless request.post? || request.put? @body_params = JSON.parse(request.body.read) end def body_params @body_params end def validate_body_for_create_user ...
require 'brew_sparkling/user' require 'brew_sparkling/recipe/recipes' module BrewSparkling module Action module Install class Base attr_reader :name def initialize(name) @name = name end def logger @logger ||= Logger.default end def reci...
require 'spec_helper' require 'pathname' require 'tempfile' MiniMagick.processor = :mogrify describe MiniMagick::Image do context 'when ImageMagick and GraphicsMagick are both unavailable' do before do MiniMagick::Utilities.expects(:which).at_least_once.returns(nil) MiniMagick.instance_variable_set(...
json.tag_taggables do json.partial! 'api/v1/tag_taggables/show', collection: @tag_taggables, as: :tag_taggable end
URL = 'http://www.bom.gov.au/vic/observations/melbourne.shtml' API_KEY = 'fca168eabed1ae61ce4569fd4681f8b1' BASE_URL = 'https://api.forecast.io/forecast' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE CARDINAL_TO_DEGREES = {"CALM"=>0, "N"=>0, "NNE"=>22, "NE"=>45, "ENE"=>67, "E"=>90, "ESE"=>112, "SE"=>135, "SSE"=...
require 'rails_helper' RSpec.describe State, type: :model do it { should validate_presence_of(:st_name) } it { should validate_presence_of(:st_abbrev) } end
require 'spec_helper' RSpec.describe Coordinates do describe '.new' do let(:coordinates) { Coordinates.new(3, 4) } it 'sets the first argument to x' do expect(coordinates.x).to eq 3 end it 'sets the second argument to y' do expect(coordinates.y).to eq 4 end end describe '#==' d...
class CreateBusinessCardOrders < ActiveRecord::Migration def self.up create_table :business_card_orders do |t| t.integer :quantity t.integer :business_card_batch_id t.boolean :reprint t.integer :business_card_id t.timestamps end end def self.down drop_table :business_c...
class CartItemsController < ApplicationController def create # raise @cart = Cart.find(cart_params[:cart_id]) @cart_item = CartItem.new(cart_params) @cart_item.product = Product.find(cart_items_params[:product]) @cart_item.strength = Strength.where(strength: cart_items_params[:strength]).first...
class FontLiberationMonoForPowerline < Formula head "https://github.com/powerline/fonts.git", branch: "master", only_path: "LiberationMono" desc "Literation Mono for Powerline" homepage "https://github.com/powerline/fonts/tree/master/LiberationMono" def install (share/"fonts").install "Literation Mono Power...
require 'rubygems' require 'yajl' require 'open-uri' require 'nokogiri' require 'uri' require 'net/http' require 'cgi' require 'rack' DEFAULT_DOWNLOAD_LOCATION = "/Volumes/justin/youtube" YT_LOG_LEVEL = "WARN" def log(entry) puts entry end class String def undelimit(options={}) not_urls = options[:not_...
class EARMMS::MembershipAdminUserEditController < EARMMS::MembershipAdminController helpers EARMMS::MembershipAdminUserEditHelpers before do @fields = [ {name: "full_name", friendly: t(:full_name), type: "text", required: true}, {name: "birthday", friendly: t(:birthday), type: "date", required: fal...
require 'simplecov' SimpleCov.start require './lib/helper_methods' include HelperMethods describe HelperMethods do describe ' #today' do it 'returns a string' do expect(today).to be_a(String) end it 'returns a 6 digit date' do expect(today.chars.count).to eq(6) end end describe 'ran...
class CreateWeddingAlbumTranslations < ActiveRecord::Migration[5.2] def change create_table :wedding_album_translations do |t| t.integer :wedding_album_id t.integer :language_id t.string :title t.text :description end add_index :wedding_album_translations, :wedding_album_id add...
class CreateBlankets < ActiveRecord::Migration def change create_table :blankets do |t| t.integer :unit_id t.timestamps end add_index :blankets, :unit_id add_column :hubs, :blanket_id, :integer add_index :hubs, :blanket_id end end
=begin Write your code for the 'Acronym' exercise in this file. Make the tests in `acronym_test.rb` pass. To get started with TDD, see the `README.md` file in your `ruby/acronym` directory. =end class Acronym def self.abbreviate(s) s.split(/\W/).map(&:chr).join.upcase end end
#Implement all parts of this assignment within (this) module2_assignment2.rb file #Implement a class called LineAnalyzer. class LineAnalyzer #Implement the following read-only attributes in the LineAnalyzer class. #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated) #...
require 'test_helper' class EventTest < ActiveSupport::TestCase test "event has a name" do event = events(:one) event.name = "" assert ! event.valid? assert event.errors.on(:name) end test "event has a description" do event = events(:one) event.description = "" assert ...
ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do div class: "blank_slate_container", id: "dashboard_default_message" do span class: "blank_slate" do span I18n.t("active_admin.dash...
class CreateCoins < ActiveRecord::Migration[5.1] def change create_table :coins do |t| t.string :symbol t.string :name t.integer :tri_fa_score t.jsonb :tri_fa_positives, default: [] t.jsonb :tri_fa_negatives, default: [] t.string :proof_type t.integer :available_supply, l...
require 'spec_helper' describe ZoteroIngest do before(:each) do # there's a lot of file moving around that needs to happen. # 1. file is seen into DIRECTORY_WATCHER_DIR, 2. file is moved to inprocess directory and given time stamp. 3. when process is completed, file is moved into completed dir...
module Dashboard class EvaluationsController < Dashboard::BaseController before_filter :set_challenge, except: :destroy before_filter :set_judge, only: :create load_and_authorize_resource def new add_crumb 'Jurado', dashboard_judges_path(challenge_id: params[:challenge_id].to_i) add_crumb...
class Classroom < ActiveRecord::Base belongs_to :user has_many :students, :dependent => :destroy has_many :invitations has_many :trips, through: :invitations accepts_nested_attributes_for :students end
require_relative 'base' class Wrapper class EmptyContainer < Wrapper::Base def initialize(entry) super() @entry = entry end private def get_template_for_html %{ <div id='<%= @div %>' > <%= @entry %> </div> } end end end
class Climb < ApplicationRecord has_many :trip_reports, dependent: :destroy belongs_to :favorites, optional: true has_paper_trail validates :name, :latitude, :longitude, :grade, :approach, :avi, presence: true end
class TdPage def initialize(page_path) @page_path = page_path load_all_pages load_all_components end def load_all_pages # require all pages Dir.glob(File.join(@page_path, '**', '*_page.rb')).each {|page| puts page if $debug requ...
class Recommendation < ApplicationRecord #association belongs_to :users_skill, counter_cache: :recommendations_count belongs_to :user end
class Show < ActiveRecord::Base has_many :characters has_many :actors, through: :characters belongs_to :network end
class UsersController < ApplicationController before_action :authenticate_user! before_action :set_user, only: [:show, :edit, :destroy] load_and_authorize_resource def index current_user.update(:role => 'user') if !current_user.role if params[:my_friends] @own_friendships = Friendship.where(["cr...
class ModifyCategory < ActiveRecord::Migration def change add_column :events, :category_id, :integer add_index :events, :category_id end end
class BatchSerializer include FastJsonapi::ObjectSerializer attributes :name, :batch_source, :batch_no, :status, :start_date, :grow_method, :current_growth_stage, :estimated_harvest_date has_many :tasks, if: Proc.new { |record, params| params.nil? || params[:exclude_tasks] != true } attribute :id do |object| ...
require_relative '../card/card' module Euchre class Player attr_reader :name, :hand def initialize(name) @name = name @hand = [] end def deal(cards) for card in cards @hand.push(card) end end def to_s "Player #{@name}" end def review_trump(su...
=begin #=============================================================================== Title: Region Overlay Author: Hime Date: Mar 5, 2013 -------------------------------------------------------------------------------- ** Change log Mar 5, 2013 - Initial release ----------------------------------------------...
# game.rb class Game attr_reader :letters, :good_letters, :bad_letters, :status, :errors def initialize(word) @letters = get_letters(word) @errors = 0 @good_letters = [] @bad_letters = [] @status = 0 end # 1. ask letter # 2. check result def ask_next_letter puts "\n Input next...
class QuestionsController < ApplicationController def index @questions = Question.order("RANDOM()").limit(5) respond_to do |format| format.html { render action: 'new' } format.json { render json: @questions, :include => [:answers] } end end end
class Review < ActiveRecord::Base has_many :replies end
class RenamePublicColumn < ActiveRecord::Migration def change rename_column :photos, :public_id, :public end end
module Gradebook module Components module Models class Score < Base include Rounding properties :activity, :subject, :score, :grade, :max_score, :min_score, :credit_points, :remarks, :credit_hours, :is_absent properties :class_highest, :class_lowest, :class_average, :class_position,...
require "rails_helper" RSpec.describe Api::V1::TransactionsController, type: :controller do describe "GET #index.json" do let(:json_response) { JSON.parse(response.body) } it "responds with successful 200 HTTP status code" do get :index, format: :json expect(response).to be_success expect...
Given /the following users have been added to the User database:/ do |user_table| user_table.hashes.each do |user| User.create(user) end end When /I click on leaderboard/ do click_link("Leader board") end Then /I should see a display of top 10 players/ do expect(page).to have_content("L...
class RetailerSerializer < ActiveModel::Serializer attributes :id, :name, :phone_no, :email, :address, :pan_number, :retailer_type, :percent, :avatars def retailer_type object.retailer_type.name end def avatars return unless object&.avatars.attached? object.image_list_url(object.avatars) end...
class Employee < User scope :active, -> { joins(:status).where("statuses.name = ?", 'Active') } scope :not_admin, -> { where(admin: false) } protected def password_required? false end end
require 'geo_ruby' require "#{File.dirname(__FILE__)}/../ext/vincenty" module GeoRuby module SimpleFeatures class Point < Geometry alias_method :orig_ellipsoidal_distance, :ellipsoidal_distance # Implementation of the Vincenty 'distance' formula to find the ellipsoidal distance between points ...
require "eventmachine" require "em-http" require "rsolr" # Need by em-http on ruby 1.8 :( unless "".respond_to?(:bytesize) class String alias :bytesize :size end end module RSolr class EM def execute client, request_context method = request_context[:method] options = {} options...
# -*- coding: utf-8 -*- $:.unshift File.dirname(__FILE__) require 'hash-from_mysql_query_result' require 'pp' describe Hash::FromMysqlQueryResult do def fixture(filename) File.dirname(__FILE__) + '/fixtures/' + filename end before do data = <<-TEST_DATA mysql> SELECT * FROM foo; +----+-------+ | id | v...
class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale rescue_from CanCan::AccessDenied do |exception| redirect_to root_path, :alert => exception.message end # see http://guides.rubyonrails.org/i18n.html # usage: http://localhost:3000?locale=de def set_local...
require 'capybara' require 'capybara/dsl' require 'capybara/poltergeist' require 'phantomjs' require 'singleton' # Example of using # ps = ProductScrapper.instance # hash = ps.scrape 'http://www.saxoprint.co.uk/shop/', 'desk-calendars' class ProductScrapper include Capybara::DSL include Singleton def initialize...
require 'test_helper' class PostHelperTest < ActiveSupport::TestCase include PostHelper test 'get_post_submission_url should not add any parameters given a nil path and ref' do # Act result = get_post_submission_url(nil, nil) # Assert assert_equal '/post/submit', result end test 'get_post_s...
class Photo attr_accessor :image, :caption, :attributedCaption, :tags, :comments, :metaData, :disabledTagging, :disabledCommenting, :disabledActivities, :disabledDelete, :disabledDeleteForTags, :disabledDeleteForComments, :disabledMiscActions class << self def photoWithProperties(photoInfo) self.initWith...
# # Plato::AnalogIO class for simulator # module Plato class AnalogIO < GPIO def read $sim.cmd "AI,#{@pin}" end def write(data) $sim.cmd "AO,#{@pin},#{data}" end end end
# frozen_string_literal: true # Determine if a sentence is a pangram class Pangram class << self def pangram?(sentence) sentence.upcase.scan(/[A-Z]/).uniq.length == 26 end end end
class OverrideAssessmentMark < ActiveRecord::Base belongs_to :assessment_group # belongs_to :assessment_plan belongs_to :course validates_numericality_of :maximum_marks,:greater_than => 0 end
require 'json' require 'open-uri' module PlaceService class Place attr_accessor :name, :location, :schedules, :open_next def initialize @schedules = [] end def has_open_next? ! @open_next.nil? end def mergeSchedule(schedules_to) ...
class AddForToAccountingTransaction < ActiveRecord::Migration def change add_column :accounting_transactions, :for, :string end end
class ChangeDayType < ActiveRecord::Migration[5.1] def change change_column :timeslots, :day, :text end end
class AddEventSerializer < ActiveModel::Serializer attributes :id, :event_id, :job_seeker_id end
class CatRentalRequestsController < ApplicationController def new @request = CatRentalRequest.new @cats = Cat.all render :new end def create @request = CatRentalRequest.new(request_params) if @request.save redirect_to cat_rental_request_url(@request) else render :new ...
require 'spec_helper' module PriorityTest::Core describe DomainObject do subject do Class.new do include DomainObject end end it "coerces property type" do subject.property :count, Integer instance = subject.new(:count => '1') instance.count.should be_kind_of(Intege...
require 'spec_helper' describe Region do it { should have_many :sightings } it { should have_many :species} end
class AddDefaultValueeeToQuastions < ActiveRecord::Migration def change change_column :thoughts, :user_id, :integer, :default => 5 end end
class Person def self.method_missing(m, *args) method = m.to_s if method.start_with?("all_with_") attr = method[9..-1] if self.public_method_defined?(attr) PEOPLE.find_all do |person| person.send(attr).include(args[0]) end else raise ArgumentError, "Can't fi...
class CreateIndices < ActiveRecord::Migration def change create_table :indices do |t| t.integer :miner t.string :mode t.integer :make t.integer :year t.integer :model t.integer :engine t.integer :system t.integer :dtc t.boolean :complete, default: false ...
# == Schema Information # # Table name: photos # # id :bigint(8) not null, primary key # user_id :integer not null # img_description :string # created_at :datetime not null # updated_at :datetime not null # img_title :string not null #...
# This class is used for two general purposes: # 1. To get answers for reports # 2. To get "answers" to generate the page for the student # # In the case #2 the page is currently generated from the answer objects. It is not generated # from questions and then student answers filled in. So any "question" that isn't ab...
# Ruby environment / installation rbenv_root = node.fetch('identity_shared_attributes').fetch('rbenv_root') # sanity checks that identity_ruby correctly installed ruby unless File.exist?(rbenv_root) raise "Cannot find rbenv_root at #{rbenv_root.inspect} -- was it created in the base AMI?" end unless File.exist?(rben...
class Talk < ApplicationRecord belongs_to :sport belongs_to :user validates :comment, presence: true def user return User.find_by(id: self.user_id) end end
class Game def initialize(player1, player2) @player1_instance = player1 @player2_instance = player2 @current_player = @player2_instance puts "Alright #{@player1_instance.name} here's your first challenge." end def generate_challenge() @current_player = set_current_player() num1 = rand(...
#! /usr/bin/env ruby # Courtesy http://wolfslittlestore.be/2013/10/rendering-markdown-in-jekyll/ =begin Jekyll tag to include Markdown text from _includes directory preprocessing with Liquid. Usage: {% include_markdown <filename> %} Dependency: - kramdown =end module Jekyll class IncludeMarkdownError < ...
module BlacklightAdvancedSearch autoload :Controller, 'blacklight_advanced_search/controller' autoload :RenderConstraintsOverride, 'blacklight_advanced_search/render_constraints_override' autoload :CatalogHelperOverride, 'blacklight_advanced_search/catalog_helper_override' autoload :QueryParser, 'blacklight_adv...
module ::Logical::Naf class Unpickler include ::Af::Application::Component create_proxy_logger attr_reader :preserves, :preservables, :input_version, :references, :context def initialize(preserves, preservables, input_version) @pr...
module PageDesc module Types module Clickable extend Action also_extend Element action :click do browser_element.click end end end end
# Encoding: UTF-8 # # # LEVEL 4 # # # class Level4 < LivingRoom def initialize @num_toys = 50 @num_kids = 8 $window.caption = " ______ Level 4 ______" super e...
# encoding: UTF-8 module GoodData class ProjectMetadata class << self def keys ProjectMetadata[:all].keys end def [](key, options = {}) if key == :all uri = "/gdc/projects/#{GoodData.project.pid}/dataload/metadata" res = GoodData.get(uri) res['meta...
class Customer < ActiveRecord::Base attr_accessible :first_name, :last_name, :doctor_id, :user_id belongs_to :created_by_user, :foreign_key => :created_by, :class_name => User validates_presence_of :first_name validates_presence_of :last_name before_create :set_created_by has_many :pets has_many ...
require 'test_helper' class DepartmentStoresControllerTest < ActionController::TestCase setup do @department_store = department_stores(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:department_stores) end test "should get new" do get :ne...
require 'spec_helper' describe 'kibana' do context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end context 'kibana class without any parameters' do it { is_expected.to compile.with_all_deps } ...
class Api::RemindersController < RecordatoriosController skip_before_filter :verify_authenticity_token before_filter :authorize_by_token, only: [:create, :update, :destroy] # GET /recordatorios # GET /recordatorios.json def index if user_signed_in? @recordatorios = current_user.recordatorios.all ...
class TasksController < ApplicationController def index @homeworks = Homework.all @problems = Problem.all @students = User.where( user_type: "student" ) end def show @task = Task.find(params[:id]) end def update @task = Task.find(params[:id]) @task.update_attributes(task_params) redirec...
# == Schema Information # # Table name: pins # # id :integer not null, primary key # user_id :integer # question :text # question2 :text # question3 :text # question4 :text # question5 :text # created_at :datetime # updated_at :datetime # question1 :text # class...
class RemoveInRangeFromUser < ActiveRecord::Migration def up remove_column :users, :in_range end def down add_column :users, :in_range, :boolean end end
require 'sinatra/base' require 'haml' require 'pdfkit' require "vitae/server/helpers" require "vitae/server/node" class Server < Sinatra::Base helpers Helpers set :views, File.dirname(__FILE__) + '/views' set :public, File.join(Vitae::project_root, "themes") rescue '' before do request.path_info = CV.fi...
# ~*~ encoding: utf-8 ~*~ require File.expand_path('../helper', __FILE__) require File.expand_path('../wiki_factory', __FILE__) class Gollum::Macro::ListArgs < Gollum::Macro def render(*args) args.map { |a| "@#{a}@" }.join("\n") end end class Gollum::Macro::ListNamedArgs < Gollum::Macro def render(opts) ...
require 'test_helper' class UsersControllerTest < ActionController::TestCase fixtures :users, :roles test "should disallow anonymous user listing" do login_as :anonymous do get :index assert_redirected_to login_path end end test "should disallow unauthorized user listing" do login_as...
class Host < ApplicationRecord validates :event_id, :user_id, presence: true belongs_to :user belongs_to :event end
class Home attr_reader(:name, :city, :capacity, :price) def initialize(name, city, capacity, price) @name = name @city = city @capacity = capacity @price = price end end #We are just login the names of the places in each city and price by night # homes.each do |i| # puts "#{i.name} in #{i.ci...
class CreateQuizAnswers < ActiveRecord::Migration[6.1] def change create_table :quiz_answers do |t| t.string :answer t.boolean :correct t.belongs_to :quiz_question, null: false, foreign_key: true t.timestamps end end end
# frozen_string_literal: true class FileController < ApplicationController include Concerns::Application::RedirectWithStatus secure!(:page) title!('Files', only: %i[new create destroy]) title!('Headers', only: %i[new_header create_header destroy_header]) def new @file = MarkdownFile.new @markdown_...
module PushBuilder class APS attr_reader :alert, :badge, :sound def badge=(badge) @badge = badge.nil? ? nil : Integer(badge) rescue ArgumentError fail TypeError, 'Invalid number for badge' end def alert=(alert) @alert = alert.nil? ? nil : String(alert) end def sound=(s...
require 'securerandom' class Invite < ApplicationRecord OWNER_LIMIT = 10 belongs_to :owner, :class_name => 'User' belongs_to :user, optional: true belongs_to :tournament validates_presence_of :tournament_id, :code, :email validate :maximum_allowed_by_owner before_validation :generate_code before_val...
module FogTracker describe AccountTracker do before(:each) do @account_receiver = double "account callback object" @account_receiver.stub(:callback) @error_receiver = double "error callback object" @error_receiver.stub(:callback) @tracker = AccountTracker.new( ...
# -*- encoding: utf-8 -*- # stub: bloom-filter 0.2.2 ruby lib # stub: ext/extconf.rb Gem::Specification.new do |s| s.name = "bloom-filter" s.version = "0.2.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Bhara...
class Api::V1::BookController < Api::V1::BaseController def get_list render json: Book.all.sort_by{|a| a.id}.map{|b| {title: b.title, id: b.id, version: better_time(b.last_updated_at)}} end def better_time(time) t = time.to_s p = /(....)-(..)-(..)/ p.match(t) year = $1.to_i mon...
require 'rails_helper' RSpec.describe Board, :type => :model do describe 'validations' do it 'validates not null and uniqueness of name and does not throw a db error' do board = FactoryGirl.create(:board) expect(FactoryGirl.build(:board, id: board.id, name: nil)).not_to be_valid end end end
json.user do |json| json.call(@user, :id, :name) json.set! :status do |stats| stats.call(@status, :automation, :imagination, :humor, :enhancement) end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Tikkie::Api::V1::Responses::Payment do subject { Tikkie::Api::V1::Responses::Payment.new(payment) } let(:payment_requests) { JSON.parse(File.read("spec/fixtures/responses/v1/payment_requests/list.json"), symbolize_names: true) } let(:payment_re...
# Lecture: Polymorphism and Ensapsulation # Polymorphism refers to the ability of different objects to respond in # different ways to the same method (or method invocation) # Polymorphism refers to the ability of different objects to respond in # different ways to the same method (or method invocation) # Polymorph...
Shindo.tests('Fog::Compute::DigitalOceanV2 | list_regions request', ['digitalocean', 'compute']) do service = Fog::Compute.new(:provider => 'DigitalOcean', :version => 'V2') region_format = { 'slug' => String, 'name' => String, 'sizes' => Array, 'available' => Fog::Boolean, 'features' => Array,...