text
stringlengths
10
2.61M
class AttachmentsController < ApplicationController def create event = Events::Base.find(params[:note_id]) authorize! :create, Attachment, event if params[:contents] attachment_content = params[:contents] else transcoder = SvgToPng.new(params[:svg_data]) attachment_content = transco...
require_relative 'base_page' class LiquidationCigarSamplersPage < BasePage path '/cigars/liquidation-cigar-samplers' validate :url, %r{/cigars/liquidation-cigar-samplers(?:\?.*|)$} validate :title, /^#{Regexp.escape('Cigar Sampler Liquidation | Famous Smoke')}$/ end
# Controller to manage user sessions/logins/tokens class SessionController < ApplicationController # Generates an HTML form for users to log in with def new end # Used to create a user session ("log in") # HTTP Parameters: # name - The User's name # password - The User's password # Returns: # ...
Movies::Application.routes.draw do root :to => "movies#index" resources :movies do get :remove, :on => :member end end
class AddressesController < ApplicationController before_action :authenticate_user!, only: %i[new edit index] before_action :authorize_address, only: %i[edit update destroy] #-------------------------------------- # Queries the Adressess model checks if current user via the fk #----------------------------------...
require 'pg' class Patient attr_reader(:name, :birthday, :condition, :dr_id) def initialize(attributes) @name = attributes[:name] @birthday = attributes[:birthday] @condition = attributes[:condition] @dr_id = attributes[:dr_id] end def self.all results = DB.exec("SELECT * FROM patients;")...
require 'spec_helper' require_relative '../../lib/paths' using ArrayExtension using StringExtension using SymbolExtension module Jabverwock RSpec.describe 'path test' do subject(:of) { OpalFileReader.new } it 'isRubyCode, not ruby' do file = "test" expect(of.isRubyCode(file)).to eq false...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
require "test_helper" class TrailsServiceTest < ActiveSupport::TestCase attr_reader :service def setup @service = TrailsService.new end test "#trails" do VCR.use_cassette("trails_service_api") do all_trails = service.get_all_trails(1) trails = all_trails.flatten first_trail ...
class AttachedFile < ActiveRecord::Base belongs_to :post validates :original_name, presence: true mount_uploader :file, AttachedFilesUploader # True if the file is an image def image? %w(.jpg .jpeg .gif .png).include? File.extname(self.file.path) end # Return de filesize def file_size file....
Pod::Spec.new do |s| s.name = "RZCellSizeManager" s.version = "1.1.2" s.summary = "Dynamic size computation and caching for cells." s.description = <<-DESC RZCellSizeManager is an object used to cache and get cell heights for UICollectionView cells and UITableView cells. ...
class SubscriptionSerializer < ActiveModel::Serializer attributes %i(id channel_id user_id messages_count) end
class User < ApplicationRecord validates :name, presence: true, uniqueness: true has_many :events =begin has_many :created events, class_name: ‘Event’ has_many :invitations has_many :attented_events, through: :invitations =end end
class AddDetaultValueForRecipe < ActiveRecord::Migration def up change_column_default :recipes, :prepare_time, 1 end def down change_column_default :recipes, :prepare_time, nil end end
require File.dirname(__FILE__) + '/../test_helper' class TestData < Test::Unit::TestCase def setup @klass = Class.new(MockChart).class_eval { include GoogleChart::Data } end should 'use simple encoding by default' do assert_match(/\bchd=s:AB89\b/, @klass.new(:data => [0, 1, 60, 61]).to_url) end ...
FactoryGirl.define do factory :question do question_text { Faker::Lorem.sentence } trait :with_answers do after(:create) do |question| wrong_answer = create(:answer, question: question, name: 'wrong') right_answer = create(:answer, question: question, name: 'right') question.set...
class ChangeTimestampsToDatetime < ActiveRecord::Migration def change change_column :tweets, :retweeted_status_timestamp, :datetime change_column :tweets, :tweet_timestamp, :datetime end end
class Room < ActiveRecord::Base validates :title, presence: true validates :address, presence: true validates :description, length: {minimum: 10, maximum:10000} validates :price_in_pence, presence: true validates :no_of_rooms, presence: true # we are passing in a default on the DB so no need to validate the is_fe...
class Commerce < ApplicationRecord has_many :reviews has_many :commerce_categories has_many :categories, through: :commerce_categories has_many :product_categories scope :filter_category, ->(cat){ joins(:categories).where('categories.name = ?', cat) if cat.present? } scope :search, ->(name) { w...
class AddLibraryMemberToBookings < ActiveRecord::Migration[5.0] def change add_reference :bookings, :email, foreign_key: true end end
module Soundex class Soundex @editedString = String.new() MAX_LENGTH = 3 FILL_CHAR = "0" def initialize(paramString,isUnitTest=false) @editedString = paramString.downcase if !isUnitTest @soundexCode = getFirstChar() @editedString = @editedString[1..-1] ...
require 'spec_helper' RSpec.describe Volunteermatch::API::SearchOrganizations do subject { Volunteermatch::Client.new('acme','1234567890ABCDEF') } before(:each) do @url = URI.parse("http://www.volunteermatch.org/api/call?action=searchOrganizations&query=" + URI.encode({ location: "94108", numberOfResults: 10,...
# Required to use OAuth2 gem for the outdated oauth2 spec to which 37signals conforms module OAuth2 module Strategy class WebServer < AuthCode def authorize_params(params={}) params.merge('type' => 'web_server', 'client_id' => @client.id) end end end end
class Admin::Attributes::VegitationsController < ApplicationController before_filter :authenticate_admin before_filter :current_admin layout 'admin' def index @vegitations = PropertyAttrVegetation.order('sort').all end def show @vegitation = PropertyAttrVegetation.find(params[:id]) @current_ad...
namespace :check do namespace :migrate do task reindex_relationships: :environment do LAST = 0 RequestStore.store[:skip_notifications] = true RequestStore.store[:skip_rules] = true old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil started = Time.now.to_i ...
require 'spec_helper' describe Sport do it { should validate_presence_of(:name).with_message("You want to play a sport with no name?") } it { should have_many(:games) } describe "#to_twitter" do before { subject.name = "9 Ball" } its(:to_twitter) { should == "#9Ball" } end end
class UserPreferencesController < ApplicationController before_filter :authenticate_user! skip_before_filter :check_for_user_preference, :only => [:new, :create, :sg_categories, :sg_suggestions, :sg_deserve_it, :category_save, :u_deserve_it_save] def new if @profile_user.user_preference.present? redir...
require 'rails_helper' RSpec.describe Professor, type: :model do describe 'validations' do it {should validate_presence_of :name} it {should validate_presence_of :age} it {should validate_presence_of :specialty} end describe 'relationships' do it {should have_many :professor_students} it {sh...
class AddAttributesToShows < ActiveRecord::Migration[4.2] def change add_column :shows, :day, :string add_column :shows, :rating, :integer end end
module UsersHelper # A helper, which is a function/method designed for use in views # Return gravatar image tag # based on user email and some default options using the gravatar_image_tag helper def gravatar_for(user, options = { :size => 50 }) gravatar_image_tag(user.email.downcase, :alt => user.name, ...
RSpec.shared_examples "api GET" do |endpoint| it_behaves_like "api endpoint" it { expect(subject.body).to be_a Hash } it { expect(subject.body).to include("status" => "ok") } it { expect(subject.status).to eq 200 } describe "custom options" do before do options.merge! custom: "optionValue" ...
@countries = [ "Argentina", "Australia", "Austria", "Belarus", "Belgium", "Bosnia and Herzegowina", "Brazil", "Bulgaria", "Canada", "Chile", "Colombia", ...
require "test_helper" class CharactersParserTest < ActiveSupport::TestCase setup do @subject = CharactersParser.new end test "should parse characters" do data = <<-JSON { "results": [ { "id": 1, "name": "character 1", "image": "/image1.jpg"}, { "id": 2, "name": "charac...
class ChangePublishAtToArticles < ActiveRecord::Migration def change remove_column :articles, :publish_at, :string add_column :articles, :publish_at, :datetime end end
class AddUploadSeason < ActiveRecord::Migration[5.2] def change add_column(:uploads, :season, :integer, default: 0, null: false) end end
class AdminDetailsController < ApplicationController def create # accessed through view admin/show_details @admin = Admin.find(params[:admin_detail][:admin_id]) @admin_detail = @admin.build_admin_detail(admin_detail_params) if @admin_detail.save flash[:success] = "Details stored." redirect_t...
require 'spec_helper' require 'puppet_x/bsd/util' describe 'PuppetX::BSD::Util' do context '#uber_merge' do it 'should combind simple hashes' do h1 = {:one => 1} h2 = {:two => 2} wanted = {:one => 1, :two => 2} expect(PuppetX::BSD::Util.uber_merge(h1, h2)).to eq(wanted) end it...
# encoding: UTF-8 class Status < ActiveRecord::Base default_scope { order(created_at: :desc) } paginates_per 10 acts_as_commontable belongs_to :character belongs_to :group belongs_to :goal belongs_to :action_goal has_many :likes, dependent: :destroy has_many :likers, through: :likes, source: :user ...
FactoryGirl.define do factory :story do name "name of story" text "text of story" after(:create) do |story_item| story_item.start end end end
module SolutionChecker UP = 'U' DOWN = 'D' LEFT = 'L' RIGHT = 'R' def self.solves?(maze, solution) return false, 'No solution provided' unless solution.present? state = SolutionChecker::MazeState.new(maze) solution.each_char.with_index do |move, index| dx, dy = case move when UP...
require 'sinatra' require 'yo-ruby' configure { set :server, :puma } configure { set :port, 8080 } Yo.api_key = "#{ENV['YO_API_KEY']}" get '/yo/:username' do begin Yo.yo!(params[:username]) rescue YoUserNotFound => e puts "User does not exist." rescue YoRateLimitExceeded => e puts "R...
class Notifier < ActionMailer::Base default from: "jobsjugaad@gmail.com" def generate_token_link(user, token, url) url + "?auth_token=#{token}&email=#{user.email}&type=#{user.class.to_s}" end def activate_user(user, token) @user = user @link = generate_token_link(user, token, activate_user_url(:ho...
class Tweet < ApplicationRecord acts_as_votable belongs_to :user scope :of_followed_users, -> (following_users) { where user_id: following_users } end
# frozen_string_literal: true require 'rails_helper' # expects 'policy' let defined RSpec.shared_context 'allows_policy_action' do |policy, action| before { expect_any_instance_of(policy).to receive(action) { true } } end # shared_examples_for 'policy_allows_action'
class Gallary < ActiveRecord::Base belongs_to :event mount_uploader :image, ImageUploader validates :image, presence: true has_many :avgrating, dependent: :destroy has_many :gallaryrating, dependent: :destroy end
task :export, [:eligibility] => :environment do |t, args| require 'csv_exporter' desc "it exports a CSV file" file = "organizations.csv" eligibility = args[:eligibility] CsvExporter.new({file: file, eligibility: eligibility}).export end
# encoding: utf-8 class SafeArray ## e.g. ## Array.of( Address ), Array.of( Integer), etc. def self.build_class( klass_value ) ## note: care for now only about value type / class ## note: keep a class cache cache = @@cache ||= {} klass = cache[ klass_value ] return klass if klass k...
class Match < ApplicationRecord RESULT_MAPPINGS = { win: 0, loss: 1, draw: 2 }.freeze TIME_OF_DAY_MAPPINGS = { morning: 0, afternoon: 1, evening: 2, night: 3 }.freeze DAY_OF_WEEK_MAPPINGS = { weekday: 0, weekend: 1 }.freeze MAX_RANK = 5000 TOTAL_PLACEMENT_MATCHES = 10 MAX_PER_SEASON = 500 MAX_FRIENDS_PER_...
class Engineer < ApplicationRecord has_one :engineer_registration_type belongs_to :engineer_status_type has_one :engineer_hiring, autosave: true has_one :office, through: :engineer_hiring belongs_to :person_info, autosave: true has_many :careers has_many :engineer_hope_businesses accepts_nested_attributes_for :...
require "Proceso" class ProcessManager def initialize() @listaProcesos = [] end def addProcess(p) # Añadir a la lista de procesos @listaProcesos << p; end def each_process() # Devolver todos los procesos @listaProcesos.each do |p| yield(p) end end def e...
class Friendship < ActiveRecord::Base # Relationships belongs_to :contact belongs_to :friend, :class_name => 'Contact' # Validations validate :uniqueness_of_combination validate :cannot_be_friends_with_self # Validate that contact and friend arent the same # Custom Methods def uniqueness_of_combinati...
require_relative "../../../base" require Vagrant.source_root.join("plugins/provisioners/chef/omnibus") describe VagrantPlugins::Chef::Omnibus, :focus do let(:prefix) { "curl -sL #{described_class.const_get(:OMNITRUCK)}" } let(:version) { :latest } let(:prerelease) { false } let(:build_command) { described_c...
class UserMailer < ApplicationMailer def create_user(user) @user = user mail(to: @user.email, subject: 'IMV Leave App') end end
Factory.define :task do |task| task.description "Do something" task.user_id :user end
require File.expand_path("../../Homebrew/node", __FILE__) class NodeFormulator < Formula desc "Homebrew node formula generator" homepage "https://github.com/chrmoritz/homebrew-node-formulator#readme" head "https://github.com/chrmoritz/homebrew-node-formulator.git" depends_on "node" resource "balanced-match...
module UserBooksHelper def book_status_for_select options = { 'To Read': UserBook::TO_READ, 'Read': UserBook::READ, 'Currently Reading': UserBook::READING } options_for_select(options) end end
# frozen_string_literal: true require "spec_helper" describe AccountFetcher do let(:klass) { described_class } let(:http_klass) { HttpAccountFetcher } let(:config_klass) { ConfigAccountFetcher } describe ".fetch_details_for_account_id" do let(:id) { 123 } subject { klass.fetch_details_for_account_id...
require 'spec_helper' RSpec.describe MaxemailApiSubscriptions do describe '#subscribe' do it 'should subscribe user to the list' do response = described_class.subscribe(email_address: ENV['MAXEMAIL_TEST_EMAIL_ADDRESS'], list_id: ENV['MAXEMAIL_TEST_LIST_ID']) expect(response.body.to_s).to include('"sub...
# frozen_string_literal: true class Integer def as_bytes return '1 Byte' if self == 1 label = %w[Bytes KiB MiB GiB TiB] i = 0 num = to_f while num >= 1024 num /= 1024 i += 1 end "#{format('%.2f', num)} #{label[i]}" end end
class Fluentd module Setting class FilterRecordTransformer include Fluentd::Setting::Plugin register_plugin("filter", "record_transformer") attribute(:record, :string) def self.initial_params { } end def common_options [ :label, :...
require 'rails_helper' RSpec.describe User do describe 'validates' do it { should validate_presence_of(:email)} it { should validate_presence_of(:password)} it { should validate_presence_of(:first_name)} it { should validate_presence_of(:last_name)} end describe 'associations' do ...
#-- # Copyright (c) 2007 by Mike Mondragon (mikemondragon@gmail.com) # # Please see the README.txt file for licensing information. #++ require File.join(File.dirname(__FILE__), 'test_helper') include Hurl::Models module TestHelper end class TestUrl < Camping::UnitTest include TestHelper def setup Hurl::Mod...
class Car attr_accessor :train def initialize @attached = false end def attached? @attached end def attached! @attached = true end def detached! @attached = false end end
require 'journey' describe Journey do let(:entry_station) { double(:entry_station, zone: 1) } let(:exit_station) { double(:exit_station, zone: 2) } describe '#start' do it 'should record allow to call the entry station' do subject.start(entry_station) expect(subject.entry_station).to eq entry_st...
require_relative '../../scraper/openfoodfacts' require_relative '../spec_helper' require 'httparty' require 'nokogiri' RSpec.describe 'openfoodfacts' do describe "Environement variables" do before(:each) do @scraper = OpenFoodFacts.new end it '/invalid item', :real_http=>true do res = @scrap...
class UsersController < ApplicationController before_action :authorize_request, except: :create before_action :find_user, except: %i[create index show_by_token] # GET /users def index @users = User.all render json: @users, status: :ok, key_transform: :camel_lower end # GET /u...
# EventHub module module EventHub # Watchdog class class ActorWatchdog include Celluloid include Helper finalizer :cleanup def initialize EventHub.logger.info("Watchdog is starting...") async.start end def start loop do watch sleep Configuration.processor[...
class UploadedImage < Media include HasImage def picture self.image_path end def media_type 'uploaded image' end end
# frozen_string_literal: true require 'google/cloud/bigquery' module Ggl class BigQuery class << self def client key = ::ENV['GOOGLE_BIGQUERY_JSON_KEY'] if key key_hash = ::JSON.parse(::JSON.parse(key)) creds = ::Google::Cloud::Bigquery::Credentials.new(key_hash) ...
#This class is created to save our orders from the cart class OrdersController < ApplicationController respond_to :json acts_as_token_authentication_handler_for User #creates order and order_items associated with the order and products from the JSON fed from ngcart def create #create new order order = Or...
require 'vcr' require 'webmock' VCR.configure do |c| c.cassette_library_dir = "spec/fixtures/cassettes" c.hook_into :webmock c.configure_rspec_metadata! c.default_cassette_options = { match_requests_on: [:method, :uri, :body] } c.allow_http_connections_when_no_cassette = false c.ignore_localhost = tr...
require 'rspec' require_relative '../binary_tree' require_relative '../node' require_relative '../binary_tree_errors' RSpec.describe BinaryTree do def create_btree root_node = Node.new(nil, 'test data') BinaryTree.new(root_node) end left_test_string = 'left' right_test_string = 'right' context 'in...
require 'rails_helper' RSpec.describe APIFrontend::V1::UsersController, type: :controller do include ApiResponse let(:user) { create(:user) } before :each do request.headers["accept"] = 'application/json' end describe 'GET #show' do context 'authorized' do action do sign_in user ...
# messages sent through the Club-Biz system # ads and announcements are also replicated as messages # as of now can only send club->student class Message < ActiveRecord::Base belongs_to :student, class_name: "Student" belongs_to :club, class_name: "Club" default_scope -> {order('created_at DESC')} end
require 'byebug' class Graph include Enumerable attr_reader :no_of_edges def initialize options={} @no_of_edges = 0 @set_of_vertices = VertexList.new @adjacent_vertices = Hash.new @directed = !!options[:directed] @weighted = !!options[:weighted] @disallow_self_loops = !options[:allow_self...
require 'minitest/autorun' require 'minitest/pride' require './lib/dog' class DogTest < Minitest::Test def test_it_exists fido = Dog.new("Bernese", "Fido", 4) assert_instance_of Dog, fido end def test_it_has_attributes fido = Dog.new("Bernese", "Fido", 4) assert_equal "Bernese", fido.breed ...
class Assistance < ApplicationRecord validates :employee_id, :shop_id, presence: true belongs_to :employee belongs_to :shop end
# frozen_string_literal: true module Queries class BaseQuery < ::GraphQL::Schema::Resolver def resolve(**args) # @type var action_name: ::String action_name = field.name unless context[:current_info][:user].can?(action_name) raise(::GraphQL::ExecutionError.new('権限がありません', extensions: {...
class TurmaAlunosController < ApplicationController def index render json: TurmaAluno.all.includes(:aluno) end def create TurmaAluno.create(turma_aluno_params) render json: 200 end def destroy #@turma_aluno = TurmaAluno.find(params[:id]) TurmaAluno.destroy(params[:id]) render json: 200 end priv...
class UserExpenseShareValue < ActiveRecord::Base belongs_to :user belongs_to :expense monetize :share_value_cents after_save :settle_expense private def settle_expense if expense.present? unless expense.user_expense_share_values.map(&:status).include? 'unresolved' expense.update_column(...
class Alerty class Plugin class Typetalk VERSION = '0.1.0'.freeze end end end
class AddArticleIdToAvatars < ActiveRecord::Migration def change add_column :avatars, :article_id, :integer end end
class CreateResearchInterests < ActiveRecord::Migration def change create_table :research_interests do |t| t.text :research_introduciton t.string :research_topic t.string :research_topic_en t.text :research_details t.text :research_details_en t.text :current_projects t.t...
class CompanySignupMailer < ApplicationMailer default from: "no-reply@recman.com" def signup_company(company, secure_password, url) @company = company @email = @company.email @url = url @secure_password = secure_password mail(to: @email, subject: "Dear #{@company.name}, you have been invited...
class V1::ProductSerializer < ActiveModel::Serializer attributes :id, :name, :description, :price, :in_stock, :slug, :order_count has_many :images, serializer: V1::ImageSerializer def order_count Order.where(product_id: object.id).count end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_request_devise private def twitter_client credentials = session["twitter_credentials"] redirect_to root_url, flash: {alert: "ログインしてください。"} and return unless credentials @twitter_client = T...
Rails.application.routes.draw do namespace :api do namespace :v1 do resources :users, only: [:index, :create] post '/login', to: 'auth#create' get '/profile', to: 'users#profile' resources :projects resources :tasks get '/projecttasks/:id', to: 'tasks#projecttasks' resour...
class Sport < ApplicationRecord has_many :places, dependent: :destroy end
# coding: utf-8 require "minitest/autorun" require "mywn" # Msub = Meronyms - Substance class TestWnMsub < MiniTest::Test def setup @ozone = "ozone" end def test_wn_msub_class assert_kind_of Array, @ozone.wn_msub end def test_word_match ozone_msub = [ "atomic_number_8" ] ozone_ms...
require "rails_helper" describe ApplicationHelper do describe "application_base_url" do it "adds a trailing / onto the request's base url" do expect(helper.application_base_url).to be end end end
class UsersController < ApplicationController def index circle = Circle.find params[:circle_id] @users = circle.users if @users render :json => @users else render json: { status: 500, errors: ['no users found'] } end end def show @user = User.find(params[:id]...
csc <<-EOL #pragma warning disable 414 public partial class ClassWithFields { public string field = "field"; public const string constField = "const"; public readonly string readOnlyField = "readonly"; public static string staticField = "static"; public static readonly string staticReadOnlyField...
class Menu < ApplicationRecord validates :name, presence: true, length: { maximum: 10 }, uniqueness: true validates :content, presence: true, length: { maximum: 20 } def ramdom_choose all_menu = Menu.all all_menu.shuffle.first end end
# frozen_string_literal: true class CreateFiis < ActiveRecord::Migration[5.0] def up return if ActiveRecord::Base.connection.table_exists?(:fiis) create_table :fiis do |table| table.string :name table.string :type table.string :administrator # TODO: Think about creating each asset as...
class MatchesController < InheritedResources::Base protected def begin_of_association_chain params[:team_id] ? Team.find(params[:team_id]) : nil end def collection @matches ||= end_of_association_chain.includes(:match_day).order('LEAST(starting_time, match_days.start_date)') end end
# frozen_string_literal: true require "rails_helper" require "stripe_mock" RSpec.describe SubscriptionsController, type: :request do let(:stripe_helper) { StripeMock.create_test_helper } before do StripeMock.start stripe_helper.create_plan( id: "example-plan-id", name: "World Domination", ...
################################################### # Section to setup necessary env vars and overrides EXPAND = ENV['CUKE_EXPAND'] ? "--expand" : "" COLOR = ENV['FORCE_COLOR'] ? "-c" : "" OTHER_TAGS = ENV['OTHER_TAGS'] ? "--tags "+ENV['OTHER_TAGS'] : "" ####################################################### $SUC...
require 'test_helper' class RomanNumeralTest < ActiveSupport::TestCase def setup @roman_to_dec = RomanNumeral.new("mdxiiii") @dec_to_roman = RomanNumeral.new(1514) end test "correct_convertion_of_numeral" do assert_equal 1514, @roman_to_dec.decimal assert_equal "mdxiiii", @roman_to_dec.numeral ...
class AddPhoneIdToDevice < ActiveRecord::Migration def change add_column :devices, :phoneId, :string end end
require './parse_exception' # <primitive command> ::= go | right | left class PrimitiveCommandNode def parse(context) @name = context.current_token context.skip_token(@name) raise ParseException, "#{@name} is undefined." unless %w[go right left].include?(@name) rescue ParseException => e puts e e...