text
stringlengths
10
2.61M
class OtherPostsController < PostsBaseController rescue_from Infrastructure::PostException, :with => :redirect_to_not_founded def show location = params[:location] friendly_title = params[:id] @post = Post.find(:location => location, :friendly_title => friendly_title) @post_url = other_post_url(@po...
class Offer < ActiveRecord::Base self.table_name = 'OFFERS' #self.primary_key = 'PRODUCT_ID' self.sequence_name = 'OFFER_ID_SEQ' belongs_to :store belongs_to :auction before_create :set_date_offer validates :store_id, :uniqueness => { :scope => :auction_id, :message=> "Your shop had already offered in...
class ChangeSemNumberFromTimetables < ActiveRecord::Migration def change rename_column :timetables, :sem_number, :current_timetable change_column :timetables, :current_timetable, :string end end
require 'pp' class Tictac attr_accessor :moves attr_reader :player1, :player2, :board def initialize @player1 = "O" @player2 = "X" @board = [1, 2, 3, 4, 5, 6, 7, 8, 9] # @display_board = [ [1, 2, 3],[4, 5, 6],[7, 8, 9] ] @moves = 0 @player = @player1 @player1_moves = [] @player2_...
class CompanionSerializer < ActiveModel::Serializer attributes :id, :name, :bio, :image, :link has_one :doctor end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root "countries#index" get "/countries", to: "countries#show" resources :countries, only: [:edit, :update, :destroy] resources :cities, only: [:show] resources :activities, o...
class AddClientToProjects < ActiveRecord::Migration[6.0] def change add_column :projects, :client_id, :bigint, null: false add_foreign_key :projects, :clients add_index :projects, :client_id end end
#INPUT: list of names #OUTPUT: hash of names and accountability group assignment number #pseudocode steps =begin 1. turn list of strings into array 2. count how many names in array 3. randomize array and split the array into groups of 4 with each_slice method 4. check how many are in the last group, if it's less than 3...
# == Schema Information # # Table name: divisions # # id :bigint not null, primary key # name :string # location :string # description :string # created_at :datetime not null # updated_at :datetime not null # ancestry :string # department_id :bigin...
# # Copyright 2015 Brandon Raabe. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
require 'spec_helper' describe 'snmp::service', :type => :class do shared_context 'Darwin' do it { should contain_service('snmpd').with({ :ensure => 'running', :enable => true, :name => 'org.macports.net-snmp', }) } it { should contain_service('org.net-snmp.snmpd').with({ :en...
class APIDeck < Syro::Deck HTTPCodes = { NOT_FOUND: 404, UNAUTHORIZED: 401, BAD_REQUEST: 400, UNPROCESSABLE: 422 } def response_with(data, status: :OK) response_data = { status: status, data: data } json response_data end end
# encoding: UTF-8 module ActiveNutrition VERSION = "0.5.1" USDA_VERSION = "24" end
class DeleteCapacityFromHall < ActiveRecord::Migration def change remove_column :halls, :capacity end end
# frozen_string_literal: true require 'rails_helper' describe UsersController, type: :controller do # let(:user) {User.create!(email: 'user@testmail.com', password: 'testers')} # let(:user2) {User.create!(email: 'user2@testmail.com', password: 'testers2')} before do @user1 = FactoryBot.create(:user) @...
module RequireJs class Builder def initialize(file, config) @config = config @file = file end def build ''.tap do |output| output << "<script>require = #{config}</script>" unless config.empty? output << "<script data-main=\"#{file}\" src=\"require.js\"></script>" e...
# frozen_string_literal: true RSpec.describe AttendancesController, type: :controller do context 'unauthenticated' do describe 'GET #new' do before { get :new, params: { event_id: 'foo' } } it { expect(response).to redirect_to new_user_session_path } end describe 'POST #create' do bef...
module MathGame # Player class have attributes that tell the player's number, player's lives. # Each player can answer questions class Player attr_reader :lives, :name def initialize(number) @name = number + 1 @lives = 3 end def lose_lives @lives -= 1 @lives = 0 if @lives ...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :picture do caption "MyText" user_id 1 experiment_id 1 tool_id 1 end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable # config.token_authentication...
# # Cookbook Name:: rails_app_server # Recipe:: default # # Copyright (c) 2016 The Authors, All Rights Reserved. include_recipe 'build-essential' include_recipe 'postgresql::client' app = search(:aws_opsworks_app).first rds_db_instance = search(:aws_opsworks_rds_db_instance).first app_path = "/srv/#{app['shortname']}"...
class UserSerializer < ActiveModel::Serializer attributes :id, :name, :password has_many :post has_many :topic end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
class MessagesController < ApplicationController before_action :authenticate_user! before_action :get_messages def index @id = current_user.id end def create message = current_user.messages.build(message_params) message.location_id = @location.id message.errors # if message.save # ...
module ApplicationHelper # returns full_page_title def full_title(page_title) base_title = "Chat App" return base_title if page_title.empty? "#{page_title} | #{base_title}" end end
require "metacrunch/hash" require "metacrunch/transformator/transformation/step" require_relative "../aleph_mab_normalization" class Metacrunch::ULBD::Transformations::AlephMabNormalization::AddVolumeCountSort2 < Metacrunch::Transformator::Transformation::Step def call target ? Metacrunch::Hash.add(target, "volu...
# # This class handles the scraping of hacker news # class Scraper # # XPATH to select the article table rows # ROW_XPATH = "//tr[td/@class='title'][not(td/a/@rel='nofollow')]" # # XPATH to select the url for an article row # LINK_XPATH = "td[@class=title]/a" # # XPATH to select a reference number...
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'thor/options' describe Thor::Options do def create(opts) opts.each do |key, value| opts[key] = Thor::Option.parse(key, value) unless value.is_a?(Thor::Option) end @opt = Thor::Options.new(opts) end def parse(*args) ...
class Client::BookingController < Client::BaseController def index @parkings = Parking.where(active: true).pluck(:id, :address) @vehicles = current_user.vehicles.pluck(:number_plate) end def create @parking_slot = ParkingSlot.find_by id: params[:slot_id] @client_book = ParkingSlot.find_by client...
class Movie < ActiveRecord::Base mount_uploader :image, ImageUploader has_many :reviews, inverse_of: :movie validates_presence_of :title validates_presence_of :year validates_presence_of :description validates_presence_of :director validates_presence_of :cast validates_numericality_of :year va...
class RenameTypeTicket < ActiveRecord::Migration def change rename_column :tickets, :type, :ticket_type_id end end
# lecture 76 - the until keyword # "until" is basically the opposite of "while" # It says "do this UNTIL this condition is true." i = 1 # while syntax for counting from 1 to 10 # while i <= 10 # puts i # i += 1 # end until i > 10 puts i i += 1 end # See also: CHALLENGE_fizzbuzz.rb
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "globase/version" Gem::Specification.new do |s| s.name = "globase" s.version = Globase::VERSION s.authors = ["Robin Wunderlin"] s.email = "robin@wunderlin.dk" s.homepage = "http://www.rhg.dk" s.summary = "Interface to the...
class Api::ProjectsController < ApiController before_action :authenticate_api_user!, only: [:show] def index projects = Project.paginate page: params[:page], per_page: params[:per_page] render json: { projects: projects.as_json(only: [:id, :project_name, :user, :creators, :technologies, :...
class String def slug downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') end end
require 'celluloid/autostart' class Counter attr_reader :counter def initialize @counter = 0 end # Not threadsafe! def increment @counter += 1 end end c = Counter.new 10.times.map { Thread.new { 1000.times { c.increment }} }.map(&:join) puts c.counter class CounterWithMutex attr_reader :co...
class CreateUsers < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.string :first_name t.string :last_name t.string :mobile t.text :address t.string :city t.string :state t.string :country t.string :postal_code t.string :passport_number ...
class Doccex::PageElements::Header < String def initialize(context, xml_string) # unlike other page elements, headers are contained in a separate file rels = context.instance_variable_get(:@rels) locals = { :rid => rels.next_id(:header) } File.open(Rails.application.root.join("#{rels.path_to_tmp}/docx/wor...
FactoryBot.define do factory :lesson do association :teacher home_task { Faker::Lorem.sentence(word_count: 3) } description { Faker::Lorem.sentence(word_count: 5) } date_at { rand(Date.current.beginning_of_week..Date.current.end_of_week) } number { rand(1..9)} association :grade associatio...
#!/Users/philippeperret/.rbenv/versions/2.6.3/bin/ruby # encoding: UTF-8 ######################!/usr/bin/env ruby def log message File.open('./log.txt','a'){|f| f.write "#{message}\n"} end log("--- [#{Time.now}] Entrée dans ajax.rb") begin require_relative 'ajax/required' require_relative 'config' Ajax.treate_...
# Code copied from AccountsController class Vault::Accounts::ManagerController < ApplicationController include ModelControllerMethods require_role "Member", :except => [:billing, :plans, :canceled, :thanks] permit "admin for :account", :only => [:edit, :change_password, :update, :plan, :plans, :cancel, :dashbo...
class AddUuidToWorkorder < ActiveRecord::Migration def change add_column :workorders, :uuid, :string add_index :workorders, :uuid end end
module InstanceCounter module ClassMethods def vagon_count_all_from_module #@@vagon_count_all self.vagon_count_all end end module MyInsMethods def register_instance_from_module #@@vagon_count_all += 1 self.vagon_count_all += 1 end end end class Vagon @@vagon_co...
require File.dirname(__FILE__) + '/../spec_helper' describe "The -r command line option" do it "requires the specified file" do ["-r fixtures/test_file", "-rfixtures/test_file"].each do |o| ruby_exe("fixtures/require.rb", :options => o, :dir => File.dirname(__FILE__)).should include("fixtures/test_fil...
require 'spec_helper' describe Deck do describe '#initialize' do it "creates a deck with a type and a card collection" do my_deck = Deck.new() expect(my_deck.type).to eq 'none' expect(my_deck.cards).to eq [] end it "when passed the type 'regular', has four cards of every rank, thirteen...
class AddUniqueIndexToStats < ActiveRecord::Migration[5.2] def change add_index :stats, %i[date key value], unique: true end end
class ChangeColumnOnSurveyNotification < ActiveRecord::Migration def change rename_column :survey_notifications, :courses_user_id, :courses_users_id end end
class CommentMailer < ActionMailer::Base default from: Proc.new { MySettings.from_email } def comment_notification(email, comment) @post = comment.commentable @comment = comment mail(:to => email, :subject => "#{MySettings.site_name} - New Comment: #{@post.title}") end end
FactoryBot.define do factory :daily_mark do mark date { Date.current } value 30 end end
module Admin class ImageGalleryGroupsController < ApplicationController def index @image_gallery_groups = ImageGalleryGroup.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @image_gallery_groups } end end # GET /image_gallery_groups/1 # GET /image...
# frozen_string_literal: true require 'spec_helper' require 'support/player' RSpec.describe Player do describe 'When damage is taken' do let(:actual) { [] } example 'it should notify the `damage_taken` observers in the order subscribed' do subject.damage_taken { |amount| actual << amount } subj...
class AdjustHealthRatings < ActiveRecord::Migration[5.2] def change remove_column :health_ratings, :rating, :string remove_column :health_ratings, :value, :string remove_column :health_ratings, :weight, :float remove_column :health_ratings, :locked, :boolean remove_index :health_ratings, :target_i...
class CandidateProfileController < ApplicationController def create p params @profile = CandidateProfile.new(candidate_params) if @profile.save CandidateMailer.report_new_candidate_email(@profile).deliver_now render :post_submit else flash[:notice] = "Nu toate campurile obligatorii s...
FactoryBot.define do factory :owner do email "a@b.com" password "123456789" document "123.456.789-12" end end
# frozen_string_literal: true require 'json' require 'sourcescrub/version' require 'sourcescrub/account' require 'sourcescrub/client' require 'sourcescrub/models' require 'sourcescrub/utils/veriables' # Sourcescrub module Sourcescrub TOKEN_URL = 'https://identity.sourcescrub.com' TOKEN_URI = '/connect/token' ...
require 'spec_helper' describe Post do context 'tags' do it 'converts array of tags into string seperated by spaces' do post = FactoryGirl.build_stubbed(:post, :tags => %w(ruby rails)) post.tag_list.should == 'ruby rails' end it 'converts string of tags into array' do post = FactoryGi...
class WorkExperienceComment < ApplicationRecord validates :body, presence: true, length: { in: 1..100 } belongs_to :user belongs_to :work_experience scope :created_at_paging, -> { order(created_at: :desc) } end
require 'stemmer' require 'sqlite3' db = SQLite3::Database.new('lyrics.db') db.results_as_hash = true db.execute("select genre from links group by genre") do |genre_row| words = Hash.new db.execute("SELECT links.genre, lyrics.author, lyrics.song, lyrics.lyrics FROM lyrics INNER JOIN links ON lyrics.link=link...
class AddMarkersToPages < ActiveRecord::Migration def self.up unless column_exists? :pages, :markers_json add_column :pages, :markers_json, :text end end def self.down if column_exists? :pages, :markers_json remove_column :pages, :markers_json end end end
class GamesController < ApplicationController # GET /games # GET /games.json def index @games = Game.all respond_to do |format| format.html # index.html.erb format.json { render json: @games } end end # GET /games/1 # GET /games/1.json def show @game = Game.fin...
class ContactsController < ApplicationController include SimpleCaptcha::ViewHelper def new @contact = Contact.new expires_in 2.days, :public => true, :'s-maxage' => '2592000' if stale?(:etag, :last_modified => Cms::Site.first.updated_at) if request.fullpath == "/contact-us" render :cms_page => '/c...
module Bouncer module Failures class RenderJSON def self.call(env) new(env).call end attr_reader :req, :res def initialize(env) @req = Rack::Request.new(env) @res = Rack::Response.new end def call res.content_type = "application/json" ...
FactoryGirl.define do factory :recipe do name "Bolo de Cenoura" kitchen_type_id '1' food_type_id '1' amount_people 8 preparation_time "60 minutos" preparation_level "Fácil" ingredients "Ovo, Leite, Farinha, Fermento, Cenoura, Chocolate" steps "Bata alguns ingredientes, depois junte com...
class Change < ActiveRecord::Migration[5.0] def change rename_column :song_votes, :type, :vote_type end end
class BuildConferenceEvent MAP = { "participant-join" => ConferenceEvents::ParticipantJoin, "participant-leave" => ConferenceEvents::ParticipantLeave, "conference-start" => ConferenceEvents::ConferenceStart, "conference-end" => ConferenceEvents::ConferenceEnd, }.freeze def self.from(params) M...
require 'ansi' require 'mini_magick' module IntegrationSpec module Screenshots extend RSpec::Matchers::DSL SIZE = 18 WRAP = true PATH = "spec/integration/screenshots" def tracked_screenshots @@tracked_screenshots ||= begin Hash[`git ls-files -s spec/featu...
class CustomersController < ApplicationController def new @customer = Customer.new @customer.build_member end def create @customer = Customer.new(customer_params) @customer.member_id = current_member.id if @customer.save redirect_to member_path(current_member) else render :...
class Cocktail < ApplicationRecord has_one_attached :photo has_many :doses, dependent: :destroy has_many :ingredients, through: :doses validates :name, presence: true, uniqueness: { case_sensitive: false } validates :pic_url, allow_blank: true, format: { with: URI::regexp, ...
module UsersHelper def card_border user return current_user == user ? "you-admin-border" : user.admin? ? 'user-admin-border' : 'user-normal-border' end def role_description(role) case role when "user" return "Has access full access except for billing, user-management." when "admi...
class AddEnabledToAccounts < ActiveRecord::Migration def change add_column :accounts, :enabled, :boolean, default: true end end
# Plugin's routes # See: http://guides.rubyonrails.org/routing.html Rails.application.routes.draw do resources :projects do resources :evm_roadmaps, :only => :index end end
require 'rails_helper' require 'open-uri' RSpec.describe Story, type: :model do let(:blank_story_wo_image) {Story.create(title: "", body: "")} let(:no_image_story) {Story.new(title: "", body: "")} let(:image_story) {Story.new(title: "Covid-19 Cancels NBA Season", body: "On March 25, the NBA Season was cancele...
# frozen_string_literal: true class Instructor < ApplicationRecord has_and_belongs_to_many :positions validates_presence_of :last_name, :first_name, :utorid validates_uniqueness_of :utorid # Returns all the positions this instructor is assigned to in a given session def positions_by_session(sessi...
require 'flex_trans/struct' module FlexTrans class Mapper class << self def mapping_attributes(*mapping_attributes) new(mapping_attributes: mapping_attributes) end def mapping_type(mapping_type) new(mapping_type: mapping_type) end end def initialize(mapping_attri...
# 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...
# array = (1..100).to_a array = [*1..100] p array array.each { |n| p n }
class GithubApiService def get_data client_id = "cdea9fa68ec51d9864b1" client_secret = "8fe7c7831ed8b379954300855900446b92d1bed4" code = code_params[:code] response = Faraday.post("https://github.com/login/oauth/access_token?client_id=#{client_id}&client_secret=#{client_secret}&code=...
class Address < ActiveRecord::Base self.table_name = "address" has_one :person belongs_to :city def to_builder Jbuilder.new do |address| address.street street address.number number address.floor floor address.flat flat address.city city.to_builder end end end
module ReportsKit module Reports class PropertiesToFilter attr_accessor :properties, :context_record def initialize(properties, context_record: nil) self.properties = properties self.context_record = context_record end def perform(filter_key) filter_key = filter_k...
require 'json' describe "api" do GATEWAY_BASE_URL = "http://sut:8080/api" context "/_" do context "get" do result = Client.get "#{GATEWAY_BASE_URL}/_" it "return 200" do expect(result.code).to eq(200) end it "return OK" do expect(result.body).to eq("OK") end en...
class CreateRepositories < ActiveRecord::Migration def change create_table :repositories do |t| t.references :user, index: true, foreign_key: true t.string :name t.string :full_name t.string :description t.boolean :private t.boolean :fork t.string :url t.string :htm...
class PostsController < ApplicationController def index @posts = Post.all.order('created_at DESC') respond_to do |format| format.html { render :index } format.json { render json: @posts } end end def show @post = Post.find(params[:id]) respond_to do |format| format.html { render :show } fo...
module Kindara class Account def self.authenticate(email, password) account = Kindara::Request.new("account", "auth", {"email" => email, "password" => password}).call new(account.fetch("name")) end def initialize(name) @name = name end def name @name end end end
class Admins::CustomersController < ApplicationController before_action :authenticate_admin! def index @customers = Customer.all end def show @customer = Customer.find(params[:id]) end def edit @customer = Customer.find(params[:id]) end def update @customer = Customer.find(params[:id]) if @custome...
module Forums class PostsController < ApplicationController include Forums::ThreadsCommon include Forums::Permissions before_action(only: [:create]) { @thread = Forums::Thread.find(params[:thread_id]) } before_action except: [:search, :recent, :create] do @post = Post.find(params[:id]) @t...
def prettify_language(language) if language == 'css' language.upcase elsif language =='react' language.capitalize end end def prettify(component) component.split('-').map(&:capitalize).join(' ') if component end class PrettyNav def initialize(nav_hash) @nav_hash = nav_hash end def to_hash ...
require 'base64' class EfficientFrontierCreator def initialize(asset_ids) raise "Asset ID's must be an array" unless asset_ids.is_a?(Array) # Upcase/sort so that cache keys (if using) are always consistent. @asset_ids = asset_ids.map(&:upcase).sort end def call # This is where you'd do a cache...
class UserMailer < ApplicationMailer default from: 'sure.crm.app@gmail.com' def welcome_email(user) @user = user @url = 'http://181.215.106.97:3000' mail(to: @user.email, subject: 'Welcome to My Awesome Site') end def removed_email(user) @user = user @url = 'http://fakeupdat...
# frozen_string_literal: true require 'spec_helper' require 'commands/load_coin' RSpec.describe Commands::LoadCoin do subject(:call) do described_class.call(denomination: denomination, quantity_to_load: quantity_to_load) end let(:logger) { instance_spy(Logger) } before { App.stub('logger', logger) } ...
class Admin::OrderItemsController < ApplicationController def update # order = Order.find(params[:order_id]) # order_item = order_id.OrderItem.find(params[:id]) order_item = OrderItem.find(params[:id]) order_item.update(making_status_params) flash[:success] = "製作ステータスを変更しました" redirect_to admin...
module IssuePriorityExtension extend ActiveSupport::Concern module Helper def self.hsv2rgb(h,s,v) h = h.to_f s = s.to_f v = v.to_f rgb = if v == 0 [0.0, 0.0, 0.0] else h = h/60 i = h.floor f = h-i p = v*(1-s) q = v*(1-(s*f)) ...
FactoryGirl.define do factory :log, :class => Log do type ["Invite"].sample action ["accept", "decline", "report", "create_report"].sample data '{"name": "Invite name", "description": "Invite description"}' end end
=begin Pseudocode: Input: grocery list items and quanitites Out: An hash connecting the items and quantities Steps: 1) create a hash, key is item, value is quantity Add an item with a quantity to the list =end def add_item(hash, item, quantity) hash[item] = quantity end #Remove an item from the list #Input is...
require 'rspec' require_relative '../app/chatterbox' RSpec.describe 'Chatterbox' do let(:chatterbox) {Chatterbox.new} describe '.exchange_transfer' do context 'when the account amount allows you to make a transfer' do let(:response) {chatterbox.exchange_transfer(1, :USD, :EUR)} it {expect(response...
require 'rails_helper' RSpec.describe Folder, type: :model do describe '.validate' do it 'is valid with the same name but different paths' do Folder.create path: 'folder1', name: 'folder3' folder = Folder.create path: 'folder1/folder2', name: 'folder3' expect(folder).to be_valid end i...
require 'rails_helper' RSpec.describe ArticlesHelper, :type => :helper do context ".formated_id" do it "allways show a dot on id" do expect(formated_id(5)).to eql "5." end end context ".formated_article" do before do @article = Article.create(description: "some text") end it "ret...
class AddIngestFieldsToProjects < ActiveRecord::Migration def change add_column :projects, :ingest_folder, :string add_column :projects, :destination_folder_uuid, :string end end
class FinishChatMessagesTable < ActiveRecord::Migration[5.2] def change add_column :chat_messages, :author_id, :integer, null: false add_column :chat_messages, :channel_id, :integer, null: false add_index :chat_messages, :author_id add_index :chat_messages, :channel_id end end
# frozen_string_literal: true # Date ranges for when a slide should be visible class DateRange < ApplicationRecord belongs_to :slide, inverse_of: :date_ranges end
# frozen_string_literal: true FactoryBot.define do factory :order do association :user, factory: :user imei { 448_674_528_976_410 } annual_price { 1000 } device_model { 'Iphone' } installments { 4 } end end