hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
acfd9dab51a7c02cffd95f3b2cbee44739c12495 | 747 | cask "bandage" do
version "0.8.1"
sha256 "13e90e5824b61bd4abe62afa8785a28627714bf7a3d4dad3edb4b8f9854d3b6d"
url "https://github.com/rrwick/Bandage/releases/download/v#{version}/Bandage_Mac_v#{version.dots_to_underscores}.zip",
verified: "github.com/rrwick/Bandage/"
name "Bandage"
desc "Bioinformatics Application for Navigating De novo Assembly Graphs"
homepage "https://rrwick.github.io/Bandage/"
app "Bandage.app"
# shim script (https://github.com/Homebrew/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/bandage.wrapper.sh"
binary shimscript, target: "bandage"
preflight do
IO.write shimscript, <<~EOS
#!/bin/sh
exec '#{appdir}/Bandage.app/Contents/MacOS/Bandage' "$@"
EOS
end
end
| 32.478261 | 120 | 0.729585 |
5d4a8ffe0a78b86d7818ded73301369372f0489f | 8,972 | #! /usr/bin/env ruby
# Copyright 2014 Frank Breedijk, Zate Berg, Trelor, Alex Smirnoff
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'optparse'
require 'uri'
require 'net/https'
require 'rexml/document'
include REXML
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Nessus Wrapper for Seccubus v2\nUsage: ./nivil.rb [options] "
opts.on('-u', '--user USER', 'Username to login to Nessus') do |username|
options[:username] = username
end
opts.on('-p', '--password PASSWD', 'Password to login to Nessus') do |passwd|
options[:passwd] = passwd
end
opts.on('-s', '--server SERVER', 'Server name (localhost is default)') do |server|
options[:server] = server
end
opts.on('-l', '--policy POLICY', 'Policy to scan with' ) do |policy|
options[:policy] = policy
end
opts.on('-t', '--target TARGET', 'Target to scan') do |target|
options[:target] = target
end
opts.on('-n', '--name NAME', 'Scan name') do |name|
options[:name] = name
end
opts.on('-h', '--help', 'Display help') do
puts opts
exit
end
opts.on('-f', '--file INFILE', 'File of hosts to scan') do |file|
options[:file] = file
end
opts.on('--show-policies', 'Shows Server Policies') do
options[:showpol] = true
end
opts.on('--show-reports', 'Shows Server Reports') do
options[:showrpt] = true
end
opts.on('-g', '--get-report RPTID', 'Download Report in Nessus V2 format.') do |rpt|
options[:rptid] = rpt
end
opts.on('-o', '--out FILE', 'Optional filename to output to.') do |out|
options[:out] = out
end
opts.on('-c', '--check', 'Checks the status of a report supplied with -g') do
options[:check] = true
end
opts.on('--port PORT', 'Optional portnumber to connect to Nessus. Defaults to 8834.') do |port|
options[:port] = port || "8834"
end
case ARGV.length
when 0
puts opts
exit
end
@fopts = opts
end
optparse.parse!
if !options[:port]
options[:port] = "8834"
end
if !options[:cfile]
if !(options[:username] and options[:passwd] and options[:server])
puts
puts("**[FAIL]** Missing Arguments")
puts
puts @fopts
exit
end
end
# Our Connection Class
class NessusConnection
def initialize(user, pass, server, port)
@username = user
@passwd = pass
@server = server
@nurl = "https://#{@server}:" + port + "/"
# @nurl = "https://#{@server}:8834/"
@token = nil
@status = nil
end
def connect(uri, post_data)
url = URI.parse(@nurl + uri)
request = Net::HTTP::Post.new( url.path )
request.set_form_data(post_data)
if not defined? @https
@https = Net::HTTP.new( url.host, url.port )
@https.use_ssl = true
@https.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
begin
res = @https.request(request)
rescue
puts("error connecting to server: #{@nurl} with URI: #{uri}")
exit
end
return res.body
end
end
def show_policy(options)
uri = "scan/list"
post_data = { "token" => @token }
stuff = @n.connect(uri, post_data)
docxml = REXML::Document.new(stuff)
policies=Array.new
docxml.elements.each('/reply/contents/policies/policies/policy') { |policy|
entry=Hash.new
entry['id']=policy.elements['policyID'].text
entry['name']=policy.elements['policyName'].text
if policy.elements['policyComments'] == nil
entry['comment']=" "
else
entry['comment']=policy.elements['policyComments'].text
end
policies.push(entry)
}
puts("ID\tName")
policies.each do |policy|
puts("#{policy['id']}\t#{policy['name']}")
end
end
def login(options)
uri = "login"
post_data = { "login" => options[:username], "password" => options[:passwd] }
#p post_data
stuff = @n.connect(uri, post_data)
docxml = REXML::Document.new(stuff)
if docxml == ''
@token=''
else
begin
@status = docxml.root.elements['status'].text
@token = docxml.root.elements['contents'].elements['token'].text
@name = docxml.root.elements['contents'].elements['user'].elements['name'].text
@admin = docxml.root.elements['contents'].elements['user'].elements['admin'].text
rescue
puts "error #{@status}"
sleep 60
exit
end
end
end
def logout(options)
uri = "logout"
post_data = { "token" => @token }
stuff = @n.connect(uri, post_data)
end
def show_reports(options)
uri = "report/list"
post_data = { "token" => @token }
stuff = @n.connect(uri, post_data)
docxml = REXML::Document.new(stuff)
reports=Array.new
docxml.elements.each('/reply/contents/reports/report') {|report|
entry=Hash.new
entry['id']=report.elements['name'].text if report.elements['name']
entry['name']=report.elements['readableName'].text if report.elements['readableName']
entry['status']=report.elements['status'].text if report.elements['status']
entry['timestamp']=report.elements['timestamp'].text if report.elements['timestamp']
reports.push(entry)
}
puts("ID\tName")
reports.sort! { |a,b| b['timestamp'] <=> a['timestamp'] }
reports.each do |report|
t = Time.at(report['timestamp'].to_i)
puts("#{report['id']}\t#{report['name']}\t\t#{t.strftime("%H:%M %b %d %Y")}")
end
end
def get_report(options)
status = nil
uri = "scan/list"
post_data = { "token" => @token }
stuff = @n.connect(uri, post_data)
begin
docxml = REXML::Document.new(stuff)
docxml.elements.each('/reply/contents/scans/scanList/scan') {|scan|
if scan.elements['uuid'].text == options[:rptid]
@status = scan.elements['status'].text
@now = scan.elements['completion_current'].text
@total = scan.elements['completion_total'].text
end
}
rescue
# puts ("Warning: cannot get scan status")
end
puts("#{@status}|#{@now}|#{@total}")
if @status != "OK"
#puts("Scan it not completed, cannot download")
exit
end
stuff = nil
uri = "file/report/download"
post_data = { "token" => @token, "report" => options[:rptid] }
stuff = @n.connect(uri, post_data)
if options[:rptid]
if options[:out]
File.open("#{options[:out]}.nessus", 'w') {|f| f.write(stuff) }
exit
else
File.open("#{options[:rptid]}.nessus", 'w') {|f| f.write(stuff) }
exit
end
else
puts("Error: No Report Specified")
end
end
@n = NessusConnection.new(options[:username], options[:passwd], options[:server], options[:port])
if options[:showpol]
login(options)
show_policy(options)
logout(options)
exit
end
if options[:showrpt]
login(options)
show_reports(options)
logout(options)
exit
end
if options[:rptid]
login(options)
get_report(options)
logout(options)
exit
end
login(options)
##verify policy
uri = "scan/list"
pid = options[:policy]
post_data = { "token" => @token }
stuff = @n.connect(uri, post_data)
docxml = REXML::Document.new(stuff)
policies=Array.new
docxml.elements.each('/reply/contents/policies/policies/policy') { |policy|
entry=Hash.new
entry['id']=policy.elements['policyID'].text
entry['name']=policy.elements['policyName'].text
if policy.elements['policyComments'] == nil
entry['comment']=" "
else
entry['comment']=policy.elements['policyComments'].text
end
policies.push(entry)
}
match = nil
policies.each {|p|
if p['id'].to_i == pid.to_i
match = pid
next
end
}
if match.nil?
puts("No Matching Policy ID: #{pid}")
exit
end
tgts = ""
if options[:file]
File.open("#{options[:file]}", "r") do |tgtf|
while (line = tgtf.gets)
tgts << line
tgts << ","
end
end
tgts.chop!
else
tgts = options[:target]
end
#start scan
uri = "scan/new"
post_data = { "token" => @token, "policy_id" => options[:policy], "scan_name" => options[:name], "target" => tgts }
stuff = @n.connect(uri, post_data)
docxml = REXML::Document.new(stuff)
uuid=docxml.root.elements['contents'].elements['scan'].elements['uuid'].text
puts("#{uuid}")
| 27.606154 | 115 | 0.604882 |
281de5bdc28360d3e637d1c30eb46a2f24330c4b | 2,221 | class Caddy < Formula
desc "Powerful, enterprise-ready, open source web server with automatic HTTPS"
homepage "https://caddyserver.com/"
url "https://github.com/caddyserver/caddy/archive/v2.4.4.tar.gz"
sha256 "0ea7b65406c77b2ce88cdf496e82b70838c78305659fa5c891ef004dfabcc17a"
license "Apache-2.0"
head "https://github.com/caddyserver/caddy.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "1f4dd7deb1ee1c337d8bee3e91c522ada5f86bd677113079ff6ce087c915e581"
sha256 cellar: :any_skip_relocation, big_sur: "931f9b62c50c28f28b930bdfd830323834260ad397d78bbdf3609d220dc60bf3"
sha256 cellar: :any_skip_relocation, catalina: "931f9b62c50c28f28b930bdfd830323834260ad397d78bbdf3609d220dc60bf3"
sha256 cellar: :any_skip_relocation, mojave: "931f9b62c50c28f28b930bdfd830323834260ad397d78bbdf3609d220dc60bf3"
sha256 cellar: :any_skip_relocation, x86_64_linux: "8c0bef614ad308b3828c08b74e04f5605a4add5d85904443c13f632ad9007908"
end
depends_on "go" => :build
resource "xcaddy" do
url "https://github.com/caddyserver/xcaddy/archive/v0.1.9.tar.gz"
sha256 "399880f59bf093394088cf2d802b19e666377aea563b7ada5001624c489b62c9"
end
def install
revision = build.head? ? version.commit : "v#{version}"
resource("xcaddy").stage do
system "go", "run", "cmd/xcaddy/main.go", "build", revision, "--output", bin/"caddy"
end
end
service do
run [opt_bin/"caddy", "run", "--config", etc/"Caddyfile"]
keep_alive true
error_log_path var/"log/caddy.log"
log_path var/"log/caddy.log"
end
test do
port1 = free_port
port2 = free_port
(testpath/"Caddyfile").write <<~EOS
{
admin 127.0.0.1:#{port1}
}
http://127.0.0.1:#{port2} {
respond "Hello, Caddy!"
}
EOS
fork do
exec bin/"caddy", "run", "--config", testpath/"Caddyfile"
end
sleep 2
assert_match "\":#{port2}\"",
shell_output("curl -s http://127.0.0.1:#{port1}/config/apps/http/servers/srv0/listen/0")
assert_match "Hello, Caddy!", shell_output("curl -s http://127.0.0.1:#{port2}")
assert_match version.to_s, shell_output("#{bin}/caddy version")
end
end
| 34.169231 | 122 | 0.70824 |
5d11646c85f98539921a513e72b6fd81bbb27768 | 7,492 | # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# A base request type containing common criteria for searching for resources.
# This class has direct subclasses. If you are using this class as input to a service operations then you should favor using a subclass over the base class
class ResourceSearch::Models::SearchDetails
MATCHING_CONTEXT_TYPE_ENUM = [
MATCHING_CONTEXT_TYPE_NONE = 'NONE'.freeze,
MATCHING_CONTEXT_TYPE_HIGHLIGHTS = 'HIGHLIGHTS'.freeze
].freeze
# **[Required]** The type of SearchDetails, whether `FreeText` or `Structured`.
# @return [String]
attr_accessor :type
# The type of matching context returned in the response. If you specify `HIGHLIGHTS`, then the service will highlight fragments in its response. (See ResourceSummary.searchContext and SearchContext for more information.) The default setting is `NONE`.
#
# @return [String]
attr_reader :matching_context_type
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'type': :'type',
'matching_context_type': :'matchingContextType'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'type': :'String',
'matching_context_type': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# Given the hash representation of a subtype of this class,
# use the info in the hash to return the class of the subtype.
def self.get_subtype(object_hash)
type = object_hash[:'type'] # rubocop:disable Style/SymbolLiteral
return 'OCI::ResourceSearch::Models::StructuredSearchDetails' if type == 'Structured'
return 'OCI::ResourceSearch::Models::FreeTextSearchDetails' if type == 'FreeText'
# TODO: Log a warning when the subtype is not found.
'OCI::ResourceSearch::Models::SearchDetails'
end
# rubocop:enable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :type The value to assign to the {#type} property
# @option attributes [String] :matching_context_type The value to assign to the {#matching_context_type} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.type = attributes[:'type'] if attributes[:'type']
self.matching_context_type = attributes[:'matchingContextType'] if attributes[:'matchingContextType']
raise 'You cannot provide both :matchingContextType and :matching_context_type' if attributes.key?(:'matchingContextType') && attributes.key?(:'matching_context_type')
self.matching_context_type = attributes[:'matching_context_type'] if attributes[:'matching_context_type']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] matching_context_type Object to be assigned
def matching_context_type=(matching_context_type)
raise "Invalid value for 'matching_context_type': this must be one of the values in MATCHING_CONTEXT_TYPE_ENUM." if matching_context_type && !MATCHING_CONTEXT_TYPE_ENUM.include?(matching_context_type)
@matching_context_type = matching_context_type
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
type == other.type &&
matching_context_type == other.matching_context_type
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[type, matching_context_type].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 38.420513 | 255 | 0.696343 |
abaf5ec0af46027c57bb7ed9a10f15901f3f3b24 | 39 | # typed: strong
module UsersHelper
end
| 9.75 | 18 | 0.794872 |
03f01d2e5c0c0595c72691743a7b664f527245dc | 107 | Fabricator :link do
name { Faker::Company.name }
url { "http://#{Faker::Internet.domain_name}" }
end | 26.75 | 51 | 0.654206 |
212bbf564912da5d53a86c5ec59b430782561e1a | 5,285 | require 'spec_helper'
module ROF::Translators
describe "translate CSV" do
it "requires rows to have an owner and type" do
s = %q{type,owner
Work,
}
expect{CsvToRof.call(s)}.to raise_error(ROF::Translators::CsvToRof::MissingOwnerOrType)
end
it "deocdes the access field into rights" do
s = %q{type,owner,access
Work,user1,"private;edit=user2,user3"
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1", "user2", "user3"]},
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n"
}])
end
it "puts metadata into substructure" do
s = %q{type,owner,dc:title,foaf:name
Work,user1,"Q, A Letter",Jane Smith|Zander
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1"]},
"metadata" => {
"@context" => ROF::RdfContext,
"dc:title" => "Q, A Letter",
"foaf:name" => ["Jane Smith", "Zander"]},
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n"
}])
end
it "renames curate_id to pid" do
s = %q{type,owner,curate_id
Work,user1,abcdefg
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"pid" => "abcdefg",
"rights" => {"edit" => ["user1"]},
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n"
}])
end
it "strips space around pipes" do
s = %q{type,owner,dc:title,foaf:name
Work,user1,"Q, A Letter",Jane Smith | Zander
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1"]},
"metadata" => {
"@context" => ROF::RdfContext,
"dc:title" => "Q, A Letter",
"foaf:name" => ["Jane Smith", "Zander"]},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n",
"properties-meta" => {"mime-type" => "text/xml"}
}])
end
it "handles follow-on generic files" do
s = %q{type,owner,dc:title,files
Work,user1,"Q, A Letter",thumb
+,user1,,extra file.txt
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1"]},
"metadata" => {
"@context" => ROF::RdfContext,
"dc:title" => "Q, A Letter"},
"files" => [
"thumb",
{
"type" => "+",
"owner" => "user1",
"files" => ["extra file.txt"],
"rights" => {"edit" => ["user1"]}
}],
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n"
}])
end
it "raises an error if a follow-on file has no preceeding work" do
s = %q{type,owner,dc:title,files
+,user1,,extra file.txt
}
expect {CsvToRof.call(s)}.to raise_error(ROF::Translators::CsvToRof::NoPriorWork)
end
it "decodes the double caret encoding correctly" do
s = %q{type,owner,dc:title,dc:contributor
Work,user1,"a title","^^dc:contributor Jane Doe^^ms:role Committee Member"
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1"]},
"metadata" => {
"dc:title" => "a title",
"dc:contributor" => {
"dc:contributor" => "Jane Doe",
"ms:role" => "Committee Member"
},
"@context" => ROF::RdfContext
},
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n"
}])
end
it "decodes multiple values of double carets correctly" do
s = %q{type,owner,dc:title,dc:contributor
Work,user1,"a title","^^name Jane Doe^^ms:role Committee Member|^^name Hugo Easton Whitman, III^^ms:role Research Advisor"
}
rof = CsvToRof.call(s)
expect(rof).to eq([{
"type" => "Work",
"owner" => "user1",
"rights" => {"edit" => ["user1"]},
"properties-meta" => {"mime-type" => "text/xml"},
"properties" => "<fields><depositor>batch_ingest</depositor>\n<owner>user1</owner>\n</fields>\n",
"metadata" => {
"dc:title" => "a title",
"dc:contributor" => [{
"name" => "Jane Doe",
"ms:role" => "Committee Member"
},{
"name" => "Hugo Easton Whitman, III",
"ms:role" => "Research Advisor"
}],
"@context" => ROF::RdfContext
}
}])
end
end
end
| 33.238994 | 128 | 0.508231 |
1c01d9bf7f6cf2aec04a0483fbfd42ac96335e9a | 1,433 | module PageObjects
module Pages
module Admin
module Cases
class NewFOIPage < PageObjects::Pages::Base
set_url '/admin/cases/new/foi'
sections :notices, '.notice-summary' do
element :heading, '.notice-summary-heading'
end
section :page_heading,
PageObjects::Sections::PageHeadingSection, '.page-heading'
element :case_type_foi_standard, '#case_foi_type_casefoistandard'
element :full_name, '#case_foi_name'
element :email, '#case_foi_email'
element :address, '#case_foi_postal_address'
element :type_of_requester, :xpath,
'//fieldset[contains(.,"Type of requester")]'
element :subject, '#case_foi_subject'
element :full_request, '#case_foi_message'
element :received_date, '#case_foi_received_date'
element :created_at, '#case_foi_created_at'
element :flag_for_disclosure_specialists,
'#case_foi_flagged_for_disclosure_specialist_clearance'
element :flag_for_press_office,
'#case_foi_flagged_for_press_office_clearance'
element :flag_for_private_office,
'#case_foi_flagged_for_private_office_clearance'
element :target_state, '#case_foi_target_state'
element :submit_button, '.button'
end
end
end
end
end
| 34.119048 | 76 | 0.636427 |
79c475bbc898f371482144480158bcc10478907d | 111 | require 'resque/tasks'
ENV["QUEUE"] = "*"
task "resque:setup" => :environment
task "jobs:work" => "resque:work" | 27.75 | 35 | 0.666667 |
1cb13a362d95b51b0ae4eb88a2675a054e318ced | 928 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "jekyll-minimagick/version"
Gem::Specification.new do |s|
s.name = "jekyll-minimagick"
s.version = Jekyll::Minimagick::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Roger López"]
s.email = ["[email protected]"]
s.homepage = "http://github.com/zroger/jekyll-minimagick"
s.summary = %q{MiniMagick integration for Jekyll}
s.description = %q{Use MiniMagick to crop and resize images in your Jekyll project.}
s.rubyforge_project = "jekyll-minimagick"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_runtime_dependency('jekyll', [">= 0.10.0"])
s.add_runtime_dependency('mini_magick', [">= 3.3"])
end
| 37.12 | 86 | 0.639009 |
6a5e2c3978815d111b1e889c14e5a1e859def844 | 1,556 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "link_to/version"
Gem::Specification.new do |spec|
spec.name = "link_to"
spec.version = LinkTo::VERSION
spec.authors = ["yamitake"]
spec.email = ["[email protected]"]
spec.summary = %q{Make the link_to method easier to use}
spec.description = %q{Make the link_to method easier to use. We provide a method group suitable for actual development, such as attaching `active` to the class attribute common to web applications.}
spec.homepage = "https://github.com/yamitake/link_to"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rails", [">= 3.2.11"]
spec.add_development_dependency "rspec", "~> 3.0"
end
| 40.947368 | 202 | 0.67545 |
61ca5206ff721e5553ecb2c70cad059bd72fcb23 | 120 | class Current < ActiveSupport::CurrentAttributes
# makes Current.user accessible in view files.
attribute :user
end
| 24 | 48 | 0.791667 |
e834f73d845f409d02670281c129865cc26391b7 | 525 | require "test_helpers"
class TestTags < RSpecQTest
def test_inclusion_filter
queue = exec_build("tagged_suite", "--tag=slow")
assert_processed_jobs [
"./spec/tagged_spec.rb",
], queue
assert_equal 1, queue.example_count
end
def test_exclusion_filter
queue = exec_build("tagged_suite", "--tag=~slow")
assert_equal 2, queue.example_count
end
def test_mixed_filter
queue = exec_build("tagged_suite", "--tag=~slow --tag=~fast")
assert_equal 1, queue.example_count
end
end
| 20.192308 | 65 | 0.699048 |
338c856588e3b6a0977d9a34db63fb0ab056a975 | 377 | class SessionsController < ApplicationController
def new; end
def create
user = User.find_by_username(params[:username])
if user
session[:user_id] = user.id
redirect_to root_path
else
render 'new'
end
end
def destroy
session[:user_id] = nil
redirect_to root_path flash[:success] = 'You have succesfully logged out'
end
end
| 19.842105 | 77 | 0.681698 |
082be1f7e1165915d411f86d6c57e6d9d78fc523 | 5,183 | # frozen_string_literal: true
module API
class Wikis < ::API::Base
helpers ::API::Helpers::WikisHelpers
feature_category :wiki
helpers do
attr_reader :container
params :common_wiki_page_params do
optional :format,
type: String,
values: Wiki::VALID_USER_MARKUPS.keys.map(&:to_s),
default: 'markdown',
desc: 'Format of a wiki page. Available formats are markdown, rdoc, asciidoc and org'
end
end
WIKI_ENDPOINT_REQUIREMENTS = API::NAMESPACE_OR_PROJECT_REQUIREMENTS.merge(slug: API::NO_SLASH_URL_PART_REGEX)
::API::Helpers::WikisHelpers.wiki_resource_kinds.each do |container_resource|
resource container_resource, requirements: WIKI_ENDPOINT_REQUIREMENTS do
after_validation do
@container = Gitlab::Lazy.new { find_container(container_resource) }
end
desc 'Get a list of wiki pages' do
success Entities::WikiPageBasic
end
params do
optional :with_content, type: Boolean, default: false, desc: "Include pages' content"
end
get ':id/wikis', urgency: :low do
authorize! :read_wiki, container
entity = params[:with_content] ? Entities::WikiPage : Entities::WikiPageBasic
options = {
with: entity,
current_user: current_user
}
present container.wiki.list_pages(load_content: params[:with_content]), options
end
desc 'Get a wiki page' do
success Entities::WikiPage
end
params do
requires :slug, type: String, desc: 'The slug of a wiki page'
optional :version, type: String, desc: 'The version hash of a wiki page'
optional :render_html, type: Boolean, default: false, desc: 'Render content to HTML'
end
get ':id/wikis/:slug', urgency: :low do
authorize! :read_wiki, container
options = {
with: Entities::WikiPage,
render_html: params[:render_html],
current_user: current_user
}
present wiki_page(params[:version]), options
end
desc 'Create a wiki page' do
success Entities::WikiPage
end
params do
requires :title, type: String, desc: 'Title of a wiki page'
requires :content, type: String, desc: 'Content of a wiki page'
use :common_wiki_page_params
end
post ':id/wikis' do
authorize! :create_wiki, container
response = WikiPages::CreateService.new(container: container, current_user: current_user, params: params).execute
page = response.payload[:page]
if response.success?
present page, with: Entities::WikiPage
else
render_validation_error!(page)
end
end
desc 'Update a wiki page' do
success Entities::WikiPage
end
params do
optional :title, type: String, desc: 'Title of a wiki page'
optional :content, type: String, desc: 'Content of a wiki page'
use :common_wiki_page_params
at_least_one_of :content, :title, :format
end
put ':id/wikis/:slug' do
authorize! :create_wiki, container
response = WikiPages::UpdateService
.new(container: container, current_user: current_user, params: params)
.execute(wiki_page)
page = response.payload[:page]
if response.success?
present page, with: Entities::WikiPage
else
render_validation_error!(page)
end
end
desc 'Delete a wiki page'
params do
requires :slug, type: String, desc: 'The slug of a wiki page'
end
delete ':id/wikis/:slug' do
authorize! :admin_wiki, container
response = WikiPages::DestroyService
.new(container: container, current_user: current_user)
.execute(wiki_page)
if response.success?
no_content!
else
unprocessable_entity!(response.message)
end
end
desc 'Upload an attachment to the wiki repository' do
detail 'This feature was introduced in GitLab 11.3.'
success Entities::WikiAttachment
end
params do
requires :file, types: [Rack::Multipart::UploadedFile, ::API::Validations::Types::WorkhorseFile], desc: 'The attachment file to be uploaded'
optional :branch, type: String, desc: 'The name of the branch'
end
post ":id/wikis/attachments" do
authorize! :create_wiki, container
result = ::Wikis::CreateAttachmentService.new(
container: container,
current_user: current_user,
params: commit_params(declared_params(include_missing: false))
).execute
if result[:status] == :success
status(201)
present result[:result], with: Entities::WikiAttachment
else
render_api_error!(result[:message], 400)
end
end
end
end
end
end
| 32.597484 | 150 | 0.60274 |
5d43f8dc98052e172aa8c89badbe4ed535d3f193 | 124 | RSpec.describe Threadfix::Cli do
it "has a version number" do
expect(Threadfix::Cli::VERSION).not_to be nil
end
end
| 20.666667 | 49 | 0.725806 |
910c4c0bd394d598e89aed91e0d961bd4e425887 | 250 | module Admin
module V1
module Types
class BaseObject < GraphQL::Schema::Object
edge_type_class(Types::BaseEdge)
connection_type_class(Types::BaseConnection)
field_class Types::BaseField
end
end
end
end
| 20.833333 | 52 | 0.676 |
38b636e4e5a36c9bf5272f2f30f8246bd4b03ec8 | 3,071 | # frozen_string_literal: true
module Gitlab
module Diff
module FileCollection
class Base
include Gitlab::Utils::StrongMemoize
attr_reader :project, :diff_options, :diff_refs, :fallback_diff_refs, :diffable
delegate :count, :size, :real_size, to: :raw_diff_files
def self.default_options
::Commit.max_diff_options.merge(ignore_whitespace_change: false, expanded: false, include_stats: true)
end
def initialize(diffable, project:, diff_options: nil, diff_refs: nil, fallback_diff_refs: nil)
diff_options = self.class.default_options.merge(diff_options || {})
@diffable = diffable
@include_stats = diff_options.delete(:include_stats)
@project = project
@diff_options = diff_options
@diff_refs = diff_refs
@fallback_diff_refs = fallback_diff_refs
@repository = project.repository
end
def diffs
@diffs ||= diffable.raw_diffs(diff_options)
end
def diff_files
raw_diff_files
end
def raw_diff_files
@raw_diff_files ||= diffs.decorate! { |diff| decorate_diff!(diff) }
end
def diff_file_paths
diff_files.map(&:file_path)
end
def pagination_data
{
current_page: nil,
next_page: nil,
total_pages: nil
}
end
# This mutates `diff_files` lines.
def unfold_diff_files(positions)
positions_grouped_by_path = positions.group_by { |position| position.file_path }
diff_files.each do |diff_file|
positions = positions_grouped_by_path.fetch(diff_file.file_path, [])
positions.each { |position| diff_file.unfold_diff_lines(position) }
end
end
def diff_file_with_old_path(old_path)
diff_files.find { |diff_file| diff_file.old_path == old_path }
end
def diff_file_with_new_path(new_path)
diff_files.find { |diff_file| diff_file.new_path == new_path }
end
def clear_cache
# No-op
end
def write_cache
# No-op
end
private
def diff_stats_collection
strong_memoize(:diff_stats) do
# There are scenarios where we don't need to request Diff Stats,
# when caching for instance.
next unless @include_stats
next unless diff_refs
@repository.diff_stats(diff_refs.base_sha, diff_refs.head_sha)
end
end
def decorate_diff!(diff)
return diff if diff.is_a?(File)
stats = diff_stats_collection&.find_by_path(diff.new_path)
Gitlab::Diff::File.new(diff,
repository: project.repository,
diff_refs: diff_refs,
fallback_diff_refs: fallback_diff_refs,
stats: stats)
end
end
end
end
end
| 28.700935 | 112 | 0.590361 |
79c7251f01af27cb4d9d12b722a96e84148e3236 | 51 | describe :string_unpack_taint, shared: true do
end
| 17 | 46 | 0.823529 |
f737f3665f87e20c9a79120adc4cfe5c2dfa5130 | 855 | ActiveAdmin.register BadgeClaim do
menu priority: 99
permit_params :badge_id, :user_id
filter :badge
action_item :create_many, only: :index do
link_to 'Create Many', admin_utilities_path
end
form do |f|
f.semantic_errors(*f.object.errors.keys)
f.inputs do
f.input :badge
f.input :user
end
f.actions
end
index do
selectable_column
column :badge
column :user
column :redemption_code
column 'claim link' do |badge_claim|
claim_link badge_claim
end
column :created_at
column :updated_at
actions
end
show do |f|
attributes_table do
row :badge do |b|
b.badge.name
end
row :user do |b|
if b.user.nil?
nil
else
b.user.display_name
end
end
row :redemption_code
end
end
end
| 17.44898 | 47 | 0.616374 |
3397b657c88f5fa0a62e5ed6950cc47357cb110b | 1,401 | class ApplicationMailbox < ActionMailbox::Base
# Last part is the regex for the UUID
# Eg: email should be something like : [email protected]
REPLY_EMAIL_USERNAME_PATTERN = /^reply\+([0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12})$/i
def self.reply_mail?
proc do |inbound_mail_obj|
is_a_reply_email = false
inbound_mail_obj.mail.to&.each do |email|
username = email.split('@')[0]
match_result = username.match(REPLY_EMAIL_USERNAME_PATTERN)
if match_result
is_a_reply_email = true
break
end
end
is_a_reply_email
end
end
def self.support_mail?
proc do |inbound_mail_obj|
is_a_support_email = false
inbound_mail_obj.mail.to&.each do |email|
channel = Channel::Email.find_by('lower(email) = ? OR lower(forward_to_email) = ?', email.downcase, email.downcase)
if channel.present?
is_a_support_email = true
break
end
end
is_a_support_email
end
end
def self.catch_all_mail?
proc { |_mail| true }
end
# routing should be defined below the referenced procs
# routes as a reply to existing conversations
routing(reply_mail? => :reply)
# routes as a new conversation in email channel
routing(support_mail? => :support)
routing(catch_all_mail? => :default)
end
| 29.808511 | 123 | 0.66167 |
28f12288b8fa1e3b323b44b1397b4ce27803da7f | 4,711 | # frozen_string_literal: true
module Blackjack
class Console
def self.print_logo
logo = <<~LOGO
===========================================================================
888888b. 888 888 d8b 888
888 "88b 888 888 Y8P 888
888 .88P 888 888 888
8888888K. 888 8888b. .d8888b 888 888 8888 8888b. .d8888b 888 888
888 "Y88b 888 "88b d88P" 888 .88P "888 "88b d88P" 888 .88P
888 888 888 .d888888 888 888888K 888 .d888888 888 888888K
888 d88P 888 888 888 Y88b. 888 "88b 888 888 888 Y88b. 888 "88b
8888888P" 888 "Y888888 "Y8888P 888 888 888 "Y888888 "Y8888P 888 888
============================================ 888 ==========================
d88P
888P"
LOGO
puts logo
end
def self.new_line
puts
end
def self.print_message(message)
puts message
end
def self.print_bordered_message(message, length: message.length, align: align)
block_message = format_messages(messages: [message], length: length, align: align)
print_horizontal([block_message])
end
def self.print_errors(errors)
errors.map do |error|
print_bordered_message("Error: #{error.message}", length: 69, align: :ljust)
end
end
def self.print_game_board
clear_screen
print_logo
new_line
end
def self.print_current_state(game)
round_text = [
"Round ##{game.round_number}",
"Current bet: #{game.round.total_bet}"
]
round_info = format_messages(messages: round_text, length: 32)
player_text = [
"Player name: #{game.player.name}",
"Player money: #{game.player.total_money}"
]
player_info = format_messages(messages: player_text, length: 32)
print_horizontal([round_info, player_info])
end
def self.print_cards_state(game)
dealer_cards_message = "Dealer's cards [points: #{game.round.dealer_points}]:"
dealer_cards_info = format_messages(messages: [dealer_cards_message], length: 69)
print_horizontal([dealer_cards_info])
print_cards(game.round.dealer_cards)
player_cards_message = "Your cards [points: #{game.round.player_points}]:"
player_cards_info = format_messages(messages: [player_cards_message], length: 69)
print_horizontal([player_cards_info])
print_cards(game.round.player_cards)
end
def self.print_result(game)
result_message = "#{game.round.status.capitalize}"
result_info = format_messages(messages: [result_message], length: 69, align: :center)
print_horizontal([result_info])
bets_message = "Your bets: #{game.round.total_bet}"
bets_info = format_messages(messages: [bets_message], length: 32)
winning_message = "Your winning: #{game.round.winning}"
winning_info = format_messages(messages: [winning_message], length: 32)
print_horizontal([bets_info, winning_info])
end
def self.print_cards(cards)
formatted_cards = cards.map { |card| format_card(card) }
print_horizontal(formatted_cards)
end
def self.print_horizontal(items)
lines_count = items.map(&:count).max
line_idents = [''] * lines_count
lines = items.reduce(line_idents) do |result, item|
result.zip(item).map { |line_parts| line_parts.join(' ') }
end
puts lines
end
def self.format_messages(messages: messages, length: 0, align: :ljust)
max_length = messages.map(&:length).max
length = max_length if length < max_length
formatted_messages = messages.map { |message| "│ #{message.send(align, *[length, ' '])} │" }
lines = [
"┌#{'─' * (length + 2)}┐",
formatted_messages,
"└#{'─' * (length + 2)}┘"
]
lines.flatten
end
def self.format_card(card)
name_to_symbol = { spades: '♠', diamonds: '♦', hearts: '♥', clubs: '♣' }
suit = name_to_symbol[card.suit]
literal = card.literal
card_is_ten = literal == '10'
top_literal = card_is_ten ? literal : "#{literal} "
bottom_literal = card_is_ten ? literal : " #{literal}"
[
'┌───────┐',
"│ #{top_literal} │",
'│ │',
"│ #{suit} │",
'│ │',
"│ #{bottom_literal} │",
'└───────┘'
]
end
def self.clear_screen
system('clear')
end
end
end
| 32.489655 | 98 | 0.560603 |
e9276a60e201a9b85e09bc0af339a823a5e74237 | 2,008 | class WorkItemStatesController < ApplicationController
respond_to :html, :json
before_action :authenticate_user!
before_action :set_item_and_state, only: [:show, :update]
before_action :init_from_params, only: :create
after_action :verify_authorized
def create
authorize @state_item
respond_to do |format|
if @state_item.save
format.json { render json: @state_item, status: :created }
else
format.json { render json: @state_item.errors, status: :unprocessable_entity }
end
end
end
def update
@state_item.update(params_for_update) if @state_item
authorize @state_item
respond_to do |format|
if @state_item.save
format.json { render json: @state_item, status: :ok }
else
format.json { render json: @state_item.errors, status: :unprocessable_entity }
end
end
end
def show
if @state_item.nil?
authorize current_user, :state_show?
respond_to do |format|
format.json { render body: nil, status: :not_found and return }
format.html { redirect_to root_url, alert: 'That Work Item State could not be found.' }
end
else
authorize @state_item
respond_to do |format|
format.json { render json: @state_item.serializable_hash }
end
end
end
private
def init_from_params
@state_item = WorkItemState.new(work_item_state_params)
end
def work_item_state_params
if request.method == 'GET'
params.require(:id)
else
params[:work_item_state] &&= params.require(:work_item_state).permit(:work_item_id, :action, :state)
end
end
def params_for_update
params.require(:work_item_state).permit(:action, :state)
end
def set_item_and_state
if params[:id]
begin
@state_item = WorkItemState.readable(current_user).find(params[:id])
@work_item = @state_item.work_item
rescue
# Don't throw RecordNotFound. Just return 404 above.
end
end
end
end
| 26.773333 | 106 | 0.679283 |
e95be460b2e33f758ba500b270398d51518bcc4f | 10,132 | # frozen_string_literal: true
require_relative '../test_helper'
# rubocop:disable Metrics/ClassLength
class GenericSortFilterTest < ActiveSupport::TestCase
subject { GenericSortFilter }
let(:query) { Offer.where('1 = 1') }
let(:invalid_query) { OpenStruct.new }
describe '#snake_case_contents' do
it 'should transform kebab-case contents to snake_case' do
params = {
sort_field: 'foo-bar', sort_model: %w[offer-translation baz-fuz],
sort_direction: 'ASC',
filters: { 'offer-translation.foo-bar' => 'dont-touch' }
}
result = subject.send(:snake_case_contents, params)
result.must_equal(
sort_field: 'foo_bar', sort_model: %w[offer_translation baz_fuz],
sort_direction: 'ASC',
filters: { 'offer_translation.foo_bar' => 'dont-touch' }
)
end
end
describe '#transform_by_searching' do
it 'does nothing without a param' do
invalid_query.expects(:search_pg).never
result = subject.send(:transform_by_searching, invalid_query, nil)
result.must_equal invalid_query
end
it 'does nothing with an empty param' do
invalid_query.expects(:search_pg).never
result = subject.send(:transform_by_searching, invalid_query, '')
result.must_equal invalid_query
end
it 'searches with a filled param for offer' do
query.expects(:search_pg).with('foo').once
subject.send(:transform_by_searching, query, 'foo')
end
# it 'searches with a filled param for orga' do
# orga_query = Organization.where('1 = 1')
# orga_query.expects(:with_pg_search_rank).once
# subject.send(:transform_by_searching, orga_query, 'orga')
# end
end
describe '#transform_by_joining' do
it 'eager_loads with a plain sort_model' do
params = { sort_model: 'contact_people' }
query.expects(:eager_load).with('contact_people')
subject.send(:transform_by_joining, query, params)
end
it 'eager_loads with a nested sort_model' do
params = { sort_model: 'contact_people.foo_bars' }
query.expects(:eager_load).with('contact_people' => 'foo_bars')
subject.send(:transform_by_joining, query, params)
end
it 'eager_loads with a filter' do
params =
{ filters: { 'solution_category.foo' => 'a',
'logic_version.bar' => 'b' } }
query.expects(:eager_load).with('solution_category').returns(query)
query.expects(:eager_load).with('logic_version').returns(query)
result = subject.send(:transform_by_joining, query, params)
result.must_equal query
end
it 'wont eager_load without a sort_model or filter' do
invalid_query.expects(:eager_load).never
result = subject.send(:transform_by_joining, invalid_query, {})
result.must_equal invalid_query
end
it 'wont eager_load with a filter that references itself' do
params = { filters: ['offer.baz'] }
query.expects(:eager_load).never
subject.send(:transform_by_joining, query, params)
end
it 'wont eager_load with a filter that uses no submodel' do
params = { filters: ['fuz'] }
query.expects(:eager_load).never
subject.send(:transform_by_joining, query, params)
end
end
describe '#transform_by_ordering' do
it 'will order with a sort_field but without sort_model (query model)' do
params = { sort_field: 'foo' }
query.expects(:order).with('offers.foo DESC')
subject.send(:transform_by_ordering, query, params)
end
it 'will order respecting sort_field, sort_model, and sort_direction' do
params =
{ sort_field: 'bar', sort_model: 'solution_category',
sort_direction: 'ASC' }
query.expects(:order).with('solution_categories.bar ASC')
subject.send(:transform_by_ordering, query, params)
end
end
describe '#model_for_filter' do
it 'should classifiy and constantize for self-referring query' do
subject.send(:model_for_filter, query, 'offer.name').must_equal Offer
end
end
describe '#sort_range' do
it 'should correctly sort date values' do
values = [DateTime.current, DateTime.current - 1.day]
subject.send(:sort_range, values).must_equal values.sort
end
it 'should correctly sort non date values via to_i' do
values = [12, 8]
subject.send(:sort_range, values).must_equal [8, 12]
end
end
describe '#transform_by_filtering' do
it 'wont transform without filters' do
params = { filters: nil }
invalid_query.expects(:where).never
result = subject.send(:transform_by_filtering, invalid_query, params)
result.must_equal invalid_query
end
it 'wont transform with an empty filter set' do
params = { filters: {} }
invalid_query.expects(:where).never
result = subject.send(:transform_by_filtering, invalid_query, params)
result.must_equal invalid_query
end
it 'wont transform with an empty filter value' do
params = { filters: { foo: '' } }
invalid_query.expects(:where).never
result = subject.send(:transform_by_filtering, invalid_query, params)
result.must_equal invalid_query
end
it 'filters for an owned field' do
params = { filters: { 'foo' => 'bar' }, controller: 'api/controller' }
query.expects(:where).with("controller.foo = 'bar'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters for an array of owned field with default OR-joining' do
params = { filters: { 'foo' => %w[bar fuz] } }
query.expects(:where).with("foo = 'bar' OR foo = 'fuz'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters for an array of owned field with !=-operator and AND-joining' do
params = { filters: { 'x' => %w[bar fuz] }, operators: { 'x' => '!=' } }
query.expects(:where)
.with("x != 'bar' OR x IS NULL AND x != 'fuz' OR x IS NULL")
subject.send(:transform_by_filtering, query, params)
end
it 'filters with a mismatching association/table name' do
params = { filters: { 'language_filters.foobar' => 'bazfuz' } }
query.expects(:where).with("filters.foobar = 'bazfuz'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters with a 2-level deep association' do
params = { filters: { 'section.cities.foobar' => 'bazfuz' } }
query.expects(:where).with("cities.foobar = 'bazfuz'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters with referring_to_own_table' do
params = { filters: { 'offers.foobar' => 'bazfuz' } }
query.expects(:where).with("offers.foobar = 'bazfuz'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters with a nullable value' do
params = { filters: { 'solution_category.baz' => 'nil' } }
query.expects(:where).with('solution_categories.baz IS NULL')
subject.send(:transform_by_filtering, query, params)
end
it 'filters with a nullable value and NOT operator value' do
params = { filters: { 'fuz' => 'NULL' }, operators: { 'fuz' => '!=' } }
query.expects(:where).with('fuz IS NOT NULL')
subject.send(:transform_by_filtering, query, params)
end
it 'includes NULL values for a "!=" string search' do
params =
{ filters: { 'title' => 'smth' }, operators: { 'title' => '!=' } }
query.expects(:where).with("title != 'smth' OR title IS NULL")
subject.send(:transform_by_filtering, query, params)
end
it 'performs case insensitive search with "ILIKE" operator' do
params =
{ filters: { 'title' => 'Smth' }, operators: { 'title' => 'ILIKE' } }
query.expects(:where).with("CAST(title AS TEXT) ILIKE '%Smth%'")
subject.send(:transform_by_filtering, query, params)
end
it 'parses times and converts them correctly' do
query = Opening.where('1 = 1')
params = { filters: { 'open' => '13:00' } }
query.expects(:where).with("open = '13:00'")
subject.send(:transform_by_filtering, query, params)
end
it 'parses datetimes and converts them correctly' do
value = '15.09.2014, 13:00'
params = { filters: { 'created_at' => value } }
query.expects(:where)
.with("created_at = '#{Time.zone.parse(value).to_datetime}'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters and sorts a range when range consists of dates' do
params = {
filters: { 'foo' => { 'first' => '2017-08-15',
'second' => '2017-08-09' } },
operators: { 'foo' => '...' }
}
query.expects(:where).with("foo BETWEEN '2017-08-09' AND '2017-08-15'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters and sorts a range when range consists of numbers' do
params = {
filters: { 'foo' => { 'first' => '5', 'second' => '1' } },
operators: { 'foo' => '...' }
}
query.expects(:where).with("foo BETWEEN '1' AND '5'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters for a single value when no second value is given for range' do
params = { filters: { 'foo' => '5' }, operators: { 'foo' => '...' } }
query.expects(:where).with("foo = '5'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters for a single value when empty second'\
' value is given for range' do
params = { filters: { 'foo' => ['5', ''] },
operators: { 'foo' => '...' } }
query.expects(:where).with("foo = '5'")
subject.send(:transform_by_filtering, query, params)
end
it 'filters with interconnecting OR operator' do
params = {
filters: { 'foo' => '1', 'fuz' => 'nil' },
operators: { 'fuz' => '=', 'interconnect' => 'OR' }
}
query.expects(:where).with("foo = '1'").returns query
query.expects(:or).with('fuz IS NULL')
subject.send(:transform_by_filtering, query, params)
end
end
end
# rubocop:enable Metrics/ClassLength
| 37.25 | 80 | 0.639262 |
26ecb26970d943bd42012d43b875823659409f28 | 2,154 | # -*- encoding: utf-8 -*-
# stub: websocket-driver 0.6.5 ruby lib
# stub: ext/websocket-driver/extconf.rb
Gem::Specification.new do |s|
s.name = "websocket-driver".freeze
s.version = "0.6.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["James Coglan".freeze]
s.date = "2017-01-22"
s.email = "[email protected]".freeze
s.extensions = ["ext/websocket-driver/extconf.rb".freeze]
s.extra_rdoc_files = ["README.md".freeze]
s.files = ["README.md".freeze, "ext/websocket-driver/extconf.rb".freeze]
s.homepage = "http://github.com/faye/websocket-driver-ruby".freeze
s.licenses = ["MIT".freeze]
s.rdoc_options = ["--main".freeze, "README.md".freeze, "--markup".freeze, "markdown".freeze]
s.rubygems_version = "2.6.13".freeze
s.summary = "WebSocket protocol handler with pluggable I/O".freeze
s.installed_by_version = "2.6.13" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<websocket-extensions>.freeze, [">= 0.1.0"])
s.add_development_dependency(%q<eventmachine>.freeze, [">= 0"])
s.add_development_dependency(%q<permessage_deflate>.freeze, [">= 0"])
s.add_development_dependency(%q<rake-compiler>.freeze, ["~> 0.8.0"])
s.add_development_dependency(%q<rspec>.freeze, [">= 0"])
else
s.add_dependency(%q<websocket-extensions>.freeze, [">= 0.1.0"])
s.add_dependency(%q<eventmachine>.freeze, [">= 0"])
s.add_dependency(%q<permessage_deflate>.freeze, [">= 0"])
s.add_dependency(%q<rake-compiler>.freeze, ["~> 0.8.0"])
s.add_dependency(%q<rspec>.freeze, [">= 0"])
end
else
s.add_dependency(%q<websocket-extensions>.freeze, [">= 0.1.0"])
s.add_dependency(%q<eventmachine>.freeze, [">= 0"])
s.add_dependency(%q<permessage_deflate>.freeze, [">= 0"])
s.add_dependency(%q<rake-compiler>.freeze, ["~> 0.8.0"])
s.add_dependency(%q<rspec>.freeze, [">= 0"])
end
end
| 43.959184 | 112 | 0.668059 |
5d887dd8dd81c473630c115d3fbb67358dd3dc42 | 8,323 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class OrphanRecordingListing
attr_accessor :entities
attr_accessor :page_size
attr_accessor :page_number
attr_accessor :total
attr_accessor :first_uri
attr_accessor :self_uri
attr_accessor :next_uri
attr_accessor :last_uri
attr_accessor :previous_uri
attr_accessor :page_count
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'entities' => :'entities',
:'page_size' => :'pageSize',
:'page_number' => :'pageNumber',
:'total' => :'total',
:'first_uri' => :'firstUri',
:'self_uri' => :'selfUri',
:'next_uri' => :'nextUri',
:'last_uri' => :'lastUri',
:'previous_uri' => :'previousUri',
:'page_count' => :'pageCount'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'entities' => :'Array<OrphanRecording>',
:'page_size' => :'Integer',
:'page_number' => :'Integer',
:'total' => :'Integer',
:'first_uri' => :'String',
:'self_uri' => :'String',
:'next_uri' => :'String',
:'last_uri' => :'String',
:'previous_uri' => :'String',
:'page_count' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'entities')
if (value = attributes[:'entities']).is_a?(Array)
self.entities = value
end
end
if attributes.has_key?(:'pageSize')
self.page_size = attributes[:'pageSize']
end
if attributes.has_key?(:'pageNumber')
self.page_number = attributes[:'pageNumber']
end
if attributes.has_key?(:'total')
self.total = attributes[:'total']
end
if attributes.has_key?(:'firstUri')
self.first_uri = attributes[:'firstUri']
end
if attributes.has_key?(:'selfUri')
self.self_uri = attributes[:'selfUri']
end
if attributes.has_key?(:'nextUri')
self.next_uri = attributes[:'nextUri']
end
if attributes.has_key?(:'lastUri')
self.last_uri = attributes[:'lastUri']
end
if attributes.has_key?(:'previousUri')
self.previous_uri = attributes[:'previousUri']
end
if attributes.has_key?(:'pageCount')
self.page_count = attributes[:'pageCount']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
entities == o.entities &&
page_size == o.page_size &&
page_number == o.page_number &&
total == o.total &&
first_uri == o.first_uri &&
self_uri == o.self_uri &&
next_uri == o.next_uri &&
last_uri == o.last_uri &&
previous_uri == o.previous_uri &&
page_count == o.page_count
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[entities, page_size, page_number, total, first_uri, self_uri, next_uri, last_uri, previous_uri, page_count].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 19.400932 | 177 | 0.515199 |
08857831b4b8fa7a61d11d19bd1bc1b38ab3323d | 2,936 | module Jekyll
module Paginate
class Pagination < Generator
# This generator is safe from arbitrary code execution.
safe true
# This generator should be passive with regard to its execution
priority :lowest
# Generate paginated pages if necessary.
#
# site - The Site.
#
# Returns nothing.
def generate(site)
if Pager.pagination_enabled?(site)
if template = self.class.template_page(site)
paginate(site, template)
else
Jekyll.logger.warn "Pagination:", "Pagination is enabled, but I couldn't find " +
"an index.html page to use as the pagination template. Skipping pagination."
end
end
end
# Paginates the blog's posts. Renders the index.html file into paginated
# directories, e.g.: page2/index.html, page3/index.html, etc and adds more
# site-wide data.
#
# site - The Site.
# page - The index.html Page that requires pagination.
#
# {"paginator" => { "page" => <Number>,
# "per_page" => <Number>,
# "posts" => [<Post>],
# "total_posts" => <Number>,
# "total_pages" => <Number>,
# "previous_page" => <Number>,
# "next_page" => <Number> }}
def paginate(site, page)
all_posts = site.site_payload['site']['posts'].reject { |post| post['hidden'] }
#all_posts = all_posts.select do |elem|
# !elem.data['tags'].include? 'foo'
#end
pages = Pager.calculate_pages(all_posts, site.config['paginate'].to_i)
(1..pages).each do |num_page|
pager = Pager.new(site, num_page, all_posts, pages)
if num_page > 1
newpage = Page.new(site, site.source, page.dir, page.name)
newpage.pager = pager
newpage.dir = Pager.paginate_path(site, num_page)
site.pages << newpage
else
page.pager = pager
end
end
end
# Static: Fetch the URL of the template page. Used to determine the
# path to the first pager in the series.
#
# site - the Jekyll::Site object
#
# Returns the url of the template page
def self.first_page_url(site)
if page = Pagination.template_page(site)
page.url
else
nil
end
end
# Public: Find the Jekyll::Page which will act as the pager template
#
# site - the Jekyll::Site object
#
# Returns the Jekyll::Page which will act as the pager template
def self.template_page(site)
site.pages.select do |page|
Pager.pagination_candidate?(site.config, page)
end.sort do |one, two|
two.path.size <=> one.path.size
end.first
end
end
end
end
| 32.622222 | 93 | 0.553815 |
0136deaccac61ac6d26c0da85410f2c28529d636 | 675 | require 'spec_helper'
describe "FriendlyForwardings", :type => :request do
describe "GET /friendly_forwardings", :type => :request do
it "should forward to the requested page after signin" do
user = FactoryBot.create(:user)
visit edit_user_path(user)
fill_in :email, :with => user.email
fill_in :password, :with => user.password
click_button
expect(response).to render_template('users/edit')
visit signout_path
visit signin_path
fill_in :email, :with => user.email
fill_in :password, :with => user.password
click_button
expect(response).to render_template('users/show')
end
end
end
| 29.347826 | 61 | 0.671111 |
ab13830922f5383e53bd67820bc738a6c15e97ba | 2,504 | require 'socket'
require 'syslog_protocol'
module RemoteSyslogSender
class Sender
# To suppress initialize warning
class Packet < SyslogProtocol::Packet
def initialize(*)
super
@time = nil
end
end
attr_reader :socket
attr_accessor :packet
def initialize(remote_hostname, remote_port, options = {})
@remote_hostname = remote_hostname
@remote_port = remote_port
@whinyerrors = options[:whinyerrors]
@packet_size = options[:packet_size] || 1024
@packet = Packet.new
local_hostname = options[:hostname] || options[:local_hostname] || (Socket.gethostname rescue `hostname`.chomp)
local_hostname = 'localhost' if local_hostname.nil? || local_hostname.empty?
@packet.hostname = local_hostname
@packet.facility = options[:facility] || 'user'
@packet.severity = options[:severity] || 'notice'
@packet.tag = options[:tag] || options[:program] || "#{File.basename($0)}[#{$$}]"
@packet.rfc = options[:rfc] || :rfc5424
@socket = nil
end
def transmit(message, packet_options = nil)
message.split(/\r?\n/).each do |line|
begin
next if line =~ /^\s*$/
packet = @packet.dup
if packet_options
packet.tag = packet_options[:program] if packet_options[:program]
packet.hostname = packet_options[:local_hostname] if packet_options[:local_hostname]
packet.rfc = packet_options[:rfc] if packet_options[:rfc]
if packet.rfc == :rfc5424
%i(hostname facility severity appname msgid procid).each do |key|
packet.send("#{key}=", packet_options[key]) if packet_options[key]
end
else
%i(hostname facility severity tag).each do |key|
packet.send("#{key}=", packet_options[key]) if packet_options[key]
end
end
end
packet.content = line
send_msg(packet.assemble(@packet_size))
rescue
if @whinyerrors
raise
else
$stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{line}"
end
end
end
end
# Make this act a little bit like an `IO` object
alias_method :write, :transmit
def close
@socket.close
end
private
def send_msg(payload)
raise NotImplementedError, "please override"
end
end
end
| 30.536585 | 119 | 0.59385 |
61b422f72e67279afff9cd8bc49e35cea7d07312 | 1,715 | class AddInfoAboutLastTransferRequestOnBalance < ActiveRecord::Migration
def up
execute %Q{
CREATE OR REPLACE VIEW "1".balances as
select
id as user_id,
balance.amount as amount,
last_transfer.amount as last_transfer_amount,
last_transfer.created_at as last_transfer_created_at,
last_transfer.in_period_yet
from public.users u
left join lateral (
SELECT sum(bt.amount) AS amount
FROM balance_transactions bt
WHERE bt.user_id = u.id
) as balance on true
left join lateral (
select
(bt.amount * -1) as amount,
bt.created_at,
(to_char(bt.created_at, 'MM/YYY') = to_char(now(), 'MM/YYY')) as in_period_yet
from balance_transactions bt
where bt.user_id = u.id
and bt.event_name in ('balance_transfer_request', 'balance_transfer_project')
and not exists (
select true
from balance_transactions bt2
where bt2.user_id = u.id
and bt2.created_at > bt.created_at
and bt2.event_name = 'balance_transfer_error'
)
order by bt.created_at desc
limit 1
) as last_transfer on true
where is_owner_or_admin(u.id);
}
end
def down
execute %Q{
drop view "1".balances;
CREATE OR REPLACE VIEW "1"."balances" AS
SELECT bt.user_id,
sum(bt.amount) AS amount
FROM balance_transactions bt
WHERE is_owner_or_admin(bt.user_id)
GROUP BY bt.user_id;
}
end
end
| 33.627451 | 97 | 0.568513 |
182a3c4b56ecde4f58f10258caeea922035153f0 | 944 | # == Schema Information
# Schema version: 16
#
# Table name: items
#
# id :integer not null, primary key
# type :string(255) not null
# title :string(255) not null
# project_id :integer
# role_id :integer not null
# person_id :integer not null
# status_id :integer not null
# code_id_priority :integer not null
# project_id_escalation :integer
# description :text
# due_on :date
# lft :integer
# rgt :integer
# updated_at :datetime not null
# person_id_updated_by :integer not null
# version :integer
# res_idx_fti :string
#
class TestCondition < Item
has_one :detail, :class_name => 'TestConditionDetail'
end
| 32.551724 | 61 | 0.48411 |
1d7399f58eff5e168c65bfe41d0a5c12c93b965a | 338 | # frozen_string_literal: true
module Fourier
module Services
module Test
module Tuist
class Unit < Base
def call
Utilities::System.system(
"swift", "test",
"--package-path", Constants::ROOT_DIRECTORY
)
end
end
end
end
end
end
| 18.777778 | 57 | 0.517751 |
11328edbda46ca15905a685c480a786d266ba551 | 3,843 | # == Schema Information
#
# Table name: papers
#
# id :integer not null, primary key
# uid :text not null
# submitter :text
# title :text not null
# abstract :text not null
# author_comments :text
# msc_class :text
# report_no :text
# journal_ref :text
# doi :text
# proxy :text
# license :text
# submit_date :datetime not null
# update_date :datetime not null
# abs_url :text not null
# pdf_url :text not null
# created_at :datetime
# updated_at :datetime
# scites_count :integer default(0), not null
# comments_count :integer default(0), not null
# pubdate :datetime
# author_str :text not null
# versions_count :integer default(1), not null
#
require 'spec_helper'
describe Paper do
let(:paper) { FactoryGirl.create(:paper) }
subject { paper }
it { is_expected.to respond_to(:title) }
it { is_expected.to respond_to(:authors) }
it { is_expected.to respond_to(:abstract) }
it { is_expected.to respond_to(:uid) }
it { is_expected.to respond_to(:abs_url) }
it { is_expected.to respond_to(:pdf_url) }
it { is_expected.to respond_to(:submit_date) }
it { is_expected.to respond_to(:update_date) }
it { is_expected.to respond_to(:scites) }
it { is_expected.to respond_to(:sciters) }
it { is_expected.to respond_to(:comments) }
it { is_expected.to respond_to(:categories) }
it { is_expected.to validate_uniqueness_of(:uid).case_insensitive }
it { is_expected.to be_valid }
describe "#to_bibtex" do
let(:paper) do
paper = FactoryGirl.create(:paper_with_versions,
author_str: "Susanta K. Khan and Madhumangal Pal",
title: "Interval-Valued Intuitionistic Fuzzy Matrices",
pubdate: "2014-05-12 01:00:00 UTC",
uid: "1404.6949",
journal_ref: "Notes on Intuitionistic Fuzzy Sets, 11(1) (2005)16-27"
)
FactoryGirl.create(:author, fullname: "Susanta K. Khan", paper_uid: paper.uid)
FactoryGirl.create(:author, fullname: "Madhumangal Pal", paper_uid: paper.uid)
paper
end
it "generates bibtex correctly" do
expect(paper.to_bibtex).to eq %Q{@misc{1404.6949,
author = {Susanta K.~Khan and Madhumangal Pal},
title = {{I}nterval-{V}alued {I}ntuitionistic {F}uzzy {M}atrices},
year = {2014},
eprint = {1404.6949},
howpublished = {Notes on Intuitionistic Fuzzy Sets, 11(1) (2005)16-27},
note = {arXiv:1404.6949v3}
}}
end
end
describe "sciting" do
let (:user) { FactoryGirl.create(:user) }
before { user.scite!(paper) }
it "scites the paper" do
expect(paper.sciters.pluck(:id)).to include(user.id)
end
end
describe "authors" do
let (:author1) { FactoryGirl.create(:author, paper: paper, position: 0) }
let (:author2) { FactoryGirl.create(:author, paper: paper, position: 1) }
it "should have the authors in the right order" do
expect(paper.reload.authors).to eq [author1, author2]
end
end
describe "comments" do
let (:user) { FactoryGirl.create(:user) }
before { user.save }
let!(:old_comment) do
FactoryGirl.create(:comment,
user: user, paper: paper, created_at: 1.day.ago)
end
let!(:new_comment) do
FactoryGirl.create(:comment,
user: user, paper: paper, created_at: 1.minute.ago)
end
let!(:med_comment) do
FactoryGirl.create(:comment,
user: user, paper: paper, created_at: 1.hour.ago)
end
it "has the right comments in the right order" do
expect(paper.comments).to eq [old_comment, med_comment, new_comment]
end
end
end
| 31.760331 | 84 | 0.617486 |
388bf2ca5a653ae3af4a729a6e3b4372dbab5367 | 412 | # current_CriticalBugs = 14
# moreInfo = "Critical status"
# differenceRate = -10
#
# SCHEDULER.every '1s' do
# last_CriticalBugs = current_CriticalBugs
# send_event('CriticalBugs', { current: current_CriticalBugs, last: last_CriticalBugs, moreinfo: moreInfo, difference:differenceRate })
# end
SCHEDULER.every '1s' do
send_event('TotalBugs', { current: 85, last: 70, moreinfo: "Normal status"})
end
| 29.428571 | 137 | 0.735437 |
030d5bb2bd8111fd68b90473484930472c02a989 | 596 | # frozen_string_literal: true
class MakeExpressionsLessGeneric < ActiveRecord::Migration[4.2]
def up
rename_column :expressions, :parent_id, :post_id
rename_column :expressions, :expression_type_id, :expression_index
remove_column :expressions, :parent_type
add_index :expressions, [:post_id, :expression_index, :user_id], unique: true, name: 'unique_by_user'
end
def down
rename_column :expressions, :post_id, :parent_id
rename_column :expressions, :expression_index, :expression_type_id
add_column :expressions, :parent_type, :string, null: true
end
end
| 31.368421 | 105 | 0.763423 |
e27c314e51a3fa4e4491ef40ad6fb740c5edeb03 | 195 | class InvoicePolicy < ApplicationPolicy
def index?
user.is_admin?
end
def download?
user.is_admin? or (record.user_id == user.id)
end
def create?
user.is_admin?
end
end
| 13.928571 | 49 | 0.676923 |
91aa59aada1e4a6718d9ac66a38ed8f50844180e | 21,309 | ##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Preview < Domain
class HostedNumbers < Version
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class AuthorizationDocumentList < ListResource
##
# Initialize the AuthorizationDocumentList
# @param [Version] version Version that contains the resource
# @return [AuthorizationDocumentList] AuthorizationDocumentList
def initialize(version)
super(version)
# Path Solution
@solution = {}
@uri = "/AuthorizationDocuments"
end
##
# Lists AuthorizationDocumentInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [authorization_document.Status] status Status of an instance resource. It
# can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5.
# failed. See the section entitled [Status
# Values](https://www.twilio.com/docs/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(email: :unset, status: :unset, limit: nil, page_size: nil)
self.stream(email: email, status: status, limit: limit, page_size: page_size).entries
end
##
# Streams AuthorizationDocumentInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [authorization_document.Status] status Status of an instance resource. It
# can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5.
# failed. See the section entitled [Status
# Values](https://www.twilio.com/docs/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(email: :unset, status: :unset, limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(email: email, status: status, page_size: limits[:page_size], )
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields AuthorizationDocumentInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of AuthorizationDocumentInstance records from the API.
# Request is executed immediately.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [authorization_document.Status] status Status of an instance resource. It
# can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5.
# failed. See the section entitled [Status
# Values](https://www.twilio.com/docs/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of AuthorizationDocumentInstance
def page(email: :unset, status: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'Email' => email,
'Status' => status,
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page(
'GET',
@uri,
params
)
AuthorizationDocumentPage.new(@version, response, @solution)
end
##
# Retrieve a single page of AuthorizationDocumentInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of AuthorizationDocumentInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
AuthorizationDocumentPage.new(@version, response, @solution)
end
##
# Retrieve a single page of AuthorizationDocumentInstance records from the API.
# Request is executed immediately.
# @param [String] hosted_number_order_sids A list of HostedNumberOrder sids that
# this AuthorizationDocument will authorize for hosting phone number capabilities
# on Twilio's platform.
# @param [String] address_sid A 34 character string that uniquely identifies the
# Address resource that is associated with this AuthorizationDocument.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [String] contact_title The title of the person authorized to sign the
# Authorization Document for this phone number.
# @param [String] contact_phone_number The contact phone number of the person
# authorized to sign the Authorization Document.
# @param [String] cc_emails Email recipients who will be informed when an
# Authorization Document has been sent and signed.
# @return [AuthorizationDocumentInstance] Newly created AuthorizationDocumentInstance
def create(hosted_number_order_sids: nil, address_sid: nil, email: nil, contact_title: nil, contact_phone_number: nil, cc_emails: :unset)
data = Twilio::Values.of({
'HostedNumberOrderSids' => Twilio.serialize_list(hosted_number_order_sids) { |e| e },
'AddressSid' => address_sid,
'Email' => email,
'ContactTitle' => contact_title,
'ContactPhoneNumber' => contact_phone_number,
'CcEmails' => Twilio.serialize_list(cc_emails) { |e| e },
})
payload = @version.create(
'POST',
@uri,
data: data
)
AuthorizationDocumentInstance.new(@version, payload, )
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Preview.HostedNumbers.AuthorizationDocumentList>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class AuthorizationDocumentPage < Page
##
# Initialize the AuthorizationDocumentPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [AuthorizationDocumentPage] AuthorizationDocumentPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of AuthorizationDocumentInstance
# @param [Hash] payload Payload response from the API
# @return [AuthorizationDocumentInstance] AuthorizationDocumentInstance
def get_instance(payload)
AuthorizationDocumentInstance.new(@version, payload, )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Preview.HostedNumbers.AuthorizationDocumentPage>'
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class AuthorizationDocumentContext < InstanceContext
##
# Initialize the AuthorizationDocumentContext
# @param [Version] version Version that contains the resource
# @param [String] sid A 34 character string that uniquely identifies this
# AuthorizationDocument.
# @return [AuthorizationDocumentContext] AuthorizationDocumentContext
def initialize(version, sid)
super(version)
# Path Solution
@solution = {sid: sid, }
@uri = "/AuthorizationDocuments/#{@solution[:sid]}"
# Dependents
@dependent_hosted_number_orders = nil
end
##
# Fetch a AuthorizationDocumentInstance
# @return [AuthorizationDocumentInstance] Fetched AuthorizationDocumentInstance
def fetch
params = Twilio::Values.of({})
payload = @version.fetch(
'GET',
@uri,
params,
)
AuthorizationDocumentInstance.new(@version, payload, sid: @solution[:sid], )
end
##
# Update the AuthorizationDocumentInstance
# @param [String] hosted_number_order_sids A list of HostedNumberOrder sids that
# this AuthorizationDocument will authorize for hosting phone number capabilities
# on Twilio's platform.
# @param [String] address_sid A 34 character string that uniquely identifies the
# Address resource that is associated with this AuthorizationDocument.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [String] cc_emails Email recipients who will be informed when an
# Authorization Document has been sent and signed
# @param [authorization_document.Status] status Status of an instance resource. It
# can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5.
# failed. See the section entitled [Status
# Values](https://www.twilio.com/docs/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses.
# @param [String] contact_title The title of the person authorized to sign the
# Authorization Document for this phone number.
# @param [String] contact_phone_number The contact phone number of the person
# authorized to sign the Authorization Document.
# @return [AuthorizationDocumentInstance] Updated AuthorizationDocumentInstance
def update(hosted_number_order_sids: :unset, address_sid: :unset, email: :unset, cc_emails: :unset, status: :unset, contact_title: :unset, contact_phone_number: :unset)
data = Twilio::Values.of({
'HostedNumberOrderSids' => Twilio.serialize_list(hosted_number_order_sids) { |e| e },
'AddressSid' => address_sid,
'Email' => email,
'CcEmails' => Twilio.serialize_list(cc_emails) { |e| e },
'Status' => status,
'ContactTitle' => contact_title,
'ContactPhoneNumber' => contact_phone_number,
})
payload = @version.update(
'POST',
@uri,
data: data,
)
AuthorizationDocumentInstance.new(@version, payload, sid: @solution[:sid], )
end
##
# Access the dependent_hosted_number_orders
# @return [DependentHostedNumberOrderList]
# @return [DependentHostedNumberOrderContext]
def dependent_hosted_number_orders
unless @dependent_hosted_number_orders
@dependent_hosted_number_orders = DependentHostedNumberOrderList.new(
@version,
signing_document_sid: @solution[:sid],
)
end
@dependent_hosted_number_orders
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Preview.HostedNumbers.AuthorizationDocumentContext #{context}>"
end
##
# Provide a detailed, user friendly representation
def inspect
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Preview.HostedNumbers.AuthorizationDocumentContext #{context}>"
end
end
##
# PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
class AuthorizationDocumentInstance < InstanceResource
##
# Initialize the AuthorizationDocumentInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] sid A 34 character string that uniquely identifies this
# AuthorizationDocument.
# @return [AuthorizationDocumentInstance] AuthorizationDocumentInstance
def initialize(version, payload, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'sid' => payload['sid'],
'address_sid' => payload['address_sid'],
'status' => payload['status'],
'email' => payload['email'],
'cc_emails' => payload['cc_emails'],
'date_created' => Twilio.deserialize_iso8601_datetime(payload['date_created']),
'date_updated' => Twilio.deserialize_iso8601_datetime(payload['date_updated']),
'url' => payload['url'],
'links' => payload['links'],
}
# Context
@instance_context = nil
@params = {'sid' => sid || @properties['sid'], }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [AuthorizationDocumentContext] AuthorizationDocumentContext for this AuthorizationDocumentInstance
def context
unless @instance_context
@instance_context = AuthorizationDocumentContext.new(@version, @params['sid'], )
end
@instance_context
end
##
# @return [String] AuthorizationDocument sid.
def sid
@properties['sid']
end
##
# @return [String] Address sid.
def address_sid
@properties['address_sid']
end
##
# @return [authorization_document.Status] The Status of this AuthorizationDocument.
def status
@properties['status']
end
##
# @return [String] Email.
def email
@properties['email']
end
##
# @return [String] A list of emails.
def cc_emails
@properties['cc_emails']
end
##
# @return [Time] The date this AuthorizationDocument was created.
def date_created
@properties['date_created']
end
##
# @return [Time] The date this AuthorizationDocument was updated.
def date_updated
@properties['date_updated']
end
##
# @return [String] The url
def url
@properties['url']
end
##
# @return [String] The links
def links
@properties['links']
end
##
# Fetch a AuthorizationDocumentInstance
# @return [AuthorizationDocumentInstance] Fetched AuthorizationDocumentInstance
def fetch
context.fetch
end
##
# Update the AuthorizationDocumentInstance
# @param [String] hosted_number_order_sids A list of HostedNumberOrder sids that
# this AuthorizationDocument will authorize for hosting phone number capabilities
# on Twilio's platform.
# @param [String] address_sid A 34 character string that uniquely identifies the
# Address resource that is associated with this AuthorizationDocument.
# @param [String] email Email that this AuthorizationDocument will be sent to for
# signing.
# @param [String] cc_emails Email recipients who will be informed when an
# Authorization Document has been sent and signed
# @param [authorization_document.Status] status Status of an instance resource. It
# can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5.
# failed. See the section entitled [Status
# Values](https://www.twilio.com/docs/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses.
# @param [String] contact_title The title of the person authorized to sign the
# Authorization Document for this phone number.
# @param [String] contact_phone_number The contact phone number of the person
# authorized to sign the Authorization Document.
# @return [AuthorizationDocumentInstance] Updated AuthorizationDocumentInstance
def update(hosted_number_order_sids: :unset, address_sid: :unset, email: :unset, cc_emails: :unset, status: :unset, contact_title: :unset, contact_phone_number: :unset)
context.update(
hosted_number_order_sids: hosted_number_order_sids,
address_sid: address_sid,
email: email,
cc_emails: cc_emails,
status: status,
contact_title: contact_title,
contact_phone_number: contact_phone_number,
)
end
##
# Access the dependent_hosted_number_orders
# @return [dependent_hosted_number_orders] dependent_hosted_number_orders
def dependent_hosted_number_orders
context.dependent_hosted_number_orders
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Preview.HostedNumbers.AuthorizationDocumentInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Preview.HostedNumbers.AuthorizationDocumentInstance #{values}>"
end
end
end
end
end
end | 45.532051 | 201 | 0.608147 |
878fd7986b68d41d6c12408a0eefc7db9f27f510 | 4,113 | class TestTrack::Visitor
include TestTrack::RequiredOptions
attr_reader :id
def initialize(opts = {})
opts = opts.dup
@id = opts.delete(:id)
@loaded = true if opts[:assignments]
@assignments = opts.delete(:assignments)
unless id
@id = SecureRandom.uuid
@assignments ||= [] # If we're generating a visitor, we don't need to fetch the assignments
end
raise "unknown opts: #{opts.keys.to_sentence}" if opts.present?
end
def vary(split_name, opts = {})
opts = opts.dup
split_name = split_name.to_s
context = require_option!(opts, :context)
raise "unknown opts: #{opts.keys.to_sentence}" if opts.present?
raise ArgumentError, "must provide block to `vary` for #{split_name}" unless block_given?
v = TestTrack::VaryDSL.new(assignment: assignment_for(split_name), context: context, split_registry: split_registry)
yield v
v.send :run
end
def ab(split_name, opts = {}) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
opts = opts.dup
split_name = split_name.to_s
true_variant = opts.delete(:true_variant)
context = require_option!(opts, :context)
raise "unknown opts: #{opts.keys.to_sentence}" if opts.present?
ab_configuration = TestTrack::ABConfiguration.new split_name: split_name, true_variant: true_variant, split_registry: split_registry
vary(split_name, context: context) do |v|
v.when ab_configuration.variants[:true] do
true
end
v.default ab_configuration.variants[:false] do
false
end
end
end
def assignment_registry
@assignment_registry ||= assignments.each_with_object({}) do |assignment, hsh|
hsh[assignment.split_name] = assignment
end
end
def unsynced_assignments
@unsynced_assignments ||= assignment_registry.values.select(&:unsynced?)
end
def assignment_json
assignment_registry.values.each_with_object({}) do |assignment, hsh|
hsh[assignment.split_name] = assignment.variant
end
end
def split_registry
@split_registry ||= TestTrack::Remote::SplitRegistry.to_hash
end
def link_identity!(identity)
opts = identifier_opts(identity)
begin
identifier = TestTrack::Remote::Identifier.create!(opts)
merge!(identifier.visitor)
rescue *TestTrack::SERVER_ERRORS => e
Rails.logger.error "TestTrack failed to link identifier, retrying. #{e}"
# If at first you don't succeed, async it - we may not display 100% consistent UX this time,
# but subsequent requests will be better off
TestTrack::Remote::Identifier.delay.create!(opts)
end
end
def offline?
@tt_offline
end
def id_loaded?
true
end
def loaded?
!offline? && @loaded
end
def id_overridden_by_existing_visitor?
@id_overridden_by_existing_visitor || false
end
private
def identifier_opts(identity)
{
identifier_type: identity.test_track_identifier_type,
visitor_id: id,
value: identity.test_track_identifier_value.to_s
}
end
def assignments
@assignments ||= remote_visitor&.assignments || []
end
def remote_visitor
@remote_visitor ||= _remote_visitor
end
def _remote_visitor
unless tt_offline?
TestTrack::Remote::Visitor.find(id).tap do |_|
@loaded = true
end
end
rescue *TestTrack::SERVER_ERRORS => e
Rails.logger.error "TestTrack failed to load remote visitor. #{e}"
@tt_offline = true
nil
end
def merge!(other)
@id_overridden_by_existing_visitor = id != other.id
@id = other.id
@assignment_registry = assignment_registry.merge(other.assignment_registry)
@unsynced_assignments = nil
end
def tt_offline?
@tt_offline || false
end
def assignment_for(split_name)
fetch_assignment_for(split_name) || generate_assignment_for(split_name)
end
def fetch_assignment_for(split_name)
assignment_registry[split_name] if assignment_registry
end
def generate_assignment_for(split_name)
assignment_registry[split_name] = TestTrack::Assignment.new(visitor: self, split_name: split_name)
end
end
| 27.059211 | 136 | 0.705811 |
1d1b3f648d3a044336dfeb71ebcb086c39d1c110 | 623 | # -*- encoding : utf-8 -*-
difficulty 3
description "A bug was introduced somewhere along the way. You know that running `ruby prog.rb 5` should output 15. You can also run `make test`. What are the first 7 chars of the hash of the commit that introduced the bug."
setup do
init_from_level
repo.init
end
solution do
"18ed2ac" == request("What are the first 7 characters of the hash of the commit that introduced the bug?")[0..6]
end
hint do
puts ["The fastest way to find the bug is with bisect.", "Don't forget to start bisect first, identify a good or bad commit, then run `git bisect run make test`."]
end
| 36.647059 | 227 | 0.727127 |
ed54865411afcae9c6c393d72a7ff84c8193240b | 528 | Headcount.configure do |config|
# config.path = 'db/headcounts.json' # where to write headcount to
config.timestamp = '%'
now = DateTime.now
count User do
a = now - 7.days
b = now - 30.days
c = now - 90.days
count User.where("last_request_at >= ?", a), :as => :active
count User.where("last_request_at < ? AND last_request_at > ?", a, b), :as => :semi_active
count User.where("last_request_at <= ?", c), :as => :inactive
end
end | 33 | 95 | 0.549242 |
187e96be2322babf543f229eaf7170bef2f3610d | 343 | class TreemapGenerator < BaseGenerator
# generate horizontal bar chart
# element - div id or class for chart
# data_url - json file with data
def generate( element, data_url )
add_assets( "#{element[1..-1]}"+'.js', js_code( element, data_url ) )
add_assets( "#{element[1..-1]}"+'.scss', css_code( element ) )
end
end | 31.181818 | 73 | 0.653061 |
2625ccb70342a3725ef387b67aa3a75f66f463a3 | 139 | class Invitation < ActiveRecord::Base
belongs_to(:person) # people can invite other people ...
belongs_to(:team) # ... into teams
end
| 19.857143 | 57 | 0.71223 |
d52e8cfcfe989c00ab277cf1d3fab7b51b740c61 | 3,148 | # This extension Gzips assets and pages when building.
# Gzipped assets and pages can be served directly by Apache or
# Nginx with the proper configuration, and pre-zipping means that we
# can use a more agressive compression level at no CPU cost per request.
#
# Use Nginx's gzip_static directive, or AddEncoding and mod_rewrite in Apache
# to serve your Gzipped files whenever the normal (non-.gz) filename is requested.
#
# Pass the :exts options to customize which file extensions get zipped (defaults
# to .html, .htm, .js and .css.
#
class Middleman::Extensions::Gzip < ::Middleman::Extension
option :exts, %w(.js .css .html .htm), 'File extensions to Gzip when building.'
def initialize(app, options_hash={})
super
require 'zlib'
require 'stringio'
require 'find'
require 'thread'
end
def after_build(builder)
num_threads = 4
paths = ::Middleman::Util.all_files_under(app.build_dir)
total_savings = 0
# Fill a queue with inputs
in_queue = Queue.new
paths.each do |path|
in_queue << path if options.exts.include?(path.extname)
end
num_paths = in_queue.size
# Farm out gzip tasks to threads and put the results in in_queue
out_queue = Queue.new
threads = num_threads.times.map do
Thread.new do
while path = in_queue.pop
out_queue << gzip_file(path.to_s)
end
end
end
# Insert a nil for each thread to stop it
num_threads.times do
in_queue << nil
end
old_locale = I18n.locale
I18n.locale = :en # use the english localizations for printing out file sizes to make sure the localizations exist
num_paths.times do
output_filename, old_size, new_size = out_queue.pop
if output_filename
total_savings += (old_size - new_size)
size_change_word = (old_size - new_size) > 0 ? 'smaller' : 'larger'
builder.say_status :gzip, "#{output_filename} (#{app.number_to_human_size((old_size - new_size).abs)} #{size_change_word})"
end
end
builder.say_status :gzip, "Total gzip savings: #{app.number_to_human_size(total_savings)}", :blue
I18n.locale = old_locale
end
def gzip_file(path)
input_file = File.open(path, 'rb').read
output_filename = path + '.gz'
input_file_time = File.mtime(path)
# Check if the right file's already there
if File.exist?(output_filename) && File.mtime(output_filename) == input_file_time
return [nil, nil, nil]
end
File.open(output_filename, 'wb') do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.mtime = input_file_time.to_i
gz.write input_file
gz.close
end
# Make the file times match, both for Nginx's gzip_static extension
# and so we can ID existing files. Also, so even if the GZ files are
# wiped out by build --clean and recreated, we won't rsync them over
# again because they'll end up with the same mtime.
File.utime(File.atime(output_filename), input_file_time, output_filename)
old_size = File.size(path)
new_size = File.size(output_filename)
[output_filename, old_size, new_size]
end
end
| 32.453608 | 131 | 0.690915 |
d536e1d4d7491a9a29b868b0a526f113a736733f | 260 | class CreateCoffees < ActiveRecord::Migration[6.0]
def change
create_table :coffees do |t|
t.string :name
t.string :notes
t.string :roast
t.belongs_to :roaster, null: false, foreign_key: true
t.timestamps
end
end
end
| 20 | 59 | 0.65 |
21fb98fdde3d8e8e7bc7dd739d4640630482ad1d | 935 | #
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
require 'ingenico/connect/sdk/factory'
require 'ingenico/connect/sdk/domain/payment/capture_payment_request'
Payment = Ingenico::Connect::SDK::Domain::Payment
def example
get_client do |client|
body = Payment::CapturePaymentRequest.new
body.amount = 2980
response = client.merchant('merchantId').payments().capture('paymentId', body)
end
end
def get_client
api_key_id = ENV.fetch('connect.api.apiKeyId', 'someKey')
secret_api_key = ENV.fetch('connect.api.secretApiKey', 'someSecret')
configuration_file_name = File.join(__FILE__, '..', '..', 'example_configuration.yml')
yield client = Ingenico::Connect::SDK::Factory.create_client_from_file(configuration_file_name, api_key_id, secret_api_key)
ensure
# Free networking resources when done
client.close unless client.nil?
end
| 33.392857 | 125 | 0.765775 |
389cc86a35bf6ee4a3f298d378b73fdad3b95bf5 | 137 | FactoryGirl.define do
factory :page do
title 'Test page'
name 'test-page'
path '/test-page'
root_folder_id 1
end
end
| 15.222222 | 21 | 0.656934 |
6ac8bd8282b84fb2f01d282c95948ca326683c69 | 131 | class AddFluidPreferenceToUser < ActiveRecord::Migration
def change
add_column :users, :fluid_preference, :boolean
end
end
| 21.833333 | 56 | 0.78626 |
1165f91707e97ca7a41a1d280738c317f78a96e7 | 19 | test_variable = 42 | 19 | 19 | 0.789474 |
b924affa50f22c5281e4a27ac814aa613a913b6f | 3,817 | require 'spec_helper'
describe Spree::Admin::FavoriteProductsController do
let(:role) { Spree::Role.create!(name: 'user') }
let(:roles) { [role] }
let(:product) { mock_model( Spree::Product) }
let(:proxy_object) { Object.new }
before(:each) do
@user = mock_model(Spree::User, generate_spree_api_key!: false)
allow(@user).to receive(:roles).and_return(proxy_object)
allow(proxy_object).to receive(:includes).and_return([])
allow(@user).to receive(:has_spree_role?).with('admin').and_return(true)
allow(controller).to receive(:spree_user_signed_in?).and_return(true)
allow(controller).to receive(:spree_current_user).and_return(@user)
allow(@user).to receive(:roles).and_return(roles)
allow(roles).to receive(:includes).with(:permissions).and_return(roles)
allow(controller).to receive(:authorize_admin).and_return(true)
allow(controller).to receive(:authorize!).and_return(true)
@favorite_products = double('favorite_products')
allow(@favorite_products).to receive(:includes).and_return(@favorite_products)
allow(@favorite_products).to receive(:order_by_favorite_users_count).and_return(@favorite_products)
allow(@favorite_products).to receive(:joins).and_return(@favorite_products)
@search = double('search', result: @favorite_products)
allow(@favorite_products).to receive(:search).and_return(@search)
allow(@favorite_products).to receive(:page).and_return(@favorite_products)
allow(@favorite_products).to receive(:per).and_return(@favorite_products)
allow(Spree::Product).to receive(:favorite).and_return(@favorite_products)
end
describe "GET index" do
def send_request
get :index, params: { page: 1, q: { s: 'name desc' } }
end
it "returns favorite products" do
expect(Spree::Product).to receive(:favorite)
send_request
end
it "searches favorite products" do
search_params = ActionController::Parameters.new(s: 'name desc')
expect(@favorite_products).to receive(:search).with(search_params)
send_request
end
it "assigns @search" do
send_request
expect(assigns(:search)).to eq(@search)
end
context 'when order favorite products by users count in asc order' do
def send_request
get :index, params: { page: 1, q: { s: 'favorite_users_count asc' } }
end
it "orders favorite products by users count in asc order" do
expect(@favorite_products).to receive(:order_by_favorite_users_count).with(true)
send_request
end
end
context 'when order favorite products by users count in desc order' do
it "orders favorite products by users count in asc order" do
expect(@favorite_products).to receive(:order_by_favorite_users_count).with(false)
send_request
end
end
it "paginates favorite products" do
expect(@favorite_products).to receive(:page).with("1")
send_request
end
it "renders favorite products template" do
send_request
expect(response).to render_template(:index)
end
end
describe "#sort_in_ascending_users_count?" do
context 'when favorite_user_count asc present in params[q][s]' do
def send_request
get :index, params: { page: 1, q: { s: 'favorite_users_count asc' } }
end
it "is true" do
expect(controller.send(:sort_in_ascending_users_count?)).to be true
end
before do
send_request
end
end
context 'when favorite_user_count not present in params' do
def send_request
get :index, params: { page: 1, q: { s: 'name asc' } }
end
it "is false" do
expect(controller.send(:sort_in_ascending_users_count?)).to be false
end
before do
send_request
end
end
end
end
| 33.482456 | 103 | 0.690333 |
ff3b7d2004348cb2dcdeeb21c78f48e20ce6b265 | 333 | module PagSeguro
class Document
include Extensions::Assignment
# Set the type.
attr_accessor :type
# Set the value.
attr_accessor :value
def ==(other)
[type, value] == [other.type, other.value]
end
def cpf?
type == 'CPF'
end
def cnpj?
type == 'CNPJ'
end
end
end
| 13.875 | 48 | 0.570571 |
7a3d5214c7c68506d0b88354dd6c5a8ac7c9ba16 | 5,987 | # frozen_string_literal: true
module Committee
module SchemaValidator
class OpenAPI3
class OperationWrapper
# # @param request_operation [OpenAPIParser::RequestOperation]
def initialize(request_operation)
@request_operation = request_operation
end
def path_params
request_operation.path_params
end
def original_path
request_operation.original_path
end
def coerce_path_parameter(validator_option)
options = build_openapi_parser_path_option(validator_option)
return {} unless options.coerce_value
request_operation.validate_path_params(options)
rescue OpenAPIParser::OpenAPIError => e
raise Committee::InvalidRequest.new(e.message)
end
# @param [Boolean] strict when not content_type or status code definition, raise error
def validate_response_params(status_code, headers, response_data, strict, check_header)
response_body = OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, response_data, headers)
return request_operation.validate_response_body(response_body, response_validate_options(strict, check_header))
rescue OpenAPIParser::OpenAPIError => e
raise Committee::InvalidResponse.new(e.message)
end
def validate_request_params(params, headers, validator_option)
ret, err = case request_operation.http_method
when 'get'
validate_get_request_params(params, headers, validator_option)
when 'post'
validate_post_request_params(params, headers, validator_option)
when 'put'
validate_post_request_params(params, headers, validator_option)
when 'patch'
validate_post_request_params(params, headers, validator_option)
when 'delete'
validate_get_request_params(params, headers, validator_option)
else
raise "Committee OpenAPI3 not support #{request_operation.http_method} method"
end
raise err if err
ret
end
def valid_request_content_type?(content_type)
if (request_body = request_operation.operation_object&.request_body)
!request_body.select_media_type(content_type).nil?
else
# if not exist request body object, all content_type allow.
# because request body object required content field so when it exists there're content type definition.
true
end
end
def request_content_types
request_operation.operation_object&.request_body&.content&.keys || []
end
private
attr_reader :request_operation
# @!attribute [r] request_operation
# @return [OpenAPIParser::RequestOperation]
# @return [OpenAPIParser::SchemaValidator::Options]
def build_openapi_parser_path_option(validator_option)
coerce_value = validator_option.coerce_path_params
datetime_coerce_class = validator_option.coerce_date_times ? DateTime : nil
validate_header = validator_option.check_header
OpenAPIParser::SchemaValidator::Options.new(coerce_value: coerce_value,
datetime_coerce_class: datetime_coerce_class,
validate_header: validate_header)
end
# @return [OpenAPIParser::SchemaValidator::Options]
def build_openapi_parser_post_option(validator_option)
coerce_value = validator_option.coerce_form_params
datetime_coerce_class = validator_option.coerce_date_times ? DateTime : nil
validate_header = validator_option.check_header
OpenAPIParser::SchemaValidator::Options.new(coerce_value: coerce_value,
datetime_coerce_class: datetime_coerce_class,
validate_header: validate_header)
end
# @return [OpenAPIParser::SchemaValidator::Options]
def build_openapi_parser_get_option(validator_option)
coerce_value = validator_option.coerce_query_params
datetime_coerce_class = validator_option.coerce_date_times ? DateTime : nil
validate_header = validator_option.check_header
OpenAPIParser::SchemaValidator::Options.new(coerce_value: coerce_value,
datetime_coerce_class: datetime_coerce_class,
validate_header: validate_header)
end
def validate_get_request_params(params, headers, validator_option)
# bad performance because when we coerce value, same check
request_operation.validate_request_parameter(params, headers, build_openapi_parser_get_option(validator_option))
rescue OpenAPIParser::OpenAPIError => e
raise Committee::InvalidRequest.new(e.message)
end
def validate_post_request_params(params, headers, validator_option)
content_type = headers['Content-Type'].to_s.split(";").first.to_s
# bad performance because when we coerce value, same check
schema_validator_options = build_openapi_parser_post_option(validator_option)
request_operation.validate_request_parameter(params, headers, schema_validator_options)
request_operation.validate_request_body(content_type, params, schema_validator_options)
rescue => e
raise Committee::InvalidRequest.new(e.message)
end
def response_validate_options(strict, check_header)
::OpenAPIParser::SchemaValidator::ResponseValidateOptions.new(strict: strict, validate_header: check_header)
end
end
end
end
end
| 45.015038 | 123 | 0.663604 |
619fc8e7d38846ea73a8d2ff2d51991d50895992 | 1,764 | # frozen_string_literal: true
require 'spec_helper'
describe TrendingProject do
let(:user) { create(:user) }
let(:public_project1) { create(:project, :public) }
let(:public_project2) { create(:project, :public) }
let(:public_project3) { create(:project, :public) }
let(:private_project) { create(:project, :private) }
let(:internal_project) { create(:project, :internal) }
before do
3.times do
create(:note_on_commit, project: public_project1)
end
2.times do
create(:note_on_commit, project: public_project2)
end
create(:note_on_commit, project: public_project3, created_at: 5.weeks.ago)
create(:note_on_commit, project: private_project)
create(:note_on_commit, project: internal_project)
end
describe '.refresh!' do
before do
described_class.refresh!
end
it 'populates the trending projects table' do
expect(described_class.count).to eq(2)
end
it 'removes existing rows before populating the table' do
described_class.refresh!
expect(described_class.count).to eq(2)
end
it 'stores the project IDs for every trending project' do
rows = described_class.order(id: :asc).all
expect(rows[0].project_id).to eq(public_project1.id)
expect(rows[1].project_id).to eq(public_project2.id)
end
it 'does not store projects that fall out of the trending time range' do
expect(described_class.where(project_id: public_project3).any?).to eq(false)
end
it 'stores only public projects' do
expect(described_class.where(project_id: [public_project1.id, public_project2.id]).count).to eq(2)
expect(described_class.where(project_id: [private_project.id, internal_project.id]).count).to eq(0)
end
end
end
| 29.898305 | 105 | 0.706916 |
6affda77b595a122f904d1d67a75219e1d623cf9 | 1,215 | require 'spec_helper'
# mesos master service
describe 'mesos master service' do
it 'should be running' do
case RSpec.configuration.os
when 'Debian'
expect(service('mesos-master')).to be_running
end
end
end
describe port(5050) do
it { should be_listening }
end
describe command('curl -sD - http://localhost:5050/health -o /dev/null') do
its(:stdout) { should match(/200 OK/) }
end
describe file('/var/log/mesos/mesos-master.INFO') do
its(:content) { should match(/INFO level logging started/) }
its(:content) { should match(/Elected as the leading master!/) }
end
describe command('curl -sD - http://localhost:5050/state.json') do
its(:stdout) { should match(/"logging_level":"INFO"/) }
its(:stdout) { should match(/"cluster":"MyMesosCluster"/) }
its(:stdout) { should match(/"authenticate":"false"/) }
its(:stdout) { should match(/"authenticate_slaves":"false"/) }
its(:stdout) { should match(/"activated_slaves":\s*1/) }
end
describe file('/etc/mesos-chef/mesos-master') do
its(:content) { should contain 'exec 1> >\\(exec logger -p user.info -t "mesos-master"\\)' }
its(:content) { should contain 'exec 2> >\\(exec logger -p user.err -t "mesos-master"\\)' }
end
| 31.973684 | 94 | 0.678189 |
1d07b69b00b09d4672c1dde3b83c6d226d4f19d2 | 694 | # frozen_string_literal: true
require "test_helper"
module ActsAsAuthenticTest
class MagicColumnsTest < ActiveSupport::TestCase
def test_validates_numericality_of_login_count
u = User.new
u.login_count = -1
refute u.valid?
refute u.errors[:login_count].empty?
u.login_count = 0
refute u.valid?
assert u.errors[:login_count].empty?
end
def test_validates_numericality_of_failed_login_count
u = User.new
u.failed_login_count = -1
refute u.valid?
refute u.errors[:failed_login_count].empty?
u.failed_login_count = 0
refute u.valid?
assert u.errors[:failed_login_count].empty?
end
end
end
| 23.133333 | 57 | 0.690202 |
e2edb5a42eaae4ae14c82942a7230447077724d5 | 1,402 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160929042951) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "matchup_tables", force: :cascade do |t|
t.jsonb "matchups"
t.text "url"
t.float "max", default: 2.0
t.float "increment_value", default: 1.0
t.text "text"
t.text "link"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "visits", default: 0
t.boolean "default", default: false
end
end
| 41.235294 | 86 | 0.692582 |
18c0c37d1e563fe756d67139faeb7efecd11cca0 | 203 | Phccontactor::Engine.routes.draw do
# Message Routes
resources :messages, only: [:create]
get 'contact_us', to: 'messages#new'
# PHCAccounts Routes
mount Phcaccounts::Engine, :at => '/'
end
| 18.454545 | 39 | 0.689655 |
ed5be8d8e3024fe018a0d755e5b29d70078a1cbb | 1,015 | module Arcade
# Error handling
class Error < RuntimeError
end
class ArgumentError < ArgumentError
end
class SymbolError < ArgumentError
end
class LoadError < LoadError
end
class ImmutableError < RuntimeError
end
class RollbackError < RuntimeError
end
end # module Arcade
# Patching Object with universally accessible top level error method.
# The method is used throughout the lib instead of plainly raising exceptions.
# This allows lib user to easily inject user-specific error handling into the lib
# by just replacing Object#error method.
def error message, type=:standard, backtrace=nil
e = case type
when :standard
Arcade::Error.new message
when :args
Arcade::ArgumentError.new message
when :symbol
Arcade::SymbolError.new message
when :load
Arcade::LoadError.new message
when :immutable
Arcade::ImmutableError.new message
when :commit
Arcade::RollbackError.new message
end
e.set_backtrace(backtrace) if backtrace
raise e
end
| 21.595745 | 82 | 0.748768 |
6a64215ade8d291ba01d82283ed03d34e4a122bc | 1,922 | class Makefile2graph < Formula
desc "Create a graph of dependencies from GNU-Make"
homepage "https://github.com/lindenb/makefile2graph"
url "https://github.com/lindenb/makefile2graph/archive/v1.5.0.tar.gz"
sha256 "9464c6c1291609c211284a9889faedbab22ef504ce967b903630d57a27643b40"
license "MIT"
head "https://github.com/lindenb/makefile2graph.git"
bottle do
cellar :any_skip_relocation
sha256 "c8278a8691b682c5499295a79b73e18e18e87c879384b7d44dbcc0f70178ee58" => :big_sur
sha256 "af7dba0cbb045f067076706310b30c52eddbd6732e60d16017ccbfadd4bc866d" => :catalina
sha256 "5b5cb69a698628af41b3de70146580bbcb2e88a8b6d87d7fe9b4f58a2f2fdfb2" => :mojave
sha256 "51231ed0ef44fd31a10f4ea0a7500570181332786ddd5a8a9a886958ad1b1408" => :high_sierra
sha256 "274ee025c45df9757d608249d64105b9314c8e59fc52a81ad6906f807498b67c" => :sierra
sha256 "ed1939b1b0fd106f3e328e310a887cf454b81481f78fdf57ce75c0480a922d7d" => :el_capitan
sha256 "37aebae489e0f341f80417ec711e5c2817f5b8097c3493dcc11bc754bdd1b1cf" => :yosemite
sha256 "0de3d4a2492797c3259798493e287ac2403f02254c6cfcf74948a16bcc4bcd0d" => :mavericks
sha256 "d9cf1abfadeef69329bed8ebf251753f2aadb18f6955b8869a468a47b76b6f10" => :x86_64_linux
end
depends_on "graphviz"
def install
system "make"
# make test fails on CI. Error: fontconfig: Couldn't find font.
# It can be fixed with apt-get install fonts-dejavu-core
system "make", "test" unless ENV["CI"]
bin.install "make2graph", "makefile2graph"
man1.install "make2graph.1", "makefile2graph.1"
doc.install "LICENSE", "README.md", "screenshot.png"
end
test do
(testpath/"Makefile").write <<~EOS
all: foo
all: bar
foo: ook
bar: ook
ook:
EOS
system "make -Bnd >make-Bnd"
system "#{bin}/make2graph <make-Bnd"
system "#{bin}/make2graph --root <make-Bnd"
system "#{bin}/makefile2graph"
end
end
| 40.041667 | 94 | 0.759625 |
01fc5c3c65ceb7c1748b759a79892abef0a604da | 259 | require 'rails_helper'
RSpec.describe ReputationJob, type: :job do
let(:question) { create(:question) }
it 'calls ReputationJob' do
expect(Services::Reputation).to receive(:calculate).with(question)
ReputationJob.perform_now(question)
end
end
| 23.545455 | 70 | 0.745174 |
b9bc1abfbe228c7c63cc633cfdb68719539b6e89 | 4,962 | require "rails_helper"
RSpec.describe ResponsiblePersonAddressLog, type: :model do
describe "validations" do
subject(:address_log) { build_stubbed(:responsible_person_address_log) }
it "fails if a street address is not specified" do
address_log.line_1 = nil
expect(address_log.valid?).to be false
expect(address_log.errors[:line_1]).to include("Line 1 can not be blank")
end
it "fails if a city is not specified" do
address_log.city = nil
expect(address_log.valid?).to be false
expect(address_log.errors[:city]).to include("City can not be blank")
end
it "fails if a postal code is not specified" do
address_log.postal_code = nil
expect(address_log.valid?).to be false
expect(address_log.errors[:postal_code]).to include("Postal code can not be blank")
end
it "fails if postal code does not belong to UK" do
address_log.postal_code = "JJJJJ"
expect(address_log.valid?).to be false
expect(address_log.errors[:postal_code]).to include("Enter a UK postcode")
end
it "acepts the second line and county not being specified" do
address_log.line_2 = nil
address_log.county = nil
expect(address_log.valid?).to be true
end
it "fails if the end date is earlier than start date" do
address_log.start_date = Time.zone.local(2021, 7, 1)
address_log.end_date = Time.zone.local(2020, 5, 1)
expect(address_log.valid?).to be false
expect(address_log.errors[:end_date]).to include("End date must be after start date")
end
end
describe "end date set on callback" do
let(:current_time) { Time.zone.local(2021, 9, 3) }
before { travel_to current_time }
after { travel_back }
it "autopopulates the end date to the current time when not provided" do
address_log = build_stubbed(:responsible_person_address_log, end_date: nil)
address_log.validate
expect(address_log.end_date).to eq(Time.zone.now)
end
it "keeps the given end date when provided" do
given_date = Time.zone.local(2021, 8, 1)
address_log = build_stubbed(:responsible_person_address_log, end_date: given_date)
address_log.validate
expect(address_log.end_date).to eq(given_date)
end
end
describe "start date set on callback" do
let(:responsible_person) { create(:responsible_person, created_at: Time.zone.local(2021, 7, 1)) }
context "when there where other previous addresses associated with the responsible person" do
before do
create(:responsible_person_address_log,
responsible_person: responsible_person,
start_date: Time.zone.local(2021, 7, 1),
end_date: Time.zone.local(2021, 8, 1))
create(:responsible_person_address_log,
responsible_person: responsible_person,
start_date: Time.zone.local(2021, 8, 1),
end_date: Time.zone.local(2021, 9, 1))
end
it "populates the start date with the last previous address end date" do
address_log = build_stubbed(:responsible_person_address_log,
responsible_person: responsible_person,
start_date: nil)
address_log.validate
expect(address_log.start_date).to eq(Time.zone.local(2021, 9, 1))
end
end
context "when there aren't previous addresses associated with the responsible person" do
it "populates the start date with the Responsible Person creation date" do
address_log = build_stubbed(:responsible_person_address_log,
responsible_person: responsible_person,
start_date: nil)
address_log.validate
expect(address_log.start_date).to eq(responsible_person.created_at)
end
end
end
describe "#to_s" do
# rubocop:disable RSpec/ExampleLength
it "returns the address in a human readable format" do
address_log = build_stubbed(:responsible_person_address_log,
line_1: "Office name",
line_2: "123 Street",
city: "London",
county: "Greater London",
postal_code: "SW1A 1AA")
expect(address_log.to_s).to eq("Office name, 123 Street, London, Greater London, SW1A 1AA")
end
it "does not include empty fields" do
address_log = build_stubbed(:responsible_person_address_log,
line_1: "Office name",
line_2: nil,
city: "London",
county: nil,
postal_code: "SW1A 1AA")
expect(address_log.to_s).to eq("Office name, London, SW1A 1AA")
end
# rubocop:enable RSpec/ExampleLength
end
end
| 38.169231 | 101 | 0.631802 |
6abf73dfe6fc55e048b8bd47dbf41d106dc06e08 | 241 | # frozen_string_literal: true
organization_name = 'IKIA'
puts "Running seeds for organization #{organization_name}"
organization = Organization.find_by(name: organization_name)
organization ||= Organization.create!(name: organization_name)
| 34.428571 | 62 | 0.817427 |
08c9b563da652f7e5687d5ae64edda361213e8db | 347 | require 'raven'
require 'raven/integrations/rack'
require 'sinatra/base'
module Travis
module Api
module Build
class Sentry < Sinatra::Base
configure do
Raven.configure do |config|
config.tags = { environment: environment }
end
use Raven::Rack
end
end
end
end
end
| 18.263158 | 54 | 0.596542 |
91fb637525414c505eddc6794bc81fcc754843cd | 473 | module ConsoleUtils #:nodoc:
module ActiveRecordUtils
extend ActiveSupport::Autoload
autoload :RandomRecord
def self.extended(mod)
ActiveSupport.on_load(:active_record) do
ActiveRecord::Relation.send(:prepend, RandomRecord::FinderMethods)
ActiveRecord::Base.send(:extend, RandomRecord::Querying)
end
end
# Shortcut to <tt>ConsoleUtils.find_user(id)</tt>
def usr(id)
ConsoleUtils.find_user(id)
end
end
end | 24.894737 | 74 | 0.699789 |
337e953200abb49adf515d3a65d9f258d99dd1b5 | 451 | Puppet::Type.newtype(:swift_ring_build_helper) do
@doc = "Base resource definition for building swift rings"
ensurable
newparam(:name) do
desc "A unique name for the resource"
end
newproperty(:swift_storage_ips, :array_matching => :all) do
desc "an array of the ip addresses of the swift storage nodes"
end
newproperty(:swift_storage_device) do
desc "the name of the storage device on each swift node"
end
end
| 23.736842 | 70 | 0.720621 |
1d56f1b059a9ace139c09240b8547106d0e2dc20 | 431 | cask 'thedesk' do
version '18.7.1'
sha256 '0e92ed2ab9b61fe9b113ae3c90af9e90281f83f1c76af2aca53a8ccda3016252'
# github.com/cutls/TheDesk was verified as official when first introduced to the cask
url "https://github.com/cutls/TheDesk/releases/download/v#{version}/TheDesk-#{version}.dmg"
appcast 'https://github.com/cutls/TheDesk/releases.atom'
name 'TheDesk'
homepage 'https://thedesk.top/'
app 'TheDesk.app'
end
| 33.153846 | 93 | 0.763341 |
ed3286180299a63d1bba5508a52c173c19be56f6 | 3,271 | require 'tempfile'
require 'fileutils'
require 'galaxy/filter'
require 'galaxy/temp'
require 'galaxy/transport'
require 'galaxy/version'
require 'galaxy/versioning'
module Helper
def Helper.mk_tmpdir
Galaxy::Temp.mk_auto_dir "testing"
end
class Mock
def initialize listeners={}
@listeners = listeners
end
def method_missing sym, *args
f = @listeners[sym]
if f
f.call(*args)
end
end
end
end
class MockConsole
def initialize agents
@agents = agents
end
def shutdown
end
def agents filters = { :set => :all }
filter = Galaxy::Filter.new filters
@agents.select(&filter)
end
end
class MockAgent
attr_reader :agent_id, :agent_group, :config_path, :stopped, :started, :restarted
attr_reader :gonsole_url, :env, :version, :type, :url, :agent_status, :proxy, :build, :core_type, :machine, :ip
attr_reader :build_version
def initialize agent_id, agent_group, url, env = nil, version = nil, type = nil, gonsole_url=nil
@agent_id = agent_id
@agent_group = agent_group
@env = env
@version = version
@type = type
@gonsole_url = gonsole_url
@stopped = @started = @restarted = false
@url = url
Galaxy::Transport.publish @url, self
@config_path = nil
@config_path = "/#{env}/#{version}/#{type}" unless env.nil? || version.nil? || type.nil?
@agent_status = 'online'
@status = 'online'
@proxy = Galaxy::Transport.locate(@url)
@build = "1.2.3"
@core_type = 'test'
@ip = nil
@drb_url = nil
@os = nil
@machine = nil
@build_version = nil
end
def shutdown
Galaxy::Transport.unpublish @url
end
def status
OpenStruct.new(
:agent_id => @agent_id,
:agent_group => @agent_group,
:url => @drb_url,
:os => @os,
:machine => @machine,
:core_type => @core_type,
:config_path => @config_path,
:build => @build,
:status => @status,
:agent_status => 'online',
:galaxy_version => Galaxy::Version
)
end
def stop!
@stopped = true
status
end
def start!
@started = true
status
end
def restart!
@restarted = true
status
end
def become! req_build_version, path, config_uri=nil, binaries_uri=nil, versioning_policy = Galaxy::Versioning::StrictVersioningPolicy
md = %r!^/([^/]+)/([^/]+)/(.*)$!.match path
new_env, new_version, new_type = md[1], md[2], md[3]
# XXX We don't test the versioning code - but it should go away soon
#raise if @version == new_version
@env = new_env
@version = new_version
@type = new_type
@config_path = "/#{@env}/#{@version}/#{@type}"
@build_version = req_build_version
status
end
def update_config! new_version, config_uri=nil, binaries_uri=nil, versioning_policy = Galaxy::Versioning::StrictVersioningPolicy
# XXX We don't test the versioning code - but it should go away soon
#raise if @version == new_version
@version = new_version
@config_path = "/#{@env}/#{@version}/#{@type}"
status
end
def check_credentials!(command, credentials)
true
end
def inspect
Galaxy::Client::SoftwareDeploymentReport.new.record_result(self)
end
end
| 23.035211 | 135 | 0.631611 |
38747e0aadf44158e476883d1fb8166437a2f980 | 15,377 | # typed: false
# frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/bottle"
describe "Homebrew.bottle_args" do
it_behaves_like "parseable arguments"
end
describe "brew bottle", :integration_test do
it "builds a bottle for the given Formula" do
# create stub patchelf
if OS.linux?
setup_test_formula "patchelf"
patchelf = HOMEBREW_CELLAR/"patchelf/1.0/bin/patchelf"
patchelf.dirname.mkpath
patchelf.write <<~EOS
#!/bin/sh
exit 0
EOS
FileUtils.chmod "+x", patchelf
FileUtils.ln_s patchelf, HOMEBREW_PREFIX/"bin/patchelf"
end
install_test_formula "testball", build_bottle: true
# `brew bottle` should not fail with dead symlink
# https://github.com/Homebrew/legacy-homebrew/issues/49007
(HOMEBREW_CELLAR/"testball/0.1").cd do
FileUtils.ln_s "not-exist", "symlink"
end
begin
expect { brew "bottle", "--no-rebuild", "testball" }
.to output(/testball--0\.1.*\.bottle\.tar\.gz/).to_stdout
.and not_to_output.to_stderr
.and be_a_success
ensure
FileUtils.rm_f Dir.glob("testball--0.1*.bottle.tar.gz")
end
end
end
def stub_hash(parameters)
<<~EOS
{
"#{parameters[:name]}":{
"formula":{
"pkg_version":"#{parameters[:version]}",
"path":"#{parameters[:path]}"
},
"bottle":{
"root_url":"#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}",
"prefix":"/usr/local",
"cellar":"#{parameters[:cellar]}",
"rebuild":0,
"tags":{
"#{parameters[:os]}":{
"filename":"#{parameters[:filename]}",
"local_filename":"#{parameters[:local_filename]}",
"sha256":"#{parameters[:sha256]}"
}
}
},
"bintray":{
"package":"#{parameters[:name]}",
"repository":"bottles"
}
}
}
EOS
end
describe Homebrew do
subject(:homebrew) { described_class }
let(:hello_hash_big_sur) {
JSON.parse(
stub_hash(
{
"name": "hello",
"version": "1.0",
"path": "/home/hello.rb",
"cellar": "any_skip_relocation",
"os": "big_sur",
"filename": "hello-1.0.big_sur.bottle.tar.gz",
"local_filename": "hello--1.0.big_sur.bottle.tar.gz",
"sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
},
),
)
}
let(:hello_hash_catalina) {
JSON.parse(
stub_hash(
{
"name": "hello",
"version": "1.0",
"path": "/home/hello.rb",
"cellar": "any_skip_relocation",
"os": "catalina",
"filename": "hello-1.0.catalina.bottle.tar.gz",
"local_filename": "hello--1.0.catalina.bottle.tar.gz",
"sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
},
),
)
}
let(:unzip_hash_big_sur) {
JSON.parse(
stub_hash(
{
"name": "unzip",
"version": "2.0",
"path": "/home/unzip.rb",
"cellar": "any_skip_relocation",
"os": "big_sur",
"filename": "unzip-2.0.big_sur.bottle.tar.gz",
"local_filename": "unzip--2.0.big_sur.bottle.tar.gz",
"sha256": "16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72",
},
),
)
}
let(:unzip_hash_catalina) {
JSON.parse(
stub_hash(
{
"name": "unzip",
"version": "2.0",
"path": "/home/unzip.rb",
"cellar": "any",
"os": "catalina",
"filename": "unzip-2.0.catalina.bottle.tar.gz",
"local_filename": "unzip--2.0.catalina.bottle.tar.gz",
"sha256": "d9cc50eec8ac243148a121049c236cba06af4a0b1156ab397d0a2850aa79c137",
},
),
)
}
specify "::parse_json_files" do
Tempfile.open("hello--1.0.big_sur.bottle.json") do |f|
f.write(
stub_hash(
{
"name": "hello",
"version": "1.0",
"path": "/home/hello.rb",
"cellar": "any_skip_relocation",
"os": "big_sur",
"filename": "hello-1.0.big_sur.bottle.tar.gz",
"local_filename": "hello--1.0.big_sur.bottle.tar.gz",
"sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
},
),
)
f.close
expect(
homebrew.parse_json_files([f.path]).first["hello"]["bottle"]["tags"]["big_sur"]["filename"],
).to eq("hello-1.0.big_sur.bottle.tar.gz")
end
end
specify "::merge_json_files" do
bottles_hash = homebrew.merge_json_files(
[hello_hash_big_sur, hello_hash_catalina, unzip_hash_big_sur, unzip_hash_catalina],
)
hello_hash = bottles_hash["hello"]
expect(hello_hash["bottle"]["cellar"]).to eq("any_skip_relocation")
expect(hello_hash["bottle"]["tags"]["big_sur"]["filename"]).to eq("hello-1.0.big_sur.bottle.tar.gz")
expect(hello_hash["bottle"]["tags"]["big_sur"]["local_filename"]).to eq("hello--1.0.big_sur.bottle.tar.gz")
expect(hello_hash["bottle"]["tags"]["big_sur"]["sha256"]).to eq(
"a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
)
expect(hello_hash["bottle"]["tags"]["catalina"]["filename"]).to eq("hello-1.0.catalina.bottle.tar.gz")
expect(hello_hash["bottle"]["tags"]["catalina"]["local_filename"]).to eq("hello--1.0.catalina.bottle.tar.gz")
expect(hello_hash["bottle"]["tags"]["catalina"]["sha256"]).to eq(
"5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
)
unzip_hash = bottles_hash["unzip"]
expect(unzip_hash["bottle"]["cellar"]).to eq("any")
expect(unzip_hash["bottle"]["tags"]["big_sur"]["filename"]).to eq("unzip-2.0.big_sur.bottle.tar.gz")
expect(unzip_hash["bottle"]["tags"]["big_sur"]["local_filename"]).to eq("unzip--2.0.big_sur.bottle.tar.gz")
expect(unzip_hash["bottle"]["tags"]["big_sur"]["sha256"]).to eq(
"16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72",
)
expect(unzip_hash["bottle"]["tags"]["catalina"]["filename"]).to eq("unzip-2.0.catalina.bottle.tar.gz")
expect(unzip_hash["bottle"]["tags"]["catalina"]["local_filename"]).to eq("unzip--2.0.catalina.bottle.tar.gz")
expect(unzip_hash["bottle"]["tags"]["catalina"]["sha256"]).to eq(
"d9cc50eec8ac243148a121049c236cba06af4a0b1156ab397d0a2850aa79c137",
)
end
end
describe "brew bottle --merge", :integration_test, :needs_linux do
let(:core_tap) { CoreTap.new }
let(:tarball) do
if OS.linux?
TEST_FIXTURE_DIR/"tarballs/testball-0.1-linux.tbz"
else
TEST_FIXTURE_DIR/"tarballs/testball-0.1.tbz"
end
end
before do
Pathname("testball-1.0.big_sur.bottle.json").write stub_hash(
"name": "testball",
"version": "1.0",
"path": "#{core_tap.path}/Formula/testball.rb",
"cellar": "any_skip_relocation",
"os": "big_sur",
"filename": "hello-1.0.big_sur.bottle.tar.gz",
"local_filename": "hello--1.0.big_sur.bottle.tar.gz",
"sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
)
Pathname("testball-1.0.catalina.bottle.json").write stub_hash(
"name": "testball",
"version": "1.0",
"path": "#{core_tap.path}/Formula/testball.rb",
"cellar": "any_skip_relocation",
"os": "catalina",
"filename": "testball-1.0.catalina.bottle.tar.gz",
"local_filename": "testball--1.0.catalina.bottle.tar.gz",
"sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
)
end
after do
FileUtils.rm_f "testball-1.0.catalina.bottle.json"
FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
end
it "adds the bottle block to a formula that has none" do
core_tap.path.cd do
system "git", "init"
setup_test_formula "testball"
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.1"
end
expect {
brew "bottle",
"--merge",
"--write",
"testball-1.0.big_sur.bottle.json",
"testball-1.0.catalina.bottle.json"
}.to output(
<<~EOS,
==> testball
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
end
EOS
).to_stdout
expect((core_tap.path/"Formula/testball.rb").read).to eq(
<<~EOS,
class Testball < Formula
desc "Some test"
homepage "https://brew.sh/testball"
url "file://#{tarball}"
sha256 "#{tarball.sha256}"
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
end
option "with-foo", "Build with foo"
def install
(prefix/"foo"/"test").write("test") if build.with? "foo"
prefix.install Dir["*"]
(buildpath/"test.c").write \
"#include <stdio.h>\\nint main(){printf(\\"test\\");return 0;}"
bin.mkpath
system ENV.cc, "test.c", "-o", bin/"test"
end
# something here
end
EOS
)
end
it "replaces the bottle block in a formula that already has a bottle block" do
core_tap.path.cd do
system "git", "init"
bottle_block = <<~EOS
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "6b276491297d4052538bd2fd22d5129389f27d90a98f831987236a5b90511b98" => :big_sur
sha256 "16cf230afdfcb6306c208d169549cf8773c831c8653d2c852315a048960d7e72" => :catalina
end
EOS
setup_test_formula("testball", "", bottle_block)
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.1"
end
expect {
brew "bottle",
"--merge",
"--write",
"testball-1.0.big_sur.bottle.json",
"testball-1.0.catalina.bottle.json"
}.to output(
<<~EOS,
==> testball
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
end
EOS
).to_stdout
expect((core_tap.path/"Formula/testball.rb").read).to eq(
<<~EOS,
class Testball < Formula
desc "Some test"
homepage "https://brew.sh/testball"
url "file://#{tarball}"
sha256 "#{tarball.sha256}"
option "with-foo", "Build with foo"
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
end
def install
(prefix/"foo"/"test").write("test") if build.with? "foo"
prefix.install Dir["*"]
(buildpath/"test.c").write \
"#include <stdio.h>\\nint main(){printf(\\"test\\");return 0;}"
bin.mkpath
system ENV.cc, "test.c", "-o", bin/"test"
end
# something here
end
EOS
)
end
it "fails to add the bottle block to a formula that has no bottle block when using --keep-old" do
core_tap.path.cd do
system "git", "init"
setup_test_formula("testball")
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.1"
end
expect {
brew "bottle",
"--merge",
"--write",
"--keep-old",
"testball-1.0.big_sur.bottle.json",
"testball-1.0.catalina.bottle.json"
}.to output("Error: --keep-old was passed but there was no existing bottle block!\n").to_stderr
end
it "updates the bottle block in a formula that already has a bottle block when using --keep-old" do
core_tap.path.cd do
system "git", "init"
bottle_block = <<~EOS
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" => :high_sierra
end
EOS
setup_test_formula("testball", "", bottle_block)
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.1"
end
expect {
brew "bottle",
"--merge",
"--write",
"--keep-old",
"testball-1.0.big_sur.bottle.json",
"testball-1.0.catalina.bottle.json"
}.to output(
<<~EOS,
==> testball
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
sha256 "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" => :high_sierra
end
EOS
).to_stdout
expect((core_tap.path/"Formula/testball.rb").read).to eq(
<<~EOS,
class Testball < Formula
desc "Some test"
homepage "https://brew.sh/testball"
url "file://#{tarball}"
sha256 "#{tarball.sha256}"
option "with-foo", "Build with foo"
bottle do
root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
cellar :any_skip_relocation
sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
sha256 "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" => :high_sierra
end
def install
(prefix/"foo"/"test").write("test") if build.with? "foo"
prefix.install Dir["*"]
(buildpath/"test.c").write \
"#include <stdio.h>\\nint main(){printf(\\"test\\");return 0;}"
bin.mkpath
system ENV.cc, "test.c", "-o", bin/"test"
end
# something here
end
EOS
)
end
end
| 33.574236 | 113 | 0.577876 |
211d3d847f2cac162306cb58b38db39d0ed2ba5b | 23,435 | require 'spec_helper'
describe GitPushService, services: true do
include RepoHelpers
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
before do
project.team << [user, :master]
@blankrev = Gitlab::Git::BLANK_SHA
@oldrev = sample_commit.parent_id
@newrev = sample_commit.id
@ref = 'refs/heads/master'
end
describe 'Push branches' do
let(:oldrev) { @oldrev }
let(:newrev) { @newrev }
subject do
execute_service(project, user, oldrev, newrev, @ref )
end
context 'new branch' do
let(:oldrev) { @blankrev }
it { is_expected.to be_truthy }
it 'calls the after_push_commit hook' do
expect(project.repository).to receive(:after_push_commit).with('master')
subject
end
it 'calls the after_create_branch hook' do
expect(project.repository).to receive(:after_create_branch)
subject
end
end
context 'existing branch' do
it { is_expected.to be_truthy }
it 'calls the after_push_commit hook' do
expect(project.repository).to receive(:after_push_commit).with('master')
subject
end
end
context 'rm branch' do
let(:newrev) { @blankrev }
it { is_expected.to be_truthy }
it 'calls the after_push_commit hook' do
expect(project.repository).to receive(:after_push_commit).with('master')
subject
end
it 'calls the after_remove_branch hook' do
expect(project.repository).to receive(:after_remove_branch)
subject
end
end
end
describe "Git Push Data" do
before do
service = execute_service(project, user, @oldrev, @newrev, @ref )
@push_data = service.push_data
@commit = project.commit(@newrev)
end
subject { @push_data }
it { is_expected.to include(object_kind: 'push') }
it { is_expected.to include(before: @oldrev) }
it { is_expected.to include(after: @newrev) }
it { is_expected.to include(ref: @ref) }
it { is_expected.to include(user_id: user.id) }
it { is_expected.to include(user_name: user.name) }
it { is_expected.to include(project_id: project.id) }
context "with repository data" do
subject { @push_data[:repository] }
it { is_expected.to include(name: project.name) }
it { is_expected.to include(url: project.url_to_repo) }
it { is_expected.to include(description: project.description) }
it { is_expected.to include(homepage: project.web_url) }
end
context "with commits" do
subject { @push_data[:commits] }
it { is_expected.to be_an(Array) }
it 'has 1 element' do
expect(subject.size).to eq(1)
end
context "the commit" do
subject { @push_data[:commits].first }
it { is_expected.to include(id: @commit.id) }
it { is_expected.to include(message: @commit.safe_message) }
it { is_expected.to include(timestamp: @commit.date.xmlschema) }
it do
is_expected.to include(
url: [
Gitlab.config.gitlab.url,
project.namespace.to_param,
project.to_param,
'commit',
@commit.id
].join('/')
)
end
context "with a author" do
subject { @push_data[:commits].first[:author] }
it { is_expected.to include(name: @commit.author_name) }
it { is_expected.to include(email: @commit.author_email) }
end
end
end
end
describe "ES indexing" do
before do
stub_application_setting(elasticsearch_search: true, elasticsearch_indexing: true)
end
after do
stub_application_setting(elasticsearch_search: false, elasticsearch_indexing: false)
end
it "does not trigger indexer when push to non-default branch" do
expect_any_instance_of(Gitlab::Elastic::Indexer).not_to receive(:run)
execute_service(project, user, @oldrev, @newrev, 'refs/heads/other')
end
it "triggers indexer when push to default branch" do
expect_any_instance_of(Gitlab::Elastic::Indexer).to receive(:run)
execute_service(project, user, @oldrev, @newrev, 'refs/heads/master')
end
end
describe "Push Event" do
before do
service = execute_service(project, user, @oldrev, @newrev, @ref )
@event = Event.find_by_action(Event::PUSHED)
@push_data = service.push_data
end
it { expect(@event).not_to be_nil }
it { expect(@event.project).to eq(project) }
it { expect(@event.action).to eq(Event::PUSHED) }
it { expect(@event.data).to eq(@push_data) }
context "Updates merge requests" do
it "when pushing a new branch for the first time" do
expect(UpdateMergeRequestsWorker).to receive(:perform_async).
with(project.id, user.id, @blankrev, 'newrev', 'refs/heads/master')
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
end
end
context "Sends System Push data" do
it "when pushing on a branch" do
expect(SystemHookPushWorker).to receive(:perform_async).with(@push_data, :push_hooks)
execute_service(project, user, @oldrev, @newrev, @ref )
end
end
end
describe "Updates git attributes" do
context "for default branch" do
it "calls the copy attributes method for the first push to the default branch" do
expect(project.repository).to receive(:copy_gitattributes).with('master')
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master')
end
it "calls the copy attributes method for changes to the default branch" do
expect(project.repository).to receive(:copy_gitattributes).with('refs/heads/master')
execute_service(project, user, 'oldrev', 'newrev', 'refs/heads/master')
end
end
context "for non-default branch" do
before do
# Make sure the "default" branch is different
allow(project).to receive(:default_branch).and_return('not-master')
end
it "does not call copy attributes method" do
expect(project.repository).not_to receive(:copy_gitattributes)
execute_service(project, user, @oldrev, @newrev, @ref)
end
end
end
describe "Webhooks" do
context "execute webhooks" do
it "when pushing a branch for the first time" do
expect(project).to receive(:execute_hooks)
expect(project.default_branch).to eq("master")
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
expect(project.protected_branches).not_to be_empty
expect(project.protected_branches.first.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::MASTER])
expect(project.protected_branches.first.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::MASTER])
end
it "when pushing a branch for the first time with default branch protection disabled" do
stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_NONE)
expect(project).to receive(:execute_hooks)
expect(project.default_branch).to eq("master")
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
expect(project.protected_branches).to be_empty
end
it "when pushing a branch for the first time with default branch protection set to 'developers can push'" do
stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_DEV_CAN_PUSH)
expect(project).to receive(:execute_hooks)
expect(project.default_branch).to eq("master")
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
expect(project.protected_branches).not_to be_empty
expect(project.protected_branches.last.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::DEVELOPER])
expect(project.protected_branches.last.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::MASTER])
end
it "when pushing a branch for the first time with an existing branch permission configured" do
stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_DEV_CAN_PUSH)
create(:protected_branch, :no_one_can_push, :developers_can_merge,
:remove_default_access_levels,
project: project, name: 'master')
expect(project).to receive(:execute_hooks)
expect(project.default_branch).to eq("master")
expect_any_instance_of(ProtectedBranches::CreateService).not_to receive(:execute)
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
expect(project.protected_branches).not_to be_empty
expect(project.protected_branches.last.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::NO_ACCESS])
expect(project.protected_branches.last.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::DEVELOPER])
end
it "when pushing a branch for the first time with default branch protection set to 'developers can merge'" do
stub_application_setting(default_branch_protection: Gitlab::Access::PROTECTION_DEV_CAN_MERGE)
expect(project).to receive(:execute_hooks)
expect(project.default_branch).to eq("master")
execute_service(project, user, @blankrev, 'newrev', 'refs/heads/master' )
expect(project.protected_branches).not_to be_empty
expect(project.protected_branches.first.push_access_levels.map(&:access_level)).to eq([Gitlab::Access::MASTER])
expect(project.protected_branches.first.merge_access_levels.map(&:access_level)).to eq([Gitlab::Access::DEVELOPER])
end
it "when pushing new commits to existing branch" do
expect(project).to receive(:execute_hooks)
execute_service(project, user, 'oldrev', 'newrev', 'refs/heads/master' )
end
end
end
describe "cross-reference notes" do
let(:issue) { create :issue, project: project }
let(:commit_author) { create :user }
let(:commit) { project.commit }
before do
project.team << [commit_author, :developer]
project.team << [user, :developer]
allow(commit).to receive_messages(
safe_message: "this commit \n mentions #{issue.to_reference}",
references: [issue],
author_name: commit_author.name,
author_email: commit_author.email
)
allow_any_instance_of(ProcessCommitWorker).to receive(:build_commit).
and_return(commit)
allow(project.repository).to receive(:commits_between).and_return([commit])
end
it "creates a note if a pushed commit mentions an issue" do
expect(SystemNoteService).to receive(:cross_reference).with(issue, commit, commit_author)
execute_service(project, user, @oldrev, @newrev, @ref )
end
it "only creates a cross-reference note if one doesn't already exist" do
SystemNoteService.cross_reference(issue, commit, user)
expect(SystemNoteService).not_to receive(:cross_reference).with(issue, commit, commit_author)
execute_service(project, user, @oldrev, @newrev, @ref )
end
it "defaults to the pushing user if the commit's author is not known" do
allow(commit).to receive_messages(
author_name: 'unknown name',
author_email: '[email protected]'
)
expect(SystemNoteService).to receive(:cross_reference).with(issue, commit, user)
execute_service(project, user, @oldrev, @newrev, @ref )
end
it "finds references in the first push to a non-default branch" do
allow(project.repository).to receive(:commits_between).with(@blankrev, @newrev).and_return([])
allow(project.repository).to receive(:commits_between).with("master", @newrev).and_return([commit])
expect(SystemNoteService).to receive(:cross_reference).with(issue, commit, commit_author)
execute_service(project, user, @blankrev, @newrev, 'refs/heads/other' )
end
end
describe "issue metrics" do
let(:issue) { create :issue, project: project }
let(:commit_author) { create :user }
let(:commit) { project.commit }
let(:commit_time) { Time.now }
before do
project.team << [commit_author, :developer]
project.team << [user, :developer]
allow(commit).to receive_messages(
safe_message: "this commit \n mentions #{issue.to_reference}",
references: [issue],
author_name: commit_author.name,
author_email: commit_author.email,
committed_date: commit_time
)
allow_any_instance_of(ProcessCommitWorker).to receive(:build_commit).
and_return(commit)
allow(project.repository).to receive(:commits_between).and_return([commit])
end
context "while saving the 'first_mentioned_in_commit_at' metric for an issue" do
it 'sets the metric for referenced issues' do
execute_service(project, user, @oldrev, @newrev, @ref)
expect(issue.reload.metrics.first_mentioned_in_commit_at).to be_like_time(commit_time)
end
it 'does not set the metric for non-referenced issues' do
non_referenced_issue = create(:issue, project: project)
execute_service(project, user, @oldrev, @newrev, @ref)
expect(non_referenced_issue.reload.metrics.first_mentioned_in_commit_at).to be_nil
end
end
end
describe "closing issues from pushed commits containing a closing reference" do
let(:issue) { create :issue, project: project }
let(:other_issue) { create :issue, project: project }
let(:commit_author) { create :user }
let(:closing_commit) { project.commit }
before do
allow(closing_commit).to receive_messages(
issue_closing_regex: /^([Cc]loses|[Ff]ixes) #\d+/,
safe_message: "this is some work.\n\ncloses ##{issue.iid}",
author_name: commit_author.name,
author_email: commit_author.email
)
allow(project.repository).to receive(:commits_between).
and_return([closing_commit])
allow_any_instance_of(ProcessCommitWorker).to receive(:build_commit).
and_return(closing_commit)
project.team << [commit_author, :master]
end
context "to default branches" do
it "closes issues" do
execute_service(project, commit_author, @oldrev, @newrev, @ref )
expect(Issue.find(issue.id)).to be_closed
end
it "adds a note indicating that the issue is now closed" do
expect(SystemNoteService).to receive(:change_status).with(issue, project, commit_author, "closed", closing_commit)
execute_service(project, commit_author, @oldrev, @newrev, @ref )
end
it "doesn't create additional cross-reference notes" do
expect(SystemNoteService).not_to receive(:cross_reference)
execute_service(project, commit_author, @oldrev, @newrev, @ref )
end
it "doesn't close issues when external issue tracker is in use" do
allow_any_instance_of(Project).to receive(:default_issues_tracker?).
and_return(false)
external_issue_tracker = double(title: 'My Tracker', issue_path: issue.iid, reference_pattern: project.issue_reference_pattern)
allow_any_instance_of(Project).to receive(:external_issue_tracker).and_return(external_issue_tracker)
# The push still shouldn't create cross-reference notes.
expect do
execute_service(project, commit_author, @oldrev, @newrev, 'refs/heads/hurf' )
end.not_to change { Note.where(project_id: project.id, system: true).count }
end
end
context "to non-default branches" do
before do
# Make sure the "default" branch is different
allow(project).to receive(:default_branch).and_return('not-master')
end
it "creates cross-reference notes" do
expect(SystemNoteService).to receive(:cross_reference).with(issue, closing_commit, commit_author)
execute_service(project, user, @oldrev, @newrev, @ref )
end
it "doesn't close issues" do
execute_service(project, user, @oldrev, @newrev, @ref )
expect(Issue.find(issue.id)).to be_opened
end
end
context "for jira issue tracker" do
include JiraServiceHelper
let(:jira_tracker) { project.create_jira_service if project.jira_service.nil? }
before do
# project.create_jira_service doesn't seem to invalidate the cache here
project.has_external_issue_tracker = true
jira_service_settings
stub_jira_urls("JIRA-1")
allow(closing_commit).to receive_messages({
issue_closing_regex: Regexp.new(Gitlab.config.gitlab.issue_closing_pattern),
safe_message: message,
author_name: commit_author.name,
author_email: commit_author.email
})
allow(project.repository).to receive_messages(commits_between: [closing_commit])
end
after do
jira_tracker.destroy!
end
context "mentioning an issue" do
let(:message) { "this is some work.\n\nrelated to JIRA-1" }
it "initiates one api call to jira server to mention the issue" do
execute_service(project, user, @oldrev, @newrev, @ref)
expect(WebMock).to have_requested(:post, jira_api_comment_url('JIRA-1')).with(
body: /mentioned this issue in/
).once
end
end
context "closing an issue" do
let(:message) { "this is some work.\n\ncloses JIRA-1" }
let(:comment_body) { { body: "Issue solved with [#{closing_commit.id}|http://#{Gitlab.config.gitlab.host}/#{project.path_with_namespace}/commit/#{closing_commit.id}]." }.to_json }
before do
open_issue = JIRA::Resource::Issue.new(jira_tracker.client, attrs: { "id" => "JIRA-1" })
closed_issue = open_issue.dup
allow(open_issue).to receive(:resolution).and_return(false)
allow(closed_issue).to receive(:resolution).and_return(true)
allow(JIRA::Resource::Issue).to receive(:find).and_return(open_issue, closed_issue)
allow_any_instance_of(JIRA::Resource::Issue).to receive(:key).and_return("JIRA-1")
end
context "using right markdown" do
it "initiates one api call to jira server to close the issue" do
execute_service(project, commit_author, @oldrev, @newrev, @ref )
expect(WebMock).to have_requested(:post, jira_api_transition_url('JIRA-1')).once
end
it "initiates one api call to jira server to comment on the issue" do
execute_service(project, commit_author, @oldrev, @newrev, @ref )
expect(WebMock).to have_requested(:post, jira_api_comment_url('JIRA-1')).with(
body: comment_body
).once
end
end
context "using wrong markdown" do
let(:message) { "this is some work.\n\ncloses #1" }
it "does not initiates one api call to jira server to close the issue" do
execute_service(project, commit_author, @oldrev, @newrev, @ref )
expect(WebMock).not_to have_requested(:post, jira_api_transition_url('JIRA-1'))
end
it "does not initiates one api call to jira server to comment on the issue" do
execute_service(project, commit_author, @oldrev, @newrev, @ref )
expect(WebMock).not_to have_requested(:post, jira_api_comment_url('JIRA-1')).with(
body: comment_body
).once
end
end
end
end
end
describe "empty project" do
let(:project) { create(:project_empty_repo) }
let(:new_ref) { 'refs/heads/feature'}
before do
allow(project).to receive(:default_branch).and_return('feature')
expect(project).to receive(:change_head) { 'feature'}
end
it 'push to first branch updates HEAD' do
execute_service(project, user, @blankrev, @newrev, new_ref )
end
end
describe "housekeeping" do
let(:housekeeping) { Projects::HousekeepingService.new(project) }
before do
# Flush any raw Redis data stored by the housekeeping code.
Gitlab::Redis.with { |conn| conn.flushall }
allow(Projects::HousekeepingService).to receive(:new).and_return(housekeeping)
end
after do
Gitlab::Redis.with { |conn| conn.flushall }
end
it 'does not perform housekeeping when not needed' do
expect(housekeeping).not_to receive(:execute)
execute_service(project, user, @oldrev, @newrev, @ref)
end
context 'when housekeeping is needed' do
before do
allow(housekeeping).to receive(:needed?).and_return(true)
end
it 'performs housekeeping' do
expect(housekeeping).to receive(:execute)
execute_service(project, user, @oldrev, @newrev, @ref)
end
it 'does not raise an exception' do
allow(housekeeping).to receive(:try_obtain_lease).and_return(false)
execute_service(project, user, @oldrev, @newrev, @ref)
end
end
it 'increments the push counter' do
expect(housekeeping).to receive(:increment!)
execute_service(project, user, @oldrev, @newrev, @ref)
end
end
describe '#update_caches' do
let(:service) do
described_class.new(project,
user,
oldrev: sample_commit.parent_id,
newrev: sample_commit.id,
ref: 'refs/heads/master')
end
context 'on the default branch' do
before do
allow(service).to receive(:is_default_branch?).and_return(true)
end
it 'flushes the caches of any special files that have been changed' do
commit = double(:commit)
diff = double(:diff, new_path: 'README.md')
expect(commit).to receive(:raw_diffs).with(deltas_only: true).
and_return([diff])
service.push_commits = [commit]
expect(ProjectCacheWorker).to receive(:perform_async).
with(project.id, %i(readme), %i(commit_count repository_size))
service.update_caches
end
end
context 'on a non-default branch' do
before do
allow(service).to receive(:is_default_branch?).and_return(false)
end
it 'does not flush any conditional caches' do
expect(ProjectCacheWorker).to receive(:perform_async).
with(project.id, [], %i(commit_count repository_size)).
and_call_original
service.update_caches
end
end
end
describe '#process_commit_messages' do
let(:service) do
described_class.new(project,
user,
oldrev: sample_commit.parent_id,
newrev: sample_commit.id,
ref: 'refs/heads/master')
end
it 'only schedules a limited number of commits' do
allow(service).to receive(:push_commits).
and_return(Array.new(1000, double(:commit, to_hash: {})))
expect(ProcessCommitWorker).to receive(:perform_async).exactly(100).times
service.process_commit_messages
end
end
def execute_service(project, user, oldrev, newrev, ref)
service = described_class.new(project, user, oldrev: oldrev, newrev: newrev, ref: ref )
service.execute
service
end
end
| 35.346908 | 190 | 0.66422 |
1cf5f9404cb10af8dc3ba655a33fc4f661279a43 | 4,516 | require 'spec_helper'
# Suppose the following class exists:
#
# class User < ActiveRecord::Base
# include Friendable::UserMethods
# end
describe Friendable::UserMethods do
def redis; Friendable.redis; end
before(:each) { redis.flushdb }
let(:current_user) { User.first }
let(:target_user) { User.last }
subject { current_user }
its(:friend_list_key) { should == "Users:friend_list:1" }
describe "#friend!" do
context "to add a friend" do
before { current_user.friend!(target_user) }
specify { current_user.friend?(target_user).should be_true }
specify { redis.hkeys(current_user.friend_list_key).should include(target_user.id.to_s) }
specify { redis.hkeys(target_user.friend_list_key).should include(current_user.id.to_s) }
end
context "to add a friend with several options" do
let(:friendship) { current_user.friend!(target_user, :foo => "bar", :hoge => "fuga") }
subject { friendship }
it { should be_a(Friendable::Friendship) }
its(:friend){ should == target_user }
its(:foo){ should == "bar" }
its(:hoge){ should == "fuga" }
end
context "to add a friend without options" do
let(:friendship) { current_user.friend!(target_user) }
subject { friendship }
it { should be_a(Friendable::Friendship) }
its(:friend){ should == target_user }
end
end
describe "#unfriend!" do
context "to remove a friendship" do
before do
current_user.friend!(target_user)
current_user.unfriend!(target_user)
end
specify { current_user.friend?(target_user).should be_false }
specify { redis.hexists(current_user.friend_list_key, target_user.id.to_s).should be_false }
specify { redis.hexists(target_user.friend_list_key, current_user.id.to_s).should be_false }
end
end
describe "#friends" do
subject { current_user.friends }
context "without friends" do
it { should be_an(ActiveRecord::Relation) }
its(:count){ should == 0 }
end
context "with one friend" do
before { current_user.friend!(target_user) }
it { should include(target_user) }
end
end
describe "#friendships" do
subject { current_user.friendships }
context "without friends to return an empty erray" do
it { should be_an(Array) }
its(:count) { should == 0 }
end
context "with one friend to return an array of friendship objects" do
before { current_user.friend!(target_user, :foo => "bar", :hoge => "fuga") }
subject { current_user.friendships.first }
it { should be_a(Friendable::Friendship) }
its(:source_resource) { should == current_user }
its(:target_resource) { should == target_user }
its(:created_at) { should be_a(ActiveSupport::TimeWithZone) }
its(:updated_at) { should be_a(ActiveSupport::TimeWithZone) }
its(:foo) { should == "bar" }
its(:hoge) { should == "fuga" }
end
end
describe "#friendship_with" do
context "without friends" do
specify do
expect {
current_user.friendship_with(target_user)
}.to raise_exception(Friendable::FriendshipNotFound)
end
end
context "with one friend" do
before { current_user.friend!(target_user, :foo => "bar", :hoge => "fuga") }
subject { current_user.friendship_with(target_user) }
it { should be_a(Friendable::Friendship) }
its(:foo) { should == "bar" }
its(:hoge) { should == "fuga" }
end
end
describe "#friend_ids" do
subject { current_user.friend_ids }
context "without friends" do
it { should be_an(Array) }
its(:count) { should == 0 }
end
context "with one friend" do
before { current_user.friend!(target_user) }
it { should include(target_user.id) }
end
context "without friends after unfriend" do
before do
current_user.friend!(target_user)
current_user.unfriend!(target_user)
end
it { should_not include(target_user.id) }
end
end
describe "#friends_count" do
subject { current_user.friends_count }
context "without friends" do
it { should == 0 }
end
context "with one friend" do
before { current_user.friend!(target_user) }
it { should == 1 }
end
context "without friends after unfriend" do
before do
current_user.friend!(target_user)
current_user.unfriend!(target_user)
end
it { should == 0 }
end
end
end
| 29.324675 | 98 | 0.64814 |
ff9ff58f814b1a2eea8f5f34bd4a498aa5e95fad | 2,645 |
RSpec.shared_context "nucleon_codes" do
#*****************************************************************************
# Code initialization
let(:codes_registry_clean) do {
:success => 0,
:help_wanted => 1,
:unknown_status => 2,
:action_unprocessed => 3,
:batch_error => 4,
:validation_failed => 5,
:access_denied => 6
}
end
let(:codes_status_index_clean) do {
0 => "success",
1 => "help_wanted",
2 => "unknown_status",
3 => "action_unprocessed",
4 => "batch_error",
5 => "validation_failed",
6 => "access_denied"
}
end
let(:codes_registry_custom) do {
:success => 0,
:help_wanted => 1,
:unknown_status => 2,
:action_unprocessed => 3,
:batch_error => 4,
:validation_failed => 5,
:access_denied => 6,
:good => 7,
:bad => 8,
:ok => 9,
:wow => 10,
:whew => 11
}
end
let(:codes_status_index_custom) do {
0 => "success",
1 => "help_wanted",
2 => "unknown_status",
3 => "action_unprocessed",
4 => "batch_error",
5 => "validation_failed",
6 => "access_denied",
7 => "good",
8 => "bad",
9 => "ok",
10 => "wow",
11 => "whew"
}
end
before(:each) do
# Set custom codes before every test
Nucleon::Codes.reset # 0 - 6 reserved
Nucleon::Codes.codes(:good, :bad, :ok, :wow, :whew) # 7 - ?
end
#*****************************************************************************
# Code test utilities
def codes_rendered_status(status_code = nil)
# Basically copied from the Codes class to ensure parity over time.
if ! status_code.nil? && codes_status_index_custom.has_key?(status_code)
status_name = codes_status_index_custom[status_code]
else
status_name = codes_status_index_custom[codes_registry_custom[:unknown_status]]
end
sprintf(" [ %3i ] - %s\n", status_code, status_name.gsub(/_/, ' ').capitalize)
end
def codes_rendered_index(status_code = nil)
# Basically copied from the Codes class to ensure parity over time.
output = "Status index:\n"
codes_status_index_custom.each do |code, name|
name = name.gsub(/_/, ' ').capitalize
if ! status_code.nil? && status_code == code
output << sprintf(" [ %3i ] - %s\n", code, name)
else
output << sprintf(" %3i - %s\n", code, name)
end
end
output << "\n"
output
end
end | 26.989796 | 85 | 0.507372 |
1df46a3fd2f83abdd5483ec111e4d6fac9795a24 | 1,384 | # Wraps up logic for querying the IAL level of an authorization request
class IalContext
attr_reader :ial, :service_provider
# @param ial [String, Integer] IAL level as either an integer (see ::Idp::Constants::IAL2, etc)
# or a string see Saml::Idp::Constants contexts
# @param service_provider [ServiceProvider, nil]
def initialize(ial:, service_provider:)
@ial = int_ial(ial)
@service_provider = service_provider
end
def ial2_service_provider?
service_provider.ial.to_i >= ::Idp::Constants::IAL2
end
def ialmax_requested?
ial&.zero?
end
def ial2_requested?
ial == ::Idp::Constants::IAL2
end
def ial2_or_greater?
ial2_requested? || ial2_strict_requested?
end
def ial2_strict_requested?
ial == ::Idp::Constants::IAL2_STRICT ||
(ial == ::Idp::Constants::IAL2 && service_provider_requires_liveness?)
end
def ial_for_identity_record
return ial unless ial == ::Idp::Constants::IAL2 && service_provider_requires_liveness?
::Idp::Constants::IAL2_STRICT
end
private
def service_provider_requires_liveness?
!!service_provider && service_provider.liveness_checking_required
end
def int_ial(input)
Integer(input)
rescue TypeError # input was nil
nil
rescue ArgumentError # input was probably a string
Saml::Idp::Constants::AUTHN_CONTEXT_CLASSREF_TO_IAL.fetch(input)
end
end
| 26.113208 | 97 | 0.726879 |
0184ddfbeffaece936f1c158adab4d80f93c86f2 | 9,109 | require 'test_helper'
class MetricsGlobalTest < Test::Unit::TestCase
include CommStub
def setup
@gateway = ActiveMerchant::Billing::MetricsGlobalGateway.new(
:login => 'X',
:password => 'Y'
)
@amount = 100
@credit_card = credit_card('4111111111111111', :verification_value => '999')
@subscription_id = '100748'
@subscription_status = 'active'
end
def test_successful_authorization
@gateway.expects(:ssl_post).returns(successful_authorization_response)
assert response = @gateway.authorize(@amount, @credit_card)
assert_instance_of Response, response
assert_success response
assert_equal '508141794', response.authorization
end
def test_successful_purchase
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card)
assert_instance_of Response, response
assert_success response
assert_equal '508141795', response.authorization
end
def test_failed_authorization
@gateway.expects(:ssl_post).returns(failed_authorization_response)
assert response = @gateway.authorize(@amount, @credit_card)
assert_instance_of Response, response
assert_failure response
assert_equal '508141794', response.authorization
end
def test_add_address_outsite_north_america
result = {}
@gateway.send(:add_address, result, :billing_address => {:address1 => '164 Waverley Street', :country => 'DE', :state => ''})
assert_equal ['address', 'city', 'company', 'country', 'phone', 'state', 'zip'], result.stringify_keys.keys.sort
assert_equal 'n/a', result[:state]
assert_equal '164 Waverley Street', result[:address]
assert_equal 'DE', result[:country]
end
def test_add_address
result = {}
@gateway.send(:add_address, result, :billing_address => {:address1 => '164 Waverley Street', :country => 'US', :state => 'CO'})
assert_equal ['address', 'city', 'company', 'country', 'phone', 'state', 'zip'], result.stringify_keys.keys.sort
assert_equal 'CO', result[:state]
assert_equal '164 Waverley Street', result[:address]
assert_equal 'US', result[:country]
end
def test_add_invoice
result = {}
@gateway.send(:add_invoice, result, :order_id => '#1001')
assert_equal '#1001', result[:invoice_num]
end
def test_add_description
result = {}
@gateway.send(:add_invoice, result, :description => 'My Purchase is great')
assert_equal 'My Purchase is great', result[:description]
end
def test_add_duplicate_window_without_duplicate_window
result = {}
@gateway.class.duplicate_window = nil
@gateway.send(:add_duplicate_window, result)
assert_nil result[:duplicate_window]
end
def test_add_duplicate_window_with_duplicate_window
result = {}
@gateway.class.duplicate_window = 0
@gateway.send(:add_duplicate_window, result)
assert_equal 0, result[:duplicate_window]
end
def test_purchase_is_valid_csv
params = { :amount => '1.01' }
@gateway.send(:add_creditcard, params, @credit_card)
assert data = @gateway.send(:post_data, 'AUTH_ONLY', params)
assert_equal post_data_fixture.size, data.size
end
def test_purchase_meets_minimum_requirements
params = {
:amount => '1.01',
}
@gateway.send(:add_creditcard, params, @credit_card)
assert data = @gateway.send(:post_data, 'AUTH_ONLY', params)
minimum_requirements.each do |key|
assert_not_nil(data =~ /x_#{key}=/)
end
end
def test_successful_refund
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.refund(@amount, '123456789', :card_number => @credit_card.number)
assert_success response
assert_equal 'This transaction has been approved', response.message
end
def test_refund_passing_extra_info
response = stub_comms do
@gateway.refund(50, '123456789', :card_number => @credit_card.number, :first_name => 'Bob', :last_name => 'Smith', :zip => '12345')
end.check_request do |endpoint, data, headers|
assert_match(/x_first_name=Bob/, data)
assert_match(/x_last_name=Smith/, data)
assert_match(/x_zip=12345/, data)
end.respond_with(successful_purchase_response)
assert_success response
end
def test_failed_refund
@gateway.expects(:ssl_post).returns(failed_refund_response)
assert response = @gateway.refund(@amount, '123456789', :card_number => @credit_card.number)
assert_failure response
assert_equal 'The referenced transaction does not meet the criteria for issuing a credit', response.message
end
def test_deprecated_credit
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert_deprecation_warning(Gateway::CREDIT_DEPRECATION_MESSAGE) do
assert response = @gateway.credit(@amount, '123456789', :card_number => @credit_card.number)
assert_success response
assert_equal 'This transaction has been approved', response.message
end
end
def test_supported_countries
assert_equal ['US'], MetricsGlobalGateway.supported_countries
end
def test_supported_card_types
assert_equal [:visa, :master, :american_express, :discover, :diners_club, :jcb], MetricsGlobalGateway.supported_cardtypes
end
def test_failure_without_response_reason_text
assert_nothing_raised do
assert_equal '', @gateway.send(:message_from, {})
end
end
def test_response_under_review_by_fraud_service
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_failure response
assert response.fraud_review?
assert_equal 'Thank you! For security reasons your order is currently being reviewed', response.message
end
def test_avs_result
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'X', response.avs_result['code']
end
def test_cvv_result
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'M', response.cvv_result['code']
end
def test_message_from
@gateway.class_eval {
public :message_from
}
result = {
:response_code => 2,
:card_code => 'N',
:avs_result_code => 'A',
:response_reason_code => '27',
:response_reason_text => 'Failure.',
}
assert_equal 'CVV does not match', @gateway.message_from(result)
result[:card_code] = 'M'
assert_equal 'Street address matches, but 5-digit and 9-digit postal code do not match.', @gateway.message_from(result)
result[:response_reason_code] = '22'
assert_equal 'Failure', @gateway.message_from(result)
end
private
def post_data_fixture
'x_encap_char=%24&x_card_num=4242424242424242&x_exp_date=0806&x_card_code=123&x_type=AUTH_ONLY&x_first_name=Longbob&x_version=3.1&x_login=X&x_last_name=Longsen&x_tran_key=Y&x_relay_response=FALSE&x_delim_data=TRUE&x_delim_char=%2C&x_amount=1.01'
end
def minimum_requirements
%w(version delim_data relay_response login tran_key amount card_num exp_date type)
end
def failed_refund_response
'$3$,$2$,$54$,$The referenced transaction does not meet the criteria for issuing a credit.$,$$,$P$,$0$,$$,$$,$1.00$,$CC$,$credit$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$39265D8BA0CDD4F045B5F4129B2AAA01$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$'
end
def successful_authorization_response
'$1$,$1$,$1$,$This transaction has been approved.$,$advE7f$,$Y$,$508141794$,$5b3fe66005f3da0ebe51$,$$,$1.00$,$CC$,$auth_only$,$$,$Longbob$,$Longsen$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$2860A297E0FE804BCB9EF8738599645C$,$P$,$2$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$'
end
def successful_purchase_response
'$1$,$1$,$1$,$This transaction has been approved.$,$d1GENk$,$Y$,$508141795$,$32968c18334f16525227$,$Store purchase$,$1.00$,$CC$,$auth_capture$,$$,$Longbob$,$Longsen$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$269862C030129C1173727CC10B1935ED$,$P$,$2$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$'
end
def failed_authorization_response
'$2$,$1$,$1$,$This transaction was declined.$,$advE7f$,$Y$,$508141794$,$5b3fe66005f3da0ebe51$,$$,$1.00$,$CC$,$auth_only$,$$,$Longbob$,$Longsen$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$2860A297E0FE804BCB9EF8738599645C$,$P$,$2$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$'
end
def fraud_review_response
'$4$,$$,$253$,$Thank you! For security reasons your order is currently being reviewed.$,$$,$X$,$0$,$$,$$,$1.00$,$$,$auth_capture$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$207BCBBF78E85CF174C87AE286B472D2$,$M$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$,$$'
end
end
| 38.597458 | 363 | 0.661324 |
399f5f3c362e80ba56baaafd9df2b57b8035f1d9 | 952 | class ENV_BANG
module Classes
class << self
attr_writer :default_class
def default_class
@default_class ||= :StringUnlessFalsey
end
def cast(value, options = {})
public_send(:"#{options.fetch(:class, default_class)}", value, options)
end
def boolean(value, options)
!(value =~ /^(|0|disabled?|false|no|off)$/i)
end
def Array(value, options)
item_options = options.merge(class: options.fetch(:of, default_class))
value.split(',').map { |value| cast(value.strip, item_options) }
end
def Symbol(value, options)
value.to_sym
end
def StringUnlessFalsey(value, options)
boolean(value, options) && value
end
# Delegate methods like Integer(), Float(), String(), etc. to the Kernel module
def method_missing(klass, value, options, &block)
Kernel.send(klass, value)
end
end
end
end
| 25.052632 | 85 | 0.609244 |
e9a29e75358ec058ca30fcbfb8e2e1b3f1c3f061 | 728 | class AssignmentFilesController < ApplicationController
before_action :set_current_course
before_action :authenticated_as_user
# GET /6.006/assignment_files/1/download
def download
@file = AssignmentFile.find params[:id]
return bounce_user unless @file.can_read? current_user
db_file = @file.db_file
# NOTE: The CSP header provides some protection against an attacker who
# tries to serve active content (HTML+JS) using the server's origin.
# DbFile also explicitly disallows the HTML and XHTML MIME types.
response.headers['Content-Security-Policy'] = "default-src 'none'"
send_data @file.contents, filename: @file.file_name,
type: db_file.f.content_type
end
end
| 38.315789 | 78 | 0.740385 |
e986ffa00ce63e4540ac1bad0bbd5ed28ff29ca4 | 2,325 | module ActiveNotifier
class Base
attr_accessor :recipient, :channels
def initialize(attributes={})
attributes.each do |(key, value)|
self.public_send("#{key}=", value)
end
end
delegate :deliver_now, to: :deliverable
def deliver_now
delivered = false
locale = self.class.locale_for(recipient)
I18n.with_locale(locale) do
until channels.empty? || delivered
channel = channels.shift
begin
deliverable(channel).deliver_now
delivered = true
rescue ActiveNotifier::DeliveryImpossible => e
delivered = false
msg = "Unable to deliver to channel #{channel}"
ActiveNotifier.logger && ActiveNotifier.logger.warn(msg)
end
end
end
end
class << self
attr_accessor :configurations, :locale_attribute
def deliver_now(attributes)
new(attributes).deliver_now
end
def deliver_through(channel, &blk)
self.configurations ||= {}
config = Configuration.new.tap(&blk)
configurations[channel] = config
end
def locale_for(recipient)
recipient.public_send(locale_attribute)
rescue
I18n.default_locale
end
end
private
def deliverable(channel)
configuration = self.class.configurations[channel]
transport = ActiveNotifier::Transports.for(channel, configuration, self)
transport.deliverable(self)
end
class Configuration
attr_accessor :data
def initialize
@data = {
from: nil,
email_attribute: nil,
subject: nil,
superclass: ActionMailer::Base
}
end
delegate :[], to: :data
def method_missing(*args, &blk)
attribute, value = args
if value.present?
@data[attribute] = value
elsif block_given?
@data[attribute] = blk
else
@data.fetch attribute do
super
end
end
end
def respond_to?(*args, &blk)
attribute, value = args
if value.present?
true
elsif block_given?
true
else
@data.fetch attribute do
super
end
end
end
end
end
end
| 23.019802 | 78 | 0.577204 |
6aaf25e072563b7bfe88fb877d09ab56ab1fd2d6 | 2,677 | Pod::Spec.new do |s|
s.name = "Nimble"
s.version = "7.1.2"
s.summary = "A Matcher Framework for Swift and Objective-C"
s.description = <<-DESC
Use Nimble to express the expected outcomes of Swift or Objective-C expressions. Inspired by Cedar.
DESC
s.homepage = "https://github.com/Quick/Nimble"
s.license = { :type => "Apache 2.0", :file => "LICENSE" }
s.author = "Quick Contributors"
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.tvos.deployment_target = "9.0"
s.source = { :git => "https://github.com/Quick/Nimble.git",
:tag => "v#{s.version}" }
s.source_files = [
"Sources/**/*.{swift,h,m,c}",
"Carthage/Checkouts/CwlCatchException/Sources/**/*.{swift,h,m,c}",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/**/*.{swift,h,m,c}",
]
s.osx.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstructionPosix.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/Posix/CwlPreconditionTesting_POSIX.h",
]
s.ios.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstructionPosix.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/Posix/CwlPreconditionTesting_POSIX.h",
]
s.tvos.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/Mach/CwlPreconditionTesting.h",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstruction.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlBadInstructionException.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlDarwinDefinitions.swift",
"Carthage/Checkouts/CwlCatchException/Sources/CwlCatchException/CwlCatchException.swift",
"Carthage/Checkouts/CwlCatchException/Sources/CwlCatchExceptionSupport/CwlCatchException.m",
"Carthage/Checkouts/CwlCatchException/Sources/CwlCatchExceptionSupport/include/CwlCatchException.h",
]
s.exclude_files = "Sources/Nimble/Adapters/NonObjectiveC/*.swift"
s.weak_framework = "XCTest"
s.requires_arc = true
s.compiler_flags = '-DPRODUCT_NAME=Nimble/Nimble'
s.pod_target_xcconfig = {
'APPLICATION_EXTENSION_API_ONLY' => 'YES',
'ENABLE_BITCODE' => 'NO',
'OTHER_LDFLAGS' => '-weak-lswiftXCTest',
'OTHER_SWIFT_FLAGS' => '$(inherited) -suppress-warnings',
'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "$(PLATFORM_DIR)/Developer/Library/Frameworks"',
}
end
| 50.509434 | 118 | 0.731789 |
b9467748793d6ff28960fbfc9971cde0982ffc13 | 239 | module ScorchedBlog
class BaseController < Scorched::Controller
render_defaults[:layout] = File.expand_path('../templates/layout.erb', __FILE__).to_sym
render_defaults[:dir] = File.expand_path('../templates', __FILE__)
end
end
| 34.142857 | 91 | 0.748954 |
ab094426054377a1c825441b0793d8b4f22fc85a | 8,488 | require "spec_helper"
module Berkshelf
describe Downloader do
let(:berksfile) do
double(Berksfile,
lockfile: lockfile,
dependencies: [])
end
let(:lockfile) do
double(Lockfile,
graph: graph)
end
let(:graph) { double(Lockfile::Graph, locks: {}) }
let(:self_signed_crt_path) { File.join(BERKS_SPEC_DATA, "trusted_certs") }
let(:self_signed_crt) { OpenSSL::X509::Certificate.new(IO.read("#{self_signed_crt_path}/example.crt")) }
let(:cert_store) { OpenSSL::X509::Store.new.add_cert(self_signed_crt) }
let(:ssl_policy) { double(SSLPolicy, store: cert_store) }
subject { described_class.new(berksfile) }
describe "#download" do
skip
end
describe "#try_download" do
let(:remote_cookbook) { double("remote-cookbook") }
let(:source) do
source = double("source")
allow(source).to receive(:cookbook) { remote_cookbook }
source
end
let(:name) { "fake" }
let(:version) { "1.0.0" }
it "supports the 'opscode' location type" do
allow(source).to receive(:type) { :supermarket }
allow(source).to receive(:options) { { ssl: {} } }
allow(remote_cookbook).to receive(:location_type) { :opscode }
allow(remote_cookbook).to receive(:location_path) { "http://api.opscode.com" }
rest = double("community-rest")
expect(CommunityREST).to receive(:new).with("http://api.opscode.com", { ssl: {} }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
it "supports the 'supermarket' location type" do
allow(source).to receive(:type) { :supermarket }
allow(source).to receive(:options) { { ssl: {} } }
allow(remote_cookbook).to receive(:location_type) { :supermarket }
allow(remote_cookbook).to receive(:location_path) { "http://api.supermarket.com" }
rest = double("community-rest")
expect(CommunityREST).to receive(:new).with("http://api.supermarket.com", { ssl: {} }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
context "supports location paths" do
before(:each) do
allow(source).to receive(:type) { :supermarket }
allow(source).to receive(:options) { { ssl: {} } }
allow(source).to receive(:uri_string).and_return("http://localhost:8081/repository/chef-proxy")
allow(remote_cookbook).to receive(:location_type) { :opscode }
end
let(:rest) { double("community-rest") }
it "that are relative and prepends the source URI for the download" do
allow(remote_cookbook).to receive(:location_path) { "/api/v1" }
expect(CommunityREST).to receive(:new).with("http://localhost:8081/repository/chef-proxy/api/v1", { ssl: {} }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
it "that are absolute and uses the given absolute URI" do
allow(remote_cookbook).to receive(:location_path) { "http://localhost:8081/repository/chef-proxy/api/v1" }
expect(CommunityREST).to receive(:new).with("http://localhost:8081/repository/chef-proxy/api/v1", { ssl: {} }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
end
context "with an artifactory source" do
it "supports the 'opscode' location type" do
allow(source).to receive(:type) { :artifactory }
allow(source).to receive(:options) { { api_key: "secret", ssl: {} } }
allow(remote_cookbook).to receive(:location_type) { :opscode }
allow(remote_cookbook).to receive(:location_path) { "http://artifactory/" }
rest = double("community-rest")
expect(CommunityREST).to receive(:new).with("http://artifactory/", { ssl: {}, headers: { "X-Jfrog-Art-Api" => "secret" } }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
it "supports the 'supermarket' location type" do
allow(source).to receive(:type) { :artifactory }
allow(source).to receive(:options) { { api_key: "secret", ssl: {} } }
allow(remote_cookbook).to receive(:location_type) { :supermarket }
allow(remote_cookbook).to receive(:location_path) { "http://artifactory/" }
rest = double("community-rest")
expect(CommunityREST).to receive(:new).with("http://artifactory/", { ssl: {}, headers: { "X-Jfrog-Art-Api" => "secret" } }) { rest }
expect(rest).to receive(:download).with(name, version)
subject.try_download(source, name, version)
end
end
describe "chef_server location type" do
let(:chef_server_url) { "http://configured-chef-server/" }
let(:ridley_client) do
instance_double(Berkshelf::RidleyCompat)
end
let(:chef_config) do
double(Berkshelf::ChefConfigCompat,
node_name: "fake-client",
client_key: "client-key",
chef_server_url: chef_server_url,
validation_client_name: "validator",
validation_key: "validator.pem",
artifactory_api_key: "secret",
cookbook_copyright: "user",
cookbook_email: "[email protected]",
cookbook_license: "apachev2",
trusted_certs_dir: self_signed_crt_path)
end
let(:berkshelf_config) do
double(Config,
ssl: double(verify: true),
chef: chef_config)
end
before do
allow(Berkshelf).to receive(:config).and_return(berkshelf_config)
allow(subject).to receive(:ssl_policy).and_return(ssl_policy)
allow(remote_cookbook).to receive(:location_type) { :chef_server }
allow(remote_cookbook).to receive(:location_path) { chef_server_url }
allow(source).to receive(:options) { { read_timeout: 30, open_timeout: 3, ssl: { verify: true, cert_store: cert_store } } }
end
it "uses the berkshelf config and provides a custom cert_store" do
credentials = {
server_url: chef_server_url,
client_name: chef_config.node_name,
client_key: chef_config.client_key,
ssl: {
verify: berkshelf_config.ssl.verify,
cert_store: cert_store,
},
}
expect(Berkshelf::RidleyCompat).to receive(:new_client).with(credentials) { ridley_client }
subject.try_download(source, name, version)
end
context "with a source option for client_name" do
before do
allow(source).to receive(:options) { { client_name: "other-client", read_timeout: 30, open_timeout: 3, ssl: { verify: true, cert_store: cert_store } } }
end
it "uses the override" do
credentials = {
server_url: chef_server_url,
client_name: "other-client",
client_key: chef_config.client_key,
ssl: {
verify: berkshelf_config.ssl.verify,
cert_store: cert_store,
},
}
expect(Berkshelf::RidleyCompat).to receive(:new_client).with(credentials) { ridley_client }
subject.try_download(source, name, version)
end
end
context "with a source option for client_key" do
before do
allow(source).to receive(:options) { { client_key: "other-key", read_timeout: 30, open_timeout: 3, ssl: { verify: true, cert_store: cert_store } } }
end
it "uses the override" do
credentials = {
server_url: chef_server_url,
client_name: chef_config.node_name,
client_key: "other-key",
ssl: {
verify: berkshelf_config.ssl.verify,
cert_store: cert_store,
},
}
expect(Berkshelf::RidleyCompat).to receive(:new_client).with(credentials) { ridley_client }
subject.try_download(source, name, version)
end
end
end
it "supports the 'file_store' location type" do
skip
end
end
end
end
| 42.228856 | 164 | 0.606032 |
ed4205a477eb5df54f345873853a2d70a34910b5 | 104 | class HomeController < ApplicationController
def index
end
def contact_us
end
end
| 9.454545 | 44 | 0.673077 |
1ae7cba70393d7c5574397e381d06de5f1a61482 | 302 | package "git-daemon-sysvinit"
directory "/srv/repos" do
recursive true
end
template '/etc/default/git-daemon' do
source 'git-daemon.erb'
owner 'root'
mode '0644'
variables :git_root => '/srv/repos'
end
service "git-daemon" do
provider Chef::Provider::Service::Init
action [:start]
end
| 16.777778 | 40 | 0.708609 |
624d0200f7817d44ea1537254e49d46ef7bb7d99 | 2,610 | require 'spec_helper'
RSpec.describe DeserializationRetry do
context 'when a Delayed::Job fails to load because the class is missing' do
it 'prevents DelayedJob from marking it as failed' do
handler = VCAP::CloudController::Jobs::Runtime::EventsCleanup.new(10_000)
VCAP::CloudController::Jobs::Enqueuer.new(handler).enqueue
job = Delayed::Job.last
job.update handler: job.handler.gsub('EventsCleanup', 'Dan')
Delayed::Worker.new.work_off
job.reload
expect(job.failed_at).to be_nil
expect(job.locked_by).to be_nil
expect(job.locked_at).to be_nil
expect(job.run_at).to be_within(2.seconds).of Delayed::Job.db_time_now + 5.minutes
expect(job.attempts).to eq(1)
end
context 'and we have been retrying for more than 24 hours' do
it 'stops retrying the job' do
handler = VCAP::CloudController::Jobs::Runtime::EventsCleanup.new(10_000)
VCAP::CloudController::Jobs::Enqueuer.new(handler).enqueue
job = Delayed::Job.last
job.update handler: job.handler.gsub('EventsCleanup', 'Dan'), created_at: Delayed::Job.db_time_now - 24.hours - 1.second
Delayed::Worker.new.work_off
expect(job.reload.failed_at).not_to be_nil
end
end
end
context 'when a Delayed::Job fails to load because of another reason' do
it 'allows the job to be marked as failed' do
handler = VCAP::CloudController::Jobs::Runtime::EventsCleanup.new(10_000)
VCAP::CloudController::Jobs::Enqueuer.new(handler).enqueue
job = Delayed::Job.last
job.update handler: 'Dan'
execute_all_jobs(expected_successes: 0, expected_failures: 1)
expect(job.reload.attempts).to eq(1)
end
end
context 'when the Delayed::Job is well formed' do
it 'executes the job' do
handler = VCAP::CloudController::Jobs::Runtime::EventsCleanup.new(10_000)
VCAP::CloudController::Jobs::Enqueuer.new(handler).enqueue
execute_all_jobs(expected_successes: 1, expected_failures: 0)
end
context 'and the job blows up during execution' do
class BoomJob < VCAP::CloudController::Jobs::CCJob
def perform
raise 'BOOOM!'
end
end
it 'does not retry' do
handler = BoomJob.new
VCAP::CloudController::Jobs::Enqueuer.new(handler).enqueue
job = Delayed::Job.last
old_run_at = job.run_at
execute_all_jobs(expected_successes: 0, expected_failures: 1)
expect(job.reload.run_at).to eq old_run_at
expect(job.reload.failed_at).not_to be_nil
end
end
end
end
| 32.222222 | 128 | 0.681992 |
7ad3a48b0eaa7f034d3f7d558db60510a1b9d733 | 137 | class OrderedPost
include Mongoid::Document
field :title, :type => String
field :rating, :type => Integer
belongs_to :person
end
| 19.571429 | 33 | 0.722628 |
5d5a335acb3df5145683cda329c8e6979efe00d1 | 19,168 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "helper"
require "gapic/grpc/service_stub"
require "google/cloud/binaryauthorization/v1beta1/service_pb"
require "google/cloud/binaryauthorization/v1beta1/service_services_pb"
require "google/cloud/binary_authorization/v1beta1/binauthz_management_service"
class ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::ClientTest < Minitest::Test
class ClientStub
attr_accessor :call_rpc_count, :requests
def initialize response, operation, &block
@response = response
@operation = operation
@block = block
@call_rpc_count = 0
@requests = []
end
def call_rpc *args, **kwargs
@call_rpc_count += 1
@requests << @block&.call(*args, **kwargs)
yield @response, @operation if block_given?
@response
end
end
def test_get_policy
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::Policy.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
get_policy_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :get_policy, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::GetPolicyRequest, request
assert_equal "hello world", request["name"]
refute_nil options
end
Gapic::ServiceStub.stub :new, get_policy_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.get_policy({ name: name }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.get_policy name: name do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.get_policy ::Google::Cloud::BinaryAuthorization::V1beta1::GetPolicyRequest.new(name: name) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.get_policy({ name: name }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.get_policy(::Google::Cloud::BinaryAuthorization::V1beta1::GetPolicyRequest.new(name: name), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, get_policy_client_stub.call_rpc_count
end
end
def test_update_policy
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::Policy.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
policy = {}
update_policy_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :update_policy, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::UpdatePolicyRequest, request
assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Cloud::BinaryAuthorization::V1beta1::Policy), request["policy"]
refute_nil options
end
Gapic::ServiceStub.stub :new, update_policy_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.update_policy({ policy: policy }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.update_policy policy: policy do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.update_policy ::Google::Cloud::BinaryAuthorization::V1beta1::UpdatePolicyRequest.new(policy: policy) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.update_policy({ policy: policy }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.update_policy(::Google::Cloud::BinaryAuthorization::V1beta1::UpdatePolicyRequest.new(policy: policy), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, update_policy_client_stub.call_rpc_count
end
end
def test_create_attestor
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::Attestor.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
parent = "hello world"
attestor_id = "hello world"
attestor = {}
create_attestor_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :create_attestor, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::CreateAttestorRequest, request
assert_equal "hello world", request["parent"]
assert_equal "hello world", request["attestor_id"]
assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Cloud::BinaryAuthorization::V1beta1::Attestor), request["attestor"]
refute_nil options
end
Gapic::ServiceStub.stub :new, create_attestor_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.create_attestor({ parent: parent, attestor_id: attestor_id, attestor: attestor }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.create_attestor parent: parent, attestor_id: attestor_id, attestor: attestor do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.create_attestor ::Google::Cloud::BinaryAuthorization::V1beta1::CreateAttestorRequest.new(parent: parent, attestor_id: attestor_id, attestor: attestor) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.create_attestor({ parent: parent, attestor_id: attestor_id, attestor: attestor }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.create_attestor(::Google::Cloud::BinaryAuthorization::V1beta1::CreateAttestorRequest.new(parent: parent, attestor_id: attestor_id, attestor: attestor), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, create_attestor_client_stub.call_rpc_count
end
end
def test_get_attestor
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::Attestor.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
get_attestor_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :get_attestor, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::GetAttestorRequest, request
assert_equal "hello world", request["name"]
refute_nil options
end
Gapic::ServiceStub.stub :new, get_attestor_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.get_attestor({ name: name }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.get_attestor name: name do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.get_attestor ::Google::Cloud::BinaryAuthorization::V1beta1::GetAttestorRequest.new(name: name) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.get_attestor({ name: name }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.get_attestor(::Google::Cloud::BinaryAuthorization::V1beta1::GetAttestorRequest.new(name: name), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, get_attestor_client_stub.call_rpc_count
end
end
def test_update_attestor
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::Attestor.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
attestor = {}
update_attestor_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :update_attestor, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::UpdateAttestorRequest, request
assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Cloud::BinaryAuthorization::V1beta1::Attestor), request["attestor"]
refute_nil options
end
Gapic::ServiceStub.stub :new, update_attestor_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.update_attestor({ attestor: attestor }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.update_attestor attestor: attestor do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.update_attestor ::Google::Cloud::BinaryAuthorization::V1beta1::UpdateAttestorRequest.new(attestor: attestor) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.update_attestor({ attestor: attestor }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.update_attestor(::Google::Cloud::BinaryAuthorization::V1beta1::UpdateAttestorRequest.new(attestor: attestor), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, update_attestor_client_stub.call_rpc_count
end
end
def test_list_attestors
# Create GRPC objects.
grpc_response = ::Google::Cloud::BinaryAuthorization::V1beta1::ListAttestorsResponse.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
parent = "hello world"
page_size = 42
page_token = "hello world"
list_attestors_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :list_attestors, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::ListAttestorsRequest, request
assert_equal "hello world", request["parent"]
assert_equal 42, request["page_size"]
assert_equal "hello world", request["page_token"]
refute_nil options
end
Gapic::ServiceStub.stub :new, list_attestors_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.list_attestors({ parent: parent, page_size: page_size, page_token: page_token }) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use named arguments
client.list_attestors parent: parent, page_size: page_size, page_token: page_token do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.list_attestors ::Google::Cloud::BinaryAuthorization::V1beta1::ListAttestorsRequest.new(parent: parent, page_size: page_size, page_token: page_token) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.list_attestors({ parent: parent, page_size: page_size, page_token: page_token }, grpc_options) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.list_attestors(::Google::Cloud::BinaryAuthorization::V1beta1::ListAttestorsRequest.new(parent: parent, page_size: page_size, page_token: page_token), grpc_options) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, list_attestors_client_stub.call_rpc_count
end
end
def test_delete_attestor
# Create GRPC objects.
grpc_response = ::Google::Protobuf::Empty.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
delete_attestor_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :delete_attestor, name
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::DeleteAttestorRequest, request
assert_equal "hello world", request["name"]
refute_nil options
end
Gapic::ServiceStub.stub :new, delete_attestor_client_stub do
# Create client
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.delete_attestor({ name: name }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.delete_attestor name: name do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.delete_attestor ::Google::Cloud::BinaryAuthorization::V1beta1::DeleteAttestorRequest.new(name: name) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.delete_attestor({ name: name }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.delete_attestor(::Google::Cloud::BinaryAuthorization::V1beta1::DeleteAttestorRequest.new(name: name), grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, delete_attestor_client_stub.call_rpc_count
end
end
def test_configure
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
client = block_config = config = nil
Gapic::ServiceStub.stub :new, nil do
client = ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client.new do |config|
config.credentials = grpc_channel
end
end
config = client.configure do |c|
block_config = c
end
assert_same block_config, config
assert_kind_of ::Google::Cloud::BinaryAuthorization::V1beta1::BinauthzManagementService::Client::Configuration, config
end
end
| 39.359343 | 203 | 0.722767 |
086e1394bf86ba33b78e9a2b2fafc7276356e3bd | 340 | module ReviewsHelper
def display_heading(object)
if object
content_tag(:h1, "Reviews for #{object.title}")
else
content_tag(:h1, "All Reviews")
end
end
def go_back(recipe)
if recipe
link_to "Back", recipe_path(recipe), class: "btn btn-dark"
else
link_to "Back", recipes_path, class: "btn btn-dark"
end
end
end
| 17.894737 | 61 | 0.694118 |
1d052fb22cc205099fb67a82885460148a1d60a2 | 771 | # frozen_string_literal: true
module CaseMixHelper
CASE_MIX_TIERS = %i[a b c d na].freeze
def case_mix_key
render partial: 'poms/case-mix/key', locals: { tiers: CASE_MIX_TIERS }
end
def case_mix_bar(pom)
tiers = {
a: pom.tier_a,
b: pom.tier_b,
c: pom.tier_c,
d: pom.tier_d,
na: pom.no_tier,
}.reject { |_tier, count| count.zero? } # filter out zero-count tiers
css_columns = tiers.values.map { |count|
# Value for CSS property grid-template-columns
%W[0 #{count}fr]
}.join(' ')
render partial: 'poms/case-mix/bar', locals: { tiers: tiers, css_columns: css_columns }
end
def tier_label(tier)
if tier == :na
'Tier N/A'
else
"Tier #{tier.to_s.upcase}"
end
end
end
| 22.028571 | 91 | 0.616083 |
1dd05b8373d513db26856bbed67a04620bfdd92a | 640 | $: << File.join(File.dirname(__FILE__), '..', 'lib')
require 'rubygems'
require '../lib/rturk'
require 'yaml'
aws = YAML.load(File.open(File.join(File.dirname(__FILE__), 'mturk.yml')))
RTurk::setup(aws['AWSAccessKeyId'], aws['AWSAccessKey'])
file = File.open(File.join(File.dirname(__FILE__), 'answers.yml'), 'w')
hits = RTurk::Hit.all_reviewable
puts "#{hits.size} reviewable hits. \n"
unless hits.empty?
puts "Reviewing all assignments"
hits.each do |hit|
hit.assignments.each do |assignment|
file.puts assignment.answers.to_hash.to_yaml
assignment.approve! if assignment.status == 'Submitted'
end
end
end | 27.826087 | 74 | 0.698438 |
ede3a4409037ac16a7f3a697f822561f234ec42d | 83,164 | require "cases/helper"
require "models/developer"
require "models/computer"
require "models/project"
require "models/company"
require "models/contract"
require "models/topic"
require "models/reply"
require "models/category"
require "models/image"
require "models/post"
require "models/author"
require "models/essay"
require "models/comment"
require "models/person"
require "models/reader"
require "models/tagging"
require "models/tag"
require "models/invoice"
require "models/line_item"
require "models/car"
require "models/bulb"
require "models/engine"
require "models/categorization"
require "models/minivan"
require "models/speedometer"
require "models/reference"
require "models/job"
require "models/college"
require "models/student"
require "models/pirate"
require "models/ship"
require "models/ship_part"
require "models/treasure"
require "models/parrot"
require "models/tyre"
require "models/subscriber"
require "models/subscription"
require "models/zine"
require "models/interest"
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
fixtures :authors, :posts, :comments
def test_should_generate_valid_sql
author = authors(:david)
# this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression
# if the reorder clauses are not correctly handled
assert author.posts_with_comments_sorted_by_comment_id.where("comments.id > 0").reorder("posts.comments_count DESC", "posts.tags_count DESC").last
end
end
class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
fixtures :authors, :essays, :subscribers, :subscriptions, :people
def test_custom_primary_key_on_new_record_should_fetch_with_query
subscriber = Subscriber.new(nick: "webster132")
assert !subscriber.subscriptions.loaded?
assert_queries 1 do
assert_equal 2, subscriber.subscriptions.size
end
assert_equal subscriber.subscriptions, Subscription.where(subscriber_id: "webster132")
end
def test_association_primary_key_on_new_record_should_fetch_with_query
author = Author.new(name: "David")
assert !author.essays.loaded?
assert_queries 1 do
assert_equal 1, author.essays.size
end
assert_equal author.essays, Essay.where(writer_id: "David")
end
def test_has_many_custom_primary_key
david = authors(:david)
assert_equal david.essays, Essay.where(writer_id: "David")
end
def test_has_many_assignment_with_custom_primary_key
david = people(:david)
assert_equal ["A Modest Proposal"], david.essays.map(&:name)
david.essays = [Essay.create!(name: "Remote Work")]
assert_equal ["Remote Work"], david.essays.map(&:name)
end
def test_blank_custom_primary_key_on_new_record_should_not_run_queries
author = Author.new
assert !author.essays.loaded?
assert_queries 0 do
assert_equal 0, author.essays.size
end
end
end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
:posts, :readers, :taggings, :cars, :jobs, :tags,
:categorizations, :zines, :interests
def setup
Client.destroyed_client_ids.clear
end
def test_sti_subselect_count
tag = Tag.first
len = Post.tagged_with(tag.id).limit(10).size
assert_operator len, :>, 0
end
def test_anonymous_has_many
developer = Class.new(ActiveRecord::Base) {
self.table_name = "developers"
dev = self
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = "developers_projects"
belongs_to :developer, anonymous_class: dev
}
has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id"
}
dev = developer.first
named = Developer.find(dev.id)
assert_operator dev.developer_projects.count, :>, 0
assert_equal named.projects.map(&:id).sort,
dev.developer_projects.map(&:project_id).sort
end
def test_default_scope_on_relations_is_not_cached
counter = 0
posts = Class.new(ActiveRecord::Base) {
self.table_name = "posts"
self.inheritance_column = "not_there"
post = self
comments = Class.new(ActiveRecord::Base) {
self.table_name = "comments"
self.inheritance_column = "not_there"
belongs_to :post, anonymous_class: post
default_scope -> {
counter += 1
where("id = :inc", inc: counter)
}
}
has_many :comments, anonymous_class: comments, foreign_key: "post_id"
}
assert_equal 0, counter
post = posts.first
assert_equal 0, counter
sql = capture_sql { post.comments.to_a }
post.comments.reset
assert_not_equal sql, capture_sql { post.comments.to_a }
end
def test_has_many_build_with_options
college = College.create(name: "UFMT")
Student.create(active: true, college_id: college.id, name: "Sarah")
assert_equal college.students, Student.where(active: true, college_id: college.id)
end
def test_add_record_to_collection_should_change_its_updated_at
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit")
updated_at = part.updated_at
travel(1.second) do
ship.parts << part
end
assert_equal part.ship, ship
assert_not_equal part.updated_at, updated_at
end
def test_clear_collection_should_not_change_updated_at
# GH#17161: .clear calls delete_all (and returns the association),
# which is intended to not touch associated objects's updated_at field
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit", ship_id: ship.id)
ship.parts.clear
part.reload
assert_nil part.ship
assert !part.updated_at_changed?
end
def test_create_from_association_should_respect_default_scope
car = Car.create(name: "honda")
assert_equal "honda", car.name
bulb = Bulb.create
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create
assert_equal "defaulty", bulb.name
end
def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
car = Car.create(name: "honda")
bulb = car.bulbs.build(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.bulbs.create(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.awesome_bulbs.build(frickinawesome: false)
assert_equal false, bulb.frickinawesome
bulb = car.awesome_bulbs.create(frickinawesome: false)
assert_equal false, bulb.frickinawesome
end
def test_build_from_association_should_respect_scope
author = Author.new
post = author.thinking_posts.build
assert_equal "So I was thinking", post.title
end
def test_create_from_association_with_nil_values_should_work
car = Car.create(name: "honda")
bulb = car.bulbs.new(nil)
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build(nil)
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create(nil)
assert_equal "defaulty", bulb.name
end
def test_do_not_call_callbacks_for_delete_all
car = Car.create(name: "honda")
car.funky_bulbs.create!
assert_equal 1, car.funky_bulbs.count
assert_nothing_raised { car.reload.funky_bulbs.delete_all }
assert_equal 0, car.funky_bulbs.count, "bulbs should have been deleted using :delete_all strategy"
end
def test_delete_all_on_association_is_the_same_as_not_loaded
author = authors :david
author.thinking_posts.create!(body: "test")
author.reload
expected_sql = capture_sql { author.thinking_posts.delete_all }
author.thinking_posts.create!(body: "test")
author.reload
author.thinking_posts.inspect
loaded_sql = capture_sql { author.thinking_posts.delete_all }
assert_equal(expected_sql, loaded_sql)
end
def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
author = authors :david
author.posts.create!(title: "test", body: "body")
author.reload
expected_sql = capture_sql { author.posts.delete_all }
author.posts.create!(title: "test", body: "body")
author.reload
author.posts.to_a
loaded_sql = capture_sql { author.posts.delete_all }
assert_equal(expected_sql, loaded_sql)
end
def test_building_the_associated_object_with_implicit_sti_base_class
firm = DependentFirm.new
company = firm.companies.build
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_explicit_sti_base_class
firm = DependentFirm.new
company = firm.companies.build(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_sti_subclass
firm = DependentFirm.new
company = firm.companies.build(type: "Client")
assert_kind_of Client, company, "Expected #{company.class} to be a Client"
end
def test_building_the_associated_object_with_an_invalid_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") }
end
def test_building_the_associated_object_with_an_unrelated_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") }
end
test "building the association with an array" do
speedometer = Speedometer.new(speedometer_id: "a")
data = [{ name: "first" }, { name: "second" }]
speedometer.minivans.build(data)
assert_equal 2, speedometer.minivans.size
assert speedometer.save
assert_equal ["first", "second"], speedometer.reload.minivans.map(&:name)
end
def test_association_keys_bypass_attribute_protection
car = Car.create(name: "honda")
bulb = car.bulbs.new
assert_equal car.id, bulb.car_id
bulb = car.bulbs.new car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create car_id: car.id + 1
assert_equal car.id, bulb.car_id
end
def test_association_protect_foreign_key
invoice = Invoice.create
line_item = invoice.line_items.new
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.new invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
end
# When creating objects on the association, we must not do it within a scope (even though it
# would be convenient), because this would cause that scope to be applied to any callbacks etc.
def test_build_and_create_should_not_happen_within_scope
car = cars(:honda)
scope = car.foo_bulbs.where_values_hash
bulb = car.foo_bulbs.build
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
bulb = car.foo_bulbs.create
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
bulb = car.foo_bulbs.create!
assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
end
def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(name: "honda")
bulbs = Car.first.bulbs
bulbs.to_a # to load all instances of bulbs
assert_no_queries do
bulbs.first()
end
assert_no_queries do
bulbs.second()
end
assert_no_queries do
bulbs.third()
end
assert_no_queries do
bulbs.fourth()
end
assert_no_queries do
bulbs.fifth()
end
assert_no_queries do
bulbs.forty_two()
end
assert_no_queries do
bulbs.third_to_last()
end
assert_no_queries do
bulbs.second_to_last()
end
assert_no_queries do
bulbs.last()
end
end
def test_finder_method_with_dirty_target
company = companies(:first_firm)
new_clients = []
assert_no_queries(ignore_none: false) do
new_clients << company.clients_of_firm.build(name: "Another Client")
new_clients << company.clients_of_firm.build(name: "Another Client II")
new_clients << company.clients_of_firm.build(name: "Another Client III")
end
assert_not company.clients_of_firm.loaded?
assert_queries(1) do
assert_same new_clients[0], company.clients_of_firm.third
assert_same new_clients[1], company.clients_of_firm.fourth
assert_same new_clients[2], company.clients_of_firm.fifth
assert_same new_clients[0], company.clients_of_firm.third_to_last
assert_same new_clients[1], company.clients_of_firm.second_to_last
assert_same new_clients[2], company.clients_of_firm.last
end
end
def test_finder_bang_method_with_dirty_target
company = companies(:first_firm)
new_clients = []
assert_no_queries(ignore_none: false) do
new_clients << company.clients_of_firm.build(name: "Another Client")
new_clients << company.clients_of_firm.build(name: "Another Client II")
new_clients << company.clients_of_firm.build(name: "Another Client III")
end
assert_not company.clients_of_firm.loaded?
assert_queries(1) do
assert_same new_clients[0], company.clients_of_firm.third!
assert_same new_clients[1], company.clients_of_firm.fourth!
assert_same new_clients[2], company.clients_of_firm.fifth!
assert_same new_clients[0], company.clients_of_firm.third_to_last!
assert_same new_clients[1], company.clients_of_firm.second_to_last!
assert_same new_clients[2], company.clients_of_firm.last!
end
end
def test_create_resets_cached_counters
person = Person.create!(first_name: "tenderlove")
post = Post.first
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
person.readers.create(post_id: post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
assert_equal post, person.readers.first.post
assert_equal person, person.readers.first.person
end
def test_update_all_respects_association_scope
person = Person.new
person.first_name = "Naruto"
person.references << Reference.new
person.id = 10
person.references
person.save!
assert_equal 1, person.references.update_all(favourite: true)
end
def test_exists_respects_association_scope
person = Person.new
person.first_name = "Sasuke"
person.references << Reference.new
person.id = 10
person.references
person.save!
assert_predicate person.references, :exists?
end
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
def test_counting_with_counter_sql
assert_equal 3, Firm.all.merge!(order: "id").first.clients.count
end
def test_counting
assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count
end
def test_counting_with_single_hash
assert_equal 1, Firm.all.merge!(order: "id").first.plain_clients.where(name: "Microsoft").count
end
def test_counting_with_column_name_and_hash
assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count(:name)
end
def test_counting_with_association_limit
firm = companies(:first_firm)
assert_equal firm.limited_clients.length, firm.limited_clients.size
assert_equal firm.limited_clients.length, firm.limited_clients.count
end
def test_finding
assert_equal 3, Firm.all.merge!(order: "id").first.clients.length
end
def test_finding_array_compatibility
assert_equal 3, Firm.order(:id).find { |f| f.id > 0 }.clients.length
end
def test_find_many_with_merged_options
assert_equal 1, companies(:first_firm).limited_clients.size
assert_equal 1, companies(:first_firm).limited_clients.to_a.size
assert_equal 3, companies(:first_firm).limited_clients.limit(nil).to_a.size
end
def test_find_should_append_to_association_order
ordered_clients = companies(:first_firm).clients_sorted_desc.order("companies.id")
assert_equal ["id DESC", "companies.id"], ordered_clients.order_values
end
def test_dynamic_find_should_respect_association_order
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type("Client")
end
def test_taking
posts(:other_by_bob).destroy
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
authors(:bob).posts.to_a
assert_equal posts(:misc_by_bob), authors(:bob).posts.take
assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
end
def test_taking_not_found
authors(:bob).posts.delete_all
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
authors(:bob).posts.to_a
assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
end
def test_taking_with_a_number
# taking from unloaded Relation
bob = Author.find(authors(:bob).id)
new_post = bob.posts.build
assert_not bob.posts.loaded?
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
# taking from loaded Relation
bob.posts.load
assert bob.posts.loaded?
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
end
def test_taking_with_inverse_of
interests(:woodsmanship).destroy
interests(:survival).destroy
zine = zines(:going_out)
interest = zine.interests.take
assert_equal interests(:hunting), interest
assert_same zine, interest.zine
end
def test_cant_save_has_many_readonly_association
authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } }
authors(:david).readonly_comments.each { |c| assert c.readonly? }
end
def test_finding_default_orders
assert_equal "Summit", Firm.all.merge!(order: "id").first.clients.first.name
end
def test_finding_with_different_class_name_and_order
assert_equal "Apex", Firm.all.merge!(order: "id").first.clients_sorted_desc.first.name
end
def test_finding_with_foreign_key
assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_of_firm.first.name
end
def test_finding_with_condition
assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms.first.name
end
def test_finding_with_condition_hash
assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms_with_hash_conditions.first.name
end
def test_finding_using_primary_key
assert_equal "Summit", Firm.all.merge!(order: "id").first.clients_using_primary_key.first.name
end
def test_update_all_on_association_accessed_before_save
firm = Firm.new(name: "Firm")
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
end
def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
firm = Firm.new(name: "Firm", id: 100)
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
end
def test_belongs_to_sanity
c = Client.new
assert_nil c.firm, "belongs_to failed sanity check on new object"
end
def test_find_ids
firm = Firm.all.merge!(order: "id").first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
client = firm.clients.find(2)
assert_kind_of Client, client
client_ary = firm.clients.find([2])
assert_kind_of Array, client_ary
assert_equal client, client_ary.first
client_ary = firm.clients.find(2, 3)
assert_kind_of Array, client_ary
assert_equal 2, client_ary.size
assert_equal client, client_ary.first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
end
def test_find_one_message_on_primary_key
firm = Firm.all.merge!(order: "id").first
e = assert_raises(ActiveRecord::RecordNotFound) do
firm.clients.find(0)
end
assert_equal 0, e.id
assert_equal "id", e.primary_key
assert_equal "Client", e.model
assert_match (/\ACouldn't find Client with 'id'=0/), e.message
end
def test_find_ids_and_inverse_of
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
firm = companies(:first_firm)
client = firm.clients_of_firm.find(3)
assert_kind_of Client, client
client_ary = firm.clients_of_firm.find([3])
assert_kind_of Array, client_ary
assert_equal client, client_ary.first
end
def test_find_all
firm = Firm.all.merge!(order: "id").first
assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
end
def test_find_each
firm = companies(:first_firm)
assert ! firm.clients.loaded?
assert_queries(4) do
firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
end
assert ! firm.clients.loaded?
end
def test_find_each_with_conditions
firm = companies(:first_firm)
assert_queries(2) do
firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
assert_equal firm.id, c.firm_id
assert_equal "Microsoft", c.name
end
end
assert ! firm.clients.loaded?
end
def test_find_in_batches
firm = companies(:first_firm)
assert ! firm.clients.loaded?
assert_queries(2) do
firm.clients.find_in_batches(batch_size: 2) do |clients|
clients.each { |c| assert_equal firm.id, c.firm_id }
end
end
assert ! firm.clients.loaded?
end
def test_find_all_sanitized
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
firm = Firm.all.merge!(order: "id").first
summit = firm.clients.where("name = 'Summit'").to_a
assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
assert_equal summit, firm.clients.where("name = :name", name: "Summit").to_a
end
def test_find_first
firm = Firm.all.merge!(order: "id").first
client2 = Client.find(2)
assert_equal firm.clients.first, firm.clients.order("id").first
assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
end
def test_find_first_sanitized
firm = Firm.all.merge!(order: "id").first
client2 = Client.find(2)
assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = ?", "Client"], order: "id").first
assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = :type", { type: "Client" }], order: "id").first
end
def test_find_all_with_include_and_conditions
assert_nothing_raised do
Developer.all.merge!(joins: :audit_logs, where: { "audit_logs.message" => nil, :name => "Smith" }).to_a
end
end
def test_find_in_collection
assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
end
def test_find_grouped
all_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1").to_a
grouped_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1", group: "firm_id", select: "firm_id, count(id) as clients_count").to_a
assert_equal 3, all_clients_of_firm1.size
assert_equal 1, grouped_clients_of_firm1.size
end
def test_find_scoped_grouped
assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
assert_equal 3, companies(:first_firm).clients_grouped_by_name.size
assert_equal 3, companies(:first_firm).clients_grouped_by_name.length
end
def test_find_scoped_grouped_having
assert_equal 1, authors(:david).popular_grouped_posts.length
assert_equal 0, authors(:mary).popular_grouped_posts.length
end
def test_default_select
assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
end
def test_select_query_method
assert_equal ["id", "body"], posts(:welcome).comments.select(:id, :body).first.attributes.keys
end
def test_select_with_block
assert_equal [1], posts(:welcome).comments.select { |c| c.id == 1 }.map(&:id)
end
def test_select_without_foreign_key
assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
end
def test_adding
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
natural = Client.new("name" => "Natural Company")
companies(:first_firm).clients_of_firm << natural
assert_equal 3, companies(:first_firm).clients_of_firm.size # checking via the collection
assert_equal 3, companies(:first_firm).clients_of_firm.reload.size # checking using the db
assert_equal natural, companies(:first_firm).clients_of_firm.last
end
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 3, first_firm.plain_clients.size
first_firm.plain_clients.create(name: "Natural Company")
assert_equal 4, first_firm.plain_clients.length
assert_equal 4, first_firm.plain_clients.size
end
def test_create_with_bang_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create! name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_regular_create_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_create_with_bang_on_has_many_raises_when_record_not_saved
assert_raise(ActiveRecord::RecordInvalid) do
firm = Firm.all.merge!(order: "id").first
firm.plain_clients.create!
end
end
def test_create_with_bang_on_habtm_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
Developer.new("name" => "Aredridel").projects.create!
end
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_adding_a_mismatch_class
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << nil }
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << Topic.find(1) }
end
def test_adding_a_collection
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")])
assert_equal 4, companies(:first_firm).clients_of_firm.size
assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
end
def test_transactions_when_adding_to_persisted
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_save: true)
begin
companies(:first_firm).clients_of_firm.concat(good, bad)
rescue Client::RaisedOnSave
end
assert_not_includes companies(:first_firm).clients_of_firm.reload, good
end
def test_transactions_when_adding_to_new_record
assert_no_queries(ignore_none: false) do
firm = Firm.new
firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
end
end
def test_inverse_on_before_validate
firm = companies(:first_firm)
assert_queries(1) do
firm.clients_of_firm << Client.new("name" => "Natural Company")
end
end
def test_new_aliased_to_build
company = companies(:first_firm)
new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.new("name" => "Another Client") }
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
def test_build
company = companies(:first_firm)
new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
def test_collection_size_after_building
company = companies(:first_firm) # company already has one client
company.clients_of_firm.build("name" => "Another Client")
company.clients_of_firm.build("name" => "Yet Another Client")
assert_equal 4, company.clients_of_firm.size
assert_equal 4, company.clients_of_firm.uniq.size
end
def test_collection_not_empty_after_building
company = companies(:first_firm)
assert_predicate company.contracts, :empty?
company.contracts.build
assert_not_predicate company.contracts, :empty?
end
def test_collection_size_twice_for_regressions
post = posts(:thinking)
assert_equal 0, post.readers.size
# This test needs a post that has no readers, we assert it to ensure it holds,
# but need to reload the post because the very call to #size hides the bug.
post.reload
post.readers.build
size1 = post.readers.size
size2 = post.readers.size
assert_equal size1, size2
end
def test_build_many
company = companies(:first_firm)
new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) }
assert_equal 2, new_clients.size
end
def test_build_followed_by_save_does_not_load_target
companies(:first_firm).clients_of_firm.build("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
def test_build_without_loading_association
first_topic = topics(:first)
Reply.column_names
assert_equal 1, first_topic.replies.length
assert_no_queries do
first_topic.replies.build(title: "Not saved", content: "Superstars")
assert_equal 2, first_topic.replies.size
end
assert_equal 2, first_topic.replies.to_ary.size
end
def test_build_via_block
company = companies(:first_firm)
new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
def test_build_many_via_block
company = companies(:first_firm)
new_clients = assert_no_queries(ignore_none: false) do
company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) do |client|
client.name = "changed"
end
end
assert_equal 2, new_clients.size
assert_equal "changed", new_clients.first.name
assert_equal "changed", new_clients.last.name
end
def test_create_without_loading_association
first_firm = companies(:first_firm)
Firm.column_names
Client.column_names
assert_equal 2, first_firm.clients_of_firm.size
first_firm.clients_of_firm.reset
assert_queries(1) do
first_firm.clients_of_firm.create(name: "Superstars")
end
assert_equal 3, first_firm.clients_of_firm.size
end
def test_create
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert new_client.persisted?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert_equal new_client, companies(:first_firm).clients_of_firm.reload.last
end
def test_create_many
companies(:first_firm).clients_of_firm.create([{ "name" => "Another Client" }, { "name" => "Another Client II" }])
assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
end
def test_create_followed_by_save_does_not_load_target
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
def test_deleting
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first)
assert_equal 1, companies(:first_firm).clients_of_firm.size
assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
end
def test_deleting_before_save
new_firm = Firm.new("name" => "A New Firm, Inc.")
new_client = new_firm.clients_of_firm.build("name" => "Another Client")
assert_equal 1, new_firm.clients_of_firm.size
new_firm.clients_of_firm.delete(new_client)
assert_equal 0, new_firm.clients_of_firm.size
end
def test_has_many_without_counter_cache_option
# Ship has a conventionally named `treasures_count` column, but the counter_cache
# option is not given on the association.
ship = Ship.create(name: "Countless", treasures_count: 10)
assert_not Ship.reflect_on_association(:treasures).has_cached_counter?
# Count should come from sql count() of treasures rather than treasures_count attribute
assert_equal ship.treasures.size, 0
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
ship.treasures.create(name: "Gold")
end
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
ship.treasures.destroy_all
end
end
def test_deleting_updates_counter_cache
topic = Topic.order("id ASC").first
assert_equal topic.replies.to_a.size, topic.replies_count
topic.replies.delete(topic.replies.first)
topic.reload
assert_equal topic.replies.to_a.size, topic.replies_count
end
def test_counter_cache_updates_in_memory_after_concat
topic = Topic.create title: "Zoom-zoom-zoom"
topic.replies << Reply.create(title: "re: zoom", content: "speedy quick!")
assert_equal 1, topic.replies_count
assert_equal 1, topic.replies.size
assert_equal 1, topic.reload.replies.size
end
def test_counter_cache_updates_in_memory_after_create
topic = Topic.create title: "Zoom-zoom-zoom"
topic.replies.create!(title: "re: zoom", content: "speedy quick!")
assert_equal 1, topic.replies_count
assert_equal 1, topic.replies.size
assert_equal 1, topic.reload.replies.size
end
def test_counter_cache_updates_in_memory_after_create_with_array
topic = Topic.create title: "Zoom-zoom-zoom"
topic.replies.create!([
{ title: "re: zoom", content: "speedy quick!" },
{ title: "re: zoom 2", content: "OMG lol!" },
])
assert_equal 2, topic.replies_count
assert_equal 2, topic.replies.size
assert_equal 2, topic.reload.replies.size
end
def test_pushing_association_updates_counter_cache
topic = Topic.order("id ASC").first
reply = Reply.create!
assert_difference "topic.reload.replies_count", 1 do
topic.replies << reply
end
end
def test_deleting_updates_counter_cache_without_dependent_option
post = posts(:welcome)
assert_difference "post.reload.tags_count", -1 do
post.taggings.delete(post.taggings.first)
end
end
def test_deleting_updates_counter_cache_with_dependent_delete_all
post = posts(:welcome)
post.update_columns(taggings_with_delete_all_count: post.tags_count)
assert_difference "post.reload.taggings_with_delete_all_count", -1 do
post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first)
end
end
def test_deleting_updates_counter_cache_with_dependent_destroy
post = posts(:welcome)
post.update_columns(taggings_with_destroy_count: post.tags_count)
assert_difference "post.reload.taggings_with_destroy_count", -1 do
post.taggings_with_destroy.delete(post.taggings_with_destroy.first)
end
end
def test_calling_empty_with_counter_cache
post = posts(:welcome)
assert_queries(0) do
assert_not post.comments.empty?
end
end
def test_custom_named_counter_cache
topic = topics(:first)
assert_difference "topic.reload.replies_count", -1 do
topic.approved_replies.clear
end
end
def test_calling_update_attributes_on_id_changes_the_counter_cache
topic = Topic.order("id ASC").first
original_count = topic.replies.to_a.size
assert_equal original_count, topic.replies_count
first_reply = topic.replies.first
first_reply.update_attributes(parent_id: nil)
assert_equal original_count - 1, topic.reload.replies_count
first_reply.update_attributes(parent_id: topic.id)
assert_equal original_count, topic.reload.replies_count
end
def test_calling_update_attributes_changing_ids_doesnt_change_counter_cache
topic1 = Topic.find(1)
topic2 = Topic.find(3)
original_count1 = topic1.replies.to_a.size
original_count2 = topic2.replies.to_a.size
reply1 = topic1.replies.first
reply2 = topic2.replies.first
reply1.update_attributes(parent_id: topic2.id)
assert_equal original_count1 - 1, topic1.reload.replies_count
assert_equal original_count2 + 1, topic2.reload.replies_count
reply2.update_attributes(parent_id: topic1.id)
assert_equal original_count1, topic1.reload.replies_count
assert_equal original_count2, topic2.reload.replies_count
end
def test_deleting_a_collection
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert_equal 3, companies(:first_firm).clients_of_firm.size
companies(:first_firm).clients_of_firm.delete([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1], companies(:first_firm).clients_of_firm[2]])
assert_equal 0, companies(:first_firm).clients_of_firm.size
assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
end
def test_delete_all
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).dependent_clients_of_firm.create("name" => "Another Client")
clients = companies(:first_firm).dependent_clients_of_firm.to_a
assert_equal 3, clients.count
assert_difference "Client.count", -(clients.count) do
companies(:first_firm).dependent_clients_of_firm.delete_all
end
end
def test_delete_all_with_not_yet_loaded_association_collection
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert_equal 3, companies(:first_firm).clients_of_firm.size
companies(:first_firm).clients_of_firm.reset
companies(:first_firm).clients_of_firm.delete_all
assert_equal 0, companies(:first_firm).clients_of_firm.size
assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
end
def test_transaction_when_deleting_persisted
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_destroy: true)
companies(:first_firm).clients_of_firm = [good, bad]
begin
companies(:first_firm).clients_of_firm.destroy(good, bad)
rescue Client::RaisedOnDestroy
end
assert_equal [good, bad], companies(:first_firm).clients_of_firm.reload
end
def test_transaction_when_deleting_new_record
assert_no_queries(ignore_none: false) do
firm = Firm.new
client = Client.new("name" => "New Client")
firm.clients_of_firm << client
firm.clients_of_firm.destroy(client)
end
end
def test_clearing_an_association_collection
firm = companies(:first_firm)
client_id = firm.clients_of_firm.first.id
assert_equal 2, firm.clients_of_firm.size
firm.clients_of_firm.clear
assert_equal 0, firm.clients_of_firm.size
assert_equal 0, firm.clients_of_firm.reload.size
assert_equal [], Client.destroyed_client_ids[firm.id]
# Should not be destroyed since the association is not dependent.
assert_nothing_raised do
assert_nil Client.find(client_id).firm
end
end
def test_clearing_updates_counter_cache
topic = Topic.first
assert_difference "topic.reload.replies_count", -1 do
topic.replies.clear
end
end
def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_with_dependent_destroy
car = Car.first
car.engines.create!
assert_difference "car.reload.engines_count", -1 do
car.engines.clear
end
end
def test_clearing_a_dependent_association_collection
firm = companies(:first_firm)
client_id = firm.dependent_clients_of_firm.first.id
assert_equal 2, firm.dependent_clients_of_firm.size
assert_equal 1, Client.find_by_id(client_id).client_of
# :delete_all is called on each client since the dependent options is :destroy
firm.dependent_clients_of_firm.clear
assert_equal 0, firm.dependent_clients_of_firm.size
assert_equal 0, firm.dependent_clients_of_firm.reload.size
assert_equal [], Client.destroyed_client_ids[firm.id]
# Should be destroyed since the association is dependent.
assert_nil Client.find_by_id(client_id)
end
def test_delete_all_with_option_delete_all
firm = companies(:first_firm)
client_id = firm.dependent_clients_of_firm.first.id
firm.dependent_clients_of_firm.delete_all(:delete_all)
assert_nil Client.find_by_id(client_id)
end
def test_delete_all_accepts_limited_parameters
firm = companies(:first_firm)
assert_raise(ArgumentError) do
firm.dependent_clients_of_firm.delete_all(:destroy)
end
end
def test_clearing_an_exclusively_dependent_association_collection
firm = companies(:first_firm)
client_id = firm.exclusively_dependent_clients_of_firm.first.id
assert_equal 2, firm.exclusively_dependent_clients_of_firm.size
assert_equal [], Client.destroyed_client_ids[firm.id]
# :exclusively_dependent means each client is deleted directly from
# the database without looping through them calling destroy.
firm.exclusively_dependent_clients_of_firm.clear
assert_equal 0, firm.exclusively_dependent_clients_of_firm.size
assert_equal 0, firm.exclusively_dependent_clients_of_firm.reload.size
# no destroy-filters should have been called
assert_equal [], Client.destroyed_client_ids[firm.id]
# Should be destroyed since the association is exclusively dependent.
assert_nil Client.find_by_id(client_id)
end
def test_dependent_association_respects_optional_conditions_on_delete
firm = companies(:odegy)
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_conditional_clients_of_firm.size
firm.destroy
# only the correctly associated client should have been deleted
assert_equal 1, Client.where(client_of: firm.id).size
end
def test_dependent_association_respects_optional_sanitized_conditions_on_delete
firm = companies(:odegy)
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
firm.destroy
# only the correctly associated client should have been deleted
assert_equal 1, Client.where(client_of: firm.id).size
end
def test_dependent_association_respects_optional_hash_conditions_on_delete
firm = companies(:odegy)
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
firm.destroy
# only the correctly associated client should have been deleted
assert_equal 1, Client.where(client_of: firm.id).size
end
def test_delete_all_association_with_primary_key_deletes_correct_records
firm = Firm.first
# break the vanilla firm_id foreign key
assert_equal 3, firm.clients.count
firm.clients.first.update_columns(firm_id: nil)
assert_equal 2, firm.clients.reload.count
assert_equal 2, firm.clients_using_primary_key_with_delete_all.count
old_record = firm.clients_using_primary_key_with_delete_all.first
firm = Firm.first
firm.destroy
assert_nil Client.find_by_id(old_record.id)
end
def test_creation_respects_hash_condition
ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
assert ms_client.save
assert_equal "Microsoft", ms_client.name
another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
assert another_ms_client.persisted?
assert_equal "Microsoft", another_ms_client.name
end
def test_clearing_without_initial_access
firm = companies(:first_firm)
firm.clients_of_firm.clear
assert_equal 0, firm.clients_of_firm.size
assert_equal 0, firm.clients_of_firm.reload.size
end
def test_deleting_a_item_which_is_not_in_the_collection
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
summit = Client.find_by_name("Summit")
companies(:first_firm).clients_of_firm.delete(summit)
assert_equal 2, companies(:first_firm).clients_of_firm.size
assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
assert_equal 2, summit.client_of
end
def test_deleting_by_integer_id
david = Developer.find(1)
assert_difference "david.projects.count", -1 do
assert_equal 1, david.projects.delete(1).size
end
assert_equal 1, david.projects.size
end
def test_deleting_by_string_id
david = Developer.find(1)
assert_difference "david.projects.count", -1 do
assert_equal 1, david.projects.delete("1").size
end
assert_equal 1, david.projects.size
end
def test_deleting_self_type_mismatch
david = Developer.find(1)
david.projects.reload
assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
end
def test_destroying
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
assert_difference "Client.count", -1 do
companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first)
end
assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
end
def test_destroying_by_integer_id
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
assert_difference "Client.count", -1 do
companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id)
end
assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
end
def test_destroying_by_string_id
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
assert_difference "Client.count", -1 do
companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id.to_s)
end
assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
end
def test_destroying_a_collection
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert_equal 3, companies(:first_firm).clients_of_firm.size
assert_difference "Client.count", -2 do
companies(:first_firm).clients_of_firm.destroy([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1]])
end
assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
end
def test_destroy_all
force_signal37_to_load_all_clients_of_firm
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
clients = companies(:first_firm).clients_of_firm.to_a
assert !clients.empty?, "37signals has clients after load"
destroyed = companies(:first_firm).clients_of_firm.destroy_all
assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id)
assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
assert companies(:first_firm).clients_of_firm.reload.empty?, "37signals has no clients after destroy all and refresh"
end
def test_dependence
firm = companies(:first_firm)
assert_equal 3, firm.clients.size
firm.destroy
assert Client.all.merge!(where: "firm_id=#{firm.id}").to_a.empty?
end
def test_dependence_for_associations_with_hash_condition
david = authors(:david)
assert_difference("Post.count", -1) { assert david.destroy }
end
def test_destroy_dependent_when_deleted_from_association
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
firm = Firm.all.merge!(order: "id").first
assert_equal 3, firm.clients.size
client = firm.clients.first
firm.clients.delete(client)
assert_raise(ActiveRecord::RecordNotFound) { Client.find(client.id) }
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(client.id) }
assert_equal 2, firm.clients.size
end
def test_three_levels_of_dependence
topic = Topic.create "title" => "neat and simple"
reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it"
reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
assert_nothing_raised { topic.destroy }
end
def test_dependence_with_transaction_support_on_failure
firm = companies(:first_firm)
clients = firm.clients
assert_equal 3, clients.length
clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
firm.destroy rescue "do nothing"
assert_equal 3, Client.all.merge!(where: "firm_id=#{firm.id}").to_a.size
end
def test_dependence_on_account
num_accounts = Account.count
companies(:first_firm).destroy
assert_equal num_accounts - 1, Account.count
end
def test_depends_and_nullify
num_accounts = Account.count
core = companies(:rails_core)
assert_equal accounts(:rails_core_account), core.account
assert_equal companies(:leetsoft, :jadedpixel), core.companies
core.destroy
assert_nil accounts(:rails_core_account).reload.firm_id
assert_nil companies(:leetsoft).reload.client_of
assert_nil companies(:jadedpixel).reload.client_of
assert_equal num_accounts, Account.count
end
def test_restrict_with_exception
firm = RestrictedWithExceptionFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedWithExceptionFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
end
def test_restrict_with_error
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
firm.destroy
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
end
def test_restrict_with_error_with_locale
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations "en", activerecord: { attributes: { restricted_with_error_firm: { companies: "client companies" } } }
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
firm.destroy
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent client companies exist", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
ensure
I18n.backend.reload!
end
def test_included_in_collection
assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
end
def test_included_in_collection_for_new_records
client = Client.create(name: "Persisted")
assert_nil client.client_of
assert_equal false, Firm.new.clients_of_firm.include?(client),
"includes a client that does not belong to any firm"
end
def test_adding_array_and_collection
assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
end
def test_replace_with_less
firm = Firm.all.merge!(order: "id").first
firm.clients = [companies(:first_client)]
assert firm.save, "Could not save firm"
firm.reload
assert_equal 1, firm.clients.length
end
def test_replace_with_less_and_dependent_nullify
num_companies = Company.count
companies(:rails_core).companies = []
assert_equal num_companies, Company.count
end
def test_replace_with_new
firm = Firm.all.merge!(order: "id").first
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
firm.save
firm.reload
assert_equal 2, firm.clients.length
assert_equal false, firm.clients.include?(:first_client)
end
def test_replace_failure
firm = companies(:first_firm)
account = Account.new
orig_accounts = firm.accounts.to_a
assert !account.valid?
assert !orig_accounts.empty?
error = assert_raise ActiveRecord::RecordNotSaved do
firm.accounts = [account]
end
assert_equal orig_accounts, firm.accounts
assert_equal "Failed to replace accounts because one or more of the " \
"new records could not be saved.", error.message
end
def test_replace_with_same_content
firm = Firm.first
firm.clients = []
firm.save
assert_queries(0, ignore_none: true) do
firm.clients = []
end
assert_equal [], firm.send("clients=", [])
end
def test_transactions_when_replacing_on_persisted
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_save: true)
companies(:first_firm).clients_of_firm = [good]
begin
companies(:first_firm).clients_of_firm = [bad]
rescue Client::RaisedOnSave
end
assert_equal [good], companies(:first_firm).clients_of_firm.reload
end
def test_transactions_when_replacing_on_new_record
assert_no_queries(ignore_none: false) do
firm = Firm.new
firm.clients_of_firm = [Client.new("name" => "New Client")]
end
end
def test_get_ids
assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], companies(:first_firm).client_ids
end
def test_get_ids_for_loaded_associations
company = companies(:first_firm)
company.clients.reload
assert_queries(0) do
company.client_ids
company.client_ids
end
end
def test_get_ids_for_unloaded_associations_does_not_load_them
company = companies(:first_firm)
assert !company.clients.loaded?
assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], company.client_ids
assert !company.clients.loaded?
end
def test_counter_cache_on_unloaded_association
car = Car.create(name: "My AppliCar")
assert_equal car.engines.size, 0
end
def test_get_ids_ignores_include_option
assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
end
def test_get_ids_for_ordered_association
assert_equal [companies(:another_first_firm_client).id, companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
end
def test_get_ids_for_association_on_new_record_does_not_try_to_find_records
Company.columns # Load schema information so we don't query below
Contract.columns # if running just this test.
company = Company.new
assert_queries(0) do
company.contract_ids
end
assert_equal [], company.contract_ids
end
def test_set_ids_for_association_on_new_record_applies_association_correctly
contract_a = Contract.create!
contract_b = Contract.create!
Contract.create! # another contract
company = Company.new(name: "Some Company")
company.contract_ids = [contract_a.id, contract_b.id]
assert_equal [contract_a.id, contract_b.id], company.contract_ids
assert_equal [contract_a, contract_b], company.contracts
company.save!
assert_equal company, contract_a.reload.company
assert_equal company, contract_b.reload.company
end
def test_assign_ids_ignoring_blanks
firm = Firm.create!(name: "Apple")
firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""]
firm.save!
assert_equal 2, firm.clients.reload.size
assert_equal true, firm.clients.include?(companies(:second_client))
end
def test_get_ids_for_through
assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids
end
def test_modifying_a_through_a_has_many_should_raise
[
lambda { authors(:mary).comment_ids = [comments(:greetings).id, comments(:more_greetings).id] },
lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] },
lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) },
lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
].each { |block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
def test_dynamic_find_should_respect_association_order_for_through
assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type("SpecialComment")
end
def test_has_many_through_respects_hash_conditions
assert_equal authors(:david).hello_posts, authors(:david).hello_posts_with_hash_conditions
assert_equal authors(:david).hello_post_comments, authors(:david).hello_post_comments_with_hash_conditions
end
def test_include_uses_array_include_after_loaded
firm = companies(:first_firm)
firm.clients.load_target
client = firm.clients.first
assert_no_queries do
assert firm.clients.loaded?
assert_equal true, firm.clients.include?(client)
end
end
def test_include_checks_if_record_exists_if_target_not_loaded
firm = companies(:first_firm)
client = firm.clients.first
firm.reload
assert ! firm.clients.loaded?
assert_queries(1) do
assert_equal true, firm.clients.include?(client)
end
assert ! firm.clients.loaded?
end
def test_include_returns_false_for_non_matching_record_to_verify_scoping
firm = companies(:first_firm)
client = Client.create!(name: "Not Associated")
assert ! firm.clients.loaded?
assert_equal false, firm.clients.include?(client)
end
def test_calling_first_nth_or_last_on_association_should_not_load_association
firm = companies(:first_firm)
firm.clients.first
firm.clients.second
firm.clients.last
assert !firm.clients.loaded?
end
def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
firm = companies(:first_firm)
firm.clients.load_target
assert firm.clients.loaded?
assert_no_queries(ignore_none: false) do
firm.clients.first
assert_equal 2, firm.clients.first(2).size
firm.clients.last
assert_equal 2, firm.clients.last(2).size
end
end
def test_calling_first_or_last_on_existing_record_with_build_should_load_association
firm = companies(:first_firm)
firm.clients.build(name: "Foo")
assert !firm.clients.loaded?
assert_queries 1 do
firm.clients.first
firm.clients.second
firm.clients.last
end
assert firm.clients.loaded?
end
def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
firm = companies(:first_firm)
firm.clients.create(name: "Foo")
assert !firm.clients.loaded?
assert_queries 3 do
firm.clients.first
firm.clients.second
firm.clients.last
end
assert !firm.clients.loaded?
end
def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
firm = Firm.new
assert_no_queries do
firm.clients.first
firm.clients.second
firm.clients.last
end
end
def test_calling_first_or_last_with_integer_on_association_should_not_load_association
firm = companies(:first_firm)
firm.clients.create(name: "Foo")
assert !firm.clients.loaded?
assert_queries 2 do
firm.clients.first(2)
firm.clients.last(2)
end
assert !firm.clients.loaded?
end
def test_calling_many_should_count_instead_of_loading_association
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.many? # use count query
end
assert !firm.clients.loaded?
end
def test_calling_many_on_loaded_association_should_not_use_query
firm = companies(:first_firm)
firm.clients.collect # force load
assert_no_queries { assert firm.clients.many? }
end
def test_calling_many_should_defer_to_collection_if_using_a_block
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.expects(:size).never
firm.clients.many? { true }
end
assert firm.clients.loaded?
end
def test_calling_many_should_return_false_if_none_or_one
firm = companies(:another_firm)
assert !firm.clients_like_ms.many?
assert_equal 0, firm.clients_like_ms.size
firm = companies(:first_firm)
assert !firm.limited_clients.many?
assert_equal 1, firm.limited_clients.size
end
def test_calling_many_should_return_true_if_more_than_one
firm = companies(:first_firm)
assert firm.clients.many?
assert_equal 3, firm.clients.size
end
def test_calling_none_should_count_instead_of_loading_association
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.none? # use count query
end
assert !firm.clients.loaded?
end
def test_calling_none_on_loaded_association_should_not_use_query
firm = companies(:first_firm)
firm.clients.collect # force load
assert_no_queries { assert ! firm.clients.none? }
end
def test_calling_none_should_defer_to_collection_if_using_a_block
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.expects(:size).never
firm.clients.none? { true }
end
assert firm.clients.loaded?
end
def test_calling_none_should_return_true_if_none
firm = companies(:another_firm)
assert firm.clients_like_ms.none?
assert_equal 0, firm.clients_like_ms.size
end
def test_calling_none_should_return_false_if_any
firm = companies(:first_firm)
assert !firm.limited_clients.none?
assert_equal 1, firm.limited_clients.size
end
def test_calling_one_should_count_instead_of_loading_association
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.one? # use count query
end
assert !firm.clients.loaded?
end
def test_calling_one_on_loaded_association_should_not_use_query
firm = companies(:first_firm)
firm.clients.collect # force load
assert_no_queries { assert ! firm.clients.one? }
end
def test_calling_one_should_defer_to_collection_if_using_a_block
firm = companies(:first_firm)
assert_queries(1) do
firm.clients.expects(:size).never
firm.clients.one? { true }
end
assert firm.clients.loaded?
end
def test_calling_one_should_return_false_if_zero
firm = companies(:another_firm)
assert ! firm.clients_like_ms.one?
assert_equal 0, firm.clients_like_ms.size
end
def test_calling_one_should_return_true_if_one
firm = companies(:first_firm)
assert firm.limited_clients.one?
assert_equal 1, firm.limited_clients.size
end
def test_calling_one_should_return_false_if_more_than_one
firm = companies(:first_firm)
assert ! firm.clients.one?
assert_equal 3, firm.clients.size
end
def test_joins_with_namespaced_model_should_use_correct_type
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = true
firm = Namespaced::Firm.create(name: "Some Company")
firm.clients.create(name: "Some Client")
stats = Namespaced::Firm.all.merge!(
select: "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
joins: :clients,
group: "#{Namespaced::Firm.table_name}.id"
).find firm.id
assert_equal 1, stats.num_clients.to_i
ensure
ActiveRecord::Base.store_full_sti_class = old
end
def test_association_proxy_transaction_method_starts_transaction_in_association_class
Comment.expects(:transaction)
Post.first.comments.transaction do
# nothing
end
end
def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
client_association = companies(:first_firm).clients
assert_equal client_association.new.attributes, client_association.send(:new).attributes
end
def test_respond_to_private_class_methods
client_association = companies(:first_firm).clients
assert !client_association.respond_to?(:private_method)
assert client_association.respond_to?(:private_method, true)
end
def test_creating_using_primary_key
firm = Firm.all.merge!(order: "id").first
client = firm.clients_using_primary_key.create!(name: "test")
assert_equal firm.name, client.firm_name
end
def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class DeleteAllModel < ActiveRecord::Base
has_many :nonentities, :dependent => :delete_all
end
EOF
end
def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class NullifyModel < ActiveRecord::Base
has_many :nonentities, :dependent => :nullify
end
EOF
end
def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
new_comment = posts(:welcome).comments.where(body: "Some content").build
assert_equal new_comment.body, "Some content"
end
def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
new_comment = posts(:welcome).comments.where(body: "Some content").where(type: "SpecialComment").build
assert_equal new_comment.body, "Some content"
assert_equal new_comment.type, "SpecialComment"
assert_equal new_comment.post_id, posts(:welcome).id
end
def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
post = Post.new
comment = post.comments.build
assert_equal true, post.comments.include?(comment)
end
def test_load_target_respects_protected_attributes
topic = Topic.create!
reply = topic.replies.create(title: "reply 1")
reply.approved = false
reply.save!
# Save with a different object instance, so the instance that's still held
# in topic.relies doesn't know about the changed attribute.
reply2 = Reply.find(reply.id)
reply2.approved = true
reply2.save!
# Force loading the collection from the db. This will merge the existing
# object (reply) with what gets loaded from the db (which includes the
# changed approved attribute). approved is a protected attribute, so if mass
# assignment is used, it won't get updated and will still be false.
first = topic.replies.to_a.first
assert_equal reply.id, first.id
assert_equal true, first.approved?
end
def test_to_a_should_dup_target
ary = topics(:first).replies.to_a
target = topics(:first).replies.target
assert_not_equal target.object_id, ary.object_id
end
def test_merging_with_custom_attribute_writer
bulb = Bulb.new(color: "red")
assert_equal "RED!", bulb.color
car = Car.create!
car.bulbs << bulb
assert_equal "RED!", car.bulbs.to_a.first.color
end
def test_abstract_class_with_polymorphic_has_many
post = SubStiPost.create! title: "fooo", body: "baa"
tagging = Tagging.create! taggable: post
assert_equal [tagging], post.taggings
end
def test_with_polymorphic_has_many_with_custom_columns_name
post = Post.create! title: "foo", body: "bar"
image = Image.create!
post.images << image
assert_equal [image], post.images
end
def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
welcome = posts(:welcome)
tagging = welcome.taggings.build(taggable_id: 99, taggable_type: "ShouldNotChange")
assert_equal welcome.id, tagging.taggable_id
assert_equal "Post", tagging.taggable_type
end
def test_dont_call_save_callbacks_twice_on_has_many
firm = companies(:first_firm)
contract = firm.contracts.create!
assert_equal 1, contract.hi_count
assert_equal 1, contract.bye_count
end
def test_association_attributes_are_available_to_after_initialize
car = Car.create(name: "honda")
bulb = car.bulbs.build
assert_equal car.id, bulb.attributes_after_initialize["car_id"]
end
def test_attributes_are_set_when_initialized_from_has_many_null_relationship
car = Car.new name: "honda"
bulb = car.bulbs.where(name: "headlight").first_or_initialize
assert_equal "headlight", bulb.name
end
def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
post = Post.new title: "title", body: "bar"
tag = Tag.create!(name: "foo")
tagging = post.taggings.where(tag: tag).first_or_initialize
assert_equal tag.id, tagging.tag_id
assert_equal "Post", tagging.taggable_type
end
def test_replace
car = Car.create(name: "honda")
bulb1 = car.bulbs.create
bulb2 = Bulb.create
assert_equal [bulb1], car.bulbs
car.bulbs.replace([bulb2])
assert_equal [bulb2], car.bulbs
assert_equal [bulb2], car.reload.bulbs
end
def test_replace_returns_target
car = Car.create(name: "honda")
bulb1 = car.bulbs.create
bulb2 = car.bulbs.create
bulb3 = Bulb.create
assert_equal [bulb1, bulb2], car.bulbs
result = car.bulbs.replace([bulb3, bulb1])
assert_equal [bulb1, bulb3], car.bulbs
assert_equal [bulb1, bulb3], result
end
def test_collection_association_with_private_kernel_method
firm = companies(:first_firm)
assert_equal [accounts(:signals37)], firm.accounts.open
end
test "first_or_initialize adds the record to the association" do
firm = Firm.create! name: "omg"
client = firm.clients_of_firm.first_or_initialize
assert_equal [client], firm.clients_of_firm
end
test "first_or_create adds the record to the association" do
firm = Firm.create! name: "omg"
firm.clients_of_firm.load_target
client = firm.clients_of_firm.first_or_create name: "lol"
assert_equal [client], firm.clients_of_firm
assert_equal [client], firm.reload.clients_of_firm
end
test "delete_all, when not loaded, doesn't load the records" do
post = posts(:welcome)
assert post.taggings_with_delete_all.count > 0
assert !post.taggings_with_delete_all.loaded?
# 2 queries: one DELETE and another to update the counter cache
assert_queries(2) do
post.taggings_with_delete_all.delete_all
end
end
test "has many associations on new records use null relations" do
post = Post.new
assert_no_queries(ignore_none: false) do
assert_equal [], post.comments
assert_equal [], post.comments.where(body: "omg")
assert_equal [], post.comments.pluck(:body)
assert_equal 0, post.comments.sum(:id)
assert_equal 0, post.comments.count
end
end
test "collection proxy respects default scope" do
author = authors(:mary)
assert !author.first_posts.exists?
end
test "association with extend option" do
post = posts(:welcome)
assert_equal "lifo", post.comments_with_extend.author
assert_equal "hello", post.comments_with_extend.greeting
end
test "association with extend option with multiple extensions" do
post = posts(:welcome)
assert_equal "lifo", post.comments_with_extend_2.author
assert_equal "hello", post.comments_with_extend_2.greeting
end
test "delete record with complex joins" do
david = authors(:david)
post = david.posts.first
post.type = "PostWithSpecialCategorization"
post.save
categorization = post.categorizations.first
categorization.special = true
categorization.save
assert_not_equal [], david.posts_with_special_categorizations
david.posts_with_special_categorizations = []
assert_equal [], david.posts_with_special_categorizations
end
test "does not duplicate associations when used with natural primary keys" do
speedometer = Speedometer.create!(id: "4")
speedometer.minivans.create!(minivan_id: "a-van-red" , name: "a van", color: "red")
assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}"
assert_equal 1, speedometer.reload.minivans.to_a.size
end
test "can unscope the default scope of the associated model" do
car = Car.create!
bulb1 = Bulb.create! name: "defaulty", car: car
bulb2 = Bulb.create! name: "other", car: car
assert_equal [bulb1], car.bulbs
assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id)
end
test "can unscope and where the default scope of the associated model" do
Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: "other") }, class_name: "Bulb"
car = Car.create!
bulb1 = Bulb.create! name: "defaulty", car: car
bulb2 = Bulb.create! name: "other", car: car
assert_equal [bulb1], car.bulbs
assert_equal [bulb2], car.other_bulbs
end
test "can rewhere the default scope of the associated model" do
Car.has_many :old_bulbs, -> { rewhere(name: "old") }, class_name: "Bulb"
car = Car.create!
bulb1 = Bulb.create! name: "defaulty", car: car
bulb2 = Bulb.create! name: "old", car: car
assert_equal [bulb1], car.bulbs
assert_equal [bulb2], car.old_bulbs
end
test "unscopes the default scope of associated model when used with include" do
car = Car.create!
bulb = Bulb.create! name: "other", car: car
assert_equal bulb, Car.find(car.id).all_bulbs.first
assert_equal bulb, Car.includes(:all_bulbs).find(car.id).all_bulbs.first
end
test "raises RecordNotDestroyed when replaced child can't be destroyed" do
car = Car.create!
original_child = FailedBulb.create!(car: car)
error = assert_raise(ActiveRecord::RecordNotDestroyed) do
car.failed_bulbs = [FailedBulb.create!]
end
assert_equal [original_child], car.reload.failed_bulbs
assert_equal "Failed to destroy the record", error.message
end
test "updates counter cache when default scope is given" do
topic = DefaultRejectedTopic.create approved: true
assert_difference "topic.reload.replies_count", 1 do
topic.approved_replies.create!
end
end
test "dangerous association name raises ArgumentError" do
[:errors, "errors", :save, "save"].each do |name|
assert_raises(ArgumentError, "Association #{name} should not be allowed") do
Class.new(ActiveRecord::Base) do
has_many name
end
end
end
end
test "passes custom context validation to validate children" do
pirate = FamousPirate.new
pirate.famous_ships << ship = FamousShip.new
assert pirate.valid?
assert_not pirate.valid?(:conference)
assert_equal "can't be blank", ship.errors[:name].first
end
test "association with instance dependent scope" do
bob = authors(:bob)
Post.create!(title: "signed post by bob", body: "stuff", author: authors(:bob))
Post.create!(title: "anonymous post", body: "more stuff", author: authors(:bob))
assert_equal ["misc post by bob", "other post by bob",
"signed post by bob"], bob.posts_with_signature.map(&:title).sort
assert_equal [], authors(:david).posts_with_signature.map(&:title)
end
test "associations autosaves when object is already persisted" do
bulb = Bulb.create!
tyre = Tyre.create!
car = Car.create! do |c|
c.bulbs << bulb
c.tyres << tyre
end
assert_equal 1, car.bulbs.count
assert_equal 1, car.tyres.count
end
test "associations replace in memory when records have the same id" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
new_bulb = Bulb.find(bulb.id)
new_bulb.name = "foo"
car.bulbs = [new_bulb]
assert_equal "foo", car.bulbs.first.name
end
test "in memory replacement executes no queries" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
new_bulb = Bulb.find(bulb.id)
assert_no_queries do
car.bulbs = [new_bulb]
end
end
test "in memory replacements do not execute callbacks" do
raise_after_add = false
klass = Class.new(ActiveRecord::Base) do
self.table_name = :cars
has_many :bulbs, after_add: proc { raise if raise_after_add }
def self.name
"Car"
end
end
bulb = Bulb.create!
car = klass.create!(bulbs: [bulb])
new_bulb = Bulb.find(bulb.id)
raise_after_add = true
assert_nothing_raised do
car.bulbs = [new_bulb]
end
end
test "in memory replacements sets inverse instance" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
new_bulb = Bulb.find(bulb.id)
car.bulbs = [new_bulb]
assert_same car, new_bulb.car
end
test "in memory replacement maintains order" do
first_bulb = Bulb.create!
second_bulb = Bulb.create!
car = Car.create!(bulbs: [first_bulb, second_bulb])
same_bulb = Bulb.find(first_bulb.id)
car.bulbs = [second_bulb, same_bulb]
assert_equal [first_bulb, second_bulb], car.bulbs
end
test "double insertion of new object to association when same association used in the after create callback of a new object" do
reset_callbacks(:save, Bulb) do
Bulb.after_save { |record| record.car.bulbs.load }
car = Car.create!
car.bulbs << Bulb.new
assert_equal 1, car.bulbs.size
end
end
class AuthorWithErrorDestroyingAssociation < ActiveRecord::Base
self.table_name = "authors"
has_many :posts_with_error_destroying,
class_name: "PostWithErrorDestroying",
foreign_key: :author_id,
dependent: :destroy
end
class PostWithErrorDestroying < ActiveRecord::Base
self.table_name = "posts"
self.inheritance_column = nil
before_destroy -> { throw :abort }
end
def test_destroy_does_not_raise_when_association_errors_on_destroy
assert_no_difference "AuthorWithErrorDestroyingAssociation.count" do
author = AuthorWithErrorDestroyingAssociation.first
assert_not author.destroy
end
end
def test_destroy_with_bang_bubbles_errors_from_associations
error = assert_raises ActiveRecord::RecordNotDestroyed do
AuthorWithErrorDestroyingAssociation.first.destroy!
end
assert_instance_of PostWithErrorDestroying, error.record
end
def test_ids_reader_memoization
car = Car.create!(name: "Tofaş")
bulb = Bulb.create!(car: car)
assert_equal [bulb.id], car.bulb_ids
assert_no_queries { car.bulb_ids }
end
def test_loading_association_in_validate_callback_doesnt_affect_persistence
reset_callbacks(:validation, Bulb) do
Bulb.after_validation { |m| m.car.bulbs.load }
car = Car.create!(name: "Car")
bulb = car.bulbs.create!
assert_equal [bulb], car.bulbs
end
end
private
def force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.load_target
end
def reset_callbacks(kind, klass)
old_callbacks = {}
old_callbacks[klass] = klass.send("_#{kind}_callbacks").dup
klass.subclasses.each do |subclass|
old_callbacks[subclass] = subclass.send("_#{kind}_callbacks").dup
end
yield
ensure
klass.send("_#{kind}_callbacks=", old_callbacks[klass])
klass.subclasses.each do |subclass|
subclass.send("_#{kind}_callbacks=", old_callbacks[subclass])
end
end
end
| 32.975416 | 180 | 0.744661 |
87a8fac852c82d0244c309a2421211c62e4308c0 | 1,443 | class FacebookPublisher < Facebooker::Rails::Publisher
helper PostsHelper, LocationsHelper, PicturesHelper, GeneralUtilities
# Defines the template for the feed item that is posted on a user's wall
# when they create a new post.
def post_feed_template
one_line_story_template "{*actor*} made a new {*title*} on Blavel."
end
# Defines how a update to a user's My Blavel profile box is published.
def profile_update(user)
send_as :profile
recipients user.facebook_user.facebook_session.user
profile render(:partial => 'facebook_publisher/profile',
:assigns => { :posts => Post.find_all_by_user_id(user.id, :order => 'created_at desc', :limit => 5),
:blavel_user => user,
:facebook_user => user.facebook_user.facebook_session.user })
end
# Defines how an update to a user's wall is published when they create a new
# post.
def post_feed(post)
pictures = Picture.find_all_by_post_id(post.id, :order => 'sequence', :limit => 3)
images = []
pictures.each do |picture|
images.push image(picture.public_filename(:tiny), show_picture_url(:id => picture.id, :host => $DEFAULT_HOST))
end
send_as :user_action
from post.user.facebook_user.facebook_session.user
data :title => post.title.blank? ? link_to('post', verbose_post_path(post, true)) : "post titled '#{link_to(post.title, verbose_post_path(post, true))}'",
:images => images
end
end
| 42.441176 | 158 | 0.704782 |
62d73c3cb31498935c0c91bd3f1d3a42de7025cb | 1,046 | # -*- encoding : utf-8 -*-
module Pacto
class ContractFactory
include Singleton
include Logger
def initialize
@factories = {}
end
def add_factory(format, factory)
@factories[format.to_sym] = factory
end
def remove_factory(format)
@factories.delete format
end
def build(contract_files, host, format = :legacy)
factory = @factories[format.to_sym]
fail "No Contract factory registered for #{format}" if factory.nil?
contract_files.map { |file| factory.build_from_file(file, host) }.flatten
end
def load_contracts(contracts_path, host, format = :legacy)
factory = @factories[format.to_sym]
files = factory.files_for(contracts_path)
contracts = ContractFactory.build(files, host, format)
contracts
end
class << self
extend Forwardable
def_delegators :instance, *ContractFactory.instance_methods(false)
end
end
end
require 'pacto/formats/legacy/contract_factory'
require 'pacto/formats/swagger/contract_factory'
| 24.904762 | 79 | 0.691205 |
5d83561758fc2d07c89e7576ccb5e30cd66867fa | 3,486 | Given(/^I have previously created the "(.*?)" service$/) do |name|
params = { name: name, slug: name.parameterize, csv_path: csv_path_for_data(name) }
@service = create_service(params)
end
Given(/^I have previously created a service with the following attributes:$/) do |table|
params = table.rows_hash.symbolize_keys!
raise ArgumentError, "name cannot be nil" if params[:name].nil?
params = {
slug: params[:name].parameterize,
csv_path: csv_path_for_data(params[:name]),
}.merge(params)
@service = create_service(params)
end
When(/^I go to the new service page$/) do
visit new_admin_service_path
end
When(/^I go to the page for the "(.*?)" service$/) do |name|
visit path_for_service(name)
end
When(/^I visit the details tab$/) do
click_link "Service details"
end
When(/^I visit the history tab$/) do
click_link "Version history"
end
When(/^I fill in the form to create the "(.*?)" service with a bad CSV$/) do |name|
params = {
name: name,
slug: name.parameterize,
csv_path: Rails.root.join("features/support/data/bad.csv"),
}
fill_in_form_with(params)
end
When(/^I fill in the form to create the "(.*?)" service with a PNG claiming to be a CSV$/) do |name|
params = {
name: name,
slug: name.parameterize,
csv_path: Rails.root.join("features/support/data/rails.csv"),
}
fill_in_form_with(params)
end
When(/^I fill in the form to create the "(.*?)" service with a PNG$/) do |name|
params = {
name: name,
slug: name.parameterize,
csv_path: Rails.root.join("features/support/data/rails.png"),
}
fill_in_form_with(params)
end
When(/^I fill out the form with the following attributes to create a service:$/) do |table|
params = table.rows_hash.symbolize_keys!
raise ArgumentError, "name cannot be nil" if params[:name].nil?
params = {
slug: params[:name].parameterize,
csv_path: csv_path_for_data(params[:name]),
}.merge(params)
fill_in_form_with(params)
end
Then(/^I should be on the page for the "(.*?)" service$/) do |name|
current_path = URI.parse(current_url).path
assert_equal path_for_service(name), current_path
end
Then(/^there should not be a "(.*?)" service$/) do |name|
assert_equal 0, Service.where(name: name).count
end
Then(/^I should see that the current service has (\d+) missing SNAC codes$/) do |count|
content = "#{count} places with missing SNAC codes."
assert page.has_content?(content)
end
Then(/^I should not see any text about missing SNAC codes$/) do
assert !page.has_content?("places with missing SNAC codes.")
end
When(/^I activate the most recent data set for the "(.*?)" service$/) do |name|
steps %(
And I go to the page for the "#{name}" service
And I visit the history tab
And I activate the most recent data set
)
end
When(/^I should see (\d+) version panels?$/) do |count|
version_panels = page.all(:css, "div .data-set")
assert_equal version_panels.size, count.to_i
end
Then(/^the first version panel has the title "(.*?)"$/) do |title|
within "div.data-set:nth-child(1)" do
within "h3.panel-title" do
assert page.has_content?(title)
end
end
end
Then(/^the first version panel has the text "(.*?)"$/) do |text|
within "div.data-set:nth-child(1)" do
assert page.has_content?(text)
end
end
Then(/^the first version panel shows a warning about missing SNAC codes$/) do
within "div.data-set:nth-child(1)" do
assert page.has_css?("p.missing-snac-warning")
end
end
| 27.448819 | 100 | 0.687894 |
213c02f8acedcba9cec0d2cbcc074227a26218d1 | 1,958 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Kevin Suh", email: "[email protected]", password: "kevinsuh1", password_confirmation: "kevinsuh1")
end
test "should be valid" do
assert @user.valid?
end
test "name cannot be too long" do
name = 'a' * 51
@user.name = name
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "email cannot be too long" do
email = 'a' * 256
@user.email = email
assert_not @user.valid?
end
test "email validation should accept valid emails" do
valid_emails = %w[[email protected] [email protected] [email protected] [email protected]]
valid_emails.each do |email|
@user.email = email
assert @user.valid?, "#{email.inspect} should be valid"
end
end
test "email validation should not accept these emails" do
invalid_emails = %w[[email protected] invalidEmail@mail,com invalidEmail_at_test.org email@mail+mail.com [email protected]]
invalid_emails.each do |email|
@user.email = email
assert_not @user.valid?, "#{email} should be marked as invalid, but it's not"
end
end
test "email should be unique" do
duplicate_user = @user.dup
@user.save
assert_not duplicate_user.valid?
# case-sensitivity should not matter in uniqueness
duplicate_user.email = @user.email.upcase
assert_not duplicate_user.valid?
end
test "email should be saved as lowercase" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
# it should lowercase it via before_save callback
assert_equal mixed_case_email.downcase, @user.email
end
test "password should be valid" do
@user.password = "notvalid"
assert_not @user.valid?
@user.password = @user.password_confirmation = "short" #minimum 6 chars
assert_not @user.valid?
@user.password = @user.password_confirmation = "validpassword1"
assert @user.valid?
end
end
| 24.78481 | 125 | 0.723698 |
62eb7352ba892b7923401484bd849c145196fe44 | 3,533 | # encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require_relative 'base_action'
module GoodData
module LCM2
class CollectSegmentClients < BaseAction
DESCRIPTION = 'Collect Clients'
PARAMS = define_params(self) do
description 'Client Used for Connecting to GD'
param :gdc_gd_client, instance_of(Type::GdClientType), required: true
description 'Organization Name'
param :organization, instance_of(Type::StringType), required: true
description 'ADS Client'
param :ads_client, instance_of(Type::AdsClientType), required: true
description 'Segments to manage'
param :segments, array_of(instance_of(Type::SegmentType)), required: true
description 'Table Name'
param :release_table_name, instance_of(Type::StringType), required: false
end
RESULT_HEADER = [
:from_name,
:from_pid,
:to_name,
:to_pid
]
DEFAULT_TABLE_NAME = 'LCM_RELEASE'
class << self
def call(params)
client = params.gdc_gd_client
domain_name = params.organization || params.domain
domain = client.domain(domain_name) || fail("Invalid domain name specified - #{domain_name}")
domain_segments = domain.segments
segments = params.segments.map do |seg|
domain_segments.find do |s|
s.segment_id == seg.segment_id
end
end
results = []
synchronize_clients = segments.map do |segment|
segment_clients = segment.clients
missing_project_clients = segment_clients.reject(&:project?).map(&:client_id)
raise "Client(s) missing workspace: #{missing_project_clients.join(', ')}. Please make sure all clients have workspace." unless missing_project_clients.empty?
replacements = {
table_name: params.release_table_name || DEFAULT_TABLE_NAME,
segment_id: segment.segment_id
}
path = File.expand_path('../../data/select_from_lcm_release.sql.erb', __FILE__)
query = GoodData::Helpers::ErbHelper.template_file(path, replacements)
res = params.ads_client.execute_select(query)
# TODO: Check res.first.nil? || res.first[:master_project_id].nil?
master = client.projects(res.first[:master_project_id])
master_pid = master.pid
master_name = master.title
sync_info = {
segment_id: segment.segment_id,
from: master_pid,
to: segment_clients.map do |segment_client|
client_project = segment_client.project
to_pid = client_project.pid
results << {
from_name: master_name,
from_pid: master_pid,
to_name: client_project.title,
to_pid: to_pid
}
{
pid: to_pid,
client_id: segment_client.client_id
}
end
}
sync_info
end
results.flatten!
# Return results
{
results: results,
params: {
synchronize: synchronize_clients
}
}
end
end
end
end
end
| 31.265487 | 170 | 0.590716 |
87d277af199035df15a56ec2e92aa24d0e6541fc | 8,498 | =begin
Copyright (c) 2019 Aspose Pty Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=end
require 'date'
module AsposeSlidesCloud
# Represents a series marker
class SeriesMarker
# size
attr_accessor :size
# symbol
attr_accessor :symbol
# Get or sets the fill format.
attr_accessor :fill_format
# Get or sets the effect format.
attr_accessor :effect_format
# Get or sets the line format.
attr_accessor :line_format
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.any?{ |s| s.casecmp(value) == 0 }
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'size' => :'Size',
:'symbol' => :'Symbol',
:'fill_format' => :'FillFormat',
:'effect_format' => :'EffectFormat',
:'line_format' => :'LineFormat'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'size' => :'Integer',
:'symbol' => :'String',
:'fill_format' => :'FillFormat',
:'effect_format' => :'EffectFormat',
:'line_format' => :'LineFormat'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'Size')
self.size = attributes[:'Size']
end
if attributes.has_key?(:'Symbol')
self.symbol = attributes[:'Symbol']
end
if attributes.has_key?(:'FillFormat')
self.fill_format = attributes[:'FillFormat']
end
if attributes.has_key?(:'EffectFormat')
self.effect_format = attributes[:'EffectFormat']
end
if attributes.has_key?(:'LineFormat')
self.line_format = attributes[:'LineFormat']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
symbol_validator = EnumAttributeValidator.new('String', ['Circle', 'Dash', 'Diamond', 'Dot', 'None', 'Picture', 'Plus', 'Square', 'Star', 'Triangle', 'X', 'NotDefined'])
return false unless symbol_validator.valid?(@symbol)
true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] symbol Object to be assigned
def symbol=(symbol)
validator = EnumAttributeValidator.new('String', ['Circle', 'Dash', 'Diamond', 'Dot', 'None', 'Picture', 'Plus', 'Square', 'Star', 'Triangle', 'X', 'NotDefined'])
unless validator.valid?(symbol)
fail ArgumentError, 'invalid value for "symbol", must be one of #{validator.allowable_values}.'
end
@symbol = symbol
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
size == o.size &&
symbol == o.symbol &&
fill_format == o.fill_format &&
effect_format == o.effect_format &&
line_format == o.line_format
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[size, symbol, fill_format, effect_format, line_format].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = AsposeSlidesCloud.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 31.474074 | 175 | 0.631796 |
bb1f100adc03dabf3d0cf34621a59b0a06136a9e | 297 | #--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++
module Racc
VERSION = '1.6.0'
Version = VERSION
Copyright = 'Copyright (c) 1999-2006 Minero Aoki'
end
| 16.5 | 70 | 0.673401 |
f8875de0a2a9f016ac4297855ff38a1ed4c70db3 | 288 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require 'simplecov'
require 'oneshot_coverage/simplecov_reporter'
OneshotCoverage::SimplecovReporter.new(
project_path: Dir.pwd,
log_path: 'coverage.json',
file_filter: OneshotCoverage::SimplecovReporter::DefaultFilter
).run
| 26.181818 | 64 | 0.798611 |
268a08bff1471c5ec932eb4037fa2cd51e06404c | 5,335 | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "demo_app_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.090909 | 114 | 0.765323 |
21178e24999dca9045e32181f0065ceee7e1649b | 231 | module MiqAeMethodService
class MiqAeServiceSwitch < MiqAeServiceModelBase
expose :hosts, :association => true
expose :guest_devices, :association => true
expose :lans, :association => true
end
end
| 28.875 | 50 | 0.688312 |
e91ac11d9d7260f38822128e992941057ddf4141 | 1,279 | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
config.eager_load = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.default_url_options = { host: 'localhost:3000' }
# Bullet gem
Bullet.enable = true
Bullet.bullet_logger = true
Bullet.rails_logger = true
end
| 32.794872 | 84 | 0.778733 |
03130cc3b745dff964776b005cc362fff875964f | 1,682 | require File.expand_path('../../spec_helper', __FILE__)
describe JobQueue do
before do
@q = JobQueue.new 2
$job_queue_results = Set.new
$job_queue_runs = 0
$job_queue_data_mutex = Mutex.new
end
class TestWorker
def perform(item, delay)
sleep delay
$job_queue_data_mutex.synchronize do
$job_queue_results.add item
$job_queue_runs += 1
end
end
end
it 'should queue and run a job' do
expect($job_queue_results.member? 'a').to be_falsey
@q.enqueue(TestWorker, 'a', 0.1)
expect($job_queue_results.member? 'a').to be_falsey
@q.wait_for_all_jobs
expect($job_queue_results.member? 'a').to be_truthy
end
it 'should run multiple jobs in background' do
expect($job_queue_results.member? 'a').to be_falsey
expect($job_queue_results.member? 'b').to be_falsey
@q.enqueue(TestWorker, 'a', 0.05)
@q.enqueue(TestWorker, 'b', 0.05)
expect($job_queue_results.member? 'a').to be_falsey
expect($job_queue_results.member? 'b').to be_falsey
sleep 0.1
expect($job_queue_results.member? 'a').to be_truthy
expect($job_queue_results.member? 'b').to be_truthy
end
it 'should run concurrent non-unique jobs' do
@q.enqueue(TestWorker, 'a', 0.05)
@q.enqueue(TestWorker, 'a', 0.05)
sleep 0.1
expect($job_queue_runs).to eq(2)
end
it 'should not start currently running unique jobs' do
@q.make_job_unique(TestWorker, 'a', 0.05)
@q.enqueue(TestWorker, 'a', 0.05)
@q.enqueue(TestWorker, 'a', 0.05)
sleep 0.1
expect($job_queue_runs).to eq(1)
@q.enqueue(TestWorker, 'a', 0.05)
sleep 0.1
expect($job_queue_runs).to eq(2)
end
end | 28.508475 | 56 | 0.669441 |
331145218374d37d24b560c6c4bf4eb80b347b1f | 16,010 | ##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
module Twilio
module REST
class Api < Domain
class V2010 < Version
class AccountContext < InstanceContext
class SipList < ListResource
class IpAccessControlListList < ListResource
##
# Initialize the IpAccessControlListList
# @param [Version] version Version that contains the resource
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [IpAccessControlListList] IpAccessControlListList
def initialize(version, account_sid: nil)
super(version)
# Path Solution
@solution = {account_sid: account_sid}
@uri = "/Accounts/#{@solution[:account_sid]}/SIP/IpAccessControlLists.json"
end
##
# Lists IpAccessControlListInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(limit: nil, page_size: nil)
self.stream(limit: limit, page_size: page_size).entries
end
##
# Streams IpAccessControlListInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(page_size: limits[:page_size], )
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields IpAccessControlListInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of IpAccessControlListInstance records from the API.
# Request is executed immediately.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of IpAccessControlListInstance
def page(page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page(
'GET',
@uri,
params
)
IpAccessControlListPage.new(@version, response, @solution)
end
##
# Retrieve a single page of IpAccessControlListInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of IpAccessControlListInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
IpAccessControlListPage.new(@version, response, @solution)
end
##
# Retrieve a single page of IpAccessControlListInstance records from the API.
# Request is executed immediately.
# @param [String] friendly_name A human readable descriptive text that describes
# the IpAccessControlList, up to 64 characters long.
# https://www.twilio.com/docs/admin/pages/add/api_reference/apireferencepage/175/#
# @return [IpAccessControlListInstance] Newly created IpAccessControlListInstance
def create(friendly_name: nil)
data = Twilio::Values.of({'FriendlyName' => friendly_name, })
payload = @version.create(
'POST',
@uri,
data: data
)
IpAccessControlListInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Api.V2010.IpAccessControlListList>'
end
end
class IpAccessControlListPage < Page
##
# Initialize the IpAccessControlListPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [IpAccessControlListPage] IpAccessControlListPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of IpAccessControlListInstance
# @param [Hash] payload Payload response from the API
# @return [IpAccessControlListInstance] IpAccessControlListInstance
def get_instance(payload)
IpAccessControlListInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Api.V2010.IpAccessControlListPage>'
end
end
class IpAccessControlListContext < InstanceContext
##
# Initialize the IpAccessControlListContext
# @param [Version] version Version that contains the resource
# @param [String] account_sid The account_sid
# @param [String] sid The ip-access-control-list Sid that uniquely identifies this
# resource
# @return [IpAccessControlListContext] IpAccessControlListContext
def initialize(version, account_sid, sid)
super(version)
# Path Solution
@solution = {account_sid: account_sid, sid: sid, }
@uri = "/Accounts/#{@solution[:account_sid]}/SIP/IpAccessControlLists/#{@solution[:sid]}.json"
# Dependents
@ip_addresses = nil
end
##
# Fetch a IpAccessControlListInstance
# @return [IpAccessControlListInstance] Fetched IpAccessControlListInstance
def fetch
params = Twilio::Values.of({})
payload = @version.fetch(
'GET',
@uri,
params,
)
IpAccessControlListInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Update the IpAccessControlListInstance
# @param [String] friendly_name A human readable descriptive text, up to 64
# characters long.
# @return [IpAccessControlListInstance] Updated IpAccessControlListInstance
def update(friendly_name: nil)
data = Twilio::Values.of({'FriendlyName' => friendly_name, })
payload = @version.update(
'POST',
@uri,
data: data,
)
IpAccessControlListInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Deletes the IpAccessControlListInstance
# @return [Boolean] true if delete succeeds, true otherwise
def delete
@version.delete('delete', @uri)
end
##
# Access the ip_addresses
# @return [IpAddressList]
# @return [IpAddressContext] if sid was passed.
def ip_addresses(sid=:unset)
raise ArgumentError, 'sid cannot be nil' if sid.nil?
if sid != :unset
return IpAddressContext.new(@version, @solution[:account_sid], @solution[:sid], sid, )
end
unless @ip_addresses
@ip_addresses = IpAddressList.new(
@version,
account_sid: @solution[:account_sid],
ip_access_control_list_sid: @solution[:sid],
)
end
@ip_addresses
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Api.V2010.IpAccessControlListContext #{context}>"
end
end
class IpAccessControlListInstance < InstanceResource
##
# Initialize the IpAccessControlListInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @param [String] sid The ip-access-control-list Sid that uniquely identifies this
# resource
# @return [IpAccessControlListInstance] IpAccessControlListInstance
def initialize(version, payload, account_sid: nil, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'sid' => payload['sid'],
'account_sid' => payload['account_sid'],
'friendly_name' => payload['friendly_name'],
'date_created' => Twilio.deserialize_rfc2822(payload['date_created']),
'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']),
'subresource_uris' => payload['subresource_uris'],
'uri' => payload['uri'],
}
# Context
@instance_context = nil
@params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [IpAccessControlListContext] IpAccessControlListContext for this IpAccessControlListInstance
def context
unless @instance_context
@instance_context = IpAccessControlListContext.new(@version, @params['account_sid'], @params['sid'], )
end
@instance_context
end
##
# @return [String] A string that uniquely identifies this resource
def sid
@properties['sid']
end
##
# @return [String] The unique sid that identifies this account
def account_sid
@properties['account_sid']
end
##
# @return [String] A human readable description of this resource
def friendly_name
@properties['friendly_name']
end
##
# @return [Time] The date this resource was created
def date_created
@properties['date_created']
end
##
# @return [Time] The date this resource was last updated
def date_updated
@properties['date_updated']
end
##
# @return [String] The subresource_uris
def subresource_uris
@properties['subresource_uris']
end
##
# @return [String] The URI for this resource
def uri
@properties['uri']
end
##
# Fetch a IpAccessControlListInstance
# @return [IpAccessControlListInstance] Fetched IpAccessControlListInstance
def fetch
context.fetch
end
##
# Update the IpAccessControlListInstance
# @param [String] friendly_name A human readable descriptive text, up to 64
# characters long.
# @return [IpAccessControlListInstance] Updated IpAccessControlListInstance
def update(friendly_name: nil)
context.update(friendly_name: friendly_name, )
end
##
# Deletes the IpAccessControlListInstance
# @return [Boolean] true if delete succeeds, true otherwise
def delete
context.delete
end
##
# Access the ip_addresses
# @return [ip_addresses] ip_addresses
def ip_addresses
context.ip_addresses
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.IpAccessControlListInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.IpAccessControlListInstance #{values}>"
end
end
end
end
end
end
end
end | 40.634518 | 120 | 0.524422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.