text
stringlengths
10
2.61M
class Post < ApplicationRecord has_many :likes, dependent: :destroy has_many :comments, dependent: :destroy belongs_to :user validates :title, presence: true def self.search(x) where("title ILIKE ? OR body ILIKE ?", "%#{x}%", "%#{x}%").order(created_at: :desc) end def like_of(user) likes.find_by...
class Api::V1::TasksController < ApplicationController skip_before_action :verify_authenticity_token swagger_controller :tasks, 'Tasks Management' swagger_api :index do summary 'Returns tasks details' param :query, :id, :integer, :required, 'Task Id' end def index @task =...
require 'rails_helper' describe User do context 'with valid attributes' do it 'should be valid' do user = User.new(name: 'テスト太郎', address: '福岡県') expect(user).to be_valid end end end
require 'pry' class Artist extend Concerns::Findable attr_accessor :name, :songs @@all = [] def initialize(name) @name = name @songs = [] end def save @@all << self end def self.create(name) puts "Artist #{name} does not exist. Creating..." new_artist = Artist.new(name) # b...
class Api::V1::CommentsController < ApplicationController before_action :confirm_post_with_id! def index comments = current_post.comments render json: { comments: comments }, status: 200 end def show begin comment = current_post.comments.find(params[:id]) render json: comment, status: 200 rescue ...
require "cli_tester" require "given_filesystem/spec_helpers" ENV["RUN_BY_RSPEC"] = "1" def with_stubbed_binary(bin_path) saved_path = ENV["PATH"] full_path = File.expand_path("../", __FILE__) full_path = File.join(full_path, bin_path) if !File.exist?(full_path) STDERR.puts "Error: stubbing binary #{full_...
class Star < ApplicationRecord belongs_to :user belongs_to :source, counter_cache: true validates :source, presence: true validates :user, presence: true validates :source, uniqueness: { scope: :user } end
require File.dirname(__FILE__) + '/spec_helper' describe "Link Filters" do include Clot::UrlFilters include Clot::LinkFilters include Liquid before(:each) do @context = {} end context "stylesheet_link filter" do specify "should create stylesheet link" do link1 = stylesheet_link "sheet" ...
FactoryBot.define do factory :customer do first_name {Faker::Name.first_name} last_name {Faker::Name.last_name} end end
Rails.application.routes.draw do # Admin panel access routes mount RailsAdmin::Engine => '/admin', as: 'rails_admin' # Root path for application root 'home#index' # design routes for api with json formate and 'api' namespace scope "api", defaults: {format: :json} do # design api routes for audits ...
require 'wsdl_mapper/type_mapping/base' require 'wsdl_mapper/dom/builtin_type' module WsdlMapper module TypeMapping Integer = Base.new do register_xml_types %w[ byte int integer long negativeInteger nonNegativeInteger nonPositiveInteger positi...
require 'securerandom' module Bitcourier class Daemon attr_accessor :server, :client, :node_manager, :peer_list, :nonce def initialize options = {} self.server = Network::Server.new self, port: options[:port] self.node_manager = NodeManager.new self, target_connections: options[:target_co...
class Api::V1::CategoriesController < ApplicationController def index render json: Category.all # categories = Category.order('created_at DESC'); # render json: {status: 'SUCCESS', message: 'Loaded categories', data: categories}, status: :ok end def create category = Category.create(category_para...
# A method which continuously asks the same question until a specific answer is given no matter what def ask_recursively(question) puts question reply = gets.chomp.downcase if reply == 'yes' # Please reply only yes or no OTHERWISE true elsif reply == 'no' false else puts 'Please answer "yes"...
# encoding: UTF-8 class Film class Brin def as_link link("brin #{id}", {href: '#', onclick:"return ShowBrin(#{id})"}) end # Retourne le code HTML pour la fiche du brin def as_fiche div( closebox("return HideCurFiche()") + showinTM_link + div(libelle.to_html, class: 'titre') + t...
class CheckinDecorator < ApplicationDecorator delegate_all def formatted_date object.checkin_date.strftime '%B %d, %Y' end end
# == Schema Information # # Table name: groups # # id :integer not null, primary key # user_id :integer # radius_name :string(255) # group_id :integer # group_name :string(255) # group_desc :string(255) # active :boolean default(FALSE) # admin :boolean defaul...
# 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...
# zero = 0 # puts "Before each call" # zero.each { |element| puts element} rescue puts "Can't do that!" # puts "After each call" =begin Before each call Can't do that! After each call =end # => without the <rescue> this returns a syntax error # zero = 0 # puts "Before each call" # zero.each { |element| puts element...
module M class Maybe < Monad def self.return(value) return value if value == Nothing Just(value) end def self.join(value) return Nothing if value == Nothing super end end class Just < Maybe; end class Nothing < Maybe class << self def bind(fn=nil, &block); se...
module Log::Write def write(message, level, tags) message = message.to_s if message.length == 0 message = '(empty log message)' end line = Log::Format.line(message, clock.iso8601(precision: 5), subject, level, &levels[level] &.message_formatter) device.write "#{line}#{$INPUT_RECORD_SEPARA...
module Refinery module ClaimsChecklists module Admin class ClaimsChecklistsController < ::Refinery::AdminController crudify :'refinery/claims_checklists/claims_checklist', :title_attribute => 'checklist_name' private # Only allow a trusted parameter "white list" th...
class CreateRepoFollowings < ActiveRecord::Migration def change create_table :repo_followings do |t| t.string :repo_owner t.string :repo_name t.string :follower end add_index :repo_followings, [:repo_owner, :repo_name] add_index :repo_followings, [:repo_owner, :repo_name, :follower...
# -*- coding: utf-8 -*- module Plugin::IntentSelector class IntentSelectorListView < ::Gtk::CRUD COLUMN_INTENT_LABEL = 0 COLUMN_MODEL_LABEL = 1 COLUMN_STRING = 2 COLUMN_INTENT = 3 COLUMN_MODEL = 4 COLUMN_UUID = 5 def initialize super intents = intent_catalog models = mo...
# frozen_string_literal: true require "dry/types/constructor" RSpec.describe Dry::Types::Constructor.wrapper_type do let(:int) { Dry::Types["coercible.integer"] } let(:constructor_block) do lambda do |input, type, &block| 300 + type.("#{input}0", &block) end end let(:type) { int.constructor(co...
class AddCountersToProject < ActiveRecord::Migration def change add_column :projects, :doing_counter, :integer add_column :projects, :done_counter, :integer add_column :projects, :do_counter, :integer end end
# frozen_string_literal: true # Root Sourcescrub module Sourcescrub # Models module Models # Company class Company < Entity ENDPOINT = 'companies' def field_ids %w[ id companyType name informalName website domain des...
=begin each_with_index The Enumerable#each_with_index method iterates over the members of a collection, passing each element and its index to the associated block. The value returned by the block is not used. each_with_index returns a reference to the original collection. Write a method called each_with_index tha...
# frozen_string_literal: true require 'ruby-kafka' require 'ruby-progressbar' require_relative 'config' class RubykafkaSetup def initialize @kafka = Kafka.new(['kafka://localhost:9092'], client_id: CLIENT) @producer = @kafka.producer @async_producer = @kafka.async_producer end def publish(topic, it...
require 'rspec' require 'rules/ca/on/maximum_weekly_hours' require 'rules/base' module Rules module Ca module On describe MaximumWeeklyHours do describe 'processing' do let(:criteria) { { minimum_daily_hours: 3.0, maximum_daily_hours: 8.0, ...
require "spec_helper" RSpec.describe EventHub::BaseException do it "raises an exception" do expect { raise EventHub::BaseException }.to raise_error(EventHub::BaseException) end it "raises an exception" do expect { raise EventHub::BaseException.new }.to raise_error(EventHub::BaseException) end it "r...
require 'rails_helper' require 'byebug' RSpec.describe KepplerFrontend::View, type: :model do context 'live editor' do # context 'render' do # before(:each) do # @view = create(:keppler_frontend_views, method: "GET") # @view.install # @editor = @view.live_editor_render # end ...
#!/usr/bin/env ruby #encoding: utf-8 module Napakalaki class Treasure def initialize(name, goldCoins, minBonus, maxBonus, type) @name = name @goldCoins = goldCoins @minBonus = minBonus @maxBonus = maxBonus @type = type end #initialize #Getters attr_reader :name attr_reader :goldCoins ...
class Entry < ActiveRecord::Base has_and_belongs_to_many :users belongs_to :feed validates_uniqueness_of :link, :scope => [:feed_id] end
class UsersController < ApplicationController before_action :control_panel, only: [:index] def control_panel authenticate_user if @current_user unless @current_user.admin redirect_to root_path, notice: "Please login with Admin privileges!" end end end def index @admin_nav ...
# require "byebug" require "set" require_relative "player" class Game def self.build_dictionary(file_name) dictionary = Set.new File.readlines(file_name).each { |line| dictionary.add(line.chomp) } dictionary end attr_reader :fragment, :players, :dictionary attr_writer :players...
class AddHealthCareCompanyRefToDoctors < ActiveRecord::Migration[6.0] def change add_reference :doctors, :health_care_company, null: false, foreign_key: true end end
require 'uri' class GistService attr_reader :url def initialize(gist_url) @url = URI.parse(gist_url) end def call gist_content rescue Octokit::NotFound nil end private def gist_content content = '' Octokit.gist(gist_id).files.to_attrs.values.each do |file| content += file[...
class CreateDbErrors < ActiveRecord::Migration def change create_table :db_errors do |t| t.text :alert, null: false t.boolean :checked, default: false, null: false t.datetime :last_run t.timestamps null: false end drop_table :selfcheckreports if table_exists? :selfcheckreports en...
require 'unit_spec_helper' describe Rpush, 'push' do before do allow(Rpush::Daemon::Synchronizer).to receive_messages(sync: nil) allow(Rpush::Daemon::AppRunner).to receive_messages(wait: nil) allow(Rpush::Daemon::Feeder).to receive_messages(start: nil) end it 'sets the push config option to true' do...
require "test_helper" class UserTest < ActiveSupport::TestCase def setup @spotify_user = RSpotify::User.new({}) @user = User.new(@spotify_user) end test 'delegates methods to RSpotify::User' do @spotify_user.stubs(:display_name).returns 'User Name' assert_equal @spotify_user, @user.spotify_user...
class PlayersController < ApplicationController def index render json: PlayerSerializer.new(Player.all).serializable_hash[:data].map{|player| player[:attributes]} end def create player = Player.new(player_params) if player.save render json: PlayerSerializer.new(...
# frozen_string_literal: true module Queries module Games class FetchGame < ::Queries::BaseQuery type Types::GameType, null: false argument :id, ID, required: true def resolve(id) Game.includes(:plays, board: :cells).find id[:id] rescue ActiveRecord::RecordNotFound => _e ...
require_relative 'counting_end_piece' require_relative 'last_end_piece' require_relative 'end_piece' require_relative 'inlet' require_relative 'joint_piece' require_relative 'piece' require_relative 'partition' require_relative 'array_end_piece' module Aqueductron module Buildering # # summarize all results ...
require 'spec_helper' describe Immutable::Vector do describe '#rindex' do let(:vector) { V[1,2,3,3,2,1] } context 'when passed an object present in the vector' do it 'returns the last index where the object is present' do vector.rindex(1).should be(5) vector.rindex(2).should be(4) ...
class Esendex module Requests class Batch def initialize(args) @args = args end def serialise Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml| xml.messagebatch(xmlns: 'http://api.esendex.com/ns/') { xml.name @args[:name] } end.to_xml...
class Employee < ApplicationRecord belongs_to :office validates :name, presence: true validates :birth, presence: true validates :address, presence: true end
require 'json' require 'optparse' environment = {} optparse = OptionParser.new do |opts| environment[:test] = false opts.on( '-test', '--test', 'Generates only 5 stars.' ) do environment[:test] = true end end optparse.parse! DATA_DIR = "./static/data" SKY_DIR = "./static/VirtualSky" TERM = { en: { ...
class User < ActiveRecord::Base MUTEX = Mutex.new has_many :template_repo_providers def self.instance MUTEX.synchronize do User.first || User.create end end def repos template_repo_providers.each_with_object({}) do |p, groups| (groups[p.name] ||= []).concat(p.repos) if p.respond_to...
require 'presstacular-api-ruby' require 'test/unit' require 'digest/md5' class SuppressMemberTest < Test::Unit::TestCase def setup load __FILE__.match('tests/') ? File.expand_path('.') + '/tests/test_vars.rb' : File.expand_path('.') + '/test_vars.rb' # connect to API @mailapi = MAILAPI::Client.new($tes...
# Runs a block of Puppet code within a Choria Data Store Lock # # This requires that you have a lockable data store, something like # consul or etcd # # @example run a set of exclusive tasks # # $ds = { # "type" => "consul", # "timeout" => 120, # "ttl" => 60 # } # # # the code will only execute ...
class AddDateToAppointments < ActiveRecord::Migration def change remove_column :appointments, :time_slot add_column :appointments, :time_slot, :datetime end end
#!/usr/bin/ruby $:.unshift File.join(File.dirname(__FILE__), ".", "..", "lib") require 'PipelineHelper' require 'FCBarcodeFinder' require 'BWAParams' require 'EmailHelper' # Class to email analysis results class ResultMailer def initialize() @bamFile = "" @emailText = "" @emailSubject = "...
require 'httparty' require 'json' require './lib/roadmap.rb' require 'pry' class Kele include HTTParty include Roadmap def initialize(n, p) @base_url = 'https://www.bloc.io/api/v1' response = self.class.post("#{@base_url}/sessions", body: { email: n, password: p }) @auth_token = response['auth_token...
require 'spec_helper' describe Series do it "has a valid factory" do FactoryGirl.create(:series).should be_valid end it "is invalid without a name" do FactoryGirl.build(:series, :name => nil, :begin_date => Date.current).should_not be_valid end it "is invalid without a begin date" do FactoryGi...
module Noel class Symbol attr_reader :name, :type, :writable attr_accessor :scope, :node def initialize(name, type, writable) @name = name @type = type @scope = nil @node = nil @writable = writable end def to_s ...
require 'slack-notifier' module Prpr module Publisher module Adapter class Slack < Base def publish(message) params = { link_names: true } if message.from params[:username] = message.from.login params[:icon_url] = message.from.avatar_url end ...
# frozen_string_literal: true module Dry module Types # A registry with predicate objects from `Dry::Logic::Predicates` # # @api private class PredicateRegistry # @api private attr_reader :predicates # @api private attr_reader :has_predicate KERNEL_RESPOND_TO = ::Kerne...
class Subject < ApplicationRecord has_many :lessons has_many :teachers validates :name, presence: true end
module Greenpeace module Configuration # Represents a doc configuration in a requirement class Doc def initialize(options, key) @doc = options.key?(key) ? validate_doc(options[key]) : 'Undefined' end def to_s @doc end private def validate_doc(doc) ...
class Account::LocationsController < ApplicationController before_action :set_location, only: [:update] def index @personal_locations = Location.where(user: current_user) end end
class ChangeIndicatorValueToInteger < ActiveRecord::Migration def change change_column :indicators, :value, :integer end end
require 'spec_helper' describe Api::V1::OrganizationsController do render_views describe 'GET #documents' do let!(:organization) { create(:organization) } let!(:designation_file) { create(:designation_file, organization: organization) } let!(:memo_file) { create(:memo_file, organization: organization)...
class Investor < ApplicationRecord has_many :investor_attributes has_many :investor_contacts accepts_nested_attributes_for :investor_contacts, allow_destroy: true, reject_if: lambda {|attributes| attributes['name'].blank?} validates :name, presence: true def sectors_primary InvestorAttribute.wher...
require_relative 'feature_spec_helper' describe "host", type: :feature do it "creates a new listing" do user = create :user, role: "default" visit "/login" fill_in "email address", with: user.email fill_in "password", with: user.password click_button "Login" click_link_or_button "My Dashb...
# # Cookbook Name:: mariadb # Resource:: replication # actions :add, :remove, :start, :stop default_action :add # name of the extra conf file, used for .cnf filename attribute :connection_name, kind_of: String, name_attribute: true attribute :host, kind_of: [String, NilClass], default: nil attribute :port, kind_of: [...
# frozen_string_literal: true autoload :Base64, 'base64' autoload :JSON, 'json' module Net autoload :HTTP, 'net/http' end module Utils extend self # Used by #yamlify_command_events MAP_REDUCE_COMMANDS = %w[ map reduce ].freeze # Used by #yamlify_command_events AUTHENTICATION_COMMANDS = %w[ saslStart sas...
module ApplicationHelper def nav_item(path,title,klass = nil, counter = nil, additional_paths = []) additional_paths << path active_class = "current" if additional_paths.map{|v| current_page?(v) }.include?(true) result = "<li class='nav-item #{klass} #{active_class}'>" common_body = content_tag(:span...
class AddAssignmentsCountToProjects < ActiveRecord::Migration def change add_column :projects, :assignments_count, :integer, default: 0 end end
require_relative('../db/sql_runner.rb') class Screening attr_reader :id attr_accessor :film_id, :time, :total_tickets_available def initialize(options) @id = options['id'].to_i @film_id = options['film_id'].to_i @time = options['time'].to_s @total_tickets_available = options['total_tickets_avail...
class AllsalesController < ApplicationController before_action :set_q, only: [:index, :search] before_action :checkrooms_find, only: [:new, :create] def index @allsale = Allsale.with_deleted.where(user_id: current_user.id) @staff = Staff.where(user_id: current_user.id) @guest = Guest.where(user_id:...
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'test_helper.rb')) class StksizeTest < Test::Unit::TestCase include KoiVMRuby test "should push an integer onto the stack representing the number of entries on the stack before the call" do (1..10).each do |x| vm = VM.new ...
class CreateFilaments < ActiveRecord::Migration[6.1] def change create_table :filaments do |t| t.timestamps t.string :filament_brand t.string :filament_color t.string :filament_type, null: false end end end
class ChangeNameSenhaToApartamentoToMatriculaIptu < ActiveRecord::Migration[5.0] def change rename_column :apartamentos, :senha, :matricula_iptu end end
ROM::SQL.migration do change do create_table :iterations do primary_key :id foreign_key :game_id, :games end end end
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user def current_user if session[:password] true else false end end def admin? session[:password] == "kikipat" end end
# encoding: utf-8 require 'logstash/outputs/kusto' require 'logstash/codecs/plain' require 'logstash/event' describe LogStash::Outputs::Kusto do let(:options) { { "path" => "./kusto_tst/%{+YYYY-MM-dd-HH-mm}", "ingest_url" => "https://ingest-sdkse2etest.eastus.kusto.windows.net/", "app_id" => "myid", "ap...
class PatientsController < ApplicationController before_action :set_patient, only: [:show, :edit, :update, :destroy] def index @patients = Patient.all new end def new @patient = Patient.new @titles = Title.all @genders = Patient.genders end def edit @titles = Title.all @gend...
class ChangeAgainNameToTeams < ActiveRecord::Migration[5.1] def change rename_column :teams, :valid, :accepted end end
class Book attr_reader:title def title=(new_title) words = new_title.split first_word = [words[0].capitalize] rest_of_words = words[1..-1].map do |word| short_words = ['a', 'an', 'and', 'if', 'in', 'of', 'on', 'over', 'the'] if short_words.include?(word) word else word...
module Goby # Functions that handle commands on the "world map." module WorldCommand # String literal providing default commands. DEFAULT_COMMANDS = %{ Command Purpose w (↑) a (←) s (↓) d (→) Movement help Show the help menu map Print the map ...
class Hostel < ActiveRecord::Base validates_presence_of :name, :location, :facilities, :rules, :email, :contact, :hostel_type, :picture validates_uniqueness_of :contact, :email mount_uploader :picture, PictureUploader end
class CreateMusicArtists < ActiveRecord::Migration def up create_table :music_artists do |t| t.string :name t.text :tag_list t.integer :author_id t.string :state t.timestamps end end def down drop_table :music_artists end end
class Channel < ActiveRecord::Base attr_accessible :channel_number, :frequency, :name has_many :recording_events end
require 'sinatra/base' require 'sinatra/flash' require_relative './lib/bookmarks.rb' require_relative './lib/comment.rb' require_relative './lib/tag.rb' require_relative './lib/bookmark_tag.rb' require_relative './lib/user' require_relative './database_connection_setup.rb' class BookmarksManager < Sinatra::Base enab...
module ManageIQ::Providers::Amazon::CloudManager::EventParser def self.parse_config_event!(event, event_hash) event_hash[:message] = event["configurationItemDiff"] event_hash[:timestamp] = event["notificationCreationTime"] event_hash[:vm_ems_ref] = parse_vm...
class Task < ApplicationRecord belongs_to :list default_scope { order(:done, :created_at) } validates :title, presence: true end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Kick class KickCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data ...
class PicturesMailer < ApplicationMailer def new_picture_email(user, picture) @user = user @picture = picture mail(to: @user.email, subject: 'New picture for You') end end
require 'rails_helper' describe 'User can sign up', " To start use canmusiccan As an authenticated user I'd like to be able to sign up " do before { visit new_user_registration_path } it 'User tries to sign up' do fill_in 'Email', with: 'user@user.user' fill_in I18n.t('devise.registrations.new.password...
require 'spec_helper' describe ForgotPasswordsController do describe 'POST create' do after { ActionMailer::Base.deliveries.clear } context 'with a known email address' do it 'redirects to the sent reset email page' do sarah = Fabricate(:user, email: 'sarah@example.com') post :create, ...
class AacCategory < ActiveRecord::Base has_many :aac_subcategories def self.list order('name ASC').pluck("name AS category") end end
# DEPRECATED in favour of https://github.com/Homebrew/homebrew-brewdler # # brew-cleanup-installed: uninstall all non-whitelisted Homebrew formulae. # # Useful for maintainers/testers who regularly install lots of formulae # they don't actually use. # # Populate ~/.brew-cleanup-installed with the formulae you want to k...
class BlogPostReadingViewController < UIViewController WEB_VIEW_TAG = 1 def loadView self.view = NSBundle.mainBundle.loadNibNamed('BlogPostReading', owner: self, options: nil).first end def provide_blog_post(blog_post) @blog_post = blog_post end def viewDidLoad super set_screen_title_to(...
# == Schema Information # # Table name: events # # id :integer not null, primary key # title :text # url :string(255) # location :string(255) # start_time :datetime # created_at :datetime not null # updated_at :datetime not null # end_time :datetime # us...
require "json" require "httparty" module Services class Session include HTTParty base_uri "https://expensable-api.herokuapp.com/" def self.login(login_data) options = { headers: { "Content-Type": "application/json" }, body: login_data.to_json } response = post("/login",...
class RFISerializer < ActiveModel::Serializer attributes :id, :rfi_num, :subject, :notes, :due_date, :assigned_user_id, :updated_at, :created_at has_one :asi has_one :user, serializer: SimpleUserSerializer has_one :assigned_user, serializer: SimpleUserSerializer has_many :attachme...
# Remove AUTO_INCREMENTs from tables in the SQL dump to avoid git diff noise namespace :db do namespace :structure do task :dump do path = Rails.root.join('db', 'structure.sql') contents = File.read(path) File.open(path, 'w'){ |file| file.write(contents.gsub(/ AUTO_INCREMENT=\d*/, '')) } end...
class Role < ActiveRecord::Base validates :name, presence: true before_save :normalize_name has_many :users has_many :teams, through: :users, source: :team scope :managers, ->{where name: 'Manager'} scope :developers, ->{where name: 'Developer'} def manager? name =~ /manager/i end private de...
require 'pry' ####################### # CREATE GAME CONSTANTS ####################### SUITS = ["♥", "♠", "♦", "♣"] VALUES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', :A] WIN_NUM = 21 NUM_BREAK = 17 ####################### # CREATE PLAYER OBJECTS ####################### HUMAN = { name: "Your", hand: [], score: ...