text
stringlengths
10
2.61M
require 'test_helper' class WelcomeControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers def setup @tester = users(:tester) end test "should get welcome index" do get welcome_index_url assert_response :success assert_select "title", "Fbcapp" end tes...
class Api::V1::NotesController < ApplicationController before_action :set_student, only: [:index, :create] def index @notes = @student.notes render json: @notes, include: [:user] end def create note = @student.notes.new(notes_params) if note.save render json: note end end priva...
#!/usr/bin/env ruby # frozen_string_literal: true require 'find' require 'tempfile' require 'fileutils' require 'pathname' require 'open3' class Installer class << self def call(app_name) return unless rename_app(app_name) install_readme bundle_install generate_cli_binstub self_de...
json.type @folder.class.name json.description 'A SubmissionFolder helps organize Submissions for a Profile.' json.folder { json.name { json.description 'Folder name.' json.type 'String' json.required true json.max_length 80 } json.filter_ids { json.description 'Filters that the Folde...
class Service < ActiveRecord::Base has_many :agent_services has_many :agencies, :through => :agent_services validates_presence_of :name, :description end
Rails.application.routes.draw do get 'about/index', as: 'about' get 'home/index', as: 'home' devise_for :users get 'persons/profile', as: 'profile' root 'home#index' get 'persons/profile', as: 'user' get 'teams/new', to: 'teams#new', as: 'new_team' get 'teams', to: 'teams#index', as: 'teams' post 't...
Trestle.resource(:questions) do menu do item :questions, icon: 'fa fa-question' end table do column :description actions end form do text_field :description select :epic_id, Epic.all, label: 'Epic' render 'answers' end end
# Write a program that: # Asks the user to enter a list of words separated by spaces. # The program should only print the words that are have an even number of characters # p "Enter a list of words separated by spaces:" user_words = gets.chomp.split user_words.each_with_index do |the_word, the_index| if the_w...
class FailuresController < LayoutsController before_action :authenticate_user!, except: [:index, :show] def index @failures = Failure.where(:share => "1") end def show @failure = Failure.find(params[:id]) end def new @failure = Failure.new end def edit @failure = Failure.find(params...
#!/usr/bin/ruby # frozen_string_literal: true require 'singleton' require_relative '../extensions/string_ext' require_relative '../panthage_ver_helper' class ConflictType IGNORE = 0 ACCEPT = IGNORE + 1 ERROR = ACCEPT + 1 end class LibType MAIN = 0 GIT = MAIN + 1 BINARY = GIT + 1 GITHUB = BINARY + 1 end...
# ------------------------------------------------------------------------------ # Flight Plan unicorn config # ------------------------------------------------------------------------------ require File.dirname(__FILE__)+'/application' user = "deployer" app_name = "flight_plan" home = "/home/#{user}/apps/#{ap...
module CrosswordGenerator class Wordlist < Array def initialize(file = '/usr/share/dict/words') super() self.replace File.read(file).upcase.split("\n").grep(/^[A-Z]*$/) end end class Filter attr_accessor :wordlist, :words def initialize @constraints = {} @length = {} @words = {} end de...
class BrowseController < ApplicationController layout 'site' before_filter :authorize_web before_filter :set_locale before_filter { |c| c.check_database_readable(true) } around_filter :timeout, :except => [:start] def start end def relation @type = "relation" @relation = Relation.find(p...
FactoryBot.define do factory :item do name { Faker::Device.model_name } cost { Faker::Commerce.price(range: 500..2000.0) } purchased_at { Time.zone.yesterday.end_of_day } status_label company default_location { association :location, company: company } model { association :model, company:...
class AddFkOrganizationIdToKits < ActiveRecord::Migration[6.0] def change add_foreign_key :kits, :organizations end end
# == Schema Information # # Table name: people # # id :integer not null, primary key # first_name :string(255) # last_name :string(255) # email :string(255) default(""), not null # group_id :integer # created_at ...
#-- # Copyright (c) 2009-2010, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/orders' => 'orders#search' get '/orders/:id' => 'orders#searchByOrder' post '/orders' => 'orders#create' end
module Rack module OAuth2 class Client class Grant class SocialLogin < Grant attr_required :email, :provider, :uid, :social_access_token end end end end end
class AddAddressToBookingRequest < ActiveRecord::Migration[6.0] def change add_column :booking_requests, :address, :string add_column :booking_requests, :new_customer_name, :string end end
def add(a,b) puts "ADDING #{a} + #{b}" return a + b end def subtract(a,b) puts "SUBTRACTING #{a} - #{b}" return a - b end def multiply(a,b) puts "MULTIPLYING #{a} * #{b}" return a * b end def divide(a,b) puts "DIVIDING #{a} / #{b}" return a/b end puts "let's do some math with just func...
class StatusTracker attr_reader :previous_data, :request, :report def initialize(options={}) @previous_data = options[:previous_data] || {} @request = options[:request] || StatusRequest.new @report = options[:report] || Report.new end def call request_data.each do |url, status| previous_...
class AddDefaultLocaleToApplication < ActiveRecord::Migration def change add_column :tr8n_applications, :default_language_id, :integer end end
class Api::V1::RandomTransactionController < ApplicationController respond_to :json def show respond_with Transaction.unscoped.order("RANDOM()").first end end
require 'rails_helper' RSpec.describe "/account_requests", type: :request do describe "GET #new" do it "renders a successful response" do get new_account_request_url expect(response).to be_successful end end describe 'GET #confirm' do context 'when given a valid token' do let!(:acc...
class FeedFinder def initialize(url) @url = url @cache = {} end def options @options ||= begin options = [] options.concat(existing_feed) if options.empty? options.concat(page_links) if options.empty? options.concat(xml) if options.empty? options.concat(youtube) if opti...
# frozen_string_literal: true module Topdown class Service class << self def create(&block) new(&block) end def expect(*args) new.expect(*args) end def call(context = {}, &block) new.call(context, &block) end end attr_reader :context def...
class HomeController < ApplicationController def index @page = params.fetch(:page, 0).to_i @planets = Planet.offset(@page * PLANETS_PER_PAGE).limit(PLANETS_PER_PAGE) end end
require 'spec_helper' RSpec.describe MarkdownMetrics::Elements::Block::Pre do let(:line) { '```ruby' } let(:next_line) { 'class Some' } let(:element) { described_class.new(lines: [line, next_line], start_at: 0) } describe '.match_element' do it { expect(described_class.match_element(line, next_line)).not_...
module ActiveCache module Store class DalliStore < AbstractStore def self.dc @@dc ||= Dalli::Client.new end def self.read(key) page = dc.get(key) case when page.nil? nil when page[:expires].nil? page[:content] els...
class UserMailer < ApplicationMailer def welcome_email(user) @user = user @url = 'localhost:3000' mail(to: user.username, subject: 'Welocome to my cats homework!') end end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'seo_noindex/version' Gem::Specification.new do |gem| gem.name = "seo_noindex" gem.version = SeoNoindex::VERSION gem.authors = ["Vsevolod Avramov"] gem.email = ["gsevka@gmail....
require "rails_helper" RSpec.describe ApplicationHelper, type: :helper do describe "#page_title" do context "as admin" do before do assign(:title, "title") controller.stub(:controller_path).and_return("admin/articles") end subject { helper.page_title } it { is_expected.t...
class Movie < ActiveRecord::Base validates_presence_of :title validates_numericality_of :price, greater_than_or_equal_to: 0 validates :description, length: { maximum: 200 } belongs_to :genre has_many :streams #before_save :set_true_to_new_movie def get_movie_price(movie_id) if movie_id.presen...
module Admin class Market::PropertiesController < BaseController handle_return_path PER_PAGE = 20 def index if params[:term].present? # autocomplete render json: ::Market::Property.where('name ILIKE ?', "#{params[:term]}%").order(:name).map { |property| {id: property.id, label: p...
=begin Write a program that takes a number from the user between 0 and 100 and reports back whether the number is between 0 and 50, 51 and 100, or above 100. evaluate(-1) -> print out 'You can't enter a negative number!' evaluate(25) -> print out '25 is between 0 and 50' evaluate(75) -> print out '75 is between 5...
class CreateProfiles < ActiveRecord::Migration def change create_table :profiles do |t| t.integer :id t.string :fname,:null => false t.string :mname t.string :lname,:null => false t.integer :age,:null => false t.string :father_name,:null => false t.date :dob,:null => fals...
--- source: - meta authors: - name: trans email: transfire@gmail.com copyrights: [] requirements: - name: detroit groups: - build development: true dependencies: [] alternatives: [] conflicts: [] repositories: - uri: git://github.com/rubyworks/shomen-model.git scm: git name: upstream resources: - uri: http:...
require "rspec/core" require "logger" RSpec.configure do |c| c.add_setting :config_path, :default => "config/" c.add_setting :template_path, :default => "template/" c.add_setting :default_template_engine, :default => ".erb" c.add_setting :use_synonym, :default => true c.add_setting :logger, :default => Logge...
RSpec.describe User, :type => :model do context "with valid info" do #subject { User.create(name: "test123", password: "abcd") } subject { build(:user) } it {should be_valid} it {should respond_to(:name) } it {should respond_to(:email) } end context "with invlalid info " do ...
require 'rails_helper' describe EventsController, type: :controller do describe 'GET search' do it 'has status code 302 and redirecto to / when request is not ajax' do get :search expect(response.code.to_i).to eq(302) expect(response).to redirect_to '/' end it 'render sucessful when the...
require 'active_support' require 'active_support/core_ext' class App < Sinatra::Base register Sinatra::Namespace # Begin devices namespace namespace '/devices' do # Register device post '/register' do begin should_be_authenticated device_token = body_params["device_token"] ...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "spliner" Gem::Specification.new do |s| s.name = "spliner" s.version = Spliner::VERSION s.authors = ["Tallak Tveide"] s.email = ["tallak@tveide.net"] s.homepage = "http://www.github.com/tallakt/spliner" s.summary = %q{Cubic spli...
class RatingsController < ApplicationController before_action :expire_cache, only: [:create, :update, :destroy] before_action :skip_if_cached, only: [:index] def index @top_beers = Rails.cache.fetch('top_beers', expires_in: 10.minutes) { Beer.top(3) } @top_breweries = Rails.cache.fetch('top_breweries', e...
class Renderer attr_accessor :text def self.get_renderer(name) return TextRenderer.new if name.to_s == 'text' return TextileRenderer.new if name.to_s == 'textile' end def render(test) text = render_header(test.name, 1) test.features.each do |f| text += render_feature(f) end text ...
VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "CentOS-6.5-x86_64-minimal" config.omnibus.chef_version = :latest config.vm.provision :chef_solo do |chef| chef.log_level = :debug chef.cookbooks_path = ["./berks-cookbooks", "./site-cookbooks" ] ch...
# encoding: utf-8 class PageController < ApplicationController def index if params[:date] ## note: allow 2015/01/01 and 2015.01.01 @date = Date.strptime( params[:date].gsub(/[\/.]/, '-'), '%Y-%m-%d' ) elsif params[ :day ] ## assume current year (plus add x days from Jan/1) @date = D...
require_relative '../helpers/is_square' class OEIS def self.a071068(n) (1..n/2).count { |i| i.is_squarefree? && (n - i).is_squarefree? } end end
module XcodeMove class File attr_reader :path def initialize(path) path = Pathname.new path @path = path.realdirpath end def project @project ||= project_load end def pbx_file @pbx_file ||= pbx_load end def header? path.extname == '.h' end ...
class Topic < ApplicationRecord has_many :blogs validates_presence_of :title validates_uniqueness_of :title, case_sensitive: false extend FriendlyId friendly_id :title, use: :slugged class << self # Get all the topics which have published posts def with_published_posts includes(:blogs).where...
# comments, helpful when reading code later # the Octothorpe tells Ruby it can ignore the rest of the line. puts "You could have code like this" # and the comment after is ignored # Comments are useful for temporarily disabling some code: # puts "this won't run" puts "This will run"
module Mobbex module Gateway class Subscriber MOBBEX_SUBSCRIBER_URL_PART = 'subscriber' def initialize(subscription_url_part, id = nil) @subscriber_url_part = subscription_url_part + '/' + MOBBEX_SUBSCRIBER_URL_PART @subscriber_url_part += "/...
module TestHelper def login(user_type) if user_type.is_a? Symbol user = FactoryGirl.create(user_type) else user = user_type end sign_in :user, user @user ||= user end end
#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy...
# Continuing with our Person class definition, what does the below print out? class Person attr_accessor :first_name, :last_name def initialize(name) parse_full_name(name) end def name "#{self.first_name} #{self.last_name}".strip end def name=(name) parse_full_name(name) end def to_s ...
class BatchesController < ApplicationController def create batch = Batch.new(purchase_channel: params['purchase_channel']) if batch.save render json: { batch: { reference: batch.reference, orders: batch.orders.count } }, status: :created else render json: { errors: b...
class CreateWardrobeOutfits < ActiveRecord::Migration[6.0] def change create_table :wardrobe_outfits do |t| t.integer :wardrobe_id t.integer :outfit_id t.timestamps end end end
class ResourceTransportationBooking < ActiveRecord::Base #Upload mount_uploader :attachment, TransportAvatarUploader #Associations #belongs_to :resource belongs_to :vehicle belongs_to :sub_category belongs_to :agency_store after_update :mail_to_user_regarding_transport_status_updates #Validation...
#require "colorize" #coding: UTF-8 class Maze attr_accessor :n, :m, :maze def initialize(n, m) @n = n @m = m @maze = [] end def load(maze) if maze.length != @m * @n puts "Please input a valid length string." return false end maze.each_char do |i| if i != "0" && i != "...
class Member include Mongoid::Document include ActiveModel::Serializers::JSON # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable field :fullname ...
# frozen_string_literal: true module BPS module PDF class Roster class Detailed module Awards def awards load_award_images awards_first_page awards_second_page awards_third_page end private def awards_first_page...
class CharactersController < ApplicationController def new @house = House.find(params[:house_id]) @character = Character.new end def show @character = Character.find(params[:id]) @house = @character.house end def edit @character = Character.find(params[:id]) @house = @character.hou...
component 'rubygem-rubyzip' do |pkg, settings, platform| pkg.version '2.3.0' pkg.md5sum '3a836c8f901f875882dde4e58178bbf8' instance_eval File.read('configs/components/_base-rubygem.rb') end
cask :v1 => 'aseprite' do version '0.9.5' sha256 '299eda3e5f11ae60d58bccdd26156169db6ebc01be8e806d7909f0b8f22e2928' url "https://aseprite.googlecode.com/files/ASEPRITE_#{version}.dmg" name 'Aseprite' homepage 'http://www.aseprite.org' license :oss app 'aseprite.app' end
class CreateUsuarios < ActiveRecord::Migration[5.2] def change create_table :usuarios do |t| t.string :nome, null: false t.string :username, null: false t.string :email, null: false t.string :password_digest, null: false t.string :token t.timestamps end end end
RSpec.describe Player::Player do context "Creating Player" do it "When attributes are specified" do label = "X" player = Player::Player.new(label) expect(label).to eq(player.label) end end end
class ContactMailer < ApplicationMailer def contact_email(contact) @contact = contact # Destinatário definido em config/{environment}.rb mail(to: @contact.subject.email_redirection , subject: 'Contato - 033Rooftop Santander', reply_to: @contact.email, from: "033Rooftop Santander<teatrosantander033ro...
class API::V2::APIController < ApplicationController skip_before_action :verify_authenticity_token # When an error occurs, respond with the proper private method below rescue_from AuthenticationTimeoutError, with: :authentication_timeout rescue_from NotAuthenticatedError, with: :user_not_authenticated prote...
#Basic Game Time + Night/Day v1.6.2b #----------# #Features: Provides a series of functions to set and recall current game time # as well customizable tints based on current game time to give the # appearance of night and day. # #Usage: Script calls: # GameTime::minute? - returns the cur...
# frozen_string_literal: true require 'rails_helper' RSpec.describe OrganizationForm do it 'is valid with name, user_name and user_email' do form = OrganizationForm.new( name: 'Ruby Conf', user_name: 'Philip Lambok', user_email: 'philiplambok@gmail.com' ) form.valid? expect(form.er...
class ProfilesController < ApplicationController before_action :authenticate_user! before_action :restrict_profile_access, only: [:edit, :update] before_action :check_if_user_has_profile!, except: [:new, :create] before_action :load_countries, only: [:new, :edit] before_action :load_interests, only: [:new, :e...
class Api::V1::SessionsController < Api::V1::BaseController def create @user = User.find_by(email: user_params[:email]) if @user && @user.authenticate(user_params[:password]) @envelop = Hash.new @envelop[:meta] = { :code => 200 } @envelop[:data] = @user @user.gravatar_url = gravatar_u...
require 'rails_helper' require 'rubygems' require 'action_view' include ActionView::Helpers::DateHelper RSpec.describe "messages" do describe "GET #index" do it "get message list" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials(...
class ApplicationController < ActionController::Base include ApplicationHelper # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :check_authenticated_user, except: [:error_handler, :notfound_handler] b...
class AddPackageIdToProduct < ActiveRecord::Migration def self.up add_column :products, :package_id, :integer add_index :products, :package_id end def self.down remove_column :products, :package_id end end
class CreateReportsTable < ActiveRecord::Migration def up create_table(:reports) do |t| t.integer :question_id t.text :reason t.timestamps end end def down end end
class AddTechnicianFkColToAppointment < ActiveRecord::Migration[6.1] def change add_reference :appointments, :technician, foreign_key: true end end
class Refunge::Instructions::Put < Refunge::Instructions::Base def execute(stack, cursor, output, code) v, x, y = stack.pop(3) code.insert(x, y, v) end end
require_relative '../db/sql_runner.rb' class User attr_reader :name, :id attr_accessor :balance def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] @balance = options['balance'] end def save() sql = "INSERT INTO users (name, balance) VALUES ('#{@name}...
class PostComment < ApplicationRecord belongs_to :post belongs_to :user has_many :notifications, dependent: :destroy validates :comment,presence: true end
class Insuline < ActiveRecord::Base belongs_to :user validates :valeur, presence: true, length: {maximum: 4}, inclusion: {in: 0..80} TYPE = ['Novorapid', 'Levemir','Novolog','Humulin R','Lantus'] def set_user!(user) self.user_id = user.id self.save! end end
class RemovetccfFromInfos < ActiveRecord::Migration[6.0] def change remove_column :infos,:ttccf,:integer end end
require "openssl" require "uri" module LibPixel class Client attr_accessor :host, :secret, :https def initialize(options={}) options.each do |key, value| send("#{key}=", value) end end def sign(uri) uri = URI.parse(uri) unless uri.kind_of?(URI::Generic) query = uri....
require 'rails_helper' RSpec.describe ApiKey, type: :model do describe 'validations' do it { should validate_uniqueness_of(:access_token) } end end
class MetaPairsMigration < ActiveRecord::Migration def self.up create_table :meta_pairs do |t| t.string :key t.string :value t.integer :object_id, :null => false t.string :object_type, :null => false, :limit => 20 t.integer :owner_id, :int t.string :owner_type, :limit => 20 ...
class RemoveFieldsFromSearches < ActiveRecord::Migration def change remove_column :searches, :address_1, :string remove_column :searches, :address_2, :string remove_column :searches, :lat1, :float remove_column :searches, :lat2, :float remove_column :searches, :lng2, :float remove_column :sear...
# Write a method that takes a number N and then # draw a triangle that has N number of letter O on each of its sides. # For example given the number 5 your will get something like: # O # O O # O O O # O O O O # O O O O O def make_triangle(n) n + 1 n.times {|x| puts "#{' ' * (4-x)} #{"O " * x}"} end prin...
# This migration comes from spree_analytics_trackers (originally 20200721163729) class AddStoreIdToSpreeTrackers < ActiveRecord::Migration[6.0] def change add_column :spree_trackers, :store_id, :integer add_index :spree_trackers, :store_id Spree::Tracker.reset_column_information default_store = Spre...
# Your program should: # - Ask for the user's first, middle, and last names (one by one!) # - Greet the user using their full name ### Your Code Here ### puts "Hello, what is your first name?" firstname = gets.chomp puts "What\'s your middle name?" middlename = gets.chomp puts "What\'s your last name?" lastname = g...
#!/usr/bin/env ruby # :title: PlanR::Plugin::Specification::Transform =begin rdoc Specifications for Document Transform plugins (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end require 'tg/plugin' require 'plan-r/document' module PlanR module Plugins module Spec # ------------------------...
class Country < ActiveRecord::Base validates :country_code, :presence => true, :uniqueness => true validates :name, :presence => true has_many :ports def to_param country_code end end
require 'rails_helper' RSpec.describe Company, type: :model do subject(:company) { FactoryBot.create(:company) } describe "Validations" do it "is valid with valid attributes" do expect(company).to be_valid end it { should validate_presence_of(:name) } it { should validate_length_of(:name)....
require 'rails_helper' RSpec.describe "Boats", type: :request do describe "GET api/boats" do it "get the list of all boats" do 10.times { Fabricate(:boat) } get api_boats_path expect(json).not_to be_empty expect(json.size).to eq(10) expect(response).to have_http_status(200) end...
# -*- coding: utf-8 -*- class StudentsController < ApplicationController before_filter :login_required before_filter :pre_load def pre_load end def index if current_user.is_student? _index_student elsif current_user.is_teacher? _index_teacher end end private def _index_student...
require 'pathname' require 'yaml' module CgScout class CLI def self.run(options) Checks.run_all config = Config.new env = options[:e] if env envs = config.get_environments raise EnvironmentNotFound.new(env, envs) unless envs.include? env ...
require 'test_helper' class TripsEditTest < ActionDispatch::IntegrationTest def setup @trip = trips(:tester) end test "unsuccessful edit" do get edit_trip_path(@trip) assert_template 'trips/edit' patch trip_path(@trip), params: { trip: { name: "", s...
# # Cookbook Name:: haproxy # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # package 'haproxy' do action :upgrade end template '/etc/haproxy/haproxy.cfg' do source 'haproxy.cfg.erb' mode '0644' notifies :restart, 'service[haproxy]' end service 'haproxy...
require 'rails_helper' RSpec.feature "LandingPages", type: :feature do context 'Going to a website' do Steps 'You are welcomed' do Given 'I am on the landing page' do visit '/' end Then 'I can see a welcome message' do expect(page).to have_content 'Welcome' end end e...
require_relative '../lib/vote' require_relative '../lib/poll' require 'date' RSpec.describe Poll do it 'has a title and candidates' do poll = Poll.new('Awesome Poll', ['Alice', 'Bob'], DateTime.new(2020, 2, 18, 14, 57, 00, 0.125)) expect(poll.title).to eq 'Awesome Poll' expect(poll.candidates).to eq ['A...
class Api::V1::PropertiesController < Api::V1::BaseController include Swagger::Blocks #before_action :subscription_filter, except: [:index, :show] before_action :set_property, only: [:show, :update, :destroy] swagger_path '/properties' do operation :post do key :summary, 'Create new object' par...