text
stringlengths
10
2.61M
require "logger" # category of log level to different output with log info as json class FiatdLogger LOG_LEVEL = { stdout: [:debug , :info , :warn], stderr: [:error , :fatal , :unknown] } def initialize(log_level) @loggers = {} LOG_LEVEL.each do |out, levels| logger = L...
class AlbumSerializer < ActiveModel::Serializer attributes :id, :title, :genre, :artist def artist object.artist.name end def genre object.genre.name end end
# frozen_string_literal: true require 'inheritance-helper' # Transfer/Map data from one model to the next module Mappable autoload :Mapping, 'mappable/mapping' autoload :Utils, 'mappable/utils' def self.included(base) base.extend InheritanceHelper::Methods base.extend ClassMethods end # no-doc m...
# Loop on Command, Loops 1, Ruby Basics, Exercises loop do puts 'Should I stop looping? (input: `yes`)' answer = gets.chomp break if answer == 'yes' puts 'Does not compute. Please answer `yes`.' end puts 'Ok, exiting loop!'
namespace :gitolite do desc "update gitolite repositories" task :update_repositories => [:environment] do projects = Project.active puts "Updating repositories for projects #{projects.join(' ')}" GitHosting.update_repositories(projects, false) end desc "fetch commits from gitolite repositories" task :fetch_c...
class Production < ApplicationRecord belongs_to :producer belongs_to :user belongs_to :client#, optional: true validates :title, presence: true validates :contract, presence: true validates :client_id, presence: true scope :significant_contracts, -> {where("contract > ?", 40000)} scope :highest_contract...
class Product < ApplicationRecord has_many :orders has_many :comments validates :name, presence: true def highest_rating_comment comments.rating_desc.first end def lowest_rating_comment comments.rating_desc.last end def average_rating comments.average(:rating).to_f end end
Rails.application.routes.draw do devise_for :users, controllers: { registrations: "users/registrations" } resources :posts, only: %i[index show new create edit update] do resources :comments, only: %i[create] resources :ratings, defaults: { format: "js" }, only: %i[create] end resources :contact, only: ...
FactoryBot.define do factory :command do title { Faker::Book.title } description { Faker::Games::HeroesOfTheStorm.quote } association :user association :genre association :command_type after(:create) do |command| create(:command_file, command: command) end end end
# frozen_string_literal: true directories %w[. lib spec] guard :rspec, cmd: 'bundle exec rspec', title: 'Permissions Test Results' do group :configuration do watch('.rspec') { 'spec' } watch('spec/spec_helper.rb') { 'spec' } end group :lib do watch(%r{^lib/(.+)\.rb$}) { |m| 'spec/per...
# == Schema Information # # Table name: projects # # id :integer not null, primary key # title :string not null # author_id :integer not null # created_at :datetime not null # updated_at :datetime not null # image_fi...
# frozen_string_literal: true module FileReaderTest module EachCodepoint def test_each_codepoint file = file_containing("tāiko") codepoints = [] file.each_codepoint do |codepoint| codepoints << codepoint end assert_equal [116, 257, 105, 107, 111], codepoints end d...
class JournalsController < ApplicationController def index @journals = Journal.all end def create @journal = Journal.new(journal_params) @journal.user_id = current_user.id if @journal.save flash[:notice] = "Journal added" else flash[:notice] = "#{@journal.errors.full_messages.firs...
require_relative "full_block" module Hotel class Block attr_reader :name, :check_in, :check_out, :rooms, :rate def initialize(name, check_in, check_out, block, rate) check_number_of_rooms(block) @name = name @check_in = check_in @check_out = check_out @rooms = block @rate...
# encoding: UTF-8 module Knapsack class Recipe module Helpers module Autotools def define_autotools return if action?(:configure) sequence :configure, :compile, :install action :configure do args = ["sh", options.configure] # detect or add --...
########################################################## ########################################################## ## _____ _ ## ## / __ \ | | ## ## | / \/_ _ ___| |_ ___ _ __ ___ ___ _ __ ___ ## ## | | | | | / __| __/...
FactoryBot.define do factory :lesson do name {Faker::Team.name} end end
# When we try to fetch something from the environment that doesn't # exist we raise an error. class MissingValue < StandardError attr_reader :key def initialize(key) @key = key end def message "No value set for #{key}" end end # When our environment has no real parent, trying to fetch any key # rai...
class AddRawXmlToSyncs < ActiveRecord::Migration def self.up add_column :syncs, :raw_xml, :text, :limit => 1.megabyte end def self.down remove_column :syncs, :raw_xml end end
require "rails_helper" feature "admin can delete user" do let!(:user) { FactoryGirl.create(:user) } let!(:contractor) { FactoryGirl.create(:contractor) } let!(:admin) { FactoryGirl.create(:admin) } let!(:admin2) { FactoryGirl.create(:admin) } scenario "admin successfully deletes home owner" do visit root...
# frozen_string_literal: true module RollbarApi class Project @projects = {} def self.configure(project_name, project_access_token) @projects[project_name] = project_access_token find(project_name) end def self.find(project_name) project_access_token = @projects[project_name] ...
require_relative '../spec_helper' describe 'API' do include Rack::Test::Methods describe 'ranking' do describe 'GET /ranking' do let!(:token) { create(:token) } let(:url) { '/ranking' } subject { last_response } describe 'without token' do before { get url } it { expe...
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 #...
FactoryGirl.define do factory :block do duration 30 start_time 1 end end
class CreateJoinTable < ActiveRecord::Migration def change create_join_table :recipe, :ingredients do |t| t.index [:recipe_id, :ingredient_id] t.index [:ingridient_id, :recipe_id] end end end
service_name = if os.redhat? && os[:release].to_i < 7 'mcelogd' else 'mcelog' end describe service(service_name) do # it { should be_enabled } # disable until inspec can figure this out on systemd based systems it { should be_running } end
# frozen_string_literal: true module CandleConcern extend ActiveSupport::Concern included do validates :time, presence: true, uniqueness: true validates :close_ask, presence: true validates :close_bid, presence: true validates :close_mid, presence: true validates :high_ask, presence: true ...
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') #require '/spec_helper' describe ConfigFileLoader do context "deep merge" do it "should merge with no target" do dm({},{}).should == {} end it "should merge with no target 2" do dm(nil,nil).should == nil end ...
def divisors(num) new_arr = [] 1.upto(num) { |x| new_arr << x if num % x == 0 } new_arr end p divisors(1) == [1] p divisors(7) == [1, 7] p divisors(12) == [1, 2, 3, 4, 6, 12] p divisors(98) == [1, 2, 7, 14, 49, 98] # p divisors(99400891) == [1, 9967, 9973, 99400891] # may take a minute # create a new array #...
require "rails_helper" feature "Search Triggers", js: true do scenario "when search is triggered an there are results" do visit root_path expect(page).to have_content("Meetups In Munich") fill_in "query", with: "rails meetup" click_on "Search" expect(page).to have_content(I18n.t("meetups.searc...
require 'rails_helper' RSpec.describe Answer, type: :model do let!(:category) { Category.create!(title: "General") } let!(:author) do User.create!( first_name: "Serge", email: "serge@example.com", password: "123123" ) end let!(:test) { Test.create!(title: "Ruby", category: category, author: autho...
Rails.application.routes.draw do mount_devise_token_auth_for 'User', at: 'api/auth' namespace :api do resources :articles, only: [:index, :show, :create, :update] end end
class Submission < ActiveRecord::Base include Viewable has_and_belongs_to_many :submission_folders # The owner can be fluid. See claimed? method below. belongs_to :owner, class_name: 'Profile', foreign_key: :owner_id # Can belong to a SubmissionGroup belongs_to :submission_group has_many :collaboration...
# # Cookbook Name:: cookbook_moodle # Recipe:: mysql # root_password = node['cookbook_moodle']['database']['root_password'] # Set the mysql version we want node.set['mysql']['version'] = node["cookbook_moodle"]["mysql_version"] # Install the MySQL service mysql_service 'default' do initial_root_password root_passw...
require './punctuation_roulette' class Player attr_accessor :name, :bank_roll, :punctuation def initialize puts "--- Players Options ---\n".colorize(:blue) options end def options puts "Players name" choice = gets.strip if choice == '' puts "Write a valid name" options ...
# frozen_string_literal: true module EntityFinder class Bulk < BaseOperation def call(input, entity_type:) input.each_with_object([]) do |entity, result| result << entity_type.with_pk!(entity.fetch(:id)) end end end end
class User class Device < ApplicationRecord self.table_name = 'user_devices' belongs_to :user, class_name: 'User', required: false belongs_to :device, class_name: 'GlobalDevice', required: false end end
class Category < ActiveRecord::Base has_many :abilities has_many :insurances, :through => :abilities end
module NumberWords DIGITS = { 1=>"one", 2=>"two", 3=>"three", 4=>"four", 5=>"five", 6=>"six", 7=>"seven", 8=>"eight", 9=>"nine", 0=>"zero" } TENS = { 0=>"zero", ...
class AppMailer < ActionMailer::Base default from: 'info@myflix.com' def welcome_user(user) @user = user mail to: user.email, subject: "You are awesome" end def send_forgot_password(user) @user = user mail to: user.email, subject: "Password Reset Requested" end def send_invitation invit...
# students = [ # {name: "Dr. Hannibal Lecter", cohort: :november}, # {name: "Darth Vader", cohort: :november}, # {name: "Nurse Ratched", cohort: :november}, # {name: "Michael Corleone", cohort: :november}, # {name: "Alex DeLarge", cohort: :november}, # {name: "The Wicked Witch of the West", cohort: :novembe...
class SpecializationPolicy < AdminApplicationPolicy def permitted_attributes [ :name, :klass_id, {:spell_ids => []} ] end end
class AddColumnToSpreeOrder < ActiveRecord::Migration def change add_column :spree_orders, :product_id, :integer add_column :spree_orders, :check_in_date, :date add_column :spree_orders, :check_ot_date, :date add_column :spree_orders, :quantity, :integer add_column :spree_orders, :f2r_hotel_invent...
class DishesController < ApplicationController before_action :set_truck before_action :find_dish, only: %i[edit update destroy] skip_after_action :verify_authorized def new @dish = Dish.new end def create @dish = Dish.new(dish_params) @dish.truck = @truck if @dish.save diet_ids = par...
require 'rails_helper' describe 'Messages requests', type: :request, active_job: true do context 'unauthenticated' do it 'rejects unauthenticated user' do client = create(:client) get reporting_relationship_scheduled_messages_index_path(client) expect(response.code).to eq '302' expect(r...
class Task < ApplicationRecord after_save :save_log after_destroy :destroy_log validates :name, :description, presence: true def save_log puts "Taks saved!" end def destroy_log puts "Taks deleted!" end end
class CreateArticles < ActiveRecord::Migration def self.up create_table :articles do |t| t.string :title t.string :section t.date :date #t.integer :school_year#, :default => 2008 t.integer :issue_id t.string :author t.string :author_position t.text :body t.int...
RSpec.describe Person do let(:existing_person) { create(:person) } describe '#update_profile_score' do let(:new_person) { create(:person) } it 'updates the score after create' do expect(new_person.profile_score).to_not eq(0) end it 'updates the score after file name update' do expect ...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
class AddTagToRestaurant < ActiveRecord::Migration def change add_column :restaurants, :tag, :string add_index :restaurants, :tag end end
# frozen_string_literal: true class CommentsController < ApplicationController include FindPolymorphic def index @commentable = find_polymorphic(params) @comments = @commentable.comments .includes([:commentable, :likers, author: :profile]) .page(params[:page]) end def create @commenta...
# frozen_string_literal: true class RemoveTitleAndVideoUrlFromTalkSummaries < ActiveRecord::Migration[5.1] def change remove_column :talk_summaries, :title remove_column :talk_summaries, :video_url end end
class CreateCustomersUsersTable < ActiveRecord::Migration def up create_table :customers_users, :id => false do |t| t.references :customer, :user end end def down drop_table :customers_users end end
class Category < ApplicationRecord belongs_to :form, optional: true has_many :competencies, dependent: :destroy accepts_nested_attributes_for :competencies, allow_destroy: true, :reject_if => lambda { |a| a[:label].blank? } end
class GoodDog end sparky = GoodDog.new module Speak def speak(sound) puts sound end end class GoodDog include Speak end class HumanBeing include Speak end sparky = GoodDog.new sparky.speak("Arf!") bob = HumanBeing.new bob.speak("Hello!") puts "---GoodDog ancestors---" puts GoodDog.ancestors puts '' pu...
class Buddy < ActiveRecord::Base def to_s "#{nick}" end end
module HelpTopicsHelper def render_help_text(text) RedCloth.new(text.gsub(/\":([a-z]+)/) { $1 == 'http' ? '":' + $1 : %{":/help_topics/#{$1}} }).to_html end def help_link(topic_name) link_to t('navigation.help'), help_topic_path(topic_name) end end
require_relative '../base' module Examples module Images class VariantImageCreation def self.run(client) if Clients::JSON === client client.pending "VariantImageCreation does not work with JSON client." return end image = File.dirname(__FILE__) + '/thinking-cat....
Rails.application.routes.draw do devise_for :users devise_scope :user do root to: 'devise/sessions#new' end authenticated :user do root :to => "main#dashboard" # Rails 4 users must specify the 'as' option to give it a unique name # root :to => "main#dashboard", :as => "authenticated_root" end...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module Resources module Properties class IndicSyllabicCategoryPropertyImporter < PropertyImporter DATA_FILE = 'ucd/IndicSyllabicCategory.txt' PROPERTY_NAME = 'Indic_Syllabic_Cat...
module SlotsHelper def direct_card_assign slot, card @slot = slot @slot.cards = [card] @slot.update_attribute(:queries, '') @slot.update_attribute(:image_url, card.image_url) @slot.save end def cards_from_result(hsh) hsh.map { |_, v| v.map { |_, v2| v2[:card] } }.flatten end def n...
#encoding: utf-8 class Ranking < Sinatra::Application get '/matches' do @matches = Match.all @teams = Team.all @tournaments = Tournament.all slim :'matches/matches' end post '/matches/new' do if authenticated? valid_match_date = validate_date(params[:match_date]) unless valid_mat...
class BalloonsController < ApplicationController # before_action :set_balloon, only: [:show, :edit] def index @balloons = Balloon.all end def show @balloon = Balloon.find(params[:id]) end def new @balloon = Balloon.new @parades = Parade.all end def create @balloon = Balloon.creat...
class Tweeter def initialize @tweets = [] end def tweet(message) # Your TODO: fill this in. # This should add the first 144 characters # of any message to the @tweets array @tweets << message[0..143] end def each @tweets.each {|tweet| yield(tweet)} ...
#TIME: ~ 30 min # Teddit Condtionals - Starter Code. # Let's add a new Teddit feature. Upvotes! # Complete the application below. # Where you see comments (lines that begin with #) replace it with code so that the program works. def get_input gets end def calculate_upvotes(story, category) # Write code so that: ...
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string # born :date # email :string default(""), not null # encrypted_password :string default(""), not null # reset...
# frozen_string_literal: true class UsersController < ApplicationController # The order of before_action method is important before_action :require_signin, except: %i[new create] before_action :require_correct_user, only: [:edit, :update, :destroy] def index @users = User.all end def show @user ...
require 'rubygems' require 'csv' require 'json' require 'ostruct' require 'open-uri' require 'delegate' require 'active_support' require 'active_support/time' require 'active_support/time_with_zone' Time.zone = "Eastern Time (US & Canada)" class SessionList def self.fetch fetch_json.map do |session| Sessio...
class HomesController < ApplicationController skip_before_action :authenticate_user!, :only => :index before_action :set_home, only: [:show, :edit, :update, :destroy] # GET /homes # GET /homes.json def index end end
module RecurrenceParser class AbsoluteYearlyParser < BaseParser protected def calculate_rule append_rule('yearly', pattern[:interval]) append_rule('day_of_month', pattern[:dayOfMonth]) append_rule('month_of_year', pattern[:month]) end end end
class BlankProperty < ActiveResourceRecord self.site = "#{Figaro.env.locate_catalogue_app}/api/v1/" self.element_name = "property" end
class AddMobileNumberToListing < ActiveRecord::Migration def change add_column :listings, :mobile_number, :string add_column :listings, :experience, :float add_column :listings, :address, :text add_column :listings, :website, :string end end
class BloksController < ApplicationController def index Blok.all.each do |b| b.next_id = 7 end @blok = Blok.all respond_to do |format| format.html # index.html.erb format.xml { render xml: @bloks } end end def new @blok = Blok.new respond_to do |format| forma...
# This class define the task model class Track < ApplicationRecord has_many :intervals belongs_to :project, dependent: :destroy belongs_to :user, dependent: :destroy validates :name, :description, presence: true end
require 'rails_helper' xdescribe 'Circle CI Hooks', subdomain: 'hooks' do let(:service) { FactoryBot.create :circle_service } let(:project) { service.projects.create name: 'jonallured/cybertail-rails' } let(:payload) do { build_num: '1', committer_name: 'Jon Allured', outcome: outcome, ...
class CohortsController < ApplicationController before_action :set_cohort, only: [:edit, :show, :update] before_action :configure_google_calendar_client, only: [:create] def index @cohorts = Cohort.all end def new @cohort = Cohort.new end def create @cohort = Cohort.new(cohort_params) @...
module TalkUp # Return an authenticated user, or nil class AuthenticateAccount class UnauthorizedError < StandardError; end def initialize(config) @config = config end def call(username, password) account_response = ApiGateway.new.account_auth(username, password) rai...
module ApplicationHelper def current_controller? controller_name params[:controller] == controller_name end def word_count Word.count end def getTypes [ [t('word_type.noun'), "noun"], [t('word_type.adjectif'), "adjectif"], [t('word_type.verb'), "verb"], ] end def getQ...
class UsersController < ApplicationController before_action :authenticate_user! before_action :authenticate_super, only: [:index, :show, :edit, :update, :destroy] before_action :authenticate_company, only: [:show, :edit, :update] def index @users = User.where(team_id:current_user.team_id) end def show...
# In the previous exercise, you developed a method that converts simple numeric strings to Integers. In this exercise, you're going to extend that method to work with signed numbers. # Write a method that takes a String of digits, and returns the appropriate number as an integer. The String may have a leading + or - s...
module HeightHelper def self.included(base) base.extend(ClassMethods) base.send :include, InstanceMethods end class MissingArgumentError < ArgumentError; end class BadArgumentError < ArgumentError; end NIL_STATUS = "is_nil" IS_NUMBER_STATUS = "is_number" INVALID_STATUS = "invalid" module Cl...
# require 'listen' class Bambamzer def initialize @files = {} listener = Listen.to('.') do |modified, _added, _removed| read unless modified.select { |name| name.split('/').last.strip == 'bambamzer.txt' }.empty? end listener.start # not blocking read sleep end def read File.re...
module TwitterCrawlerHelper def short_date(d) ret = "" unless (d.nil?) date = Date.parse(d) if (Date.today == date) ret = "today" else ret = date.strftime("%a, %d %b") end end ret end def short_timestamp(ts) un...
class Notice < ActiveRecord::Base # Note: When creating a notice to be displayed immediately, set the starting_date to Time.now and not to a past date belongs_to :account validates_presence_of :starting_date, :message, :message_type validates_inclusion_of :message_type, :in => ["notice","alert"] def sel...
## # This module requires Metasploit: http//metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE def initialize(info = {}) super(u...
# Your Names # 1)Chris Lamkin # 2)Alec Hendrickson =begin 1.) Refactor error counter using has_key? 2.) Suggested baking items give user a more accurate message =end # We spent [#] hours on this challenge. # Bakery Serving Size portion calculator. # Define method, creates hash, sets parameters for input def servin...
execute 'delivery-ctl reconfigure' do action :nothing end cache_path = Chef::Config[:file_cache_path] file "#{cache_path}/delivery.firstrun" do action :create not_if do ::File.exists?("#{cache_path}/delivery.firstrun") || !::File.exists?("/var/opt/delivery/license/delivery.license") end notifies :run, 'execut...
# -*- coding: utf-8 -*- =begin João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo exce...
class FinalidadeSerializer < BaseSerializer attributes :id, :nome, :descricao has_many :imovel link(:self) { finalidade_path(object) } link(:imovel) { finalidade_imovel_path(object) } end
class AddRecordCategoryIdToHealths < ActiveRecord::Migration def change add_reference :healths, :record_category, index: true, foreign_key: true end end
class AddIdSocialNetworkToTfl < ActiveRecord::Migration def self.up add_column :twitter_data, :id_social_network, :integer add_column :facebook_data, :id_social_network, :integer add_column :linkedin_data, :id_social_network, :integer end def self.down remove_column :twitter_data, :id_social_netw...
class List < ApplicationRecord searchkick belongs_to :user has_many :items, dependent: :destroy has_many :collaborators, dependent: :destroy accepts_nested_attributes_for :items, reject_if: :all_blank, allow_destroy: true accepts_nested_attributes_for :collaborators, reject_if: :all_blank, allow_destroy: ...
require 'json' # Geo ## See: http://en.wikipedia.org/wiki/ISO_3166-2:MY regions = Region.create!([ { code: '01', name: 'Johor' }, { code: '02', name: 'Kedah' }, { code: '03', name: 'Kelantan' }, { code: '04', name: 'Melaka' }, { code: '05', name: 'Negeri Sembilan' }, { code: '06', name: 'Pahang' }, { co...
require 'faye/websocket' require 'eventmachine' require 'json' require 'pp' require 'active_record' require File.join(File.dirname(__FILE__), 'helpers', 'DatabaseHelper') require File.join(File.dirname(__FILE__), 'model', 'tick') class Channel def Channel.unsubscribe_message(channel) uuid = case channel when...
json.array!(@unicorns) do |unicorn| json.extract! unicorn, :id, :name json.url unicorn_url(unicorn, format: :json) end
class TagPost < ApplicationRecord validates_uniqueness_of :tag_id, :scope => :post_id belongs_to :tag belongs_to :post end
# encoding: utf-8 class <%= controller_class_name %>Controller < ApplicationController respond_to :html before_action :set_<%= singular_table_name %>, only: [:show, :edit, :update, :destroy] add_breadcrumb '<%= human_name %>', '/<%= plural_table_name %>' def index @<%= plural_table_name %> = <%= class_nam...
# For methods, refer to the properties of the CloudFormation CodeBuild::Project https://amzn.to/2UTeNlr # For convenience methods, refer to the source https://github.com/tongueroo/cody/blob/master/lib/cody/dsl/project.rb # Docs: # # * https://cody.run/docs/dsl/project/ # * https://cody.run/docs/docs/dsl/helpers/ # # n...
require "rubygems" require "rake/extensiontask" require 'rdoc/task' require 'rake/testtask' Rake::Task[:test].prerequisites << :compile Rake::TestTask.new do |t| t.test_files = FileList['test/test*.rb'] end Rake::ExtensionTask.new "fast_containers" do |ext| ext.lib_dir = "lib/fast_containers" end # -------------...
require 'bank' Given(/^I have deposited \$(\d+) in my account$/) do |amount| # Deposit money into an account account.deposit(amount.to_i) # RSpec assertion: # Check to see if the deposited amount == the amount in the account expect(account.balance).to eq(amount.to_i), "Expected account bal...