text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe Product, type: :model do
describe 'Validations' do
it 'initial test with four fields' do
@category = Category.new(name:"123")
@product = Product.new(
name:"onetwothree",
price_cents:123,
qua... |
require_relative '../spec_helper'
describe "user goes to trip dashboard" do
it "sees the shortest ride time" do
subscription = Subscription.create(account: "subscriber")
city = City.create(name: "San Jose")
station_1 = city.stations.create(name: "Golden Gate", dock_count: 22,
installation_date: '01... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "a user should enter a first name" do
user = User.new
assert !user.save
put.errors.inspect
assert !user.errors[:first_name].empty?
end
test "a user should enter a last name" do
us... |
#!/usr/bin/env ruby
class Node
attr_accessor :name
attr_accessor :parent
def initialize(name, parent)
@parent = parent
@name = name
end
def is_root?
parent == nil
end
def to_s
name
end
# get depth to root
def get_depth
get_parents.size
end
def get_parents
if is_root... |
class Admin < User
def subdomain
'admin'
end
end
# == Schema Information
#
# Table name: users
#
# id :integer(4) not null, primary key
# email :string(100) not null
# encrypted_password :string(40)
# password_salt :string(20)
# confirmation_token :... |
class Friendship < ActiveRecord::Base
belongs_to :requestor, class_name: "User", foreign_key: :friendable_id
belongs_to :acceptor, class_name: "User", foreign_key: :friend_id
end
|
FactoryBot.define do
factory :book do
start_booking { DateTime.current + 2.days }
end_booking { DateTime.current + 10.days }
item { create(:random_item) }
user { create(:random_user) }
end
end
|
require 'rails_helper'
RSpec.describe "providers/index", type: :view do
before(:each) do
assign(:providers, [
Provider.create!(
:name => "Name 1 "
),
Provider.create!(
:name => "Name 2"
)
])
end
it "renders a list of providers" do
render
assert_select "tr#... |
namespace :cars do
task park_single: :environment do
car = Car.unparked.first
raise 'All cars have been parked' unless car.present?
if car.can_park? then car.park!
else raise 'No available parking spaces'
end
end
task unpark_all: :environment do
Car.clear_out!
end
end
|
FactoryBot.define do
factory :educator do
type { "Educator" }
sequence(:email) { |n| "educator-#{n}@example.com" }
password { "password" }
end
end |
##
# BOUQUET Tristan
#
# La classe Joueur est là pour stocker les informations de l'utilisateur et servir d'intermédiaire entre le jeu et les bases de données
# L'objet Joueur dispose de plusieurs méthode qui permettent d'envoyer les nouvelles informations de l'utilisateur après avoir agit dans le jeu
# La classe opère... |
require 'rails_helper'
RSpec.describe EmployeesController, type: :controller do
before(:each) do
login_admin
@job_title = create(:job_title)
@department = create(:department)
@location = create(:location)
@status = create(:status)
end
let(:valid_attributes) {
{
first_name: 'John',... |
module FreeImage
class Boolean
extend FFI::DataConverter
native_type :uint32
def self.to_native(val, ctx)
val == false ? 0 : 1
end
def self.from_native(val, ctx)
val == 0 ? false : true
end
end
end |
# elements located before the minimum, move to the end of the array
# Дан целочисленный массив. Необходимо разместить элементы,
# расположенные до минимального, в конце массива.
array = [1, 0, 6, 7, 8, -9, 12, -2, 2]
before_min = []
array.each do |elem|
before_min << elem
break unless elem != array.min
end
before_m... |
class Round < ActiveRecord::Base
belongs_to :debate
has_many :messages
validates :debate_id, :round_number, presence: true
validate :confirm_both_sides_finished, on: :update
def confirm_both_sides_finished
debate = self.debate
case round_number
when 1
errors.add(:status,"Please wait until ... |
# frozen_string_literal: true
require 'spec_helper'
require 'bolt_spec/conn'
require 'bolt_spec/files'
require 'bolt_spec/integration'
describe "errors gracefully attempting to apply a manifest block" do
include BoltSpec::Conn
include BoltSpec::Integration
let(:modulepath) { File.join(__dir__, '../fixtures/app... |
# The object that acts as a container for the generated output report.
# This object will actually generate the report based on its attribute self.drivers
#
# @attr_accessor drivers [Array<Drivers] an array of Drivers with associated Trips
#
# CONSTANT SPACE [Regexp] a single space " " character
# CONSTANT NEWLINE [Ch... |
p "".empty?
p "content".empty?
# Empty just checks to see if a strings length is equal to zero.
puts
p "".nil?
# Nil doesn't check for 'empty'. It checks for absence of
# a value.
puts
name = "Donald Duck"
last_name = name[100]
p last_name.nil?
puts
last_name = name[3, 4]
p last_name
p last_name.nil?
|
class VideosController < ApplicationController
before_action :check_grants
def create
video = BoatVideo.new(video_params)
respond_to do |format|
if video.save
format.json {render json: video, status: :ok }
else
format.json {render json: {message: 'Не удалось обновить таблицу хара... |
Rails.application.routes.draw do
resources :products
root 'home#index'
end
|
require "spec_helper"
describe "Add to project", reset: false do
collection_name = '15 Minute Stream Flow Data: USGS (FIFE)'
before(:all) do
Capybara.reset_sessions!
load_page :search, q: 'C179003030-ORNL_DAAC'
end
context "in the collection results list" do
it 'displays "Add" buttons for collecti... |
require_relative 'orchestrator'
#________________________________________________________________#
# CREATE ORCHESTRATOR OBJECT #
# (Automatically authenticates) #
# Params: tenant, username, password, [orchestrator url] #
#____________... |
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
... |
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
silence_warnings do
# Minitest is giving warnings that we can ignore for now
require 'rspec/rails'
end
require 'database_cleaner'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |co... |
require 'rails_helper'
require_relative '../support/devise'
RSpec.describe "Assignments", type: :request do
def assign_toables
{
item: create(:item, {
company: @admin.active_company
}),
person: create(:person, {
company: @admin.active_company
}),
location: create(:lo... |
class ReceiversController < ApplicationController
CATEGORY = 'administration'
SUBCATEG = 'tubes'
layout "other_components"
protect_from_forgery :except => [:auto_complete_receiver_name]
def auto_complete_receiver_name
# debugger
pp "receiver name"
@receivers = Receiver.find(:all,
:conditions... |
require_relative "base_address_po"
class BaseOrganisationAddressPage < ::BaseAddressPage
def self.on_page_text
I18n.t "enrollments.states.organisation_address.heading"
end
def prev_page
raise "unimplemented abstract method"
end
def visit_page
prev_page.advance_page
self
end
def advance... |
class TrailsController < ApplicationController
def new
@title = "Make New Trail"
@trail = Trail.new
@trail.status = false
end
def create
@user = current_user
@trail = Trail.new(params[:trail])
@trail.user_id = @user.id
logger.debug "TRAIL!!!!!!!!!!!!create: am i in a trial? #{@t... |
class AddIndexesToUsers < ActiveRecord::Migration
def change
add_index :users, [:published, :approved]
end
end
|
class PageVersion
include ApplicationRecord
field :version, type: Integer, default: 0
field :slug, type: String
field :title, type: String
field :desc, type: String
field :body, type: String
belongs_to :user
belongs_to :page
end
|
class Review < ApplicationRecord
validates :user_id, :listing_id, :review_body, presence: true
belongs_to :author,
foreign_key: :user_id,
class_name: :User
belongs_to :listing,
foreign_key: :listing_id,
class_name: :Listing
end |
module Roglew
module GL
MAP_FLUSH_EXPLICIT_BIT ||= 0x0010
MAP_INVALIDATE_BUFFER_BIT ||= 0x0008
MAP_INVALIDATE_RANGE_BIT ||= 0x0004
MAP_READ_BIT ||= 0x0001
MAP_UNSYNCHRONIZED_BIT ||= 0x0020
MAP_WRITE_BIT ||= 0x0002
end
end
module GL_ARB_map_buffer_range
modu... |
require 'rails_helper'
RSpec.describe Question, :type => :model do
it 'has a valid factory' do
expect(build(:question)).to be_valid
end
it { is_expected.to validate_presence_of :title }
it { is_expected.to validate_presence_of :body }
it { is_expected.to belong_to :user }
it { is_expected.to have_many... |
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :book_name
t.string :book_site
t.string :book_author
t.integer :translator_id
t.string :publishing_house
t.integer :brand_id
t.string :paperback
t.string :series_book_ids
... |
require 'fission-package-builder'
module Fission
module PackageBuilder
module Formatters
class Mail < Fission::Formatter
SOURCE = :package_builder
DESTINATION = :mail
def format(payload)
pkg = payload[:data][:package_builder]
dest_email = payload.fetch(:data, ... |
require 'json'
# An extremely simple key-value store for demo use only.
class JSONDb
include Enumerable
def members
load_data if @@members.length == 0
@@members
end
def initialize(filename)
@filepath = File.join("tmp", filename)
@filename = filename
load_data
end
def load_data
i... |
# frozen_string_literal: true
Hanami.app.register_provider :persistence, namespace: true do
prepare do
require "rom-changeset"
require "rom/core"
require "rom/sql"
configuration = ROM::Configuration.new :sql, target["settings"].database_url
configuration.plugin :sql, relations: :instrumentation... |
require 'rails_helper'
RSpec.describe "branches/edit", :type => :view do
before(:each) do
@branch = assign(:branch, Branch.create!(
:code => "MyString",
:address => "MyText",
:email => "MyString",
:phone => "MyString",
:fax => "MyString"
))
end
it "renders the edit branch f... |
class AnyType
attr_reader :idx
def initialize(idx)
@idx = idx
end
def accept?(_)
true
end
def to_s
(idx + 97).chr
end
end
|
# frozen_string_literal: true
shared_examples "split opinions" do
let!(:opinions) { create_list :opinion, 3, component: current_component }
let!(:target_component) { create :opinion_component, participatory_space: current_component.participatory_space }
include Decidim::ComponentPathHelper
context "when selec... |
class AddFailureColumnsToTransactionReportSync < ActiveRecord::Migration
def self.up
add_column :transaction_report_syncs, :last_error, :text
add_column :transaction_report_syncs, :failed_at, :datetime
end
def self.down
remove_column :transaction_report_syncs, :failed_at
remove_column :transactio... |
require "rails_helper"
RSpec.describe GovukDesignSystem::SelectHelper, type: :helper do
describe "#govukSelect" do
it "returns the correct HTML for the default example" do
html = helper.govukSelect({
id: "sort",
name: "sort",
label: {
text: "Sort by"
},
ite... |
class Category < ActiveRecord::Base
has_many :refund_requests
validates :title, presence: true, uniqueness: true
validates :refund_percentage, numericality: { greater_than: 0,
less_than_or_equal_to: 100 }
end
|
require 'rails_helper'
RSpec.feature "Fill in Claimants Details Page", js: true do
let(:earnings_and_benefits_page) { ET3::Test::EarningsAndBenefitsPage.new }
scenario "correctly will enable user to continue to next page" do
claimants_details_page.load
given_i_am(:company01)
answer_claimants_name_que... |
require 'spec_helper'
describe CoversController do
let(:cvr_original) { 'cvr9781231231230_9781231231230_lg.jpg' }
let(:cvr_new) { 'cvr9781231231230_9781231231230_no_op_100_lg.jpg' }
let(:cvr_feature) { 'cvr9781231231230_9781231231230_auto_enhance_100_lg.jpg' }
let(:cvr_original_2) { 'cvr9781231231231_9781231... |
# frozen_string_literal: true
# Preview all emails at http://localhost:3001/rails/mailers/user
class UserMailerPreview < ActionMailer::Preview
def confirmation
user = ::FactoryBot.create(:user, :unconfirmed)
auth_token = ::AuthToken.create(user: user, token: SecureRandom.uuid)
UserMailer.with(user_id: ... |
class Photo < ActiveRecord::Base
belongs_to :album
mount_uploader :photo, PhotoUploader
validates :photo, presence: true
end
|
# Write a program that prompts the user for their age
# Output to screen: age in days, hours, minutes and seconds
# Not using Methods
# puts "What's your age?"
# my_age = gets.chomp.to_i
# my_days = my_age * 365
# my_hours = my_days * 24
# my_minutes = my_hours * 60
# my_seconds = my_minutes * 60
# puts "The user ... |
require 'pry'
values = {
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'f' => 6,
'g' => 7,
'h' => 8,
'i' => 9,
'j' => 10,
'k' => 11,
'l' => 12,
'm' => 13,
... |
require 'queue'
describe Queue do
let(:queue) { Queue.new }
it 'starts out empty' do
expect(queue.length).to eq 0
expect { queue.first }.to raise_error 'index out of bounds'
end
it 'can store more than 8 items' do
10.times { |i| queue.enqueue(i) }
expect(queue.length).to eq 10
end
descri... |
require 'faker'
FactoryGirl.define do
factory :book do |f|
f.cover_image { Faker::Avatar.image }
f.create_at { Faker::Time.between(DateTime.now - 365, DateTime.now) }
f.name { Faker::Book.title }
f.description { Faker::Lorem.paragraphs(1) }
end
end
|
# encoding: utf-8
#
# Базовый класс «Запись» — здесь мы определим основные методы и свойства,
# общие для всех типов записей.
class Post
# Метод post_types класса Post, возвращает всех известных ему детей класса
# Post в виде массива классов.
#
# Обратите внимание, что класс, объявленный с self. перед название ... |
require 'json'
require 'base64'
module Starfish
class ServiceManifest
class Process
attr_reader :name, :command
def initialize(name:, command:)
@name = name
@command = command
end
end
def initialize(project, branch:, github_token:)
@project = project
@branc... |
class CommandsController < ApplicationController
def index
# TODO: check ACL - SysAdmins only here
@commands = Command.all
end
# Define new commands
def new
# TODO: check ACL - SysAdmins only here
@command = Command.new(params[:command])
render :edit
end
# Create command entry. On s... |
require "rails_helper"
RSpec.describe Api::V1::CapesController, type: :controller do
let!(:first_user) { User.create(
first_name: "Bobby",
last_name: "Wick",
email: "bobby@example.com",
password: "password",
role: "member"
) }
let!(:first_cape) { Cape.create(
user: first_user,
name: ... |
module Dexter
class JsonLogParser < LogParser
FIRST_LINE_REGEX = /\A.+/
def perform
@logfile.each_line do |line|
row = JSON.parse(line.chomp)
if (m = REGEX.match(row["message"]))
# replace first line with match
# needed for multiline queries
active_line = r... |
require 'spec_helper'
if os[:family] == 'redhat'
describe package 'openssh-server' do
it { is_expected.to be_installed }
end
describe service 'sshd' do
it { is_expected.to be_enabled }
it { is_expected.to be_running }
end
describe port 22 do
it { is_expected.to be_listening }
end
descr... |
if ARGV.length < 1
puts "Usage: ruby reverse-string.rb [string]"
else
string = ARGV[0]
puts string.reverse
end |
def profile(block_description, &block)
run_me = true # bey default profile test will not run unless set to true
if run_me == true
start_time = Time.new # sets the time now
block.call # call the block you will write after 'do' in the process to be tested
d... |
class AddPaymentType < ActiveRecord::Migration[6.0]
def change
add_column :holders, :payment_method, :string, default: 'DEBITO_AUTOMATICO'
add_column :holders, :cuil, :string, default: '00000000000'
add_column :holders, :cbu, :string
add_column :holders, :ccard_number, :string
add_column :holders,... |
class Team < ApplicationRecord
belongs_to :league
has_many :team_seasons
has_many :team_home_seasons, through: :team_seasons
has_many :team_away_seasons, through: :team_seasons
has_many :players
has_many :player_seasons, through: :players
def shortened_team_name
case self.name
when "Arsenal"
... |
class ContactsController < ApplicationController
def create
@contact = Contact.new(contact_params)
if @contact.valid?
ContactEmailJob.perform_async(@contact)
flash[:notice] = "Message sent successfully"
redirect_to root_path
else
render "welcome/home"
end
end
private
de... |
class User < ActiveRecord::Base
has_secure_password has_many :workouts
end
|
class Notifier < ActionMailer::Base
default from: "nathan@passportfitnessdc.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.notifier.subscription_confirmation.subject
#
def subscription_confirmation(potential_member)
attachments.inline['passp... |
require 'spec_helper'
describe Group do
let(:group) { FactoryGirl.build :group }
# factory
it { should have_a_valid_factory }
# associations
it { should have_many(:group_memberships).dependent(:destroy) }
it { should have_many(:users).through(:group_memberships) }
# validations
# - name
it {... |
class OffersController < ApplicationController
skip_before_action :authenticate_user!, only: [ :index ]
def index
@offers = Offer.all
@redemption = Redemption.new
end
end
|
require 'rails_helper'
RSpec.describe 'Tokens', type: :request do
it 'Returns http succes' do
post '/tokens'
expect(response).to have_http_status(:success)
end
it 'Deletes Token' do
str = SecureRandom.hex
token = Token.create(token: str)
delete "/tokens/#{token.id}", params: { token: str, to... |
require 'nokogiri'
require 'fastlane/action'
require_relative '../helper/clang_tools_helper'
module Fastlane
module Actions
class ClangAnalyzerAction < Action
def self.run(params)
# Parse CLI parameters
analyze_params, err_msg = prepare(params)
if analyze_params.nil?
puts... |
require 'Win32API' # For getting character input
require 'colorize' # For changing color of text
module OutputSpacing # Different space sizes
NO_SPACING = 0
NEXT_LINE_SPACING = 1
ONE_LINE_SPACING = 2
DEFAULT_SPACING = NEXT_LINE_SPACING
end
module TypingSpeed
SLOW = 0.09
NORMAL = 0.05
FAST = 0.001
end
class IO... |
require 'minitest/autorun'
require './board'
class TestBoard < Minitest::Test
def setup
@board = Board.new
end
def test_that_there_are_sixty_four_squares
assert_equal 64, @board.square_count
end
def test_that_a_new_board_has_no_queens_on_it
assert @board.has_no_queens?
end
def test_that_th... |
require 'deck'
describe 'Deck' do
let(:deck) { Deck.new }
describe '#initialize' do
it "creates a deck of 52 cards " do
expect(deck.current_deck.length).to eq(52)
end
it 'contains 13 spades' do
suite_arr = deck.current_deck.select {|card| card.suite == "Spade"}
expect(suite_arr.length).to... |
=begin
- input: string
- output: string with alternating capitalization scheme. Chars other than "a-zA-Z" left alone.
- model the problem:
- string[0] = upcase
- string[1] = downcase
- string[2] = upcase
- ...
-generally:
- even numbered idx is upper case, odd is lower case
Algorithm:
- convert strin... |
class Tag < ApplicationRecord
has_and_belongs_to_many :notes, optional: true
end
|
require 'yaml'
require_relative '../classes/author.rb'
module OopLibrary
def self.generateAuthorsData
authors = [
Author.new("Miguel de Cervantes", "1547-1616"),
Author.new("Marcel Proust", "1871-1922"),
Author.new("James Joyce", "1882-1941"),
Author.new("Homer", "9th century BC - 8th century BC"),
A... |
# frozen_string_literal: true
RSpec.describe 'Mod Withdraw Request', type: :request do
include_context 'with branch location'
include_context 'with user token'
include_context 'with json response'
include_context 'with event'
include_context 'with mods'
let(:mod) { mod_a_1 }
let(:attendee) { build(:even... |
class Vote < ActiveRecord::Base
belongs_to :topic
has_many :vote_user_agents
has_many :vote_options
has_many :users, through: :vote_user_agents
validates :vote_options, presence: true
end
|
class Region < ActiveRecord::Base
belongs_to :city
has_many :playgrounds
validates :name, :city_id, :presence => true
end
|
module Result
#
#指定されたパラメータの内容でJSONデータを生成して返す
#_success_ :: 処理結果(true:成功、false:失敗)をBoolean型で指定します
#_message_ :: messageデータに渡すメッセージを指定します
#_result_ :: resultというキーで生成されるデータが表示されます,結果情報ハッシュデータを指定します
#
#戻り値:: JSONデータ
#
def result_for_json(success, message, result)
ret = {
:success =... |
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :statuses
has_many :follower_connections, class_name: 'Connection', foreign_key: 'leader_id'
has_many :followers, through: :follower_connections, source: :fo... |
class StoresController < ApplicationController
before_filter :authenticate_user!
before_filter :assign_company
before_filter :check_company_has_no_store_already
def new
end
def create
if @company.update_attributes(company_params)
provision_store_for(@company)
redirect_to dashboards_path,... |
#!/usr/bin/env ruby
module XCodeRun# {{{
def self.run args
opts = RuntimeFlags.new.hashify_args(args)
runner = Runner.new(opts.args_hash)
runner.run
end
class Runner# {{{
def initialize options = {}
@opts = options
@xcode_args = filter_xcode options
@tmp_file = File.new("#{optio... |
class Player < ApplicationRecord
has_many :bets
validates :name, :last_name, presence: true, length: { minimum: 4 }
include ColorFunction
#Funcion que busca players con dinero
scope :player_with_cash, -> { where("cash > ?", 0) }
#Si cash de Player es igual a 1000 va All in
def self.amount_player_bet ... |
require "rubygems"
$: << File.join(File.dirname(__FILE__), "lib")
require "cabin"
require "cabin/mixins/CAPSLOCK"
require "logger"
# instance method
class Derp
def logger
logger = Cabin::Channel.new
logger.extend(Cabin::Mixins::CAPSLOCK)
rubylog = Logger.new('/tmp/sensu.log')
logger.subscribe(rubylo... |
require( 'minitest/autorun' )
require( 'minitest/rg')
require_relative( '../bear.rb' )
require_relative( '../fish.rb' )
require_relative( '../river.rb' )
class TestBear < Minitest::Test
def setup
@bear = Bear.new("Bob","Polar")
@fish_1 = Fish.new("Nemo")
@fish_2 = Fish.new("Kirk")
@river = River.new... |
require File.dirname(__FILE__) + '/../../spec_helper'
describe Admin::UsersController do
fixtures :users
before(:each) do
login_as :quentin
stub!(:reset_session)
@blog = mock_model(Blog)
@user = mock_model(User, :destroy => true)
@users = mock("Array of users", :to_xml => "XML")
Blog.st... |
require 'will_paginate/array'
class EnumMastersController < ApplicationController
before_action :set_enum_master, only: [:show, :update, :destroy]
# GET /enum_masters
def index
if params[:category_name].present?
page_count = params[:per_page].present? ? params[:per_page] : "7"
page = params[... |
class WidgetsController < ApplicationController
include WidgetsHelper
def index
@widgets = Widget.find(:all, :order => "row")
@widgets.each do |widget|
send(widget.setup)
end
respond_to do |format|
format.html
format.xml { render :xml => @widgets }
end
end
def show
... |
class AddExistToAmbulance < ActiveRecord::Migration
def change
add_column :ambulances, :exist, :integer
end
end
|
module Puppet::Parser::Functions
newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-EOT
EOT
) do |args|
raise(Puppet::ParseError, "load_module_metadata(): Wrong number of arguments, expects one") unless args.size == 1
mod = args[0]
module_path = function_get_module_path([mod])
metadat... |
class Namespace < ActiveRecord::Base
belongs_to :parent, class_name: 'Namespace', inverse_of: :children
has_many :children, class_name: 'Namespace', foreign_key: :parent_id, inverse_of: :parent
has_and_belongs_to_many :predicates
def self.get_root
Frest::RootNamespace
end
def add_child id = SecureR... |
class AddLibraryIdToPart < ActiveRecord::Migration
def change
add_column :parts, :library_id, :integer
end
end
|
# It's time-y wime-y and wibbly wobbley. Abracadabra.
# @author Richard Harrah
module Timewizard
# Version of this gem.
# @return [String] current version
VERSION = '0.3.9'
end
|
require 'test/unit'
class ComparingObjectsTest < Test::Unit::TestCase
def test_1
# il valore è uguale
p 1 == 1
p 1 == 1.0
end
def test_2
# stesso tipo di base (NUMERIC) e stesso valore
p 1 === 1.0
end
def test_3
# stesso tipo e stesso valore
p 1.eql?(1.0) # integer non è float
... |
class DeleteSwiftypeDocument
attr_reader :post_id
def initialize(post_id)
@post_id = post_id
end
def run
client = Swiftype::Client.new
client.destroy_document(ENV['SWIFTYPE_ENGINE_SLUG'], post.model_name.singular, post_id) #Post.model_name.singular can be replaced with a document type from your engi... |
module ParameterNormalizer
def self.normalize(value)
value.kind_of?(Hash) ? normalize_references(value) : value
end
private
def self.normalize_references(hash)
hash.inject({}) do |normalized, (key, value)|
case value
when Hash
if ref = value.delete('$ref')
normaliz... |
#!/usr/bin/env ruby
require "base64"
require "open-uri"
def loop_base64_decoder()
pattern = /(?<=")(.+)(?=")/
loop do
if !File.exist?('processed_apply.rb') then
file_name = "apply.rb"
else
file_name = "processed_apply.rb"
end
base64 = ""
File.open(file_name).each_line do |line|
string = line[pa... |
class ParseLogsJob
include Sidekiq::Worker
require 'net/http'
require 'open-uri'
require 'json'
def perform(*args)
file = ENV.fetch('LOG_FILE_PATH')
return unless File.exists?(file)
f = File.open(file, 'r:ISO-8859-1:UTF-8')
# Check log timestamp against last db entry time
last_log_time = ... |
require_relative '../../lib/example'
RSpec.describe Example, '#temperature' do
context "checking temperature" do
it "checks temp" do
my_example = Example.new
total = my_example.addNumbers(20, 30)
expect(total).to equal(50)
volume = my_example.calculateVolume(20, 50, 8)
expect(volu... |
class FieldSelector < ApplicationService
def self.select_fields(object_attrs, fields)
selected_attrs = {}
fields.each do |field|
is_negation = field[0] == '-'
field = field[1..-1] if is_negation
if field == '*'
selected_attrs = deep_clone_hash(object_attrs)
elsif field.include?... |
module SearchRebuilder
extend ActiveSupport::Concern
module ClassMethods
def rebuild model=nil
return rebuild_all if model.nil?
where(searchable_type: model.to_s).destroy_all
model.find_each { |record| record.sync_search_document }
end
def rebuild_all
self::VALID_SEARCHABLE_TY... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.