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
|
---|---|---|---|---|---|
38cef1d21b0ef2232cbd9c3556892d0ea1f2f86b | 340 | module SkipMongoidQueryCache
private
def system_collection?
return true if cache_skip?
super
end
def cache_skip?
return true if selector.reject { |k, v| k == '_id' }.present?
return true if options.reject { |k, v| k == 'limit' }.present?
end
end
Mongo::Collection::View.__send__(:include, SkipMongoidQueryCache)
| 22.666667 | 66 | 0.697059 |
012f9eb11b7110e01fd0c8dbe8b2dd220faa4a21 | 1,813 | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 33.574074 | 85 | 0.760618 |
ed9e70270a67221a2c10f55c5ba69f7ee6867366 | 2,180 | require 'formula'
class Gpsim < Formula
homepage 'http://gpsim.sourceforge.net/'
url 'http://downloads.sourceforge.net/project/gpsim/gpsim/0.26.0/gpsim-0.26.1.tar.gz'
sha1 '7e1c3cc5a821b3458717a94a09bc484bf6937b25'
head 'svn://svn.code.sf.net/p/gpsim/code/trunk'
depends_on 'pkg-config' => :build
depends_on 'popt'
depends_on 'glib'
# Patch is upstream; test if it is needed in next release
def patches
DATA
end
def install
system "./configure", "--disable-gui",
"--disable-shared",
"--prefix=#{prefix}"
system "make all"
system "make install"
end
end
__END__
diff -Naur gpsim-0.26.1/configure.ac gpsim-0.26.1-patch/configure.ac
--- gpsim-0.26.1/configure.ac 2011-04-26 07:13:37.000000000 -0300
+++ gpsim-0.26.1-patch/configure.ac 2013-04-23 10:42:52.000000000 -0300
@@ -79,15 +79,20 @@
else
dnl gtk2 checks
- $PKGCONFIG --exists gtkextra-2.0
+ GTKEXTRAMOD="gtkextra-2.0"
+ $PKGCONFIG --exists $GTKEXTRAMOD
if test $? != 0; then
- AC_MSG_ERROR(Cannot find gtkextra-2.0 package)
+ GTKEXTRAMOD="gtkextra-3.0"
+ $PKGCONFIG --exists $GTKEXTRAMOD
+ if test $? != 0; then
+ AC_MSG_ERROR(Cannot find gtkextra-2.0 or gtkextra-3.0 package)
+ fi
fi
X_LDFLAGS=`$PKGCONFIG --libs gtk+-2.0 gthread-2.0`
X_CFLAGS=`$PKGCONFIG --cflags gtk+-2.0`
- Y_LDFLAGS=`$PKGCONFIG --libs gtkextra-2.0`
- Y_CFLAGS=`$PKGCONFIG --cflags gtkextra-2.0`
+ Y_LDFLAGS=`$PKGCONFIG --libs $GTKEXTRAMOD`
+ Y_CFLAGS=`$PKGCONFIG --cflags $GTKEXTRAMOD`
GTK_VERSION_T=`$PKGCONFIG --modversion gtk+-2.0`
echo linking with gtk-$GTK_VERSION_T
AC_DEFINE_UNQUOTED([GTK_VERSION],"$GTK_VERSION_T",[gtk version])
diff -Naur gpsim-0.26.1/src/bitlog.h gpsim-0.26.1-patch/src/bitlog.h
--- gpsim-0.26.1/src/bitlog.h 2010-06-05 03:46:30.000000000 -0300
+++ gpsim-0.26.1-patch/src/bitlog.h 2013-04-23 10:37:09.000000000 -0300
@@ -25,7 +25,7 @@
// include the absolute minimum portion of GLIB to get the definitions
// for guint64, etc.
-#include <glibconfig.h>
+#include <glib.h>
/**********************************************************************
* boolean event logging
| 31.142857 | 87 | 0.652294 |
1c325aa9dcc8e1c641b3c1d049e678a2c55fe72d | 1,039 | # frozen_string_literal: true
require "se_providers_api_client/dsl"
module SeProvidersApiClient
module DSL
module LineItems
# GET /api/providers/v1/line_items
# Get line_items. See https://demo.scienceexchange.com/api-docs/providers#/line_items/getProvidersV1LineItems
# @return [Array].
def get_line_items
Resources::LineItem.parse(request(:get, "line_items/", nil, nil))
end
# GET /api/providers/v1/line_items/{id}
# Get an line item. See https://demo.scienceexchange.com/api-docs/providers#/line_items/getProvidersV1LineItemsId
# @param [Hash] options The options to get a line item with.
# @option options [String, Fixnum] :id A line item ID.
# @raise [ArgumentError] If the :id is blank
# @return [SeProvidersApiClient::Resources::LineItem, nil].
def get_line_item(options = {})
id = options[:id] || raise(ArgumentError, "Must supply :id")
Resources::LineItem.parse(request(:get, "line_items/#{id}"))
end
end
end
end
| 37.107143 | 119 | 0.682387 |
e26c46b2efd56151d78aeea9e53bdedf44f14155 | 11,566 | # Copyright: Copyright (c) 2012 Opscode, Inc.
# License: Apache License, Version 2.0
#
# 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 'pedant/rspec/cookbook_util'
# FIXME We don't test GET /cookbooks/NAME/VERSION when we have
# any files in the segments. Thus we're not checking the creation
# of the S3 URLs that should be returned for all the files in the
# cookbook
describe "Cookbooks API endpoint", :cookbooks do
include Pedant::RSpec::CookbookUtil
context "GET /cookbooks" do
let(:url) { cookbook_collection_url }
let(:request_url) { cookbook_collection_url }
let(:request_method) { :GET }
let(:requestor) { admin_user }
let(:cookbook_collection_url) { api_url("/cookbooks") }
let(:fetch_cookbook_collection_success_exact_response) do
{
:status => 200,
:body_exact => fetched_cookbooks
}
end
context "with an operational server", :smoke do
it { should look_like ok_response }
end
context "without existing cookbooks" do
let(:expected_response) { fetch_cookbook_collection_success_exact_response }
# Assert that there are no cookbooks
let(:fetched_cookbooks) { { } }
# NOTE: This test must the first one dealing with cookbooks
# so that there are no cookbooks existing on the server
should_respond_with 200, "and an empty collection"
# Add test to check for empty case with different num_versions
context 'with a num_versions' do
let(:expected_response) { bad_request_response }
let(:request_url) { api_url("/cookbooks?num_versions=#{num_versions}") }
let(:error_message) { invalid_versions_msg }
def self.expects_response_of_400_with(message, _value)
context "with #{message}", :validation do
let(:num_versions) { _value }
should_respond_with 400
end
end
expects_response_of_400_with "a negative num_versions", '-1'
expects_response_of_400_with "a missing num_versions", ''
expects_response_of_400_with "an invalid num_versions", 'foo'
end # when requesting with num_versions
end # without existing cookbooks
context "with existing cookbooks and multiple versions" do
let(:expected_response) { fetch_cookbook_collection_success_exact_response }
let(:request_url) { api_url("/cookbooks?num_versions=#{num_versions}") }
let(:fetched_cookbooks) { cookbook_collection }
let(:cookbook_name) { "cookbook_name" }
let(:cookbook_name2) { "cookbook_name2" }
let(:version1) { "0.0.1" }
let(:version2) { "0.0.2" }
let(:cookbooks) do
{
cookbook_name => {
version1 => [],
version2 => []
},
cookbook_name2 => {
version1 => []
}
}
end
before(:each) do
setup_cookbooks(cookbooks)
end
after(:each) do
remove_cookbooks(cookbooks)
end
context 'with num_versions set to 0' do
let(:num_versions) { 0 }
let(:cookbook_collection) do
{
cookbook_name => { "url" => cookbook_url(cookbook_name), "versions" => [] },
cookbook_name2 => { "url" => cookbook_url(cookbook_name2), "versions" => [] }
}
end
it "should respond with cookbook collection with no version" do
should look_like expected_response
end
end # with num_versions set to 0
let(:cookbook_collection_with_one_version) do
{
cookbook_name => {
"url" => cookbook_url(cookbook_name),
"versions" =>
[{ "version" => version2,
"url" => cookbook_version_url(cookbook_name,version2) }]},
cookbook_name2 => {
"url" => cookbook_url(cookbook_name2),
"versions" =>
[{ "version" => version1,
"url" => cookbook_version_url(cookbook_name2, version1) }]}
}
end
context 'when num_versions is not set' do
let(:request_url) { cookbook_collection_url }
let(:cookbook_collection) { cookbook_collection_with_one_version }
it 'should return cookbook collection with one version per cookbook' do
should look_like expected_response
end
end # without num_versions
context 'when num_versions is set to 1' do
let(:num_versions) { 1 }
let(:cookbook_collection) { cookbook_collection_with_one_version }
it 'should return cookbook collection with one version per cookbook' do
should look_like expected_response
end
end
context 'when num_versions is set to "all"' do
let(:num_versions) { 'all' }
let(:cookbook_collection) do
{
cookbook_name => {
"url" => cookbook_url(cookbook_name),
"versions" => [
{ "version" => version2,
"url" => cookbook_version_url(cookbook_name, version2) },
{ "version" => version1,
"url" => cookbook_version_url(cookbook_name, version1) } ]},
cookbook_name2 => {
"url" => cookbook_url(cookbook_name2),
"versions" => [
{ "version" => version1,
"url" => cookbook_version_url(cookbook_name2, version1) }]}
}
end
it 'should respond with a cookbook collection containing all versions of each cookbook' do
should look_like expected_response
end
end
end # context returns different results depending on num_versions
context "with varying numbers of existing cookbooks" do
let(:expected_response) { fetch_cookbook_success_exact_response }
let(:request_url) { api_url("/cookbooks?num_versions=all") }
let(:fetched_cookbook) { cookbook_collection }
let(:cookbook_name) { "cookbook_name" }
let(:cookbook_version) { "1.2.3" }
context 'with a single, existing cookbook' do
let(:cookbook_collection) do
{
cookbook_name => {
"url" => cookbook_url(cookbook_name),
"versions" => [
{ "version" => cookbook_version,
"url" => cookbook_version_url(cookbook_name, cookbook_version) }]}
}
end
it 'should respond with a single cookbook in the collection' do
make_cookbook(admin_user, cookbook_name, cookbook_version)
should look_like expected_response
delete_cookbook(admin_user, cookbook_name, cookbook_version)
end
end
context 'with multiple, existing cookbooks' do
let(:cookbook_collection) do
{
"cb1" => {
"url" => cookbook_url("cb1"),
"versions" => [
{ "version" => "0.0.1",
"url" => cookbook_version_url("cb1", "0.0.1") }]},
"cb2" => {
"url" => cookbook_url("cb2"),
"versions" => [
{ "version" => "0.0.2",
"url" => cookbook_version_url("cb2", "0.0.2") }]}
}
end
it "multiple cookbooks can be listed" do
# Upload cookbook
make_cookbook(admin_user, "cb1", "0.0.1")
make_cookbook(admin_user, "cb2", "0.0.2")
should look_like expected_response
# cleanup
delete_cookbook(admin_user, "cb1", "0.0.1")
delete_cookbook(admin_user, "cb2", "0.0.2")
end # it multiple cookbooks can be listed
end # with multiple, existing cookbooks
end # with varying numbers of existing cookbooks
end # context GET /cookbooks
context "GET /cookbooks/<name>/<version>" do
let(:request_method) { :GET }
let(:request_url) { named_cookbook_url }
let(:cookbook_name) { "the_cookbook_name" }
let(:cookbook_version) { "1.2.3" }
let(:recipe_name) { "test_recipe" }
let(:recipe_content) { "hello-#{unique_suffix}" }
let(:recipe_spec) do
{
:name => recipe_name,
:content => recipe_content
}
end
let(:cookbooks) do
{
cookbook_name => {
cookbook_version => [recipe_spec]
}
}
end
before(:each) { setup_cookbooks(cookbooks) }
after(:each) { remove_cookbooks(cookbooks) }
let(:fetched_cookbook) do
# NOTE: the cookbook returned will actually have some recipe
# data. We don't yet have a nice way to do the required soft
# verification for the URL and checksum.
#
# To get around this, we'll just pass in a proc that asserts
# that the "recipes" key is an array of hashes with the correct
# keys.
retrieved_cookbook(cookbook_name,
cookbook_version,
:recipes => lambda{|recipes|
recipes.is_a?(Array) &&
recipes.all?{|recipe|
recipe.is_a?(Hash) &&
recipe.keys.sort == ["name", "path", "checksum", "specificity", "url"].sort
}
})
end
context 'as a normal user' do
let(:expected_response) { fetch_cookbook_success_exact_response }
let(:requestor) { normal_user }
should_respond_with 200
context "allows access to cookbook recipe files via" do
# These tests verify that the pre-signed URL that comes back
# within cookbook_version responses is usable. Validating both
# the URL generation, but also the use of bookshelf via the
# load balancer.
let(:cbv) { parse(response) }
let(:recipe_url) { cbv["recipes"].first["url"] }
it "net/http" do
uri = URI.parse(recipe_url)
http = Net::HTTP.new(uri.hostname, uri.port)
if uri.scheme == "https"
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
response = http.get(uri.request_uri, {})
response.body.should == recipe_content
end
it "curl" do
got = `curl -gsk '#{recipe_url}'`
got.should == recipe_content
end
end # access to recipe file content
end # as a normal user
context 'as an admin user' do
let(:expected_response) { fetch_cookbook_success_exact_response }
let(:requestor) { admin_user }
should_respond_with 200
end # as an admin user
context 'as an user outside of the organization', :authorization do
let(:expected_response) { unauthorized_access_credential_response }
let(:requestor) { outside_user }
should_respond_with 403
end # as an outside user
context 'with invalid user', :authentication do
let(:expected_response) { invalid_credential_exact_response }
let(:requestor) { invalid_user }
should_respond_with 401
end
end # context GET /cookbooks/<name>/<version>
end # describe Cookbooks API endpoint
| 34.320475 | 104 | 0.604617 |
abaa21f2bdc7c423b08899a960d213f144a5b232 | 1,718 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{acts_as_amazon_product}
s.version = "2.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Scott Nedderman", "Chris Beck"]
s.date = %q{2009-07-21}
s.email = %q{[email protected]}
s.extra_rdoc_files = [
"README"
]
s.files = [
".gitignore",
"CHANGELOG",
"COPYING",
"README",
"Rakefile",
"VERSION",
"acts_as_amazon_product.gemspec",
"generators/acts_as_amazon_product_migration/acts_as_amazon_product_migration_generator.rb",
"generators/acts_as_amazon_product_migration/templates/migration.rb",
"init.rb",
"install.rb",
"lib/acts_as_amazon_product.rb",
"lib/amazon_product.rb",
"tasks/acts_as_amazon_product_tasks.rake",
"test/acts_as_amazon_product_test.rb",
"test/config-example.yml",
"test/example.rb",
"uninstall.rb"
]
s.homepage = %q{http://github.com/netphase/aaap}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.3}
s.summary = %q{A package for simplifying use of the Amazon/ECS API}
s.test_files = [
"test/acts_as_amazon_product_test.rb",
"test/example.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<amazon-ecs>, [">= 0.5.6"])
else
s.add_dependency(%q<amazon-ecs>, [">= 0.5.6"])
end
else
s.add_dependency(%q<amazon-ecs>, [">= 0.5.6"])
end
end
| 30.140351 | 105 | 0.662398 |
e80cb18c055a3ce4c49b70e34e8ad5a2549125ef | 254 | class AddFirstNameLastNameAndImageUrlToUser < ActiveRecord::Migration[5.1]
def change
add_column :users, :first_name, :string, null: false
add_column :users, :last_name, :string, null: false
add_column :users, :image_url, :string
end
end
| 31.75 | 74 | 0.744094 |
7a1562e329c91c51387762025f729d01fa0e55ef | 443 | # require 'hanami/model'
# require 'hanami/mailer'
# Dir["#{ __dir__ }/static_assets_app/**/*.rb"].each { |file| require_relative file }
# Hanami::Model.configure do
# adapter type: :file_system, uri: ENV['STATIC_ASSETS_APP_DATABASE_URL']
# mapping do
# end
# end.load!
# Hanami::Mailer.configure do
# root "#{ __dir__ }/static_assets_app/mailers"
# delivery do
# development :test
# test :test
# end
# end.load!
| 23.315789 | 85 | 0.663657 |
ab80fb99cf938a37d857c1fb8da81c3d7c681105 | 2,893 | # 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: 2022_01_11_230946) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "comments", force: :cascade do |t|
t.text "content", null: false
t.integer "user_id", null: false
t.integer "post_id", null: false
t.integer "parent_comment_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["parent_comment_id"], name: "index_comments_on_parent_comment_id"
t.index ["post_id"], name: "index_comments_on_post_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "post_subs", force: :cascade do |t|
t.integer "post_id", null: false
t.integer "sub_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id", "sub_id"], name: "index_post_subs_on_post_id_and_sub_id", unique: true
t.index ["post_id"], name: "index_post_subs_on_post_id"
t.index ["sub_id"], name: "index_post_subs_on_sub_id"
end
create_table "posts", force: :cascade do |t|
t.string "title", null: false
t.string "url"
t.text "content"
t.integer "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "subs", force: :cascade do |t|
t.string "name", null: false
t.text "description", null: false
t.integer "moderator_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["moderator_id"], name: "index_subs_on_moderator_id"
t.index ["name"], name: "index_subs_on_name", unique: true
end
create_table "users", force: :cascade do |t|
t.string "username", null: false
t.string "password_digest", null: false
t.string "session_token", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["session_token"], name: "index_users_on_session_token", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
end
| 40.746479 | 94 | 0.718977 |
87d00c1a1063d7b927c22fadbbc3b7844d960557 | 595 | class SessionsController < ApplicationController
before_filter :signed, only: [:new, :create]
def new
end
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or user
else
flash.now[:error] = 'Invalid email/password combination' # Not quite right!
render 'new'
end
end
def destroy
sign_out
redirect_to root_path
end
private
def signed
redirect_to root_path, notice: "You are already signed-in." if signed_in?
end
end
| 20.517241 | 81 | 0.678992 |
ac8197e6c5471f3a2f46d667d26cf4b43ca26464 | 1,314 | Pod::Spec.new do |s|
s.name = 'JSQMessagesViewController'
s.version = '7.3.4'
s.summary = 'An elegant messages UI library for iOS.'
s.homepage = 'http://jessesquires.github.io/JSQMessagesViewController'
s.license = 'MIT'
s.platform = :ios, '7.0'
s.author = 'Jesse Squires'
s.social_media_url = 'https://twitter.com/jesse_squires'
s.screenshots = ['https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/Screenshots/screenshot0.png',
'https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/Screenshots/screenshot1.png',
'https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/Screenshots/screenshot2.png',
'https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/Screenshots/screenshot3.png']
s.source = { :git => 'https://github.com/jessesquires/JSQMessagesViewController.git', :tag => s.version }
s.source_files = 'JSQMessagesViewController/**/*.{h,m}'
s.resources = ['JSQMessagesViewController/Assets/JSQMessagesAssets.bundle', 'JSQMessagesViewController/**/*.{xib}']
s.frameworks = 'QuartzCore', 'CoreGraphics', 'CoreLocation', 'MapKit', 'AVFoundation'
s.requires_arc = true
s.dependency 'JSQSystemSoundPlayer', '~> 2.0.1'
end
| 48.666667 | 131 | 0.734399 |
912944065bd988a6359e396d15ec0a6498b134cd | 848 | class Bcal < Formula
desc "Storage conversion and expression calculator"
homepage "https://github.com/jarun/bcal"
url "https://github.com/jarun/bcal/archive/v1.9.tar.gz"
sha256 "5d075deaef087680ea4c153ed5f0696f8be149a59ce0e5aaeb3f5b1180b2ec81"
bottle do
cellar :any_skip_relocation
# sha256 "7e4e6c646db9a2f18743618e221a45deb5a2a14a3204a62a07081b5f6123c079" => :mojave
sha256 "3c00afb8282817dbd475d0611972a67583e38b61aba69197c754443a1c65c2fc" => :high_sierra
sha256 "1a192e98388164010d63d19f9f858bc6c60473ce0abe1b3aea21130f5b2f366d" => :sierra
sha256 "4b75a0f2083440568deecc1328a1106617f8dbd3342a558e755109b00aa6fbfc" => :el_capitan
end
def install
system "make", "install", "PREFIX=#{prefix}"
end
test do
assert_match "9333353817", shell_output("#{bin}/bcal '56 gb / 6 + 4kib * 5 + 4 B'")
end
end
| 36.869565 | 93 | 0.775943 |
8713ddc34f401763651b95181a04f4225b973bce | 6,062 | #
# Cookbook Name:: cpe_nudge
# Resources:: cpe_nudge_install
#
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright (c) 2019-present, Uber Technologies, Inc.
# All rights reserved.
#
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
#
resource_name :cpe_nudge_install
provides :cpe_nudge_install, :os => 'darwin'
default_action :manage
action :manage do
install if install? && !uninstall?
remove if uninstall?
end
action_class do # rubocop:disable Metrics/BlockLength
def custom_resources?
node['cpe_nudge']['custom_resources']
end
def install?
node['cpe_nudge']['install']
end
def uninstall?
node['cpe_nudge']['uninstall']
end
def label
# This portion is taken from cpe_launchd. Since we use cpe_launchd to
# create our launch agent, the label specified in the attributes will not
# match the actual label/path that's created. Doing this will result in
# the right file being targeted.
label = node['cpe_nudge']['la_identifier']
if label.start_with?('com')
name = label.split('.')
name.delete('com')
label = name.join('.')
label = "#{node['cpe_launchd']['prefix']}.#{label}"
end
label
end
def install
# Create nudge base folders
[
'/Library/nudge',
'/Library/nudge/Resources',
'/Library/nudge/Resources/nudge.nib',
].each do |dir|
directory dir do
owner root_owner
group root_group
mode '0755'
action :create
end
end
# Create Log folder with 777 permissions so user agent can write to it.
directory '/Library/nudge/Logs' do
owner root_owner
group root_group
mode '0777'
action :create
end
# Create Log file with 777 permissions so user agent can write to it.
file '/Library/nudge/Logs/nudge.log' do
mode '0777'
action :create
end
# nudge files
nudge_files = [
'gurl.py',
'nibbler.py',
'nudge',
]
# Install nudge files
# If we are updating nudge, we need to disable the launch agent.
# cpe_launchd will turn it back on later in the run so we don't have a
# mismatch in what's loaded in memory and what's on disk
nudge_files.each do |item|
if item == 'nudge'
if ::File.exists?(node['cpe_nudge']['python_path'])
# Python file
template "/Library/nudge/Resources/#{item}" do
backup false
owner root_owner
group root_group
mode '0755'
source item
variables('shebang' => node['cpe_nudge']['shebang'])
if ::File.exists?("/Library/LaunchAgents/#{label}.plist")
notifies :disable, "launchd[#{label}]", :immediately
end
end
else
# Use legacy nudge if python framework doesn't exist
cookbook_file "/Library/nudge/Resources/#{item}" do
backup false
owner root_owner
group root_group
mode '0755'
action :create
path "/Library/nudge/Resources/#{item}"
source "resources/py2_#{item}"
if ::File.exists?("/Library/LaunchAgents/#{label}.plist")
notifies :disable, "launchd[#{label}]", :immediately
end
end
end
else
cookbook_file "/Library/nudge/Resources/#{item}" do
owner root_owner
group root_group
mode '0755'
action :create
path "/Library/nudge/Resources/#{item}"
if ::File.exists?(node['cpe_nudge']['python_path'])
source "resources/#{item}"
# Use legacy nudge if python framework doesn't exist
else
source "resources/py2_#{item}"
end
if ::File.exists?("/Library/LaunchAgents/#{label}.plist")
notifies :disable, "launchd[#{label}]", :immediately
end
end
end
end
# nudge resource files
nudge_resource_files = [
'company_logo.png',
'update_ss.png',
]
# Figure out the path of the resource files
if custom_resources?
source_path = 'custom'
else
source_path = 'resources'
end
# Install nudge resource files
nudge_resource_files.each do |item|
cookbook_file "/Library/nudge/Resources/#{item}" do
owner root_owner
group root_group
mode '0755'
action :create
path "/Library/nudge/Resources/#{item}"
source "#{source_path}/#{item}"
if ::File.exists?("/Library/LaunchAgents/#{label}.plist")
notifies :disable, "launchd[#{label}]", :immediately
end
end
end
# nudge nib files
nudge_nib_files = [
'designable.nib',
'keyedobjects.nib',
]
# Install nudge nib files
nudge_nib_files.each do |item|
cookbook_file "/Library/nudge/Resources/nudge.nib/#{item}" do
owner root_owner
group root_group
mode '0755'
action :create
path "/Library/nudge/Resources/nudge.nib/#{item}"
source "nudge.nib/#{item}"
if ::File.exists?("/Library/LaunchAgents/#{label}.plist")
notifies :disable, "launchd[#{label}]", :immediately
end
end
end
# Triggered Launch Agent action
launchd label do
action :nothing
type 'agent'
end
# Delete old nudge directory
directory '/Library/Application Support/nudge' do
action :delete
recursive true
end
end
def remove
# Delete old nudge directory
directory '/Library/Application Support/nudge' do
action :delete
recursive true
end
# Delete nudge directory
directory '/Library/nudge' do
action :delete
recursive true
end
# Delete Launch Agent
launchd label do
action :delete
only_if { ::File.exist?("/Library/LaunchAgents/#{label}.plist") }
type 'agent'
end
end
end
| 26.942222 | 77 | 0.605246 |
d5edda62f499b9370ea3b487d32db5399d8512e6 | 32 | module LedgerAccountsHelper
end
| 10.666667 | 27 | 0.90625 |
b988de3d9c358eb1158864f477f9375f9aaa6c48 | 6,272 | # Copyright (C) 2009-2013 MongoDB, 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.
require 'test_helper'
class ReplicaSetBasicTest < Test::Unit::TestCase
def setup
ensure_cluster(:rs)
end
def test_connect
client = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name, :op_timeout => TEST_OP_TIMEOUT)
assert client.connected?
assert_equal @rs.primary_name, client.primary.join(':')
assert_equal @rs.secondary_names.sort, client.secondaries.collect{|s| s.join(':')}.sort
assert_equal @rs.arbiter_names.sort, client.arbiters.collect{|s| s.join(':')}.sort
client.close
silently do
client = MongoReplicaSetClient.new(@rs.repl_set_seeds_old, :name => @rs.repl_set_name)
end
assert client.connected?
client.close
end
def test_safe_option
client = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name)
assert client.connected?
assert client.write_concern[:w] > 0
client.close
client = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name, :w => 0)
assert client.connected?
assert client.write_concern[:w] < 1
client.close
client = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name, :w => 2)
assert client.connected?
assert client.write_concern[:w] > 0
client.close
end
def test_multiple_concurrent_replica_set_connection
client1 = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name)
client2 = MongoReplicaSetClient.new(@rs.repl_set_seeds, :name => @rs.repl_set_name)
assert client1.connected?
assert client2.connected?
assert client1.manager != client2.manager
assert client1.local_manager != client2.local_manager
client1.close
client2.close
end
def test_cache_original_seed_nodes
host = @rs.servers.first.host
seeds = @rs.repl_set_seeds << "#{host}:19356"
client = MongoReplicaSetClient.new(seeds, :name => @rs.repl_set_name)
assert client.connected?
assert client.seeds.include?([host, 19356]), "Original seed nodes not cached!"
assert_equal [host, 19356], client.seeds.last, "Original seed nodes not cached!"
client.close
end
def test_accessors
client = MongoReplicaSetClient.from_uri(@uri)
assert_equal @rs.primary_name, [client.host, client.port].join(':')
assert_equal client.host, client.primary_pool.host
assert_equal client.port, client.primary_pool.port
assert_equal 2, client.secondaries.length
assert_equal 2, client.secondary_pools.length
assert_equal @rs.repl_set_name, client.replica_set_name
assert client.secondary_pools.include?(client.read_pool({:mode => :secondary}))
assert_equal 90, client.refresh_interval
assert_equal client.refresh_mode, false
client.close
end
def test_write_commands_and_operations
@client = MongoReplicaSetClient.from_uri(@uri)
@coll = @client[TEST_DB]['test-write-commands-and-operations']
with_write_commands_and_operations(@client) do
@coll.remove
@coll.insert({:foo => "bar"})
assert_equal(1, @coll.count)
end
end
def test_wnote_does_not_raise_exception_with_err_nil
@client = MongoReplicaSetClient.from_uri(@uri)
if @client.server_version < '2.5.5'
@coll = @client[TEST_DB]['test-wnote']
begin
result = @coll.remove({:foo => 1}, :w => 2)
rescue => ex
assert(false, "should not raise an exception for a wnote response field from a remove that does not match any documents")
end
assert_nil result["err"]
assert_true result.has_key?("wnote")
end
end
context "Socket pools" do
context "checking out writers" do
setup do
@client = MongoReplicaSetClient.from_uri(@uri)
@coll = @client[TEST_DB]['test-connection-exceptions']
end
should "close the connection on send_message for major exceptions" do
with_write_operations(@client) do # explicit even if w 0 maps to write operations
@client.expects(:checkout_writer).raises(SystemStackError)
@client.expects(:close)
begin
@coll.insert({:foo => "bar"}, :w => 0)
rescue SystemStackError
end
end
end
should "close the connection on send_write_command for major exceptions" do
with_write_commands(@client) do
@client.expects(:checkout_reader).raises(SystemStackError)
@client.expects(:close)
begin
@coll.insert({:foo => "bar"})
rescue SystemStackError
end
end
end
should "close the connection on send_message_with_gle for major exceptions" do
with_write_operations(@client) do
@client.expects(:checkout_writer).raises(SystemStackError)
@client.expects(:close)
begin
@coll.insert({:foo => "bar"})
rescue SystemStackError
end
end
end
should "close the connection on receive_message for major exceptions" do
@client.expects(:checkout_reader).raises(SystemStackError)
@client.expects(:close)
begin
@coll.find({}, :read => :primary).next
rescue SystemStackError
end
end
end
context "checking out readers" do
setup do
@client = MongoReplicaSetClient.from_uri(@uri)
@coll = @client[TEST_DB]['test-connection-exceptions']
end
should "close the connection on receive_message for major exceptions" do
@client.expects(:checkout_reader).raises(SystemStackError)
@client.expects(:close)
begin
@coll.find({}, :read => :secondary).next
rescue SystemStackError
end
end
end
end
end
| 34.651934 | 129 | 0.685906 |
5d0d35291eb7f383c0b5dfdb992525dddcb4e5ea | 1,658 | class ApplicationController < ActionController::Base
SECRET_KEY = Rails.application.secrets.secret_key_base.to_s
def hello
# render html: "Hello, world from Azure App Service on Linux! Render User json"
render file: 'public/index.html'
end
def ping
render json: {message:"Farm Juan Api is up yeaahhhh"}
end
def must_be_authenticated
p 'authenticating'
p request.headers['x-access-token']
token = request.headers['x-access-token']
error_403 if token.blank? || token == 0 || token == ""
data = decode token
@current_user = User.find(data["user_id"])
error_403 if @current_user.nil?
error_403 if @current_user.user_token != data["secret"]
@current_user
p 'It is authenticated'
end
def error_403
render json: {message:"Unauthorized",code:403},status:403
end
def encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, SECRET_KEY)
end
def decode(token)
decoded = JWT.decode(token, SECRET_KEY)[0]
HashWithIndifferentAccess.new decoded
end
def is_permitted? service_id, srv_policy_id
if !@current_user.user_role.nil?
role = @current_user.user_role.user_group.role_policies.where("role_policies.service_id = ? AND service_policy_id = ?",service_id,srv_policy_id)
.joins(:service_policy).where("service_policies.status = ?",true)#.where(service_policy:{status:true})
return role.present?
else
return false
end
end
def json_response a,b
render json: {status:a,message:b},status: :ok
end
end
| 30.703704 | 155 | 0.664656 |
bf0e592a9773102a9cfeae640f1f45410ba5422a | 2,034 | class Gopass < Formula
desc "The slightly more awesome Standard Unix Password Manager for Teams"
homepage "https://www.justwatch.com/gopass"
url "https://github.com/justwatchcom/gopass/releases/download/v1.6.10/gopass-1.6.10.tar.gz"
sha256 "2b481d0847abb2cb2446dfca6533c2e051b976011f42745c1ab1abbbf0bbdc8b"
head "https://github.com/justwatchcom/gopass.git"
bottle do
cellar :any_skip_relocation
sha256 "a30f17220395b1aeb731ea60f6f3e0fe0443915e41fdf7c71d0e703798b70a64" => :high_sierra
sha256 "14e3be402cb9784aecd694e2cf3bba7bc123d9e90d6ed79fcc2c0f9a4c3a3d8c" => :sierra
sha256 "3da71a728f98b072a1bfa087cbda00566d5c5011edd4e72e701041a5486bc00f" => :el_capitan
end
depends_on "go" => :build
depends_on "gnupg"
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/justwatchcom/gopass").install buildpath.children
cd "src/github.com/justwatchcom/gopass" do
prefix.install_metafiles
ENV["PREFIX"] = prefix
system "make", "install"
end
output = Utils.popen_read("#{bin}/gopass completion bash")
(bash_completion/"gopass-completion").write output
end
test do
assert_match version.to_s, shell_output("#{bin}/gopass version")
(testpath/"batch.gpg").write <<~EOS
Key-Type: RSA
Key-Length: 2048
Subkey-Type: RSA
Subkey-Length: 2048
Name-Real: Testing
Name-Email: [email protected]
Expire-Date: 1d
%no-protection
%commit
EOS
begin
system Formula["gnupg"].opt_bin/"gpg", "--batch", "--gen-key", "batch.gpg"
system bin/"gopass", "init", "--nogit", "[email protected]"
system bin/"gopass", "generate", "Email/[email protected]", "15"
assert_predicate testpath/".password-store/Email/[email protected]", :exist?
ensure
system Formula["gnupg"].opt_bin/"gpgconf", "--kill", "gpg-agent"
system Formula["gnupg"].opt_bin/"gpgconf", "--homedir", "keyrings/live",
"--kill", "gpg-agent"
end
end
end
| 34.474576 | 93 | 0.681416 |
ffc0c98434c7dc4c6923722bfb3b0af59cced2d3 | 895 | module Spree
class StockMovement < Spree::Base
QUANTITY_LIMITS = {
max: 2**31 - 1,
min: -2**31
}.freeze
belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_movements
belongs_to :originator, polymorphic: true
after_create :update_stock_item_quantity
with_options presence: true do
validates :stock_item
validates :quantity, numericality: {
greater_than_or_equal_to: QUANTITY_LIMITS[:min],
less_than_or_equal_to: QUANTITY_LIMITS[:max],
only_integer: true
}
end
scope :recent, -> { order(created_at: :desc) }
self.whitelisted_ransackable_attributes = ['quantity']
def readonly?
persisted?
end
private
def update_stock_item_quantity
return unless stock_item.should_track_inventory?
stock_item.adjust_count_on_hand quantity
end
end
end
| 22.948718 | 88 | 0.686034 |
5d47b7ae8766300b530115d24658999b17351f3e | 4,039 | module Supply
class Setup
def perform_download
UI.message("🕗 Downloading metadata, images, screenshots...")
if File.exist?(metadata_path)
UI.important("Metadata already exists at path '#{metadata_path}'")
return
end
client.begin_edit(package_name: Supply.config[:package_name])
client.listings.each do |listing|
store_metadata(listing)
download_images(listing)
end
if Supply.config[:version_name].to_s == ""
latest_version = client.latest_version(Supply.config[:track])
if latest_version
Supply.config[:version_name] = latest_version.name
else
UI.user_error!("Could not find the latest version to download metadata, images, and screenshots from")
end
end
client.release_listings(Supply.config[:version_name]).each do |release_listing|
store_release_listing(release_listing)
end
client.abort_current_edit
UI.success("✅ Successfully stored metadata in '#{metadata_path}'")
end
def store_metadata(listing)
UI.message("📝 Downloading metadata (#{listing.language})")
containing = File.join(metadata_path, listing.language)
FileUtils.mkdir_p(containing)
Supply::AVAILABLE_METADATA_FIELDS.each do |key|
path = File.join(containing, "#{key}.txt")
UI.message("Writing to #{path}...")
File.open(path, 'w:UTF-8') { |file| file.write(listing.send(key)) }
end
end
def download_images(listing)
UI.message("🖼️ Downloading images (#{listing.language})")
require 'net/http'
allowed_imagetypes = [Supply::IMAGES_TYPES, Supply::SCREENSHOT_TYPES].flatten
allowed_imagetypes.each do |image_type|
begin
path = File.join(metadata_path, listing.language, IMAGES_FOLDER_NAME, image_type)
p = Pathname.new(path)
if IMAGES_TYPES.include?(image_type) # IMAGE_TYPES are stored in locale/images location
FileUtils.mkdir_p(p.dirname.to_s)
else # SCREENSHOT_TYPES go under their respective folders.
FileUtils.mkdir_p(p.to_s)
end
UI.message("Downloading `#{image_type}` for #{listing.language}...")
urls = client.fetch_images(image_type: image_type, language: listing.language)
next if urls.nil? || urls.empty?
image_counter = 1 # Used to prefix the downloaded files, so order is preserved.
urls.each do |url|
if IMAGES_TYPES.include?(image_type) # IMAGE_TYPES are stored in locale/images
file_path = "#{path}.#{FastImage.type(url)}"
else # SCREENSHOT_TYPES are stored in locale/images/<screensho_types>
file_path = File.join(path, "#{image_counter}_#{listing.language}.#{FastImage.type(url)}")
end
File.binwrite(file_path, Net::HTTP.get(URI.parse(url)))
UI.message("\tDownloaded - #{file_path}")
image_counter += 1
end
rescue => ex
UI.error(ex.to_s)
UI.error("Error downloading '#{image_type}' for #{listing.language}...")
end
end
end
def store_release_listing(release_listing)
UI.message("🔨 Downloading changelogs (#{release_listing.language}, #{release_listing.version})")
containing = File.join(metadata_path, release_listing.language, CHANGELOGS_FOLDER_NAME)
unless File.exist?(containing)
FileUtils.mkdir_p(containing)
end
path = File.join(containing, "#{release_listing.version}.txt")
UI.message("Writing to #{path}...")
File.write(path, release_listing.release_notes)
end
private
def metadata_path
@metadata_path ||= Supply.config[:metadata_path]
@metadata_path ||= "fastlane/metadata/android" if Helper.fastlane_enabled?
@metadata_path ||= "metadata" unless Helper.fastlane_enabled?
return @metadata_path
end
def client
@client ||= Client.make_from_config
end
end
end
| 33.380165 | 112 | 0.649913 |
623f57231e6e9f8b62a4eb342c1a8987a1cf40b4 | 506 | module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
@current_user = nil
end
def is_admin?
current_user.isadmin?
end
end
| 18.071429 | 59 | 0.679842 |
38e38c54546f4632cb094f0cbea61b0e743c9000 | 885 | class SiteAnnouncement < ActiveRecord::Base
class BodyHelper
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
end
belongs_to :site_announcement_category
belongs_to :announcer,:polymorphic=>true
scope :headline_announcements,:conditions=>(["is_headline = ? and expires_at > ? ",true,Time.now]),:order=>"created_at DESC",:limit=>1
validates_presence_of :title
def self.headline_announcement
self.headline_announcements.first
end
def self.feed_announcements options={}
options[:limit] ||= 5
self.where(["show_in_feed = ?",true]).order("created_at DESC").limit(options[:limit])
end
def body_html
helper.simple_format(helper.auto_link(body,:sanitize=>true),{},:sanitize=>true).html_safe
end
private
def helper
@helper ||= BodyHelper.new
end
end
| 24.583333 | 136 | 0.729944 |
032c8b38d663460448ec8d1df30191e128c0b478 | 14,381 | require 'open-uri'
require 'nokogiri'
require 'base64'
require_relative 'register'
DIRECTIVE_CODE = /\d+\/\d+(\/[A-Z]+)?/
WHITESPACE_WITH_NBSP = /\s|\u00A0/
RSFs = FileList[
'legislation.rsf',
'product.rsf',
'procedure.rsf',
'body-type.rsf',
'body.rsf'
]
CACHE = './cache/'
STORE = 'nando.catalogue.sqlite'
def nando_rel_link page
"http://ec.europa.eu/growth/tools-databases/nando/#{page}"
end
def nando action
nando_rel_link "index.cfm?fuseaction=#{action}"
end
def cached href
File.join CACHE, "#{Base64.urlsafe_encode64(href, padding: false)}.html"
end
def page href
filename = cached href
unless File.exist? filename
rake_output_message "GET #{href}"
File.write filename, open(href, &:read)
end
open(filename, &Nokogiri.method(:HTML))
end
def parse_legislation_text text
words, code, name = text.strip.partition(DIRECTIVE_CODE)
legislation_id = words + code
[legislation_id, name]
end
def progress done, total
msg = "Progress: #{done}/#{total}"
STDERR.write msg
STDERR.write "\b" * msg.length
end
task :default => RSFs
directory CACHE
task :clean do
rm RSFs
rm STORE
end
task :mrproper => :clean do
rm_r CACHE
end
file 'legislation.rsf' do |t|
legislation = Register.new t.name
legislation.init(
'legislation',
'European-Commission-NANDO',
'EU product harmonisation legislation - can be in the form of a Directive, a Regulation or a Decision.',
Register::Field.new('legislation', 'string', 'Unique code or text that identifies the legislation.', 1),
Register::Field.new('name', 'string', 'Summary of types of products that the legislation covers.', 1))
legislation.custodian = 'Simon Worthington'
legislation_page = page nando('directive.main')
legislation_page.css('#main_content table table tr').each do |legislation_row|
text = legislation_row.css('a').first.text.strip
legislation_id, name = parse_legislation_text text
legislation.append_entry :user, legislation_id, {legislation: legislation_id, name: name.strip}
end
legislation.close
end
def find_legislation_page legislation_id
legislation_page = page nando_rel_link('index.cfm?fuseaction=notifiedbody.notifiedbodies&num=DNB&text=')
dir_id = legislation_page.css('select[name="dir_id"] option').find do |option|
text = option.text.strip
parsed_legislation_id, _ = parse_legislation_text text
legislation_id == parsed_legislation_id
end.attribute('value').value
"index.cfm?fuseaction=directive.notifiedbody&dir_id=#{dir_id}"
end
def truncated_string_match? full, maybe_truncated, truncation='...'
# downcases sadly necessary, data quality is odd
if maybe_truncated.end_with? truncation
full.downcase.start_with? maybe_truncated[0...-(truncation.length)].downcase
else
full.downcase == maybe_truncated.downcase
end
end
file 'body.rsf' do
products = Register.new 'product.rsf'
products.init(
'product',
'European-Commission-NANDO',
'Products covered by a particular EU product Directive/Regulation.',
Register::Field.new('product', 'integer', 'The NANDO unique identifier for these products.', 1),
Register::Field.new('legislation', 'curie', 'The item of EU legislation that covers the products.', 1),
Register::Field.new('description', 'string', 'Description of product types covered.', 1),
Register::Field.new('parent', 'curie', 'The NANDO unique identifier for the parent product category, if this product has one.', 1)
)
products.custodian = 'Simon Worthington'
find_product_id = proc do |legislation_id, description, parent|
listing_link = nando_rel_link find_legislation_page legislation_id
listing_page = page listing_link
product_option = listing_page.css('table table select[name="pro_id"] option').find do |option|
truncated_string_match? description, option.text.strip
end
product_option ||= begin
parent = products.items.find {|p| p[:product] == parent }
listing_page.css('table table select[name="pro_id"] option').find do |option|
truncated_string_match? "#{parent[:description]} (#{description})", option.text.strip
end
end
raise "Unable to find product #{description.inspect} [#{parent}] in #{cached listing_link}" if product_option.nil?
product_option.attribute('value').value.to_i
end
find_or_add_product = proc do |legislation_id, description, parent|
product = products.items.find {|p| p[:description] == description && p[:parent] == (parent.nil? ? nil : "product:#{parent}") && p[:legislation] == "legislation:#{legislation_id}" }
if product.nil?
product = {
product: find_product_id.call(legislation_id, description, parent),
legislation: "legislation:#{legislation_id}",
description: description,
parent: (parent.nil? ? nil : "product:#{parent}")
}
products.append_entry :user, product[:product], product
end
product
end
procedures = Register.new 'procedure.rsf'
procedures.init(
'procedure',
'European-Commission-NANDO',
'Conformity assessment procedure as set out in Annex II of Decision 758/2008/EC, and in the relevant EU product legislation',
Register::Field.new('procedure', 'integer', 'The NANDO unique identifier for this procedure.'),
Register::Field.new('legislation', 'curie', 'The item of EU legislation that includes the procedure.'),
Register::Field.new('annexes', 'string', 'Annex or Article of the Directive/Regulation which is the source of the procedure.'),
Register::Field.new('description', 'string', 'Summary of what activity the procedure defines.')
)
procedures.custodian = 'Simon Worthington'
find_procedure_id = proc do |legislation_id, description, annexes|
listing_page = page nando_rel_link find_legislation_page legislation_id
listing_page.css('table table select[name="prc_anx"] option').find do |option|
truncated_string_match? "#{description} / #{annexes}", option.text.strip
end.attribute('value').value.to_i
end
find_or_add_procedure = proc do |legislation_id, description, annexes|
procedure = procedures.items.find {|p| p[:description] == description && p[:annexes] == annexes && p[:legislation] == "legislation:#{legislation_id}" }
if procedure.nil?
procedure = {
procedure: find_procedure_id.call(legislation_id, description, annexes),
legislation: "legislation:#{legislation_id}",
description: description.strip,
annexes: annexes.strip
}
procedures.append_entry :user, procedure[:procedure], procedure
end
procedure
end
bodies = Register.new 'body.rsf'
bodies.init(
'body',
'European-Commission-NANDO',
'Organisations that, having fulfilled the relevant requirements, are designated to carry out conformity assessment according to specific legislation.',
Register::Field.new('body', 'string', 'The NANDO unique identifier for this body.'),
Register::Field.new('type', 'curie', 'The unique code for the type that this body is.'),
Register::Field.new('notified-body-number', 'integer', 'The unique number assigned to this body if it has notified.'),
Register::Field.new('name', 'string', 'The name of this body.'),
Register::Field.new('country', 'curie', 'Code of the country that this body is based in.'), #TODO desc
Register::Field.new('address', 'string', 'The address the body is based at.'),
Register::Field.new('phone', 'string', 'A phone number on which the body can receive calls.'),
Register::Field.new('fax', 'string', 'A phone number on which the body can receive faxes.'),
Register::Field.new('email', 'string', 'An e-mail address at which the body can receive mail.'),
Register::Field.new('website', 'string', 'URL of a website describing the body.'), #TODO type
Register::Field.new('products', 'string', 'Product types the body is accredited to handle.'), #TODO desc
Register::Field.new('procedures', 'string', 'Procedures the body is accredited to carry out.') #TODO desc
)
bodies.custodian = 'Simon Worthington'
bodies_nav_page = page nando('notifiedbody.main')
bodies_nav_page.css('#main_content table table td img + a.list').each do |bodies_page_link|
bodies_page = page nando_rel_link(bodies_page_link.attribute('href').value)
bodies_page.css('#main_content table tr:nth-child(6) table tr:not(:first-child)').each_with_index do |body_row|
body_info = {}
body_type, _ = body_row.at_css('td:first-child').text.split(' ')
body_info[:type] = "body-type:#{body_type.gsub(/[^A-Z]/, '')}" #to handle nbsp
href = body_row.at_css('a').attribute('href').value
query_params = URI.parse(href).query.split('&').map {|s| s.split('=')}.to_h
body_info[:body] = URI.decode(query_params['refe_cd'])
# First look through the body page and pull out the contact information
body_page = page nando_rel_link(href)
body_page.at_css('#main_content > table > tr:nth-child(3) > td:nth-child(2)').children.each do |c|
case c
when Nokogiri::XML::Element
body_info[:name] ||= c.text if c.name == 'strong'
when Nokogiri::XML::Text
name_or_value, maybe_value = c.text.split(':', 2)
if ['Country', 'Phone', 'Fax', 'Email', 'Website', 'Notified Body number'].include? name_or_value.strip
name = name_or_value.strip.downcase.gsub(' ', '-').to_sym
value = maybe_value.strip
body_info[name] = value if value != '' && value != '-'
elsif ['Body', 'Last update'].include? name_or_value.strip
next
elsif c.text.strip != ''
# Address line
body_info[:address] = (body_info[:address] || '') + c.text.strip + "\n"
end
end
end
# Now look at all the legislations this body is notified for
body_page.css('#main_content table table tr:not(:first-child)').each do |legislation_row|
href = legislation_row.at_xpath('.//a[text() = "HTML"]').attribute('href').value
legislation_id, _ = parse_legislation_text legislation_row.at_css('td:nth-child(1)').text
next if legislation_id == 'Regulation (EU) No 305/2011' # skip construction products for now
legislation_page = page nando_rel_link(href)
last_top_product = nil
legislation_page.at_css('#main_content table table table tr:not(:first-child) td:first-child').children.each do |c|
next unless c.is_a? Nokogiri::XML::Text
description = c.text.gsub(/^(#{WHITESPACE_WITH_NBSP})+/, '').gsub(/(#{WHITESPACE_WITH_NBSP})+$/, '')
next unless description != ''
subproduct = description.start_with?('-')
description = subproduct ? description[2..-1] : description
parent = subproduct ? last_top_product : nil
begin
product = find_or_add_product.call legislation_id, description, parent
rescue Exception => e
STDERR.puts e
next
end
body_info[:products] = (body_info[:products] || "") + "product:#{product[:product]};"
last_top_product = product[:product] unless subproduct
end
procedure_cells = legislation_page.at_css('#main_content table table table tr:not(:first-child) td:nth-child(2)').children
annex_cells = legislation_page.at_css('#main_content table table table tr:not(:first-child) td:nth-child(3)').children
procedure_cells.zip(annex_cells).each do |procedure_description, annex|
raise 'Looks like procedures and annexes are not 1-1 after all' unless annex.class == procedure_description.class
next unless procedure_description.is_a? Nokogiri::XML::Text
next unless procedure_description.text.strip != ''
procedure = find_or_add_procedure.call legislation_id, procedure_description.text.strip, annex.text.strip
body_info[:procedures] = (body_info[:procedures] || "") + "procedure:#{procedure[:procedure]};"
end
end
bodies.append_entry :user, body_info[:body], body_info
progress bodies.items.size, 2900
end
end
products.close
procedures.close
bodies.close
end
file 'product.rsf' => 'body.rsf'
file 'procedure.rsf' => 'body.rsf'
file 'body-type.rsf' do |t|
body_types = Register.new t.name
body_types.init(
'body-type',
'European-Commission-NANDO',
'Types of body defined by NANDO.',
Register::Field.new('body-type', 'string', 'Unique abbreviation representing the type of the body.'),
Register::Field.new('name', 'string', 'Full name of the body type.'),
Register::Field.new('definition', 'string', 'Characteristic that a body has to have to be this type.')
)
body_types.custodian = 'Simon Worthington'
body_types.append_entry :user, "CAB", {'body-type': "CAB", name: "Conformity Assessment Body", definition: "A body that performs one or several elements of conformity assessment, including one or several of the following activities: calibration, testing, certification and inspection."}
body_types.append_entry :user, "NB", {'body-type': "NB", name: "Notified Body", definition: "A conformity assessment body officially designated by the national authority to carry out the procedures for conformity assessment within the meaning of applicable Union harmonisation legislation."}
body_types.append_entry :user, "TAB", {'body-type': "TAB", name: "Technical Assessment Body", definition: "An organisation that has been designated by a Member State as being entrusted with the establishment of draft European Assessment Documents and the issuing of European Technical Assessments in accordance with the Construction Products Regulation (EU) No 305/ 2011 (CPR)."}
body_types.append_entry :user, "UI", {'body-type': "UI", name: "User Inspectorate", definition: "A conformity assessment body notified to carry out the tasks set out in Article 16 of Directive 2014/68/EU on Pressure Equipment (PED)."}
body_types.append_entry :user, "RTPO", {'body-type': "RTPO", name: "Recognised Third Party Organisation", definition: "A conformity assessment body notified to carry out the tasks set out in Article 20 of Directive 2014/68/EU on Pressure Equipment (PED)."}
body_types.close
end
file STORE => RSFs do |t|
RSFs.each do |rsf|
sh ["orc", "-S", t.name, "digest", rsf].join(" ")
end
end | 46.691558 | 383 | 0.697378 |
bbd6b103ef118490dcd33828bf0cc6417ec86d25 | 180 | require_dependency 'support/application_record'
module Support
module Common
class Program < ApplicationRecord
self.table_name = 'commonx.programs'
end
end
end
| 18 | 47 | 0.75 |
ff398f269be6c5db1810ca125b9dc361e8b63735 | 7,094 | require File.join(File.dirname(__FILE__), 'spec_helper')
class TestPacket < Nanite::Packet
@@cls_attr = "ignore"
def initialize(attr1)
@attr1 = attr1
end
end
describe "Packet: Base class" do
before(:all) do
end
it "should be an abstract class" do
lambda { Nanite::Packet.new }.should raise_error(NotImplementedError, "Nanite::Packet is an abstract class.")
end
it "should know how to dump itself to JSON" do
packet = TestPacket.new(1)
packet.should respond_to(:to_json)
end
it "should dump the class name in 'json_class' JSON key" do
packet = TestPacket.new(42)
packet.to_json().should =~ /\"json_class\":\"TestPacket\"/
end
it "should dump instance variables in 'data' JSON key" do
packet = TestPacket.new(188)
packet.to_json().should =~ /\"data\":\{\"attr1\":188\}/
end
it "should not dump class variables" do
packet = TestPacket.new(382)
packet.to_json().should_not =~ /cls_attr/
end
it "should store instance variables in 'data' JSON key as JSON object" do
packet = TestPacket.new(382)
packet.to_json().should =~ /\"data\":\{[\w:"]+\}/
end
it "should remove '@' from instance variables" do
packet = TestPacket.new(2)
packet.to_json().should_not =~ /@attr1/
packet.to_json().should =~ /attr1/
end
end
describe "Packet: FileStart" do
it "should dump/load as JSON objects" do
packet = Nanite::FileStart.new('foo.txt', 'somewhere/foo.txt', '0xdeadbeef')
packet2 = JSON.parse(packet.to_json)
packet.filename.should == packet2.filename
packet.dest.should == packet2.dest
packet.token.should == packet2.token
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::FileStart.new('foo.txt', 'somewhere/foo.txt', '0xdeadbeef')
packet2 = Marshal.load(Marshal.dump(packet))
packet.filename.should == packet2.filename
packet.dest.should == packet2.dest
packet.token.should == packet2.token
end
end
describe "Packet: FileEnd" do
it "should dump/load as JSON objects" do
packet = Nanite::FileEnd.new('0xdeadbeef', 'metadata')
packet2 = JSON.parse(packet.to_json)
packet.meta.should == packet2.meta
packet.token.should == packet2.token
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::FileEnd.new('0xdeadbeef', 'metadata')
packet2 = Marshal.load(Marshal.dump(packet))
packet.meta.should == packet2.meta
packet.token.should == packet2.token
end
end
describe "Packet: FileChunk" do
it "should dump/load as JSON objects" do
packet = Nanite::FileChunk.new('chunk','0xdeadbeef')
packet2 = JSON.parse(packet.to_json)
packet.chunk.should == packet2.chunk
packet.token.should == packet2.token
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::FileChunk.new('chunk','0xdeadbeef')
packet2 = Marshal.load(Marshal.dump(packet))
packet.chunk.should == packet2.chunk
packet.token.should == packet2.token
end
end
describe "Packet: Request" do
it "should dump/load as JSON objects" do
packet = Nanite::Request.new('/some/foo', 'payload', :from => 'from', :token => '0xdeadbeef', :reply_to => 'reply_to')
packet2 = JSON.parse(packet.to_json)
packet.type.should == packet2.type
packet.payload.should == packet2.payload
packet.from.should == packet2.from
packet.token.should == packet2.token
packet.reply_to.should == packet2.reply_to
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::Request.new('/some/foo', 'payload', :from => 'from', :token => '0xdeadbeef', :reply_to => 'reply_to')
packet2 = Marshal.load(Marshal.dump(packet))
packet.type.should == packet2.type
packet.payload.should == packet2.payload
packet.from.should == packet2.from
packet.token.should == packet2.token
packet.reply_to.should == packet2.reply_to
end
end
describe "Packet: Result" do
it "should dump/load as JSON objects" do
packet = Nanite::Result.new('0xdeadbeef', 'to', 'results', 'from')
packet2 = JSON.parse(packet.to_json)
packet.token.should == packet2.token
packet.to.should == packet2.to
packet.results.should == packet2.results
packet.from.should == packet2.from
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::Result.new('0xdeadbeef', 'to', 'results', 'from')
packet2 = Marshal.load(Marshal.dump(packet))
packet.token.should == packet2.token
packet.to.should == packet2.to
packet.results.should == packet2.results
packet.from.should == packet2.from
end
end
describe "Packet: IntermediateMessage" do
it "should dump/load as JSON objects" do
packet = Nanite::IntermediateMessage.new('0xdeadbeef', 'to', 'from', 'messagekey', 'message')
packet2 = JSON.parse(packet.to_json)
packet.token.should == packet2.token
packet.to.should == packet2.to
packet.from.should == packet2.from
packet.messagekey.should == packet2.messagekey
packet.message.should == packet2.message
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::IntermediateMessage.new('0xdeadbeef', 'to', 'from', 'messagekey', 'message')
packet2 = Marshal.load(Marshal.dump(packet))
packet.token.should == packet2.token
packet.to.should == packet2.to
packet.from.should == packet2.from
packet.messagekey.should == packet2.messagekey
packet.message.should == packet2.message
end
end
describe "Packet: Register" do
it "should dump/load as JSON objects" do
packet = Nanite::Register.new('0xdeadbeef', ['/foo/bar', '/nik/qux'], 0.8, ['foo'])
packet2 = JSON.parse(packet.to_json)
packet.identity.should == packet2.identity
packet.services.should == packet2.services
packet.status.should == packet2.status
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::Register.new('0xdeadbeef', ['/foo/bar', '/nik/qux'], 0.8, ['foo'])
packet2 = Marshal.load(Marshal.dump(packet))
packet.identity.should == packet2.identity
packet.services.should == packet2.services
packet.status.should == packet2.status
end
end
describe "Packet: UnRegister" do
it "should dump/load as JSON objects" do
packet = Nanite::UnRegister.new('0xdeadbeef')
packet2 = JSON.parse(packet.to_json)
packet.identity.should == packet2.identity
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::UnRegister.new('0xdeadbeef')
packet2 = Marshal.load(Marshal.dump(packet))
packet.identity.should == packet2.identity
end
end
describe "Packet: Ping" do
it "should dump/load as JSON objects" do
packet = Nanite::Ping.new('0xdeadbeef', 0.8)
packet2 = JSON.parse(packet.to_json)
packet.identity.should == packet2.identity
packet.status.should == packet2.status
end
it "should dump/load as Marshalled ruby objects" do
packet = Nanite::Ping.new('0xdeadbeef', 0.8)
packet2 = Marshal.load(Marshal.dump(packet))
packet.identity.should == packet2.identity
packet.status.should == packet2.status
end
end
| 32.099548 | 122 | 0.693544 |
0115d75d09ae222de9b05c2a647a5d8b1914b432 | 442 | #
# Cookbook Name:: build
# Spec:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
require 'spec_helper'
describe 'build::lint' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
it 'converges successfully' do
chef_run # This should not raise an error
end
end
end
| 18.416667 | 74 | 0.69457 |
ab1f966e13b2bb8b9bb62d4e979b4511f2452ccf | 71 | class ContentsController < ApplicationController
def index
end
end
| 14.2 | 48 | 0.816901 |
acf6c3fd6e9a3b20a1ba1dc449773be81358d9a6 | 3,323 | # Copyright (C) 2016 Colin Fulton
# All rights reserved.
#
# This software may be modified and distributed under the
# terms of the three-clause BSD license. See LICENSE.txt
# (located in root directory of this project) for details.
require_relative './each_works'
require_relative './match_result_basics'
def expression_basics klass
group klass do
match_result_basics klass
content_1 = 'here is some text'
content_2 = 'even more text!'
content_3 = 'what?! more text?!'
expression_content = [
Lextacular::Token.new(content_1),
Lextacular::Token.new(content_2)
]
empty_expression = klass.new
expression = klass.new(*expression_content)
nested_expression = klass.new(
expression,
Lextacular::Token.new(content_3)
)
group '#to_s' do
assert 'returns the joined content of all the children' do
expression.to_s == content_1 + content_2
end
assert 'works with nested groups' do
nested_expression.to_s == expression.to_s + content_3
end
assert 'returns an empty string when initialized with nothing' do
empty_expression.to_s == ''
end
end
group '#size' do
assert 'returns the sum of the sizes of all the children' do
expression.size == content_1.size + content_2.size
end
assert 'works with nested groups' do
nested_expression.size == expression.size + content_3.size
end
assert 'returns 0 when initialized with nothing' do
empty_expression.size.zero?
end
end
group '#empty?' do
assert 'returns truthy when size == 0' do
empty_expression.empty?
end
assert 'returns falsy when size > 0' do
!expression.empty?
end
end
group '#children' do
assert 'returns the children given when initialized' do
expression.children == expression_content
end
end
assert 'includes Enumerable' do
expression.class.ancestors.include?(Enumerable)
end
group '#each' do
assert 'exists' do
expression.respond_to?(:each)
end
group 'goes over each item' do
each_works enumerable: expression, content: expression_content
end
assert 'returns Enumerator when not given a block' do
expression.each.is_a?(Enumerator)
end
group 'returned Enumerator is valid' do
each_works enumerable: expression.each, content: expression_content
end
end
group '#without_temps' do
assert 'returns false if initialzed as temp' do
!klass.new(temp: true).without_temps
end
assert 'returns new instance of class, filtering out temp children if not temp' do
name = :wilhelm
children = [klass.new(temp: true), klass.new(temp: false), klass.new(temp: true)]
filtered = children.map { |part| part.without_temps }.compact
klass.new(*children, temp: false, name: name).without_temps ==
klass.new(*filtered, temp: false, name: name)
end
assert 'temp defaults to falsy' do
klass.new.without_temps
end
end
yield expression, expression_content
end
end
| 27.92437 | 89 | 0.631959 |
6172da6e43edf4d0960c36931c5649c07a503f39 | 947 | $:.push File.expand_path("../lib", __FILE__)
require "r509/validity/redis/version"
spec = Gem::Specification.new do |s|
s.name = 'r509-validity-redis'
s.version = R509::Validity::Redis::VERSION
s.platform = Gem::Platform::RUBY
s.has_rdoc = false
s.summary = "A Validity::Writer and Validity::Checker for r509, implemented with a Redis backend"
s.description = "A Validity::Writer and Validity::Checker for r509, implemented with a Redis backend"
s.add_dependency 'r509'
s.add_dependency 'redis'
s.add_dependency 'rake'
s.add_development_dependency 'rspec'
s.add_development_dependency 'syntax'
s.add_development_dependency 'simplecov'
s.author = "Sean Schulte"
s.email = "[email protected]"
s.homepage = "http://langui.sh"
s.required_ruby_version = ">= 1.9.3"
s.files = %w(README.md Rakefile) + Dir["{lib,script,spec,doc,cert_data}/**/*"]
s.test_files= Dir.glob('test/*_spec.rb')
s.require_path = "lib"
end
| 36.423077 | 103 | 0.715945 |
61f696c47abed49211698b118cc88d6172ecb2e2 | 417 |
# == Schema Information
#
# Table name: list_subscribers
#
# id :integer not null, primary key
# email :string not null
# subscribed :boolean default(TRUE)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# confirmed :boolean default(FALSE)
# confirm_code :string
# email_format :string
#
| 26.0625 | 55 | 0.580336 |
0826fb80fd34441bfc110aadd41e6eef27f9a3e1 | 1,678 | require 'rails_helper'
RSpec.describe Task, type: :model do
let(:user) {FactoryBot.create(:user)}
let(:project) {FactoryBot.create(:project, user: user)}
let(:task) {FactoryBot.create(:task, project: project)}
it 'user after Factory valid with valid attributes' do
expect(task).to be_valid
end
describe 'oil must have all important attributes' do
it { expect(:name).to be}
it { expect(:priority).to be}
it { expect(:status).to be}
it { expect(:created_at).to be}
it { expect(:updated_at).to be}
end
describe 'trying to create and validate task with or without nesessary attributes' do
it 'without name - invalid' do
task = Task.new(priority: '')
expect(task.valid?).to eq(false)
end
it 'without priority or status - invalid' do
task.priority = 'asdasd'
expect(task.valid?).to eq(false)
task.priority = nil
expect(task.valid?).to eq(false)
task.status = nil
expect(task.valid?).to eq(false)
end
end
describe 'test up and down methods' do
it 'testing up method' do
task.priority = 4
expect(task.priority).to eq(4)
task.up
expect(task.priority).to eq(5)
task.up
expect(task.priority).to eq(5)
end
it 'testing down method' do
task.priority = 2
expect(task.priority).to eq(2)
task.down
expect(task.priority).to eq(1)
task.down
expect(task.priority).to eq(1)
end
end
describe 'test status enum\'s' do
it 'enums' do
task.in_process!
expect(task.status).to eq('in_process')
task.done!
expect(task.status).to eq('done')
end
end
end
| 25.424242 | 87 | 0.628129 |
d5d01a6bc6d463d96506e824ed189f955d217c74 | 468 | module Locomotive
module SitesHelper
def ordered_current_site_locales
current_site.locales + (Locomotive.config.site_locales - current_site.locales)
end
def options_for_site_locales
Locomotive.config.site_locales.map do |locale|
[I18n.t("locomotive.locales.#{locale}"), locale]
end
end
def options_for_site_timezones
ActiveSupport::TimeZone.all.map do |tz|
[tz, tz.name]
end
end
end
end | 22.285714 | 84 | 0.681624 |
384f4886d05cf6d7a45960480b7f9cce33317f8e | 1,514 | class Admin::ReviewsController < Admin::ApplicationController
before_action :current_paper, if: -> { params.has_key?(:paper_id) }
def approve
review = @paper.reviews.create(user: current_user, reviewed: "approve")
review.approve!
@paper.activity.notify("paper_status_changed", @paper)
redirect_to admin_activity_papers_path(@paper.activity)
rescue StandardError
redirect_to admin_activity_papers_path(@paper.activity), alert: "You already reviewed this paper"
end
def disapprove
review = @paper.reviews.create(user: current_user, reviewed: "disapprove")
review.disapprove!
@paper.activity.notify("paper_status_changed", @paper)
redirect_to admin_activity_papers_path(@paper.activity)
rescue StandardError
redirect_to admin_activity_papers_path(@paper.activity), alert: "You already reviewed this paper"
end
def accept
@paper.accept!
@paper.activity.notify("paper_status_changed", @paper)
redirect_to admin_activity_papers_path(@paper.activity)
rescue StandardError
redirect_to admin_activity_papers_path(@paper.activity_id), alert: "發生錯誤"
end
def reject
@paper.reject!
@paper.activity.notify("paper_status_changed", @paper)
redirect_to admin_activity_papers_path(@paper.activity)
rescue StandardError
redirect_to admin_activity_papers_path(@paper.activity), alert: "發生錯誤"
end
protect_from_forgery
protected
def current_paper
@paper = Paper.find_by(uuid: params[:paper_id])
end
end
| 32.913043 | 103 | 0.754293 |
1d05f534685db310e3eca08a43cbbc93918acb43 | 230 | class Fix2014BExamDates < ActiveRecord::Migration
def change
Semester.find_all_by_exams_end(DateTime.new(2014, 8, 1)).each do |s|
s.update_attributes :exams_end => DateTime.new(2014, 8, 8)
s.save
end
end
end
| 25.555556 | 74 | 0.708696 |
386996161cd3e1231ba4f5c73d30842d17cde37a | 6,676 | require 'test_helper'
module Rails3JQueryAutocomplete
module Orm
class ActiveRecordTest < Test::Unit::TestCase
include Rails3JQueryAutocomplete::Orm::ActiveRecord
context "#get_autocomplete_order" do
context 'order is specified' do
should 'returns that order option' do
assert_equal "field ASC", active_record_get_autocomplete_order(:field, {:order => 'field ASC'})
end
end
context 'no order is specified' do
should 'return the order clause by the LOWER(table_name.field) ASC' do
assert_equal "LOWER(field) ASC", active_record_get_autocomplete_order(:field, {})
end
context 'a different model is specified' do
should 'return the order clause by the LOWER(table_name.field) ASC' do
model = Object.new
mock(model).table_name { 'table_name' }
assert_equal "LOWER(table_name.field) ASC", active_record_get_autocomplete_order(:field, {}, model)
end
end
end
end
context '#active_record_get_autocomplete_items' do
should 'retrieve the items from ActiveRecord' do
class Dog ; end
model = Dog
scoped = []
whered = []
term = 'query'
method = :field
options = {
:model => model,
:term => term,
:method => method,
:options => {}
}
mock(self).get_autocomplete_limit(anything) { 10 }
mock(self).active_record_get_autocomplete_order(anything, anything, anything) { "order ASC" }
mock(self).get_autocomplete_select_clause(model, method, {}) { ["field"] }
mock(self).get_autocomplete_where_clause(model, term, method, {}) { ["WHERE something"] }
mock(model).table_name.times(any_times) { 'model_table_name' }
mock(model).scoped { model }
mock(model).select(["field"]) { model }
mock(model).where(["WHERE something"]).mock!.limit(10).mock!.
order("order ASC") { 1 }
assert_equal 1, active_record_get_autocomplete_items(options)
end
should 'use hstore method if present' do
class Dog ; end
model = Dog
scoped = []
whered = []
term = 'query'
method = :field
hsmethod = :hsfield
options = {
:model => model,
:term => term,
:method => method,
:options => {hstore: {method: hsmethod}}
}
mock(self).get_autocomplete_limit(anything) { 10 }
mock(self).active_record_get_autocomplete_order(anything, anything, anything) { "order ASC" }
mock(self).get_autocomplete_select_clause(model, hsmethod, options[:options]) { ["hsfield"] }
mock(self).get_autocomplete_where_clause(model, term, hsmethod, options[:options]) { ["WHERE something"] }
mock(model).table_name.times(any_times) { 'model_table_name' }
mock(model).scoped { model }
mock(model).select(["hsfield"]) { model }
mock(model).where(["WHERE something"]).mock!.limit(10).mock!.
order("order ASC") { 1 }
assert_equal 1, active_record_get_autocomplete_items(options)
end
end
context '#get_autocomplete_select_clause' do
setup do
@model = Object.new
mock(@model).table_name { 'table_name' }
mock(@model).primary_key { 'id' }
end
should 'create a select clause' do
assert_equal ["table_name.id", "table_name.method"],
get_autocomplete_select_clause(@model, :method, {})
end
should 'create a select clause with hstore method' do
assert_equal ["table_name.id", "table_name.hsmethod"],
get_autocomplete_select_clause(@model, :hsmethod, {hstore: {method: :hsmethod}})
end
context 'with extra options' do
should 'return those extra fields on the clause' do
options = {:extra_data => ['table_name.created_at']}
assert_equal ["table_name.id", "table_name.method", "table_name.created_at"],
get_autocomplete_select_clause(@model, :method, options)
end
end
end
context '#get_autocomplete_where_clause' do
setup do
@model = Object.new
mock(@model).table_name { 'table_name' }
@term = 'query'
@options = {}
@method = :method
end
context 'Not Postgres' do
should 'return options for where' do
mock(self).postgres?(@model) { false }
assert_equal ["LOWER(table_name.method) LIKE ?", "query%"], get_autocomplete_where_clause(@model, @term, @method, @options)
end
end
context 'Postgres' do
should 'return options for where with ILIKE' do
mock(self).postgres?(@model) { true }
assert_equal ["LOWER(table_name.method) ILIKE ?", "query%"], get_autocomplete_where_clause(@model, @term, @method, @options)
end
end
context 'HStore' do
should 'return options for where from hstore options' do
mock(self).postgres?(@model) { true }
@options[:hstore] = {method: :hsmethod, key: :hskey}
@method = :hsmethod
assert_equal ["LOWER(table_name.hsmethod -> 'hskey') LIKE ?", "query%"], get_autocomplete_where_clause(@model, @term, @method, @options)
end
end
context 'full search' do
should 'return options for where with the term sourrounded by %%' do
mock(self).postgres?(@model) { false }
@options[:full] = true
assert_equal ["LOWER(table_name.method) LIKE ?", "%query%"], get_autocomplete_where_clause(@model, @term, @method, @options)
end
end
end
context '#postgres?' do
setup do
@model = stub
end
context 'the connection class is not postgres' do
setup do
mock(@model).connection { stub }
end
should 'return nil if the connection class matches PostgreSQLAdapter' do
assert_nil self.postgres?(@model)
end
end
context 'the connection class matches PostgreSQLAdapter' do
setup do
class PostgreSQLAdapter; end
mock(@model).connection { PostgreSQLAdapter.new }
end
should 'return true' do
assert self.postgres?(@model)
end
end
end
end
end
end
| 34.95288 | 148 | 0.579688 |
b9debf643b3db54dcf8cdd2b302a134a2edfc52b | 1,947 | module Seed
class ExperimentSeeder
include ActiveSupport::Benchmarkable
class << self
delegate :transaction, to: ActiveRecord::Base
end
def self.create_current_experiment(start_time:, end_time:, experiment_name:, max_patients_per_day:)
transaction do
Experimentation::Experiment.current_patients.create!(
name: experiment_name,
start_time: start_time,
end_time: end_time,
max_patients_per_day: max_patients_per_day
).tap do |experiment|
_control_group = experiment.treatment_groups.create!(description: "control")
single_group = experiment.treatment_groups.create!(description: "single_notification")
single_group.reminder_templates.create!(message: "notifications.set01.basic", remind_on_in_days: -1)
cascade = experiment.treatment_groups.create!(description: "cascade")
cascade.reminder_templates.create!(message: "notifications.set01.basic", remind_on_in_days: -1)
cascade.reminder_templates.create!(message: "notifications.set02.basic", remind_on_in_days: 0)
cascade.reminder_templates.create!(message: "notifications.set03.basic", remind_on_in_days: 3)
end
end
end
def self.create_stale_experiment(start_time:, end_time:, max_patients_per_day:, experiment_name:)
transaction do
Experimentation::Experiment.stale_patients.create!(
name: experiment_name,
start_time: start_time,
end_time: end_time,
max_patients_per_day: max_patients_per_day
).tap do |experiment|
_control_group = experiment.treatment_groups.create!(description: "control")
single_group = experiment.treatment_groups.create!(description: "single_notification")
single_group.reminder_templates.create!(message: "notifications.set03.basic", remind_on_in_days: 0)
end
end
end
end
end
| 41.425532 | 110 | 0.709296 |
bfdf5e2e9492b808ae60df08db652a477f4ed4c2 | 47 | module ArelTransformer
VERSION = "0.1.0"
end
| 11.75 | 22 | 0.723404 |
081adaf702f06bb9df11905f7d1b963cf4d36b17 | 1,756 | #
# Authors:: AJ Christensen (<[email protected]>)
# Richard Manyanza (<[email protected]>)
# Copyright:: Copyright (c) Chef Software Inc.
# Copyright:: Copyright 2014-2016, Richard Manyanza.
# License:: Apache License, Version 2.0
#
# 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_relative "package"
require_relative "../provider/package/freebsd/port"
require_relative "../provider/package/freebsd/pkgng"
class Chef
class Resource
class FreebsdPackage < Chef::Resource::Package
unified_mode true
provides :freebsd_package
provides :package, platform: "freebsd"
description "Use the **freebsd_package** resource to manage packages for the FreeBSD platform."
# make sure we assign the appropriate underlying providers based on what
# package managers exist on this FreeBSD system or the source of the package
#
# @return [void]
def after_created
assign_provider
end
private
def assign_provider
@provider = if /^ports$/i.match?(source.to_s)
Chef::Provider::Package::Freebsd::Port
else
Chef::Provider::Package::Freebsd::Pkgng
end
end
end
end
end
| 32.518519 | 101 | 0.68451 |
01d63d34f4c71c8a60b68cb86fa37c5f138ee4b4 | 228 | json.id service.id
json.channel service.channel
json.on_post service.on_post
json.on_comment service.on_comment
json.type service.type
json.webhook_url service.webhook_url
json.name service.name
json.icon_name service.icon_name
| 25.333333 | 36 | 0.859649 |
1c91ca0eb99751822034f6fb9fbe1e96cfc9edf1 | 467 | require 'rails_helper'
RSpec.describe 'Webhooks::LineController', type: :request do
describe 'POST /webhooks/line/{:line_channel_id}' do
it 'call the line events job with the params' do
allow(Webhooks::LineEventsJob).to receive(:perform_later)
expect(Webhooks::LineEventsJob).to receive(:perform_later)
post '/webhooks/line/line_channel_id', params: { content: 'hello' }
expect(response).to have_http_status(:success)
end
end
end
| 35.923077 | 73 | 0.72591 |
269fbd66bccc021d0444f5c638ba80fe7864fd44 | 1,997 | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!
# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
on_worker_boot do
ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
end
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| 41.604167 | 85 | 0.767151 |
ed99f5afa4cc2fc2af20460cbc634e9485861486 | 1,397 | # Set up gems listed in the Gemfile.
# See: http://gembundler.com/bundler_setup.html
# http://stackoverflow.com/questions/7243486/why-do-you-need-require-bundler-setup
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
# Require gems we care about
require 'rubygems'
require 'pry'
require 'bcrypt'
require 'uri'
require 'pathname'
require 'pg'
require 'active_record'
require 'logger'
require 'sinatra'
require "sinatra/reloader" if development?
require 'erb'
# Some helper constants for path-centric logic
APP_ROOT = Pathname.new(File.expand_path('../../', __FILE__))
APP_NAME = APP_ROOT.basename.to_s
configure do
# By default, Sinatra assumes that the root is the file that calls the configure block.
# Since this is not the case for us, we set it manually.
set :root, APP_ROOT.to_path
# See: http://www.sinatrarb.com/faq.html#sessions
enable :sessions
set :session_secret, ENV['SESSION_SECRET'] || 'this is a secret shhhhh'
# Set the views to
set :views, File.join(Sinatra::Application.root, "app", "views")
end
# Set up the controllers and helpers
Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file }
Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file }
# Set up the database and models
require APP_ROOT.join('config', 'database')
| 29.104167 | 89 | 0.724409 |
91e1ba4a7ee818e604250adddade5643febc17f3 | 3,885 | # encoding: utf-8
require "logstash/inputs/base"
require "logstash/namespace"
require "socket" # for Socket.gethostname
require "stud/interval"
require "rufus/scheduler"
# Periodically run a shell command and capture the whole output as an event.
#
# Notes:
#
# * The `command` field of this event will be the command run.
# * The `message` field of this event will be the entire stdout of the command.
#
class LogStash::Inputs::Exec < LogStash::Inputs::Base
config_name "exec"
default :codec, "plain"
# Command to run. For example : `uptime`
config :command, :validate => :string, :required => true
# Interval to run the command. Value is in seconds.
# Either `interval` or `schedule` option must be defined.
config :interval, :validate => :number
# Schedule of when to periodically run command, in Cron format
# For example: "* * * * *" (execute command every minute, on the minute)
# Either `interval` or `schedule` option must be defined.
config :schedule, :validate => :string
def register
@logger.info("Registering Exec Input", :type => @type, :command => @command, :interval => @interval, :schedule => @schedule)
@hostname = Socket.gethostname
@io = nil
if (@interval.nil? && @schedule.nil?) || (@interval && @schedule)
raise LogStash::ConfigurationError, "jdbc input: either 'interval' or 'schedule' option must be defined."
end
end # def register
def run(queue)
if @schedule
@scheduler = Rufus::Scheduler.new(:max_work_threads => 1)
@scheduler.cron @schedule do
execute(queue)
end
@scheduler.join
else
while !stop?
duration = execute(queue)
wait_until_end_of_interval(duration)
end # loop
end
end # def run
def stop
close_io()
@scheduler.shutdown(:wait) if @scheduler
end
# Execute a given command
# @param [String] A command string
# @param [Array or Queue] A queue to append events to
def execute(queue)
start = Time.now
output = exit_status = nil
begin
@logger.debug? && @logger.debug("Running exec", :command => @command)
output, exit_status = run_command()
rescue StandardError => e
@logger.error("Error while running command",
:command => @command, :e => e, :backtrace => e.backtrace)
rescue Exception => e
@logger.error("Exception while running command",
:command => @command, :e => e, :backtrace => e.backtrace)
end
duration = Time.now - start
@logger.debug? && @logger.debug("Command completed", :command => @command, :duration => duration)
if output
@codec.decode(output) do |event|
decorate(event)
event.set("host", @hostname)
event.set("command", @command)
event.set("[@metadata][duration]", duration)
event.set("[@metadata][exit_status]", exit_status)
queue << event
end
end
duration
end
private
def run_command
@io = IO.popen(@command)
output = @io.read
@io.close # required in order to read $?
exit_status = $?.exitstatus # should be threadsafe as per rb_thread_save_context
[output, exit_status]
ensure
close_io()
end
# Close @io
def close_io
return if @io.nil? || @io.closed?
@io.close
@io = nil
end
# Wait until the end of the interval
# @param [Integer] the duration of the last command executed
def wait_until_end_of_interval(duration)
# Sleep for the remainder of the interval, or 0 if the duration ran
# longer than the interval.
sleeptime = [0, @interval - duration].max
if sleeptime > 0
Stud.stoppable_sleep(sleeptime) { stop? }
else
@logger.warn("Execution ran longer than the interval. Skipping sleep.",
:command => @command, :duration => duration, :interval => @interval)
end
end
end # class LogStash::Inputs::Exec
| 30.116279 | 128 | 0.651223 |
e9c4ae1618715c84ecf7e2ae66692253367f45db | 1,458 | require File.expand_path('../../env', __FILE__)
task :doc_prep do
output_dir = "#{RESULTS}/doc"
manifest_dir = "#{RESULTS}/manifests"
if File.directory?(output_dir)
FileUtils.rm_r output_dir
end
if File.directory?(manifest_dir)
FileUtils.rm_r manifest_dir
end
FileUtils.mkdir_p manifest_dir
end
# TODO: Revisit this when/if it becomes available in Puppet Faces
desc "Create puppet module documentation."
task :doc => [:doc_prep] do
puts "Generating puppet module documentation..."
output_dir = "#{RESULTS}/doc"
manifest_dir = "#{RESULTS}/manifests"
sh %{puppet doc --mode rdoc --manifestdir #{manifest_dir} --modulepath ../ --outputdir #{output_dir}}
work_dir = "#{MODULE_ROOT_DIR}"
parent_dir = File.dirname(work_dir)
if File.directory? "#{output_dir}/files/#{work_dir}"
FileUtils.mv "#{output_dir}/files/#{work_dir}", "#{output_dir}/files"
end
FileList["#{output_dir}/**/*.html"].each do |fn|
text = File.read(fn)
replace = text.gsub(%r(#{parent_dir}), "")
File.open(fn, "w") { |file| file.puts replace }
end
FileList["#{output_dir}/files/**/*_pp.html"].each do |fn|
depth_below_doc = fn.split(/\//).length - 3
original_string = /[\.\/]*rdoc-style.css/
replacement_string = '../' * depth_below_doc + 'rdoc-style.css'
text = File.read(fn)
replace = text.gsub(original_string, replacement_string)
File.open(fn, "w") { |file| file.puts replace }
end
end
| 30.375 | 103 | 0.66941 |
5d8739916f58b9ffba701993d71b465c07f04b16 | 35 | module MemberMfaSessionsHelper
end
| 11.666667 | 30 | 0.914286 |
7a896b42a598a95862b7b92362ebdab18ff663a3 | 123 | require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
# test "the truth" do
# assert true
# end
end
| 15.375 | 45 | 0.707317 |
d5dbb8bcd05182741fe415a81280d26e4e6dc2e5 | 6,906 | # Copyright (C) 2014-2015 MongoDB, 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.
module Mongo
module Operation
# Result wrapper for operations.
#
# @since 2.0.0
class Result
extend Forwardable
include Enumerable
# The number of documents updated in the write.
#
# @since 2.0.0
N = 'n'.freeze
# The ok status field in the result.
#
# @since 2.0.0
OK = 'ok'.freeze
# @return [ Array<Protocol::Reply> ] replies The wrapped wire protocol replies.
attr_reader :replies
# Is the result acknowledged?
#
# @note On MongoDB 2.6 and higher all writes are acknowledged since the
# driver uses write commands for all write operations. On 2.4 and
# lower, the result is acknowledged if the GLE has been executed after
# the command. If not, no replies will be specified. Reads will always
# return true here since a replies is always provided.
#
# @return [ true, false ] If the result is acknowledged.
#
# @since 2.0.0
def acknowledged?
!!@replies
end
# Determine if this result is a collection of multiple replies from the
# server.
#
# @example Is the result for multiple replies?
# result.multiple?
#
# @return [ true, false ] If the result is for multiple replies.
#
# @since 2.0.0
def multiple?
replies.size > 1
end
# Get the cursor id if the response is acknowledged.
#
# @note Cursor ids of 0 indicate there is no cursor on the server.
#
# @example Get the cursor id.
# result.cursor_id
#
# @return [ Integer ] The cursor id.
#
# @since 2.0.0
def cursor_id
acknowledged? ? replies.last.cursor_id : 0
end
# Get the namespace of the cursor. The method should be defined in
# result classes where 'ns' is in the server response.
#
# @return [ Nil ]
#
# @since 2.0.0
def namespace
nil
end
# Get the documents in the result.
#
# @example Get the documents.
# result.documents
#
# @return [ Array<BSON::Document> ] The documents.
#
# @since 2.0.0
def documents
if acknowledged?
replies.flat_map{ |reply| reply.documents }
else
[]
end
end
# Iterate over the documents in the replies.
#
# @example Iterate over the documents.
# result.each do |doc|
# p doc
# end
#
# @return [ Enumerator ] The enumerator.
#
# @since 2.0.0
#
# @yieldparam [ BSON::Document ] Each document in the result.
def each(&block)
documents.each(&block)
end
# Initialize a new result.
#
# @example Instantiate the result.
# Result.new(replies)
#
# @param [ Protocol::Reply ] replies The wire protocol replies.
#
# @since 2.0.0
def initialize(replies)
@replies = replies.is_a?(Protocol::Reply) ? [ replies ] : replies
end
# Get the pretty formatted inspection of the result.
#
# @example Inspect the result.
# result.inspect
#
# @return [ String ] The inspection.
#
# @since 2.0.0
def inspect
"#<Mongo::Operation::Result:#{object_id} documents=#{documents}>"
end
# Get the first reply from the result.
#
# @example Get the first reply.
# result.reply
#
# @return [ Protocol::Reply ] The first reply.
#
# @since 2.0.0
def reply
if acknowledged?
replies.first
else
nil
end
end
# Get the count of documents returned by the server.
#
# @example Get the number returned.
# result.returned_count
#
# @return [ Integer ] The number of documents returned.
#
# @since 2.0.0
def returned_count
if acknowledged?
multiple? ? aggregate_returned_count : reply.number_returned
else
0
end
end
# If the result was a command then determine if it was considered a
# success.
#
# @note If the write was unacknowledged, then this will always return
# true.
#
# @example Was the command successful?
# result.successful?
#
# @return [ true, false ] If the command was successful.
#
# @since 2.0.0
def successful?
return true if !acknowledged?
if first_document.has_key?(OK)
first_document[OK] == 1 && parser.message.empty?
else
parser.message.empty?
end
end
# Validate the result by checking for any errors.
#
# @note This only checks for errors with writes since authentication is
# handled at the connection level and any authentication errors would
# be raised there, before a Result is ever created.
#
# @example Validate the result.
# result.validate!
#
# @raise [ Error::OperationFailure ] If an error is in the result.
#
# @return [ Result ] The result if verification passed.
#
# @since 2.0.0
def validate!
!successful? ? raise(Error::OperationFailure.new(parser.message)) : self
end
# Get the number of documents written by the server.
#
# @example Get the number of documents written.
# result.written_count
#
# @return [ Integer ] The number of documents written.
#
# @since 2.0.0
def written_count
if acknowledged?
multiple? ? aggregate_written_count : (first_document[N] || 0)
else
0
end
end
alias :n :written_count
private
def aggregate_returned_count
replies.reduce(0) do |n, reply|
n += reply.number_returned
n
end
end
def aggregate_written_count
documents.reduce(0) do |n, document|
n += (document[N] || 0)
n
end
end
def parser
@parser ||= Error::Parser.new(first_document)
end
def first_document
@first_document ||= first || BSON::Document.new
end
end
end
end
| 26.561538 | 85 | 0.576166 |
e20ea4674b4846d4639773249fdf8999e08e1d4a | 3,083 | # Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "devise-i18n-views"
s.version = "0.2.8"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["mcasimir"]
s.date = "2013-09-23"
s.description = "I18n support for devise views"
s.email = "[email protected]"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
".project",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"app/views/devise/_links.erb",
"app/views/devise/confirmations/new.html.erb",
"app/views/devise/mailer/confirmation_instructions.html.erb",
"app/views/devise/mailer/reset_password_instructions.html.erb",
"app/views/devise/mailer/unlock_instructions.html.erb",
"app/views/devise/passwords/edit.html.erb",
"app/views/devise/passwords/new.html.erb",
"app/views/devise/registrations/edit.html.erb",
"app/views/devise/registrations/new.html.erb",
"app/views/devise/sessions/new.html.erb",
"app/views/devise/shared/_links.erb",
"app/views/devise/unlocks/new.html.erb",
"devise-i18n-views.gemspec",
"lib/devise-i18n-views.rb",
"lib/generators/devise/views/i18n_templates/i18n_templates_generator.rb",
"lib/generators/devise/views/locale/locale_generator.rb",
"locales/ca.yml",
"locales/de.yml",
"locales/en.yml",
"locales/es-AR.yml",
"locales/es-ES.yml",
"locales/es.yml",
"locales/fr.yml",
"locales/hu.yml",
"locales/it.yml",
"locales/nl.yml",
"locales/pl.yml",
"locales/pt-BR.yml",
"locales/ru.yml",
"locales/zh-CN.yml",
"locales/zh-TW.yml",
"spec/devise-i18n-views_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = "http://github.com/mcasimir/devise-i18n-views"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.25"
s.summary = "I18n support for devise views"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rspec>, [">= 2.4.0"])
s.add_development_dependency(%q<bundler>, [">= 0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.3"])
s.add_development_dependency(%q<i18n-spec>, [">= 0"])
s.add_development_dependency(%q<localeapp>, [">= 0"])
else
s.add_dependency(%q<rspec>, [">= 2.4.0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
s.add_dependency(%q<i18n-spec>, [">= 0"])
s.add_dependency(%q<localeapp>, [">= 0"])
end
else
s.add_dependency(%q<rspec>, [">= 2.4.0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
s.add_dependency(%q<i18n-spec>, [">= 0"])
s.add_dependency(%q<localeapp>, [">= 0"])
end
end
| 32.797872 | 105 | 0.636393 |
1d7fc508d58909af66c7443175d2d6f4fc7b2415 | 6,004 | # frozen_string_literal: true
require "bundler/vendored_thor" unless defined?(Thor)
require "bundler"
module Bundler
class GemHelper
include Rake::DSL if defined? Rake::DSL
class << self
# set when install'd.
attr_accessor :instance
def install_tasks(opts = {})
new(opts[:dir], opts[:name]).install
end
def gemspec(&block)
gemspec = instance.gemspec
block.call(gemspec) if block
gemspec
end
end
attr_reader :spec_path, :base, :gemspec
def initialize(base = nil, name = nil)
Bundler.ui = UI::Shell.new
@base = (base ||= SharedHelpers.pwd)
gemspecs = name ? [File.join(base, "#{name}.gemspec")] : Dir[File.join(base, "{,*}.gemspec")]
raise "Unable to determine name from existing gemspec. Use :name => 'gemname' in #install_tasks to manually set it." unless gemspecs.size == 1
@spec_path = gemspecs.first
@gemspec = Bundler.load_gemspec(@spec_path)
end
def install
built_gem_path = nil
desc "Build #{name}-#{version}.gem into the pkg directory."
task "build" do
built_gem_path = build_gem
end
desc "Build and install #{name}-#{version}.gem into system gems."
task "install" => "build" do
install_gem(built_gem_path)
end
desc "Build and install #{name}-#{version}.gem into system gems without network access."
task "install:local" => "build" do
install_gem(built_gem_path, :local)
end
desc "Create tag #{version_tag} and build and push #{name}-#{version}.gem to #{gem_push_host}\n" \
"To prevent publishing in RubyGems use `gem_push=no rake release`"
task "release", [:remote] => ["build", "release:guard_clean",
"release:source_control_push", "release:rubygem_push"] do
end
task "release:guard_clean" do
guard_clean
end
task "release:source_control_push", [:remote] do |_, args|
tag_version { git_push(args[:remote]) } unless already_tagged?
end
task "release:rubygem_push" do
rubygem_push(built_gem_path) if gem_push?
end
GemHelper.instance = self
end
def build_gem
file_name = nil
sh("gem build -V '#{spec_path}'") do
file_name = File.basename(built_gem_path)
SharedHelpers.filesystem_access(File.join(base, "pkg")) {|p| FileUtils.mkdir_p(p) }
FileUtils.mv(built_gem_path, "pkg")
Bundler.ui.confirm "#{name} #{version} built to pkg/#{file_name}."
end
File.join(base, "pkg", file_name)
end
def install_gem(built_gem_path = nil, local = false)
built_gem_path ||= build_gem
out, _ = sh_with_code("gem install '#{built_gem_path}'#{" --local" if local}")
raise "Couldn't install gem, run `gem install #{built_gem_path}' for more detailed output" unless out[/Successfully installed/]
Bundler.ui.confirm "#{name} (#{version}) installed."
end
protected
def rubygem_push(path)
gem_command = "gem push '#{path}'"
gem_command += " --key #{gem_key}" if gem_key
gem_command += " --host #{allowed_push_host}" if allowed_push_host
unless allowed_push_host || Bundler.user_home.join(".gem/credentials").file?
raise "Your rubygems.org credentials aren't set. Run `gem push` to set them."
end
sh(gem_command)
Bundler.ui.confirm "Pushed #{name} #{version} to #{gem_push_host}"
end
def built_gem_path
Dir[File.join(base, "#{name}-*.gem")].sort_by {|f| File.mtime(f) }.last
end
def git_push(remote = "")
perform_git_push remote
perform_git_push "#{remote} --tags"
Bundler.ui.confirm "Pushed git commits and tags."
end
def allowed_push_host
@gemspec.metadata["allowed_push_host"] if @gemspec.respond_to?(:metadata)
end
def gem_push_host
env_rubygems_host = ENV["RUBYGEMS_HOST"]
env_rubygems_host = nil if
env_rubygems_host && env_rubygems_host.empty?
allowed_push_host || env_rubygems_host || "rubygems.org"
end
def perform_git_push(options = "")
cmd = "git push #{options}"
out, code = sh_with_code(cmd)
raise "Couldn't git push. `#{cmd}' failed with the following output:\n\n#{out}\n" unless code == 0
end
def already_tagged?
return false unless sh("git tag").split(/\n/).include?(version_tag)
Bundler.ui.confirm "Tag #{version_tag} has already been created."
true
end
def guard_clean
clean? && committed? || raise("There are files that need to be committed first.")
end
def clean?
sh_with_code("git diff --exit-code")[1] == 0
end
def committed?
sh_with_code("git diff-index --quiet --cached HEAD")[1] == 0
end
def tag_version
sh "git tag -m \"Version #{version}\" #{version_tag}"
Bundler.ui.confirm "Tagged #{version_tag}."
yield if block_given?
rescue
Bundler.ui.error "Untagging #{version_tag} due to error."
sh_with_code "git tag -d #{version_tag}"
raise
end
def version
gemspec.version
end
def version_tag
"v#{version}"
end
def name
gemspec.name
end
def sh(cmd, &block)
out, code = sh_with_code(cmd, &block)
unless code.zero?
raise(out.empty? ? "Running `#{cmd}` failed. Run this command directly for more detailed output." : out)
end
out
end
def sh_with_code(cmd, &block)
cmd += " 2>&1"
outbuf = String.new
Bundler.ui.debug(cmd)
SharedHelpers.chdir(base) do
outbuf = `#{cmd}`
status = $?.exitstatus
block.call(outbuf) if status.zero? && block
[outbuf, status]
end
end
def gem_key
Bundler.settings["gem.push_key"].to_s.downcase if Bundler.settings["gem.push_key"]
end
def gem_push?
!%w[n no nil false off 0].include?(ENV["gem_push"].to_s.downcase)
end
end
end
| 29.576355 | 148 | 0.624584 |
8752592f21b91cea65ca5f2b81d9fc55bb1a0ebd | 290 | # frozen_string_literal: true
RSpec.describe StoryKey::Generator do
subject(:call) { described_class.new(bitsize:, format:).call }
let(:bitsize) { StoryKey::DEFAULT_BITSIZE }
let(:format) { :bin }
it 'generates a binary string' do
expect(call).to match(/[01]{256}/)
end
end
| 24.166667 | 64 | 0.696552 |
18cff8f880ff42095de46c0f9e1462735401666a | 246 | # frozen_string_literal: true
require 'spec_helper'
describe 'profile::database_server' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
it { is_expected.to compile }
end
end
end
| 17.571429 | 40 | 0.674797 |
b9a0f3b5e3c9bc35a2c4ac9fc453213384c5abb0 | 3,969 | module Console::ModelHelper
def gear_group_states(states)
return states[0].to_s.humanize if states.uniq.length == 1
"#{states.count{ |s| s == :started }}/#{states.length} started"
end
def gear_group_state(states)
css_class = if states.all? {|s| s == :started}
'state_started'
elsif states.none? {|s| s == :started}
'state_stopped'
end
content_tag(:span, gear_group_states(states), :class => css_class)
end
def gear_group_count(gears)
types = gears.inject({}){ |h,g| h[g.gear_profile.to_s] ||= 0; h[g.gear_profile.to_s] += 1; h }
return 'None' if types.empty?
types.keys.sort.map do |k|
"#{types[k]} #{k.humanize.downcase}"
end.to_sentence
end
def web_cartridge_scale_title(cartridge)
if cartridge.current_scale == cartridge.scales_from
'Your web cartridge is running on the minimum amount of gears and will scale up if needed'
elsif cartridge.current_scale == cartridge.scales_to
'Your web cartridge is running on the maximum amount of gears and cannot scale up any further'
else
'Your web cartridge is running multiple copies to handle increased web traffic'
end
end
def cartridge_gear_group_count(group)
return 'None' if group.gears.empty?
"#{group.gears.length} #{group.gear_profile.to_s.humanize.downcase}"
end
def gear_group_count_title(total_gears)
"OpenShift runs each cartridge inside one or more gears on a server and is allocated a fixed portion of CPU time and memory use."
end
def cartridge_storage(cart)
storage_string(cart.total_storage)
end
def scaled_cartridge_storage(cart)
storage_string(cart.total_storage, cart.current_scale)
end
def storage_string(quota,multiplier = 0)
parts = []
if multiplier > 1
parts << "#{multiplier} x"
end
parts << "%s GB" % quota
parts.join(' ').strip
end
def scale_range(from, to, max, max_choices)
limit = to == -1 ? max : to
return if limit > max_choices
(from .. limit).map{ |i| [i.to_s, i] }
end
def scale_from_options(obj, max, max_choices=20)
if range = scale_range(obj.supported_scales_from, obj.supported_scales_to, max, max_choices)
{:as => :select, :collection => range, :include_blank => false}
else
{:as => :string}
end
end
def scale_to_options(obj, max, max_choices=20)
if range = scale_range(obj.supported_scales_from, obj.supported_scales_to, max, max_choices)
range << ['All available', -1] if obj.supported_scales_to == -1
{:as => :select, :collection => range, :include_blank => false}
else
{:as => :string, :hint => 'Use -1 to scale to your current account limits'}
end
end
def storage_options(min,max)
{:as => :select, :collection => (min..max), :include_blank => false}
end
def scale_options
[['No scaling',false],['Scale with web traffic',true]]
end
def can_scale_application_type(type, capabilities)
type.scalable? and capabilities.gears_free >= 2
end
def cannot_scale_title(type, capabilities)
unless can_scale_application_type(type, capabilities)
if type.scalable?
"You need at least two free gears to create a scaling application; you are currently using #{capabilities.consumed_gears} out of #{capabilities.max_gears}."
else
"This application shares resources and can't be scaled."
end
end
end
def in_groups_by_tag(ary, tags)
groups = {}
other = ary.reject do |t|
tags.any? do |tag|
(groups[tag] ||= []) << t if t.tags.include?(tag)
end
end
groups = tags.map do |tag|
types = groups[tag]
if types
if types.length < 2
other.concat(types)
nil
else
[tag, types]
end
end
end.compact
[groups, other]
end
def common_tags_for(ary)
ary.length < 2 ? [] : ary.inject(nil){ |tags, a| tags ? (a.tags & tags) : a.tags } || []
end
end
| 31.007813 | 164 | 0.657848 |
6a6c2bcb30a47b83c77754ac5a48df8be463fb89 | 5,756 | require 'spec_helper'
describe GroupsController do
before do
Feature.activate(:collaborator_groups)
end
describe 'GET #index' do
let(:group1) { create(:group) }
let(:group2) { create(:group) }
before do
expect(Group.all).to include(group1, group2)
end
it 'assigns groups' do
get :index
expect(assigns(:groups)).to include(group1, group2)
end
it 'renders the json format when requested' do
get :index, format: :json
expect(response).to be_success
end
context 'when passing a query string' do
let(:a_group) { create(:group, name: 'a-group') }
let(:b_group) { create(:group, name: 'b-group') }
let(:c_group) { create(:group, name: 'c-group') }
before do
expect(Group.all).to include(a_group, b_group, c_group)
end
it 'returns groups only matching the query string' do
get :index, params: { q: 'a', format: :json }
group = assigns(:groups)
expect(group.count(:all)).to eq(1)
end
end
end
describe 'GET #new' do
it 'makes a new record' do
get :new
expect(assigns(:group)).to be_new_record
end
it 'renders the new template' do
get :new
expect(response).to render_template('new')
end
end
describe 'POST #create' do
let(:user) { create(:user) }
before do
allow(controller).to receive(:current_user).and_return(user)
end
context 'with valid input' do
let(:group_input) do
{ name: 'My Group' }
end
context 'when the groups feature is not active' do
before do
Feature.deactivate(:collaborator_groups)
expect(Feature.active?(:collaborator_groups)).to eq(false)
end
it 'does not save the new group to the database' do
expect { post :create, params: { group: group_input } }.to change(Group, :count).by(0)
end
end
context 'when the groups feature is active' do
before do
expect(Feature.active?(:collaborator_groups)).to eq(true)
end
it 'saves the new group to the database' do
expect { post :create, params: { group: group_input } }.to change(Group, :count).by(1)
end
context 'after the save' do
let(:group) { create(:group) }
before do
allow(Group).to receive(:new).and_return(group)
allow(group).to receive(:save).and_return(true)
end
it 'shows a success message' do
post :create, params: { group: group_input }
expect(flash[:notice]).to include('Group successfully created!')
end
it 'rendirects to the group show template' do
post :create, params: { group: group_input }
expect(response).to redirect_to(group_path(assigns[:group]))
end
context 'group members' do
it 'adds the creating user as a member' do
post :create, params: { group: group_input }
expect(Group.last.members).to include(user)
end
it 'sets the creating user as an admin member' do
post :create, params: { group: group_input }
expect(GroupMember.last.admin).to eq(true)
end
end
end
end
context 'with invalid input' do
let(:group_input) do
{ name: '' }
end
it 'does not save the group to the database' do
expect { post :create, params: { group: group_input } }.to change(Group, :count).by(0)
end
context 'after the save' do
let(:group) { create(:group) }
before do
allow(Group).to receive(:new).and_return(group)
allow(group).to receive(:save).and_return(false)
end
it 'shows an error' do
post :create, params: { group: group_input }
expect(flash[:warning]).to include('An error has occurred')
end
it 'redirects to the new group template' do
post :create, params: { group: group_input }
expect(response).to redirect_to(new_group_path)
end
end
end
end
end
describe 'GET #show' do
let(:group) { create(:group) }
let(:user) { create(:user) }
let!(:member) do
create(:group_member, user: user, group: group)
end
let(:admin_user) { create(:user) }
let!(:admin_member) do
create(:admin_group_member, user: admin_user, group: group)
end
before do
expect(group.members).to include(user)
end
it 'finds the correct group' do
get :show, params: { id: group }
expect(assigns(:group)).to eq(group)
end
context 'listing admins' do
before do
expect(group.members).to include(admin_user)
expect(admin_member.admin).to eq(true)
end
it 'includes users who are admins' do
get :show, params: { id: group }
expect(assigns(:admin_members)).to include(admin_member)
end
it 'does not include users who are not admins' do
get :show, params: { id: group }
expect(assigns(:admin_members)).to_not include(user)
end
end
context 'listing group members' do
it 'includes users who are members' do
get :show, params: { id: group }
expect(assigns(:members)).to include(member)
end
it 'does not include admin members' do
get :show, params: { id: group }
expect(assigns(:members)).to_not include(admin_member)
end
end
it 'renders the group show template' do
get :show, params: { id: group }
expect(response).to render_template('show')
end
end
end
| 27.150943 | 96 | 0.587735 |
e81437da002d9a8ef4485087ef963d098c41cc84 | 1,803 | # frozen_string_literal: true
module Solargraph
# The namespace for pins used in maps.
#
module Pin
autoload :Common, 'solargraph/pin/common'
autoload :Conversions, 'solargraph/pin/conversions'
autoload :Base, 'solargraph/pin/base'
autoload :BaseMethod, 'solargraph/pin/base_method'
autoload :Method, 'solargraph/pin/method'
autoload :MethodAlias, 'solargraph/pin/method_alias'
autoload :Attribute, 'solargraph/pin/attribute'
autoload :BaseVariable, 'solargraph/pin/base_variable'
autoload :InstanceVariable, 'solargraph/pin/instance_variable'
autoload :ClassVariable, 'solargraph/pin/class_variable'
autoload :LocalVariable, 'solargraph/pin/local_variable'
autoload :GlobalVariable, 'solargraph/pin/global_variable'
autoload :Constant, 'solargraph/pin/constant'
autoload :Symbol, 'solargraph/pin/symbol'
autoload :Closure, 'solargraph/pin/closure'
autoload :Namespace, 'solargraph/pin/namespace'
autoload :Keyword, 'solargraph/pin/keyword'
autoload :Parameter, 'solargraph/pin/parameter'
autoload :Reference, 'solargraph/pin/reference'
autoload :Documenting, 'solargraph/pin/documenting'
autoload :Block, 'solargraph/pin/block'
autoload :Localized, 'solargraph/pin/localized'
autoload :ProxyType, 'solargraph/pin/proxy_type'
autoload :DuckMethod, 'solargraph/pin/duck_method'
autoload :YardPin, 'solargraph/pin/yard_pin'
autoload :Singleton, 'solargraph/pin/singleton'
autoload :KeywordParam, 'solargraph/pin/keyword_param'
ROOT_PIN = Pin::Namespace.new(type: :class, name: '', closure: nil)
end
end
| 47.447368 | 71 | 0.672768 |
871091044764c8639a7b23af4e17e067140d8b67 | 453 | require 'stylus'
require 'stylus/tilt'
module Middleman
module Renderers
# Sass renderer
module Stylus
# Setup extension
class << self
# Once registered
def registered(app)
# Default less options
app.set :styl, {}
app.before_configuration do
template_extensions :styl => :css
end
end
alias :included :registered
end
end
end
end
| 15.62069 | 45 | 0.567329 |
0110f8a4f34fb683e362cafb4ddb8e6d0a08628b | 208 | desc 'qlvideo' do
latest = github('Marginal', 'QLVideo').first
version = latest.name.gsub(/Release/, '').strip
url = latest.assets.first.browser_download_url
Latest.new version: version, url: url
end
| 29.714286 | 49 | 0.721154 |
e200835053d6372492ffdfd7d70051e14bdd1847 | 248 | # frozen_string_literal: true
module ActsAsTaggableOnMongoid
module Models
# A class representing all tags that have ever been set on a model.
class Tag
include ActsAsTaggableOnMongoid::Models::Concerns::TagModel
end
end
end
| 22.545455 | 71 | 0.754032 |
4a49e05aed5d2026b44bfa5043c726888acb095d | 2,066 | # frozen_string_literal: true
require 'test_helper'
class TimelinesControllerTest < ActionDispatch::IntegrationTest
setup do
@timeline = timelines(:timeline_1)
@user = users(:users_1)
sign_in @user
end
test 'should get index' do
get timelines_url
assert_response :success
end
test 'should get new' do
get new_timeline_url
assert_response :success
end
test 'should create timeline' do
assert_difference('Timeline.count') do
post timelines_url,
params: { timeline: { description: @timeline.description, name: @timeline.name, user_id: @user.id } }
end
assert_redirected_to timeline_url(Timeline.last)
end
test 'should not create timeline' do
assert_difference('Timeline.count', 0) do
post timelines_url, params: { timeline: { description: @timeline.description, name: '' } }
end
assert_response :success
end
test 'should show timeline' do
get timeline_url(@timeline)
assert_response :success
end
test 'should map timeline' do
get geo_map_timeline_url(@timeline)
assert_response :success
end
test 'should show timeline timeline' do
get timeline_timeline_url(timeline_id: @timeline.id)
assert_response :success
end
test 'should show timeline events' do
get timeline_display_url(@timeline)
assert_response :success
end
test 'should get edit' do
get edit_timeline_url(@timeline)
assert_response :success
end
test 'should update timeline' do
patch timeline_url(@timeline),
params: { timeline: { description: @timeline.description, name: @timeline.name, user_id: @user.id } }
assert_redirected_to timeline_url(@timeline)
end
test 'should not update timeline' do
patch timeline_url(@timeline), params: { timeline: { description: @timeline.description, name: '' } }
assert_response :success
end
test 'should destroy timeline' do
assert_difference('Timeline.count', -1) do
delete timeline_url(@timeline)
end
assert_redirected_to timelines_url
end
end
| 25.195122 | 112 | 0.712972 |
acaff90e6f831b2ebec85fb1fdd4512a150ab71d | 32 | module PortfolioNamesHelper
end
| 10.666667 | 27 | 0.90625 |
288b64fee74201a353f1069ba00d7adf9149e3fe | 4,208 | module ApiaiResponses
def simple_apiai_response
{
id: "93ae6b04-9f27-496d-a135-1863384fad4c",
timestamp: "2017-09-27T19:14:04.693Z",
lang: "it",
result: {
source: "agent",
resolvedQuery: "ciao!",
action: "input.welcome",
actionIncomplete: false,
parameters: {},
contexts: [],
metadata: {
intentId: "bbb7cc04-07e4-4a4c-9609-777a50246962",
webhookUsed: "false",
webhookForSlotFillingUsed: "false",
intentName: "Default Welcome Intent"
},
fulfillment: {
speech: "Cià",
messages: [
{
type: 0,
speech: "Buongiorno"
}
]
},
score: 0.47999998927116394
},
status: {
code: 200,
errorType: "success"
},
sessionId: "63117d74-0a53-4083-b6d3-841658f8ae4b"
}
end
def weather_apiai_response
{
id: "2557adc1-d773-41d9-bffa-7ca73fdc14f9",
timestamp: "2017-09-27T19:23:45.605Z",
lang: "it",
result: {
source: "agent",
resolvedQuery: "che tempo fa domani a Fano?",
action: "weather",
actionIncomplete: false,
parameters: {
address: {
city: "Fano"
},
:"date-time"=>"2017-09-28"
},
contexts: [
{
name: "weather",
parameters: {
:"date-time.original"=>"domani",
address: {
city: "Fano",
:"city.original"=>"Fano"
},
:"date-time"=>"2017-09-28",
:"address.original"=>"Fano"
},
lifespan: 2
}
],
metadata: {
intentId: "f1b75ecb-a35f-4a26-88fb-5a8049b92b02",
webhookUsed: "false",
webhookForSlotFillingUsed: "false",
intentName: "weather"
},
fulfillment: {
speech: "",
messages: [
{
type: 0,
speech: ""
}
]
},
score: 0.9599999785423279
},
status: {
code: 200,
errorType: "success"
},
sessionId: "e49c9861-befb-4c57-9f95-26c72422ff4a"
}
end
def web_query_apiai_response
{
id: "101ae06a-afa9-4d10-889d-c6a5d1196193",
timestamp: "2017-09-27T19:31:24.881Z",
lang: "it",
result: {
source: "agent",
resolvedQuery: "cerca fanolug",
action: "web_query",
actionIncomplete: false,
parameters: {
query: "fanolug"
},
contexts: [],
metadata: {
intentId: "c0eb4973-d656-4aeb-b0cf-a70bc429f19a",
webhookUsed: "false",
webhookForSlotFillingUsed: "false",
intentName: "web search"
},
fulfillment: {
speech: "",
messages: [
{
type: 0,
speech: ""
}
]
},
score: 1.0
},
status: {
code: 200,
errorType: "success"
},
sessionId: "a611afa8-e989-42f1-adb4-0e6dd8f24dd4"
}
end
def comparison_apiai_response(subjects: ["linux", "windows"])
{
id: "48b50c0e-dc20-43b9-b152-b6698768a96f",
timestamp: "2017-09-27T19:44:59.986Z",
lang: "it",
result: {
source: "agent",
resolvedQuery: "è meglio linux o windows?",
action: "comparison",
actionIncomplete: false,
parameters: {
subjects: subjects
},
contexts: [],
metadata: {
intentId: "66da1a59-58b5-4db1-978f-6188beb15779",
webhookUsed: "false",
webhookForSlotFillingUsed: "false",
intentName: "Comparison"
},
fulfillment: {
speech: "",
messages: [
{
type: 0,
speech: ""
}
]
},
score: 0.8500000238418579
},
status: {
code: 200,
errorType: "success"
},
sessionId: "d6c995c3-80cb-47c1-967f-f2537893fb52"
}
end
end
| 24.323699 | 63 | 0.469582 |
bf82037007b5d1bb8054ea2f4c0b15f2632ab7d8 | 13,521 | =begin
#OpenAPI Extension with dynamic servers
#This specification shows how to use dynamic servers.
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: unset
=end
require 'date'
require 'json'
require 'logger'
require 'tempfile'
require 'time'
require 'typhoeus'
module DynamicServers
class ApiClient
# The Configuration object holding settings to be used in the API client.
attr_accessor :config
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Initializes the ApiClient
# @option config [Configuration] Configuration for initializing the object, default to Configuration.default
def initialize(config = Configuration.default)
@config = config
@user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
@default_headers = {
'Content-Type' => 'application/json',
'User-Agent' => @user_agent
}
end
def self.default
@@default ||= ApiClient.new
end
# Call an API with given options.
#
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.timed_out?
fail ApiError.new('Connection timed out')
elsif response.code == 0
# Errors from libcurl will be made visible here
fail ApiError.new(:code => 0,
:message => response.return_message)
else
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
response.status_message
end
end
if opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.code, response.headers
end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, opts = {})
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
# set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
_verify_ssl_host = @config.verify_ssl_host ? 2 : 0
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:ssl_verifypeer => @config.verify_ssl,
:ssl_verifyhost => _verify_ssl_host,
:sslcert => @config.cert_file,
:sslkey => @config.key_file,
:verbose => @config.debugging
}
# set custom cert, if provided
req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update :body => req_body
if @config.debugging
@config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
request = Typhoeus::Request.new(url, req_opts)
download_file(request) if opts[:return_type] == 'File'
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
header_params['Content-Type'] == 'multipart/form-data'
data = {}
form_params.each do |key, value|
case value
when ::File, ::Array, nil
# let typhoeus handle File, Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
# The response body is written to the file in chunks in order to handle files which
# size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
# process can use.
#
# @see Configuration#temp_folder_path
def download_file(request)
tempfile = nil
encoding = nil
request.on_headers do |response|
content_disposition = response.headers['Content-Disposition']
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
prefix = sanitize_filename(filename)
else
prefix = 'download-'
end
prefix = prefix + '-' unless prefix.end_with?('-')
encoding = response.body.encoding
tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
@tempfile = tempfile
end
request.on_body do |chunk|
chunk.force_encoding(encoding)
tempfile.write(chunk)
end
request.on_complete do |response|
if tempfile
tempfile.close
@config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
"with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
"will be deleted automatically with GC. It's also recommended to delete the temp file "\
"explicitly with `tempfile.delete`"
end
end
end
# Check if the given MIME is a JSON MIME.
# JSON MIME examples:
# application/json
# application/json; charset=UTF8
# APPLICATION/JSON
# */*
# @param [String] mime MIME
# @return [Boolean] True if the MIME is application/json
def json_mime?(mime)
(mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end
# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date Time).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular type
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'Boolean'
data == true
when 'Time'
# parse date time (expecting ISO 8601 format)
Time.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object (usually a Hash), return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map { |item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models (e.g. Pet) or oneOf
klass = DynamicServers.const_get(return_type)
klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
end
end
# Sanitize filename by removing path.
# e.g. ../../sun.gif becomes sun.gif
#
# @param [String] filename the filename to be sanitized
# @return [String] the sanitized filename
def sanitize_filename(filename)
filename.gsub(/.*[\/\\]/, '')
end
def build_request_url(path, opts = {})
# Add leading and trailing slashes to path
path = "/#{path}".gsub(/\/+/, '/')
@config.base_url(opts[:operation]) + path
end
# Update hearder and query params based on authentication settings.
#
# @param [Hash] header_params Header parameters
# @param [Hash] query_params Query parameters
# @param [String] auth_names Authentication scheme name
def update_params_for_auth!(header_params, query_params, auth_names)
Array(auth_names).each do |auth_name|
auth_setting = @config.auth_settings[auth_name]
next unless auth_setting
case auth_setting[:in]
when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
else fail ArgumentError, 'Authentication token must be in `query` or `header`'
end
end
end
# Sets user agent in HTTP header
#
# @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
return nil if accepts.nil? || accepts.empty?
# use JSON when present, otherwise use all of the provided
json_accept = accepts.find { |s| json_mime?(s) }
json_accept || accepts.join(',')
end
# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
# use application/json by default
return 'application/json' if content_types.nil? || content_types.empty?
# use JSON when present, otherwise use the first one
json_content_type = content_types.find { |s| json_mime?(s) }
json_content_type || content_types.first
end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
# Build parameter value according to the given collection format.
# @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
def build_collection_param(param, collection_format)
case collection_format
when :csv
param.join(',')
when :ssv
param.join(' ')
when :tsv
param.join("\t")
when :pipes
param.join('|')
when :multi
# return the array directly as typhoeus will handle it as expected
param
else
fail "unknown collection format: #{collection_format.inspect}"
end
end
end
end
| 34.669231 | 118 | 0.632128 |
f755b0ad2edb65347888a5ebe35599a7678c1a13 | 11,030 | require 'fluent/plugin/output'
require 'fluent/timezone'
require 'fog/openstack'
require 'zlib'
require 'time'
require 'tempfile'
require 'open3'
module Fluent::Plugin
class SwiftOutput < Output
Fluent::Plugin.register_output('swift', self)
helpers :compat_parameters, :formatter, :inject
def initialize
super
@uuid_flush_enabled = false
end
desc "Path prefix of the files on Swift"
config_param :path, :string, :default => ""
# openstack auth
desc "Authentication URL. set a value or `#{ENV['OS_AUTH_URL']}`"
config_param :auth_url, :string
desc "Authentication User Name. if you use TempAuth, auth_user is ACCOUNT:USER .set a value or `#{ENV['OS_USERNAME']}`"
config_param :auth_user, :string
desc "Authentication Key (Password). set a value or `#{ENV['OS_PASSWORD']}`"
config_param :auth_api_key, :string
# identity v2
config_param :auth_tenant, :string, default: nil
# identity v3
desc "Authentication Project. set a value or `#{ENV['OS_PROJECT_NAME']}`"
config_param :project_name, :string, default: nil
desc "Authentication Domain. set a value or `#{ENV['OS_PROJECT_DOMAIN_NAME']}`"
config_param :domain_name, :string, default: nil
desc "Authentication Region. Optional, not required if there is only one region available. set a value or `#{ENV['OS_REGION_NAME']}`"
config_param :auth_region, :string, default: nil
config_param :swift_account, :string, default: nil
desc "Swift container name"
config_param :swift_container, :string
desc "Archive format on Swift"
config_param :store_as, :string, :default => "gzip"
desc "If false, the certificate of endpoint will not be verified"
config_param :ssl_verify, :bool, :default => true
desc "The format of Swift object keys"
config_param :swift_object_key_format, :string, :default => "%{path}%{time_slice}_%{index}.%{file_extension}"
desc "Create Swift container if it does not exists"
config_param :auto_create_container, :bool, :default => true
config_param :check_apikey_on_start, :bool, :default => true
desc "URI of proxy environment"
config_param :proxy_uri, :string, :default => nil
desc "The length of `%{hex_random}` placeholder(4-16)"
config_param :hex_random_length, :integer, default: 4
desc "`sprintf` format for `%{index}`"
config_param :index_format, :string, default: "%d"
desc "Overwrite already existing path"
config_param :overwrite, :bool, default: false
DEFAULT_FORMAT_TYPE = "out_file"
config_section :format do
config_set_default :@type, DEFAULT_FORMAT_TYPE
end
config_section :buffer do
config_set_default :chunk_keys, ['time']
config_set_default :timekey, (60 * 60 * 24)
end
# attr_reader :storage
MAX_HEX_RANDOM_LENGTH = 16
def configure(conf)
compat_parameters_convert(conf, :buffer, :formatter, :inject)
super
if @auth_url.empty?
raise Fluent::ConfigError, "auth_url parameter or OS_AUTH_URL variable not defined"
end
if @auth_user.empty?
raise Fluent::ConfigError, "auth_user parameter or OS_USERNAME variable not defined"
end
if @auth_api_key.empty?
raise Fluent::ConfigError, "auth_api_key parameter or OS_PASSWORD variable not defined"
end
if @project_name.empty?
raise Fluent::ConfigError, "project_name parameter or OS_PROJECT_NAME variable not defined"
end
if @domain_name.empty?
raise Fluent::ConfigError, "domain_name parameter or OS_PROJECT_DOMAIN_NAME variable not defined"
end
@ext, @mime_type = case @store_as
when 'gzip' then ['gz', 'application/x-gzip']
when 'lzo' then
begin
Open3.capture3('lzop -V')
rescue Errno::ENOENT
raise ConfigError, "'lzop' utility must be in PATH for LZO compression"
end
['lzo', 'application/x-lzop']
when 'json' then ['json', 'application/json']
else ['txt', 'text/plain']
end
@formatter = formatter_create
if @hex_random_length > MAX_HEX_RANDOM_LENGTH
raise Fluent::ConfigError, "hex_random_length parameter must be less than or equal to #{MAX_HEX_RANDOM_LENGTH}"
end
unless @index_format =~ /^%(0\d*)?[dxX]$/
raise Fluent::ConfigError, "index_format parameter should follow `%[flags][width]type`. `0` is the only supported flag, and is mandatory if width is specified. `d`, `x` and `X` are supported types"
end
@swift_object_key_format = process_swift_object_key_format
# For backward compatibility
# TODO: Remove time_slice_format when end of support compat_parameters
@configured_time_slice_format = conf['time_slice_format']
@values_for_swift_object_chunk = {}
@time_slice_with_tz = Fluent::Timezone.formatter(@timekey_zone, @configured_time_slice_format || timekey_to_timeformat(@buffer_config['timekey']))
end
def multi_workers_ready?
true
end
def start
Excon.defaults[:ssl_verify_peer] = @ssl_verify
begin
@storage = Fog::OpenStack::Storage.new(openstack_auth_url: @auth_url,
openstack_username: @auth_user,
openstack_project_name: @project_name,
openstack_domain_name: @domain_name,
openstack_api_key: @auth_api_key,
openstack_region: @auth_region)
# rescue Fog::OpenStack::Storage::NotFound
# ignore NoSuchBucket Error because ensure_bucket checks it.
rescue => e
raise "can't call Swift API. Please check your ENV OS_*, your credentials or auth_url configuration. error = #{e.inspect}"
end
@storage.change_account @swift_account if @swift_account
check_container
super
end
def format(tag, time, record)
r = inject_values_to_record(tag, time, record)
@formatter.format(tag, time, r)
end
def write(chunk)
i = 0
metadata = chunk.metadata
previous_path = nil
time_slice = if metadata.timekey.nil?
''.freeze
else
@time_slice_with_tz.call(metadata.timekey)
end
begin
@values_for_swift_object_chunk[chunk.unique_id] ||= {
"%{hex_random}" => hex_random(chunk),
}
values_for_swift_object_key_pre = {
"%{path}" => @path,
"%{file_extension}" => @ext,
}
values_for_swift_object_key_post = {
"%{time_slice}" => time_slice,
"%{index}" => sprintf(@index_format,i),
}.merge!(@values_for_swift_object_chunk[chunk.unique_id])
values_for_swift_object_key_post["%{uuid_flush}".freeze] = uuid_random if @uuid_flush_enabled
swift_path = @swift_object_key_format.gsub(%r(%{[^}]+})) do |matched_key|
values_for_swift_object_key_pre.fetch(matched_key, matched_key)
end
swift_path = extract_placeholders(swift_path, metadata)
swift_path = swift_path.gsub(%r(%{[^}]+}), values_for_swift_object_key_post)
if (i > 0) && (swift_path == previous_path)
if @overwrite
log.warn "#{swift_path} already exists, but will overwrite"
break
else
raise "duplicated path is generated. use %{index} in swift_object_key_format: path = #{swift_path}"
end
end
i += 1
previous_path = swift_path
end while check_object_exists(@swift_container, swift_path)
tmp = Tempfile.new("swift-")
tmp.binmode
begin
if @store_as == "gzip"
w = Zlib::GzipWriter.new(tmp)
chunk.write_to(w)
w.close
elsif @store_as == "lzo"
w = Tempfile.new("chunk-tmp")
chunk.write_to(w)
w.close
tmp.close
# We don't check the return code because we can't recover lzop failure.
system "lzop -qf1 -o #{tmp.path} #{w.path}"
else
chunk.write_to(tmp)
tmp.close
end
File.open(tmp.path) do |file|
@storage.put_object(@swift_container, swift_path, file, {:content_type => @mime_type})
@values_for_swift_object_chunk.delete(chunk.unique_id)
end
# log.debu "out_swift: write chunk #{dump_unique_id_hex(chunk.unique_id)} with metadata #{chunk.metadata} to swift://#{@swift_container}/#{swift_path}"
# $log.info "out_swift: Put Log to Swift. container=#{@swift_container} object=#{swift_path}"
ensure
tmp.close(true) rescue nil
w.close rescue nil
w.unlink rescue nil
end
end
private
def hex_random(chunk)
unique_hex = Fluent::UniqueId.hex(chunk.unique_id)
unique_hex.reverse! # unique_hex is like (time_sec, time_usec, rand) => reversing gives more randomness
unique_hex[0...@hex_random_length]
end
def uuid_random
::UUIDTools::UUID.random_create.to_s
end
# This is stolen from Fluentd
def timekey_to_timeformat(timekey)
case timekey
when nil then ''
when 0...60 then '%Y%m%d%H%M%S' # 60 exclusive
when 60...3600 then '%Y%m%d%H%M'
when 3600...86400 then '%Y%m%d%H'
else '%Y%m%d'
end
end
def check_container
begin
@storage.get_container(@swift_container)
rescue Fog::OpenStack::Storage::NotFound
if @auto_create_container
$log.info "Creating container #{@swift_container} on #{@auth_url}, #{@swift_account}"
@storage.put_container(@swift_container)
else
raise "The specified container does not exist: container = #{swift_container}"
end
end
end
def process_swift_object_key_format
%W(%{uuid} %{uuid:random} %{uuid:hostname} %{uuid:timestamp}).each { |ph|
if @swift_object_key_format.include?(ph)
raise Fluent::ConfigError, %!#{ph} placeholder in swift_object_key_format is removed!
end
}
if @swift_object_key_format.include?('%{uuid_flush}')
# test uuidtools works or not
begin
require 'uuidtools'
rescue LoadError
raise Fluent::ConfigError, "uuidtools gem not found. Install uuidtools gem first"
end
begin
uuid_random
rescue => e
raise Fluent::ConfigError, "Generating uuid doesn't work. Can't use %{uuid_flush} on this environment. #{e}"
end
@uuid_flush_enabled = true
end
@swift_object_key_format.gsub('%{hostname}') { |expr|
log.warn "%{hostname} will be removed in the future. Use \"\#{Socket.gethostname}\" instead"
Socket.gethostname
}
end
def check_object_exists(container, object)
begin
@storage.head_object(container, object)
rescue Fog::OpenStack::Storage::NotFound
return false
end
return true
end
end
end
| 35.352564 | 206 | 0.64379 |
edf3ff93c98762a1ef5763e6873317c262c3c456 | 388 | require 'spec_helper'
describe Order do
describe 'schema' do
it { expect(subject).to have_db_column(:user_name).of_type(:string) }
it { expect(subject).to have_db_column(:user_email).of_type(:string) }
it { expect(subject).to have_db_column(:user_phone).of_type(:string) }
end
describe 'associations' do
it { expect(subject).to have_many(:order_items) }
end
end
| 27.714286 | 74 | 0.716495 |
bf78b900b3ba8d70aede2505b84d82f7f0f8d64d | 13,169 | RSpec.describe Mdm::Workspace, type: :model do
subject(:workspace) do
FactoryBot.build(:mdm_workspace)
end
let(:default) do
'default'
end
it_should_behave_like 'Metasploit::Concern.run'
context 'factory' do
it 'should be valid' do
workspace = FactoryBot.build(:mdm_workspace)
expect(workspace).to be_valid
end
end
context '#destroy' do
it 'should successfully destroy the object and dependent objects' do
workspace = FactoryBot.create(:mdm_workspace)
listener = FactoryBot.create(:mdm_listener, :workspace => workspace)
task = FactoryBot.create(:mdm_task, :workspace => workspace)
expect {
workspace.destroy
}.to_not raise_error
expect {
workspace.reload
}.to raise_error(ActiveRecord::RecordNotFound)
expect {
listener.reload
}.to raise_error(ActiveRecord::RecordNotFound)
expect {
task.reload
}.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'associations' do
it { is_expected.to have_many(:clients).class_name('Mdm::Client').through(:hosts) }
it { is_expected.to have_many(:creds).class_name('Mdm::Cred').through(:services) }
it { is_expected.to have_many(:events).class_name('Mdm::Event') }
it { is_expected.to have_many(:exploited_hosts).class_name('Mdm::ExploitedHost').through(:hosts) }
it { is_expected.to have_many(:hosts).class_name('Mdm::Host') }
it { is_expected.to have_many(:listeners).class_name('Mdm::Listener').dependent(:destroy) }
it { is_expected.to have_many(:loots).class_name('Mdm::Loot').through(:hosts) }
it { is_expected.to have_many(:notes).class_name('Mdm::Note') }
it { is_expected.to belong_to(:owner).class_name('Mdm::User').with_foreign_key('owner_id') }
it { is_expected.to have_many(:services).class_name('Mdm::Service').through(:hosts).with_foreign_key('service_id') }
it { is_expected.to have_many(:sessions).class_name('Mdm::Session').through(:hosts) }
it { is_expected.to have_many(:tasks).class_name('Mdm::Task').dependent(:destroy).order('created_at DESC') }
it { is_expected.to have_and_belong_to_many(:users).class_name('Mdm::User') }
it { is_expected.to have_many(:vulns).class_name('Mdm::Vuln').through(:hosts) }
end
context 'callbacks' do
context 'before_save' do
context '#normalize' do
it 'should be called' do
expect(workspace).to receive(:normalize)
workspace.run_callbacks(:save)
end
end
end
end
context 'columns' do
it { is_expected.to have_db_column(:boundary).of_type(:string).with_options(:limit => 4 * (2 ** 10)) }
it { is_expected.to have_db_column(:description).of_type(:string).with_options(:limit => 4 * (2 ** 10)) }
it { is_expected.to have_db_column(:limit_to_network).of_type(:boolean).with_options(:default => false, :null => false) }
it { is_expected.to have_db_column(:name).of_type(:string) }
it { is_expected.to have_db_column(:owner_id).of_type(:integer) }
context 'timestamps' do
it { is_expected.to have_db_column(:created_at).of_type(:datetime).with_options(:null => false) }
it { is_expected.to have_db_column(:updated_at).of_type(:datetime).with_options(:null => false) }
end
end
context 'CONSTANTS' do
it 'should define the DEFAULT name' do
expect(described_class::DEFAULT).to eq(default)
end
end
context 'validations' do
context 'description' do
it { is_expected.to validate_length_of(:description).is_at_most(4 * (2 ** 10)) }
end
context 'name' do
it { is_expected.to validate_length_of(:name).is_at_most(2**8 - 1) }
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_uniqueness_of :name }
end
end
context 'methods' do
let(:hosts) do
FactoryBot.create_list(:mdm_host, 2, :workspace => workspace)
end
let(:other_hosts) do
FactoryBot.create_list(:mdm_host, 2, :workspace => other_workspace)
end
let(:other_services) do
other_hosts.collect do |host|
FactoryBot.create(:mdm_service, :host => host)
end
end
let(:other_web_sites) do
other_services.collect { |service|
FactoryBot.create(:mdm_web_site, :service => service)
}
end
let(:other_workspace) do
FactoryBot.create(:mdm_workspace)
end
let(:services) do
hosts.collect do |host|
FactoryBot.create(:mdm_service, :host => host)
end
end
let(:web_sites) do
services.collect { |service|
FactoryBot.create(:mdm_web_site, :service => service)
}
end
context '#creds' do
#
# Let!s (let + before(:each))
#
let!(:creds) do
services.collect do |service|
FactoryBot.create(:mdm_cred, :service => service)
end
end
let!(:other_creds) do
other_services.collect do |service|
FactoryBot.create(:mdm_cred, :service => service)
end
end
it 'should be an ActiveRecord::Relation' do
expect(workspace.creds).to be_a ActiveRecord::Relation
end
it 'should include services' do
# to_a to make query return instances
found_creds = workspace.creds.to_a
expect(found_creds.length).to be > 0
expect(
found_creds.none? { |found_cred|
found_cred.service.nil?
}
).to eq(true)
end
it 'should return only Mdm::Creds from hosts in workspace' do
found_creds = workspace.creds
expect(found_creds.length).to eq(creds.length)
expect(
found_creds.all? { |cred|
cred.service.host.workspace == workspace
}
).to eq(true)
end
end
context 'default' do
context 'with default workspace' do
before(:example) do
FactoryBot.create(
:mdm_workspace,
:name => default
)
end
it 'should not create workspace' do
workspace = nil
expect {
workspace = described_class.default
}.to change(Mdm::Workspace, :count).by(0)
expect(workspace).to be_default
end
end
context 'without default workspace' do
it 'should create workspace' do
workspace = nil
expect {
workspace = described_class.default
}.to change(Mdm::Workspace, :count).by(1)
expect(workspace).to be_default
end
end
end
context '#default?' do
subject do
workspace.default?
end
context 'with DEFAULT name' do
before(:example) do
workspace.name = default
end
it { is_expected.to eq(true) }
end
context 'without DEFAULT name' do
it { is_expected.to eq(false) }
end
end
context '#each_cred' do
it 'should pass each of the #creds to the block' do
creds = FactoryBot.create_list(:mdm_cred, 2)
allow(workspace).to receive(:creds).and_return(creds)
expect { |block|
workspace.each_cred(&block)
}.to yield_successive_args(*creds)
end
end
context '#each_host_tag' do
it 'should pass each of the #host_tags to the block' do
tags = FactoryBot.create_list(:mdm_tag, 2)
expect(workspace).to receive(:host_tags).and_return(tags)
expect { |block|
workspace.each_host_tag(&block)
}.to yield_successive_args(*tags)
end
end
context '#host_tags' do
let(:host_tags) do
workspace.host_tags
end
#
# lets
#
let(:other_tags) do
FactoryBot.create_list(
:mdm_tag,
2
)
end
let(:tags) do
FactoryBot.create_list(
:mdm_tag,
2
)
end
#
# Let!s (let + before(:each))
#
let!(:first_host_tags) do
host_tags = []
hosts.zip(tags) do |host, tag|
host_tag = FactoryBot.create(:mdm_host_tag, :host => host, :tag => tag)
host_tags << host_tag
end
host_tags
end
let!(:second_host_tags) do
host_tags = []
other_hosts.zip(other_tags) do |host, tag|
host_tag = FactoryBot.create(:mdm_host_tag, :host => host, :tag => tag)
host_tags << host_tag
end
host_tags
end
it 'should return an ActiveRecord::Relation' do
expect(workspace.host_tags).to be_a ActiveRecord::Relation
end
it 'should return only Mdm::Tags from hosts in the workspace' do
expect(host_tags.length).to eq(tags.length)
expect(
host_tags.all? { |tag|
tag.hosts.any? { |host|
host.workspace == workspace
}
}
).to eq(true)
end
end
context '#normalize' do
let(:normalize) do
workspace.send(:normalize)
end
before(:example) do
workspace.boundary = boundary
end
context 'with boundary' do
let(:boundary) do
" #{stripped_boundary} "
end
let(:stripped_boundary) do
'192.168.0.1'
end
it "should remove spaces" do
normalize
expect(workspace.boundary).to eq(stripped_boundary)
end
end
context 'without boundary' do
let(:boundary) do
nil
end
it 'should not raise error' do
expect {
normalize
}.to_not raise_error
end
end
end
context '#web_forms' do
subject do
workspace.web_forms
end
#
# Let!s (let + before(:each))
#
let!(:other_web_forms) do
other_web_sites.collect { |web_site|
FactoryBot.create(:web_form, :web_site => web_site)
}
end
let!(:web_forms) do
web_sites.collect { |web_site|
FactoryBot.create(:web_form, :web_site => web_site)
}
end
it 'should return an ActiveRecord:Relation' do
is_expected.to be_a ActiveRecord::Relation
end
it 'should return only Mdm::WebPages from hosts in the workspace' do
found_web_forms = workspace.web_forms
expect(found_web_forms.length).to eq(web_forms.length)
expect(
found_web_forms.all? { |web_form|
web_form.web_site.service.host.workspace == workspace
}
).to eq(true)
end
end
context '#web_sites' do
subject do
workspace.web_sites
end
#
# Let!s (let + before(:each))
#
before(:example) do
other_web_sites
web_sites
end
it 'should return an ActiveRecord:Relation' do
is_expected.to be_a ActiveRecord::Relation
end
it 'should return only Mdm::WebVulns from hosts in the workspace' do
# there are more web sites than those in the workspace
expect(Mdm::WebSite.count).to be > web_sites.count
found_web_sites = workspace.web_sites
expect(found_web_sites.length).to eq(web_sites.count)
expect(
found_web_sites.all? { |web_site|
web_site.service.host.workspace == workspace
}
).to eq(true)
end
end
context '#web_vulns' do
subject do
workspace.web_vulns
end
#
# Let!s (let + before(:each))
#
let!(:other_web_vulns) do
other_web_sites.collect { |web_site|
FactoryBot.create(:mdm_web_vuln, :web_site => web_site)
}
end
let!(:web_vulns) do
web_sites.collect { |web_site|
FactoryBot.create(:mdm_web_vuln, :web_site => web_site)
}
end
it 'should return an ActiveRecord:Relation' do
is_expected.to be_a ActiveRecord::Relation
end
it 'should return only Mdm::WebVulns from hosts in the workspace' do
expect(Mdm::WebVuln.count).to be > web_vulns.length
found_web_vulns = workspace.web_vulns
expect(found_web_vulns.length).to eq(web_vulns.length)
expect(
found_web_vulns.all? { |web_vuln|
web_vuln.web_site.service.host.workspace == workspace
}
).to eq(true)
end
end
context '#web_unique_forms' do
let(:rejected_address) do
hosts[1].address
end
let(:selected_address) do
hosts[0].address
end
it 'should return an ActiveRecord:Relation',
:pending => 'https://www.pivotaltracker.com/story/show/43219917' do
is_expected.to be_a ActiveRecord::Relation
end
it "should reject #unique_web_forms from host addresses that aren't in addresses" do
web_forms = workspace.web_unique_forms([selected_address])
expect(
web_forms.all? { |web_form|
expect(web_form.web_site.service.host.address.to_s).to eq(selected_address)
}
).to eq(true)
end
end
end
end
| 26.285429 | 125 | 0.601336 |
ed4f54cdcdf486c3c932e3416dc28f3f84a67f03 | 545 | test_name "group should not create existing group"
name = "test-group-#{Time.new.to_i}"
step "ensure the group exists on the target node"
on(agents, puppet_resource('group', name, 'ensure=present'))
step "verify that we don't try and create the existing group"
on(agents, puppet_resource('group', name, 'ensure=present')) do
fail_test "looks like we created the group" if
stdout.include? '/Group[bozo]/ensure: created'
end
step "clean up the system after the test run"
on(agents, puppet_resource('group', name, 'ensure=absent'))
| 34.0625 | 63 | 0.73211 |
4acf27e10ab6d3994a740fcfcff102eb36eb3505 | 2,019 | class Harfbuzz < Formula
desc "OpenType text shaping engine"
homepage "https://github.com/harfbuzz/harfbuzz"
url "https://github.com/harfbuzz/harfbuzz/releases/download/2.6.8/harfbuzz-2.6.8.tar.xz"
sha256 "6648a571a27f186e47094121f0095e1b809e918b3037c630c7f38ffad86e3035"
bottle do
cellar :any
sha256 "895c050d4c7cf989e3fd212e88ab904db5d91900b3e7455ff2f026574923042b" => :catalina
sha256 "2e8462507d2501793c335f4c7aff91dd8d2e38beb060fc416af7d9bf577158a9" => :mojave
sha256 "9ca4eaac80b2db11439e865f977d6b7b330b2bd5ca8f558e23be49acda67b23e" => :high_sierra
sha256 "a00d74acb32149639beba6fab99ae0bb1d19966ea7c12e65a618996cde986f8f" => :x86_64_linux
end
head do
url "https://github.com/behdad/harfbuzz.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "ragel" => :build
end
depends_on "gobject-introspection" => :build
depends_on "pkg-config" => :build
depends_on "cairo"
depends_on "freetype"
depends_on "glib"
depends_on "graphite2"
depends_on "icu4c"
resource "ttf" do
url "https://github.com/behdad/harfbuzz/raw/fc0daafab0336b847ac14682e581a8838f36a0bf/test/shaping/fonts/sha1sum/270b89df543a7e48e206a2d830c0e10e5265c630.ttf"
sha256 "9535d35dab9e002963eef56757c46881f6b3d3b27db24eefcc80929781856c77"
end
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--enable-introspection=yes
--enable-static
--with-cairo=yes
--with-coretext=#{OS.mac? ? "yes" : "no"}
--with-freetype=yes
--with-glib=yes
--with-gobject=yes
--with-graphite2=yes
--with-icu=yes
]
system "./autogen.sh" if build.head?
system "./configure", *args
system "make", "install"
end
test do
resource("ttf").stage do
shape = `echo 'സ്റ്റ്' | #{bin}/hb-shape 270b89df543a7e48e206a2d830c0e10e5265c630.ttf`.chomp
assert_equal "[glyph201=0+1183|U0D4D=0+0]", shape
end
end
end
| 31.546875 | 161 | 0.718177 |
0852eba1c905d34c7a45858fdfeb51c1e8718d67 | 1,205 | module Patterns
# Doctors -> Object
#
# Acts as a single object containing multiple other objects that it manages. (This is an example of the Component pattern, or Object Composition)
class Doctors
# The surgeon object
attr_accessor :surgeon
# The oncologist object
attr_accessor :oncologist
# The general practitioner object
attr_accessor :general_practitioner
# The pediatrician object
attr_accessor :pediatrician
# The list of all of the doctors
attr_accessor :doctors_list
# Initializes the Doctors object and all of its members, then adds those members to the list.
def initialize
@doctors_list = []
@surgeon = Surgeon.new
@oncologist = Oncologist.new(surgeon)
@general_practitioner = GeneralPractitioner.new(oncologist)
@pediatrician = Pediatrician.new(general_practitioner)
@doctors_list << @surgeon
@doctors_list << @oncologist
@doctors_list << @general_practitioner
@doctors_list << @pediatrician
end
# Starts the chain of responsibility by having the pediatrician see the first patient
def see_patient(patient)
@pediatrician.see_patient(patient)
end
end
end | 32.567568 | 147 | 0.718672 |
4a4800863562674d15560d69857188e0a13fcfc3 | 283 | cask 'terraform-0.13.2' do
version '0.13.2'
sha256 '7af2f9c03e8687c87e7798178a2dac9a3061955eb19f0f69501475e017b8d8f6'
url "https://releases.hashicorp.com/terraform/#{version}/terraform_#{version}_darwin_amd64.zip"
name 'Terraform'
homepage 'https://www.terraform.io/'
end
| 31.444444 | 97 | 0.777385 |
ac7393337a3be6bc0c6356cfa4894a8ba74e5b54 | 33 | require "middleman-critical_css"
| 16.5 | 32 | 0.848485 |
08d1d88fcdafecc3148ef5450ed5cd05db212633 | 53,901 | # frozen_string_literal: true
require('spec_helper')
RSpec.describe ProjectsController do
include ExternalAuthorizationServiceHelpers
include ProjectForksHelper
using RSpec::Parameterized::TableSyntax
let_it_be(:project, reload: true) { create(:project, :with_export, service_desk_enabled: false) }
let_it_be(:public_project) { create(:project, :public) }
let_it_be(:user) { create(:user) }
let(:jpg) { fixture_file_upload('spec/fixtures/rails_sample.jpg', 'image/jpg') }
let(:txt) { fixture_file_upload('spec/fixtures/doc_sample.txt', 'text/plain') }
describe 'GET new' do
context 'with an authenticated user' do
let_it_be(:group) { create(:group) }
before do
sign_in(user)
end
context 'when namespace_id param is present' do
context 'when user has access to the namespace' do
it 'renders the template' do
group.add_owner(user)
get :new, params: { namespace_id: group.id }
expect(response).to have_gitlab_http_status(:ok)
expect(response).to render_template('new')
end
end
context 'when user does not have access to the namespace' do
it 'responds with status 404' do
get :new, params: { namespace_id: group.id }
expect(response).to have_gitlab_http_status(:not_found)
expect(response).not_to render_template('new')
end
end
end
end
end
describe 'GET index' do
context 'as a user' do
it 'redirects to root page' do
sign_in(user)
get :index
expect(response).to redirect_to(root_path)
end
end
context 'as a guest' do
it 'redirects to Explore page' do
get :index
expect(response).to redirect_to(explore_root_path)
end
end
end
describe "GET #activity as JSON" do
include DesignManagementTestHelpers
render_views
let_it_be(:project) { create(:project, :public, issues_access_level: ProjectFeature::PRIVATE) }
before do
enable_design_management
create(:event, :created, project: project, target: create(:issue))
sign_in(user)
request.cookies[:event_filter] = 'all'
end
context 'when user has permission to see the event' do
before do
project.add_developer(user)
end
def get_activity(project)
get :activity, params: { namespace_id: project.namespace, id: project, format: :json }
end
it 'returns count' do
get_activity(project)
expect(json_response['count']).to eq(1)
end
context 'design events are visible' do
include DesignManagementTestHelpers
let(:other_project) { create(:project, namespace: user.namespace) }
before do
enable_design_management
create(:design_event, project: project)
request.cookies[:event_filter] = EventFilter::DESIGNS
end
it 'returns correct count' do
get_activity(project)
expect(json_response['count']).to eq(1)
end
end
end
context 'when user has no permission to see the event' do
it 'filters out invisible event' do
get :activity, params: { namespace_id: project.namespace, id: project, format: :json }
expect(json_response['html']).to eq("\n")
expect(json_response['count']).to eq(0)
end
end
end
describe "GET show" do
context "user not project member" do
before do
sign_in(user)
end
context "user does not have access to project" do
let(:private_project) { create(:project, :private) }
it "does not initialize notification setting" do
get :show, params: { namespace_id: private_project.namespace, id: private_project }
expect(assigns(:notification_setting)).to be_nil
end
end
context "user has access to project" do
before do
expect(::Gitlab::GitalyClient).to receive(:allow_ref_name_caching).and_call_original
end
context "and does not have notification setting" do
it "initializes notification as disabled" do
get :show, params: { namespace_id: public_project.namespace, id: public_project }
expect(assigns(:notification_setting).level).to eq("global")
end
end
context "and has notification setting" do
before do
setting = user.notification_settings_for(public_project)
setting.level = :watch
setting.save!
end
it "shows current notification setting" do
get :show, params: { namespace_id: public_project.namespace, id: public_project }
expect(assigns(:notification_setting).level).to eq("watch")
end
end
end
describe "when project repository is disabled" do
render_views
before do
project.add_developer(user)
project.project_feature.update_attribute(:repository_access_level, ProjectFeature::DISABLED)
end
it 'shows wiki homepage' do
get :show, params: { namespace_id: project.namespace, id: project }
expect(response).to render_template('projects/_wiki')
end
it 'shows issues list page if wiki is disabled' do
project.project_feature.update_attribute(:wiki_access_level, ProjectFeature::DISABLED)
create(:issue, project: project)
get :show, params: { namespace_id: project.namespace, id: project }
expect(response).to render_template('projects/issues/_issues')
expect(assigns(:issuable_meta_data)).not_to be_nil
end
it 'shows activity page if wiki and issues are disabled' do
project.project_feature.update_attribute(:wiki_access_level, ProjectFeature::DISABLED)
project.project_feature.update_attribute(:issues_access_level, ProjectFeature::DISABLED)
get :show, params: { namespace_id: project.namespace, id: project }
expect(response).to render_template("projects/_activity")
end
it 'shows activity if enabled by user' do
user.update_attribute(:project_view, 'activity')
get :show, params: { namespace_id: project.namespace, id: project }
expect(response).to render_template("projects/_activity")
end
end
end
context "project with empty repo" do
let_it_be(:empty_project) { create(:project_empty_repo, :public) }
before do
sign_in(user)
end
User.project_views.keys.each do |project_view|
context "with #{project_view} view set" do
before do
user.update!(project_view: project_view)
get :show, params: { namespace_id: empty_project.namespace, id: empty_project }
end
it "renders the empty project view" do
expect(response).to render_template('empty')
end
end
end
end
context "project with broken repo" do
let_it_be(:empty_project) { create(:project_broken_repo, :public) }
before do
sign_in(user)
end
User.project_views.keys.each do |project_view|
context "with #{project_view} view set" do
before do
user.update!(project_view: project_view)
get :show, params: { namespace_id: empty_project.namespace, id: empty_project }
end
it "renders the empty project view" do
allow(Project).to receive(:repo).and_raise(Gitlab::Git::Repository::NoRepository)
expect(response).to render_template('projects/no_repo')
end
end
end
end
context "rendering default project view" do
let_it_be(:public_project) { create(:project, :public, :repository) }
render_views
def get_show
get :show, params: { namespace_id: public_project.namespace, id: public_project }
end
it "renders the activity view" do
allow(controller).to receive(:current_user).and_return(user)
allow(user).to receive(:project_view).and_return('activity')
get_show
expect(response).to render_template('_activity')
end
it "renders the files view" do
allow(controller).to receive(:current_user).and_return(user)
allow(user).to receive(:project_view).and_return('files')
get_show
expect(response).to render_template('_files')
end
it "renders the readme view" do
allow(controller).to receive(:current_user).and_return(user)
allow(user).to receive(:project_view).and_return('readme')
get_show
expect(response).to render_template('_readme')
end
it 'does not make Gitaly requests', :request_store, :clean_gitlab_redis_cache do
# Warm up to populate repository cache
get_show
RequestStore.clear!
expect { get_show }.not_to change { Gitlab::GitalyClient.get_request_count }
end
it "renders files even with invalid license" do
controller.instance_variable_set(:@project, public_project)
expect(public_project.repository).to receive(:license_key).and_return('woozle wuzzle').at_least(:once)
get_show
expect(response).to have_gitlab_http_status(:ok)
expect(response).to render_template('_files')
expect(response.body).to have_content('LICENSE') # would be 'MIT license' if stub not works
end
describe "PUC highlighting" do
render_views
before do
expect(controller).to receive(:find_routable!).and_return(public_project)
end
context "option is enabled" do
it "adds the highlighting class" do
expect(public_project).to receive(:warn_about_potentially_unwanted_characters?).and_return(true)
get_show
expect(response.body).to have_css(".project-highlight-puc")
end
end
context "option is disabled" do
it "doesn't add the highlighting class" do
expect(public_project).to receive(:warn_about_potentially_unwanted_characters?).and_return(false)
get_show
expect(response.body).not_to have_css(".project-highlight-puc")
end
end
end
end
context "when the url contains .atom" do
let(:public_project_with_dot_atom) { build(:project, :public, name: 'my.atom', path: 'my.atom') }
it 'expects an error creating the project' do
expect(public_project_with_dot_atom).not_to be_valid
end
end
context 'when the project is pending deletions' do
it 'renders a 404 error' do
project = create(:project, pending_delete: true)
sign_in(user)
get :show, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'redirection from http://someproject.git' do
where(:user_type, :project_visibility, :expected_redirect) do
:anonymous | :public | :redirect_to_project
:anonymous | :internal | :redirect_to_signup
:anonymous | :private | :redirect_to_signup
:signed_in | :public | :redirect_to_project
:signed_in | :internal | :redirect_to_project
:signed_in | :private | nil
:member | :public | :redirect_to_project
:member | :internal | :redirect_to_project
:member | :private | :redirect_to_project
end
with_them do
let(:redirect_to_signup) { new_user_session_path }
let(:redirect_to_project) { project_path(project) }
let(:expected_status) { expected_redirect ? :found : :not_found }
before do
project.update!(visibility: project_visibility.to_s)
project.team.add_user(user, :guest) if user_type == :member
sign_in(user) unless user_type == :anonymous
end
it 'returns the expected status' do
get :show, params: { namespace_id: project.namespace, id: project }, format: :git
expect(response).to have_gitlab_http_status(expected_status)
expect(response).to redirect_to(send(expected_redirect)) if expected_status == :found
end
end
end
context 'when project is moved and git format is requested' do
let(:old_path) { project.path + 'old' }
before do
project.redirect_routes.create!(path: "#{project.namespace.full_path}/#{old_path}")
project.add_developer(user)
sign_in(user)
end
it 'redirects to new project path' do
get :show, params: { namespace_id: project.namespace, id: old_path }, format: :git
expect(response).to redirect_to(project_path(project, format: :git))
end
end
context 'when the project is forked and has a repository', :request_store do
let(:public_project) { create(:project, :public, :repository) }
let(:other_user) { create(:user) }
render_views
before do
# View the project as a user that does not have any rights
sign_in(other_user)
fork_project(public_project)
end
it 'does not increase the number of queries when the project is forked' do
expected_query = /#{public_project.fork_network.find_forks_in(other_user.namespace).to_sql}/
expect { get(:show, params: { namespace_id: public_project.namespace, id: public_project }) }
.not_to exceed_query_limit(2).for_query(expected_query)
end
end
end
describe 'POST create' do
subject { post :create, params: { project: params } }
before do
sign_in(user)
end
context 'on import' do
let(:params) do
{
path: 'foo',
description: 'bar',
namespace_id: user.namespace.id,
import_url: project.http_url_to_repo
}
end
context 'when import by url is disabled' do
before do
stub_application_setting(import_sources: [])
end
it 'does not create project and reports an error' do
expect { subject }.not_to change { Project.count }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when import by url is enabled' do
before do
stub_application_setting(import_sources: ['git'])
end
it 'creates project' do
expect { subject }.to change { Project.count }
expect(response).to have_gitlab_http_status(:redirect)
end
end
end
context 'with new_project_sast_enabled', :experiment do
let(:params) do
{
path: 'foo',
description: 'bar',
namespace_id: user.namespace.id,
initialize_with_sast: '1'
}
end
it 'tracks an event on project creation' do
expect(experiment(:new_project_sast_enabled)).to track(:created,
property: 'blank',
checked: true,
project: an_instance_of(Project),
namespace: user.namespace
).on_next_instance.with_context(user: user)
post :create, params: { project: params }
end
end
end
describe 'GET edit' do
it 'allows an admin user to access the page', :enable_admin_mode do
sign_in(create(:user, :admin))
get :edit,
params: {
namespace_id: project.namespace.path,
id: project.path
}
expect(response).to have_gitlab_http_status(:ok)
end
it 'sets the badge API endpoint' do
sign_in(user)
project.add_maintainer(user)
get :edit,
params: {
namespace_id: project.namespace.path,
id: project.path
}
expect(assigns(:badge_api_endpoint)).not_to be_nil
end
end
describe 'POST #archive' do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
before do
sign_in(user)
end
context 'for a user with the ability to archive a project' do
before do
group.add_owner(user)
post :archive, params: {
namespace_id: project.namespace.path,
id: project.path
}
end
it 'archives the project' do
expect(project.reload.archived?).to be_truthy
end
it 'redirects to projects path' do
expect(response).to have_gitlab_http_status(:found)
expect(response).to redirect_to(project_path(project))
end
end
context 'for a user that does not have the ability to archive a project' do
before do
project.add_maintainer(user)
post :archive, params: {
namespace_id: project.namespace.path,
id: project.path
}
end
it 'does not archive the project' do
expect(project.reload.archived?).to be_falsey
end
it 'returns 404' do
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
describe 'POST #unarchive' do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, :archived, group: group) }
before do
sign_in(user)
end
context 'for a user with the ability to unarchive a project' do
before do
group.add_owner(user)
post :unarchive, params: {
namespace_id: project.namespace.path,
id: project.path
}
end
it 'unarchives the project' do
expect(project.reload.archived?).to be_falsey
end
it 'redirects to projects path' do
expect(response).to have_gitlab_http_status(:found)
expect(response).to redirect_to(project_path(project))
end
end
context 'for a user that does not have the ability to unarchive a project' do
before do
project.add_maintainer(user)
post :unarchive, params: {
namespace_id: project.namespace.path,
id: project.path
}
end
it 'does not unarchive the project' do
expect(project.reload.archived?).to be_truthy
end
it 'returns 404' do
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
describe '#housekeeping' do
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project, group: group) }
let(:housekeeping) { Repositories::HousekeepingService.new(project) }
context 'when authenticated as owner' do
before do
group.add_owner(user)
sign_in(user)
allow(Repositories::HousekeepingService).to receive(:new).with(project, :gc).and_return(housekeeping)
end
it 'forces a full garbage collection' do
expect(housekeeping).to receive(:execute).once
post :housekeeping,
params: {
namespace_id: project.namespace.path,
id: project.path
}
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when authenticated as developer' do
let(:developer) { create(:user) }
before do
group.add_developer(developer)
end
it 'does not execute housekeeping' do
expect(housekeeping).not_to receive(:execute)
post :housekeeping,
params: {
namespace_id: project.namespace.path,
id: project.path
}
expect(response).to have_gitlab_http_status(:found)
end
end
end
describe "#update", :enable_admin_mode do
render_views
let(:admin) { create(:admin) }
before do
sign_in(admin)
end
shared_examples_for 'updating a project' do
context 'when there is a conflicting project path' do
let(:random_name) { "project-#{SecureRandom.hex(8)}" }
let!(:conflict_project) { create(:project, name: random_name, path: random_name, namespace: project.namespace) }
it 'does not show any references to the conflicting path' do
expect { update_project(path: random_name) }.not_to change { project.reload.path }
expect(response).to have_gitlab_http_status(:ok)
expect(response.body).not_to include(random_name)
end
end
context 'when only renaming a project path' do
it "doesnt change the disk_path when using hashed storage" do
skip unless project.hashed_storage?(:repository)
hashed_storage_path = ::Storage::Hashed.new(project).disk_path
original_repository_path = Gitlab::GitalyClient::StorageSettings.allow_disk_access do
project.repository.path
end
expect { update_project path: 'renamed_path' }.to change { project.reload.path }
expect(project.path).to include 'renamed_path'
assign_repository_path = Gitlab::GitalyClient::StorageSettings.allow_disk_access do
assigns(:repository).path
end
expect(original_repository_path).to include(hashed_storage_path)
expect(assign_repository_path).to include(hashed_storage_path)
end
it "upgrades and move project to hashed storage when project was originally legacy" do
skip if project.hashed_storage?(:repository)
hashed_storage_path = Storage::Hashed.new(project).disk_path
original_repository_path = Gitlab::GitalyClient::StorageSettings.allow_disk_access do
project.repository.path
end
expect { update_project path: 'renamed_path' }.to change { project.reload.path }
expect(project.path).to include 'renamed_path'
assign_repository_path = Gitlab::GitalyClient::StorageSettings.allow_disk_access do
assigns(:repository).path
end
expect(original_repository_path).not_to include(hashed_storage_path)
expect(assign_repository_path).to include(hashed_storage_path)
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project has container repositories with tags' do
before do
stub_container_registry_config(enabled: true)
stub_container_registry_tags(repository: /image/, tags: %w[rc1])
create(:container_repository, project: project, name: :image)
end
it 'does not allow to rename the project' do
expect { update_project path: 'renamed_path' }
.not_to change { project.reload.path }
expect(controller).to set_flash[:alert].to(s_('UpdateProject|Cannot rename project because it contains container registry tags!'))
expect(response).to have_gitlab_http_status(:ok)
end
end
it 'updates Fast Forward Merge attributes' do
controller.instance_variable_set(:@project, project)
params = {
merge_method: :ff
}
put :update,
params: {
namespace_id: project.namespace,
id: project.id,
project: params
}
expect(response).to have_gitlab_http_status(:found)
params.each do |param, value|
expect(project.public_send(param)).to eq(value)
end
end
it 'does not update namespace' do
controller.instance_variable_set(:@project, project)
params = {
namespace_id: 'test'
}
expect do
put :update,
params: {
namespace_id: project.namespace,
id: project.id,
project: params
}
end.not_to change { project.namespace.reload }
end
def update_project(**parameters)
put :update,
params: {
namespace_id: project.namespace.path,
id: project.path,
project: parameters
}
end
end
context 'hashed storage' do
let_it_be(:project) { create(:project, :repository) }
it_behaves_like 'updating a project'
end
context 'legacy storage' do
let_it_be(:project) { create(:project, :repository, :legacy_storage) }
it_behaves_like 'updating a project'
end
context 'as maintainer' do
before do
project.add_maintainer(user)
sign_in(user)
end
it_behaves_like 'unauthorized when external service denies access' do
subject do
put :update,
params: {
namespace_id: project.namespace,
id: project,
project: { description: 'Hello world' }
}
project.reload
end
it 'updates when the service allows access' do
external_service_allow_access(user, project)
expect { subject }.to change(project, :description)
end
it 'does not update when the service rejects access' do
external_service_deny_access(user, project)
expect { subject }.not_to change(project, :description)
end
end
end
context 'when updating boolean values on project_settings' do
using RSpec::Parameterized::TableSyntax
where(:boolean_value, :result) do
'1' | true
'0' | false
1 | true
0 | false
true | true
false | false
end
with_them do
it 'updates project settings attributes accordingly' do
put :update, params: {
namespace_id: project.namespace,
id: project.path,
project: {
project_setting_attributes: {
show_default_award_emojis: boolean_value
}
}
}
project.reload
expect(project.show_default_award_emojis?).to eq(result)
end
end
end
context 'with project feature attributes' do
using RSpec::Parameterized::TableSyntax
where(:feature, :initial_value, :update_to) do
:metrics_dashboard_access_level | ProjectFeature::PRIVATE | ProjectFeature::ENABLED
:container_registry_access_level | ProjectFeature::ENABLED | ProjectFeature::PRIVATE
end
with_them do
it "updates the project_feature new" do
params = {
namespace_id: project.namespace,
id: project.path,
project: {
project_feature_attributes: {
"#{feature}": update_to
}
}
}
expect { put :update, params: params }.to change {
project.reload.project_feature.public_send(feature)
}.from(initial_value).to(update_to)
end
end
end
end
describe '#transfer', :enable_admin_mode do
render_views
let(:project) { create(:project) }
let_it_be(:admin) { create(:admin) }
let_it_be(:new_namespace) { create(:namespace) }
shared_examples 'project namespace is not changed' do |flash_message|
it 'project namespace is not changed' do
controller.instance_variable_set(:@project, project)
sign_in(admin)
old_namespace = project.namespace
put :transfer,
params: {
namespace_id: old_namespace.path,
new_namespace_id: new_namespace_id,
id: project.path
},
format: :js
project.reload
expect(project.namespace).to eq(old_namespace)
expect(response).to redirect_to(edit_project_path(project))
expect(flash[:alert]).to eq flash_message
end
end
it 'updates namespace' do
sign_in(admin)
put :transfer,
params: {
namespace_id: project.namespace.path,
new_namespace_id: new_namespace.id,
id: project.path
},
format: :js
project.reload
expect(project.namespace).to eq(new_namespace)
expect(response).to redirect_to(edit_project_path(project))
end
context 'when new namespace is empty' do
let(:new_namespace_id) { nil }
it_behaves_like 'project namespace is not changed', s_('TransferProject|Please select a new namespace for your project.')
end
context 'when new namespace is the same as the current namespace' do
let(:new_namespace_id) { project.namespace.id }
it_behaves_like 'project namespace is not changed', s_('TransferProject|Project is already in this namespace.')
end
end
describe "#destroy", :enable_admin_mode do
let_it_be(:admin) { create(:admin) }
it "redirects to the dashboard", :sidekiq_might_not_need_inline do
controller.instance_variable_set(:@project, project)
sign_in(admin)
orig_id = project.id
delete :destroy, params: { namespace_id: project.namespace, id: project }
expect { Project.find(orig_id) }.to raise_error(ActiveRecord::RecordNotFound)
expect(response).to have_gitlab_http_status(:found)
expect(response).to redirect_to(dashboard_projects_path)
end
context "when the project is forked" do
let(:project) { create(:project, :repository) }
let(:forked_project) { fork_project(project, nil, repository: true) }
let(:merge_request) do
create(:merge_request,
source_project: forked_project,
target_project: project)
end
it "closes all related merge requests", :sidekiq_might_not_need_inline do
project.merge_requests << merge_request
sign_in(admin)
delete :destroy, params: { namespace_id: forked_project.namespace, id: forked_project }
expect(merge_request.reload.state).to eq('closed')
end
end
end
describe 'PUT #new_issuable_address for issue' do
subject do
put :new_issuable_address,
params: {
namespace_id: project.namespace,
id: project,
issuable_type: 'issue'
}
user.reload
end
before do
sign_in(user)
project.add_developer(user)
allow(Gitlab.config.incoming_email).to receive(:enabled).and_return(true)
end
it 'has http status 200' do
expect(response).to have_gitlab_http_status(:ok)
end
it 'changes the user incoming email token' do
expect { subject }.to change { user.incoming_email_token }
end
it 'changes projects new issue address' do
expect { subject }.to change { project.new_issuable_address(user, 'issue') }
end
end
describe 'PUT #new_issuable_address for merge request' do
subject do
put :new_issuable_address,
params: {
namespace_id: project.namespace,
id: project,
issuable_type: 'merge_request'
}
user.reload
end
before do
sign_in(user)
project.add_developer(user)
allow(Gitlab.config.incoming_email).to receive(:enabled).and_return(true)
end
it 'has http status 200' do
expect(response).to have_gitlab_http_status(:ok)
end
it 'changes the user incoming email token' do
expect { subject }.to change { user.incoming_email_token }
end
it 'changes projects new merge request address' do
expect { subject }.to change { project.new_issuable_address(user, 'merge_request') }
end
end
describe "POST #toggle_star" do
it "toggles star if user is signed in" do
sign_in(user)
expect(user.starred?(public_project)).to be_falsey
post(:toggle_star,
params: {
namespace_id: public_project.namespace,
id: public_project
})
expect(user.starred?(public_project)).to be_truthy
post(:toggle_star,
params: {
namespace_id: public_project.namespace,
id: public_project
})
expect(user.starred?(public_project)).to be_falsey
end
it "does nothing if user is not signed in" do
post(:toggle_star,
params: {
namespace_id: project.namespace,
id: public_project
})
expect(user.starred?(public_project)).to be_falsey
post(:toggle_star,
params: {
namespace_id: project.namespace,
id: public_project
})
expect(user.starred?(public_project)).to be_falsey
end
end
describe "DELETE remove_fork" do
context 'when signed in' do
before do
sign_in(user)
end
context 'with forked project' do
let(:forked_project) { fork_project(create(:project, :public), user) }
it 'removes fork from project' do
delete(:remove_fork,
params: {
namespace_id: forked_project.namespace.to_param,
id: forked_project.to_param
},
format: :js)
expect(forked_project.reload.forked?).to be_falsey
expect(flash[:notice]).to eq(s_('The fork relationship has been removed.'))
expect(response).to redirect_to(edit_project_path(forked_project))
end
end
context 'when project not forked' do
let(:unforked_project) { create(:project, namespace: user.namespace) }
it 'does nothing if project was not forked' do
delete(:remove_fork,
params: {
namespace_id: unforked_project.namespace,
id: unforked_project
},
format: :js)
expect(flash[:notice]).to be_nil
expect(response).to redirect_to(edit_project_path(unforked_project))
end
end
end
it "does nothing if user is not signed in" do
delete(:remove_fork,
params: {
namespace_id: project.namespace,
id: project
},
format: :js)
expect(response).to have_gitlab_http_status(:unauthorized)
end
end
describe "GET refs" do
let_it_be(:project) { create(:project, :public, :repository) }
it 'gets a list of branches and tags' do
get :refs, params: { namespace_id: project.namespace, id: project, sort: 'updated_desc' }
expect(json_response['Branches']).to include('master')
expect(json_response['Tags']).to include('v1.0.0')
expect(json_response['Commits']).to be_nil
end
it "gets a list of branches, tags and commits" do
get :refs, params: { namespace_id: project.namespace, id: project, ref: "123456" }
expect(json_response["Branches"]).to include("master")
expect(json_response["Tags"]).to include("v1.0.0")
expect(json_response["Commits"]).to include("123456")
end
context 'when gitaly is unavailable' do
before do
expect_next_instance_of(TagsFinder) do |finder|
allow(finder).to receive(:execute).and_raise(Gitlab::Git::CommandError)
end
end
it 'gets an empty list of tags' do
get :refs, params: { namespace_id: project.namespace, id: project, ref: "123456" }
expect(json_response["Branches"]).to include("master")
expect(json_response["Tags"]).to eq([])
expect(json_response["Commits"]).to include("123456")
end
end
context "when preferred language is Japanese" do
before do
user.update!(preferred_language: 'ja')
sign_in(user)
end
it "gets a list of branches, tags and commits" do
get :refs, params: { namespace_id: project.namespace, id: project, ref: "123456" }
expect(json_response["Branches"]).to include("master")
expect(json_response["Tags"]).to include("v1.0.0")
expect(json_response["Commits"]).to include("123456")
end
end
context 'when private project' do
let(:project) { create(:project, :repository) }
context 'as a guest' do
it 'renders forbidden' do
user = create(:user)
project.add_guest(user)
sign_in(user)
get :refs, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
context 'when input params are invalid' do
let(:request) { get :refs, params: { namespace_id: project.namespace, id: project, ref: { invalid: :format } } }
it 'does not break' do
request
expect(response).to have_gitlab_http_status(:success)
end
context 'when "strong_parameters_for_project_controller" FF is disabled' do
before do
stub_feature_flags(strong_parameters_for_project_controller: false)
end
it 'raises an exception' do
expect { request }.to raise_error(TypeError)
end
end
end
end
describe 'POST #preview_markdown' do
before do
sign_in(user)
end
it 'renders json in a correct format' do
post :preview_markdown, params: { namespace_id: public_project.namespace, id: public_project, text: '*Markdown* text' }
expect(json_response.keys).to match_array(%w(body references))
end
context 'when not authorized' do
let(:private_project) { create(:project, :private) }
it 'returns 404' do
post :preview_markdown, params: { namespace_id: private_project.namespace, id: private_project, text: '*Markdown* text' }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'state filter on references' do
let_it_be(:issue) { create(:issue, :closed, project: public_project) }
let(:merge_request) { create(:merge_request, :closed, target_project: public_project) }
it 'renders JSON body with state filter for issues' do
post :preview_markdown, params: {
namespace_id: public_project.namespace,
id: public_project,
text: issue.to_reference
}
expect(json_response['body']).to match(/\##{issue.iid} \(closed\)/)
end
it 'renders JSON body with state filter for MRs' do
post :preview_markdown, params: {
namespace_id: public_project.namespace,
id: public_project,
text: merge_request.to_reference
}
expect(json_response['body']).to match(/\!#{merge_request.iid} \(closed\)/)
end
end
context 'when path parameter is provided' do
let(:project_with_repo) { create(:project, :repository) }
let(:preview_markdown_params) do
{
namespace_id: project_with_repo.namespace,
id: project_with_repo,
text: "\n",
path: 'files/images/README.md'
}
end
before do
project_with_repo.add_maintainer(user)
end
it 'renders JSON body with image links expanded' do
expanded_path = "/#{project_with_repo.full_path}/-/raw/master/files/images/logo-white.png"
post :preview_markdown, params: preview_markdown_params
expect(json_response['body']).to include(expanded_path)
end
end
context 'when path and ref parameters are provided' do
let(:project_with_repo) { create(:project, :repository) }
let(:preview_markdown_params) do
{
namespace_id: project_with_repo.namespace,
id: project_with_repo,
text: "\n",
ref: 'other_branch',
path: 'files/images/README.md'
}
end
before do
project_with_repo.add_maintainer(user)
project_with_repo.repository.create_branch('other_branch')
end
it 'renders JSON body with image links expanded' do
expanded_path = "/#{project_with_repo.full_path}/-/raw/other_branch/files/images/logo-white.png"
post :preview_markdown, params: preview_markdown_params
expect(json_response['body']).to include(expanded_path)
end
end
end
describe '#ensure_canonical_path' do
before do
sign_in(user)
end
context 'for a GET request' do
context 'when requesting the canonical path' do
context "with exactly matching casing" do
it "loads the project" do
get :show, params: { namespace_id: public_project.namespace, id: public_project }
expect(assigns(:project)).to eq(public_project)
expect(response).to have_gitlab_http_status(:ok)
end
end
context "with different casing" do
it "redirects to the normalized path" do
get :show, params: { namespace_id: public_project.namespace, id: public_project.path.upcase }
expect(assigns(:project)).to eq(public_project)
expect(response).to redirect_to("/#{public_project.full_path}")
expect(controller).not_to set_flash[:notice]
end
end
end
context 'when requesting a redirected path' do
let!(:redirect_route) { public_project.redirect_routes.create!(path: "foo/bar") }
it 'redirects to the canonical path' do
get :show, params: { namespace_id: 'foo', id: 'bar' }
expect(response).to redirect_to(public_project)
expect(controller).to set_flash[:notice].to(project_moved_message(redirect_route, public_project))
end
it 'redirects to the canonical path (testing non-show action)' do
get :refs, params: { namespace_id: 'foo', id: 'bar' }
expect(response).to redirect_to(refs_project_path(public_project))
expect(controller).to set_flash[:notice].to(project_moved_message(redirect_route, public_project))
end
end
end
context 'for a POST request' do
context 'when requesting the canonical path with different casing' do
it 'does not 404' do
post :toggle_star, params: { namespace_id: public_project.namespace, id: public_project.path.upcase }
expect(response).not_to have_gitlab_http_status(:not_found)
end
it 'does not redirect to the correct casing' do
post :toggle_star, params: { namespace_id: public_project.namespace, id: public_project.path.upcase }
expect(response).not_to have_gitlab_http_status(:moved_permanently)
end
end
context 'when requesting a redirected path' do
let!(:redirect_route) { public_project.redirect_routes.create!(path: "foo/bar") }
it 'returns not found' do
post :toggle_star, params: { namespace_id: 'foo', id: 'bar' }
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
context 'for a DELETE request', :enable_admin_mode do
before do
sign_in(create(:admin))
end
context 'when requesting the canonical path with different casing' do
it 'does not 404' do
delete :destroy, params: { namespace_id: project.namespace, id: project.path.upcase }
expect(response).not_to have_gitlab_http_status(:not_found)
end
it 'does not redirect to the correct casing' do
delete :destroy, params: { namespace_id: project.namespace, id: project.path.upcase }
expect(response).not_to have_gitlab_http_status(:moved_permanently)
end
end
context 'when requesting a redirected path' do
let!(:redirect_route) { project.redirect_routes.create!(path: "foo/bar") }
it 'returns not found' do
delete :destroy, params: { namespace_id: 'foo', id: 'bar' }
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
end
describe 'project export' do
before do
sign_in(user)
project.add_maintainer(user)
end
shared_examples 'rate limits project export endpoint' do
before do
allow(Gitlab::ApplicationRateLimiter)
.to receive(:increment)
.and_return(Gitlab::ApplicationRateLimiter.rate_limits["project_#{action}".to_sym][:threshold].call + 1)
end
it 'prevents requesting project export' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response.body).to eq('This endpoint has been requested too many times. Try again later.')
expect(response).to have_gitlab_http_status(:too_many_requests)
end
end
describe '#export' do
let(:action) { :export }
context 'when project export is enabled' do
it 'returns 302' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project export is disabled' do
before do
stub_application_setting(project_export_enabled?: false)
end
it 'returns 404' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when the endpoint receives requests above the limit', :clean_gitlab_redis_rate_limiting do
include_examples 'rate limits project export endpoint'
end
end
describe '#download_export', :clean_gitlab_redis_rate_limiting do
let(:action) { :download_export }
context 'object storage enabled' do
context 'when project export is enabled' do
it 'returns 302' do
get action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project export file is absent' do
it 'alerts the user and returns 302' do
project.export_file.file.delete
get action, params: { namespace_id: project.namespace, id: project }
expect(flash[:alert]).to include('file containing the export is not available yet')
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project export is disabled' do
before do
stub_application_setting(project_export_enabled?: false)
end
it 'returns 404' do
get action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when the endpoint receives requests above the limit', :clean_gitlab_redis_rate_limiting do
before do
allow(Gitlab::ApplicationRateLimiter)
.to receive(:increment)
.and_return(Gitlab::ApplicationRateLimiter.rate_limits[:project_download_export][:threshold].call + 1)
end
it 'prevents requesting project export' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response.body).to eq('This endpoint has been requested too many times. Try again later.')
expect(response).to have_gitlab_http_status(:too_many_requests)
end
it 'applies correct scope when throttling' do
expect(Gitlab::ApplicationRateLimiter)
.to receive(:throttled?)
.with(:project_download_export, scope: [user, project])
post action, params: { namespace_id: project.namespace, id: project }
end
end
end
end
describe '#remove_export' do
let(:action) { :remove_export }
context 'when project export is enabled' do
it 'returns 302' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project export is disabled' do
before do
stub_application_setting(project_export_enabled?: false)
end
it 'returns 404' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
describe '#generate_new_export' do
let(:action) { :generate_new_export }
context 'when project export is enabled' do
it 'returns 302' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:found)
end
end
context 'when project export is disabled' do
before do
stub_application_setting(project_export_enabled?: false)
end
it 'returns 404' do
post action, params: { namespace_id: project.namespace, id: project }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when the endpoint receives requests above the limit', :clean_gitlab_redis_rate_limiting do
include_examples 'rate limits project export endpoint'
end
end
end
context 'GET show.atom' do
let_it_be(:public_project) { create(:project, :public) }
let_it_be(:event) { create(:event, :commented, project: public_project, target: create(:note, project: public_project)) }
let_it_be(:invisible_event) { create(:event, :commented, project: public_project, target: create(:note, :confidential, project: public_project)) }
it 'filters by calling event.visible_to_user?' do
expect(EventCollection).to receive_message_chain(:new, :to_a).and_return([event, invisible_event])
expect(event).to receive(:visible_to_user?).and_return(true)
expect(invisible_event).to receive(:visible_to_user?).and_return(false)
get :show, format: :atom, params: { id: public_project, namespace_id: public_project.namespace }
expect(response).to render_template('xml.atom')
expect(assigns(:events)).to eq([event])
end
it 'filters by calling event.visible_to_user?' do
get :show, format: :atom, params: { id: public_project, namespace_id: public_project.namespace }
expect(response).to render_template('xml.atom')
expect(assigns(:events)).to eq([event])
end
end
describe 'GET resolve' do
shared_examples 'resolvable endpoint' do
it 'redirects to the project page' do
get :resolve, params: { id: project.id }
expect(response).to have_gitlab_http_status(:found)
expect(response).to redirect_to(project_path(project))
end
end
context 'with an authenticated user' do
before do
sign_in(user)
end
context 'when user has access to the project' do
before do
project.add_developer(user)
end
it_behaves_like 'resolvable endpoint'
end
context 'when user has no access to the project' do
it 'gives 404 for existing project' do
get :resolve, params: { id: project.id }
expect(response).to have_gitlab_http_status(:not_found)
end
end
it 'gives 404 for non-existing project' do
get :resolve, params: { id: '0' }
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'non authenticated user' do
context 'with a public project' do
let(:project) { public_project }
it_behaves_like 'resolvable endpoint'
end
it 'gives 404 for private project' do
get :resolve, params: { id: project.id }
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
it 'updates Service Desk attributes' do
project.add_maintainer(user)
sign_in(user)
allow(Gitlab::IncomingEmail).to receive(:enabled?) { true }
allow(Gitlab::IncomingEmail).to receive(:supports_wildcard?) { true }
params = {
service_desk_enabled: true
}
put :update,
params: {
namespace_id: project.namespace,
id: project,
project: params
}
project.reload
expect(response).to have_gitlab_http_status(:found)
expect(project.service_desk_enabled).to eq(true)
end
def project_moved_message(redirect_route, project)
"Project '#{redirect_route.path}' was moved to '#{project.full_path}'. Please update any links and bookmarks that may still have the old path."
end
describe 'GET #unfoldered_environment_names' do
it 'shows the environment names of a public project to an anonymous user' do
create(:environment, project: public_project, name: 'foo')
get(
:unfoldered_environment_names,
params: { namespace_id: public_project.namespace, id: public_project, format: :json }
)
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq(%w[foo])
end
it 'does not show environment names of a private project to anonymous users' do
create(:environment, project: project, name: 'foo')
get(
:unfoldered_environment_names,
params: { namespace_id: project.namespace, id: project, format: :json }
)
expect(response).to redirect_to(new_user_session_path)
end
it 'shows environment names of a private project to a project member' do
create(:environment, project: project, name: 'foo')
project.add_developer(user)
sign_in(user)
get(
:unfoldered_environment_names,
params: { namespace_id: project.namespace, id: project, format: :json }
)
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq(%w[foo])
end
it 'does not show environment names of a private project to a logged-in non-member' do
create(:environment, project: project, name: 'foo')
sign_in(user)
get(
:unfoldered_environment_names,
params: { namespace_id: project.namespace, id: project, format: :json }
)
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
| 30.906537 | 150 | 0.63355 |
61dce278119011da792c40b68f867ea19a364579 | 1,797 | # frozen_string_literal: true
class UserLettersController < ApplicationController
respond_to :html, :xml, :json
before_action :authenticate_user!, only: %i[new create destroy]
def show
@user_letter = UserLetter.find(params[:id])
redirect_to(letter_path(@user_letter.letter_id)) && return
end
def new
@user_letter = UserLetter.new(status: 0)
end
def create
@user_letter = UserLetter.new(user_letter_params)
if @user_letter.save
flash[:notice] = 'Successfully created user_letter.'
begin
UserLetterMailer.user_letter_create(@user_letter, current_user).deliver_now # оповестим нового исполнителя
rescue StandardError => e
flash[:alert] = "Error sending mail to #{@user_letter.user.email}\n#{e}"
end
letter = Letter.find(@user_letter.letter_id)
letter.update! status: 5 if letter.status < 1 # если есть ответственные - статус = Назначено
else
flash[:alert] = 'Error create user_letter'
end
respond_with(@user_letter)
end
def destroy
@user_letter = UserLetter.find(params[:id]) # нашли удаляемую связь
@letter = Letter.find(@user_letter.letter_id) # запомнили письмо для этой удаляемой связи
begin
UserLetterMailer.user_letter_destroy(@user_letter, current_user).deliver_now # оповестим исполнителя
rescue StandardError => e
flash[:alert] = "Error sending mail to #{@user_letter.user.email}\n#{e}"
end
if @user_letter.destroy # удалили связь
@letter.update! status: 0 unless @letter.user_letter.first # если нет ответственных - статус = Новое
end
respond_with(@letter) # вернулись в письмо
end
private
def user_letter_params
params.require(:user_letter)
.permit(:user_id, :letter_id, :status, :user_name)
end
end
| 33.277778 | 114 | 0.708403 |
2138c292c52cfef438af4687944fdee82646ab23 | 9,110 | # frozen_string_literal: true
require 'cancancan'
require 'ethereum_api'
require 'info_api'
class Kyc < ApplicationRecord
MAX_BLOCK_DELAY = Rails.configuration.ethereum['max_block_delay'].to_i
MINIMUM_AGE = 18
VERIFICATION_PATTERN = /\A(\d+)-(\h{2})-(\h{2})\Z/.freeze
IMAGE_SIZE_LIMIT = 10.megabytes
IMAGE_FILE_TYPES = ['image/jpeg', 'image/jpeg', 'image/png', 'application/pdf'].freeze
enum status: { pending: 1, rejected: 2, approved: 3, approving: 7 }
enum gender: { male: 1, female: 2 }
enum employment_status: { employed: 0, self_employed: 1, unemployed: 2 }
enum identification_proof_type: { passport: 0, national_id: 1, identity_card: 2 }, _prefix: :identification
enum residence_proof_type: { utility_bill: 0, bank_statement: 1 }, _prefix: :residence
belongs_to :user
belongs_to :officer,
class_name: 'User',
foreign_key: :officer_id,
optional: true
has_one_attached :residence_proof_image
has_one_attached :identification_proof_image
has_one_attached :identification_pose_image
include Discard::Model
validates :first_name,
presence: true,
length: { maximum: 150 }
validates :last_name,
presence: true,
length: { maximum: 150 }
validates :gender,
presence: true
validates :birthdate,
presence: true,
timeliness: { on_or_before: -> { MINIMUM_AGE.years.ago } }
validates :birth_country,
presence: true,
country: true
validates :nationality,
presence: true,
country: true
validates :nationality,
presence: true,
country: true
validates :phone_number,
presence: true,
length: { maximum: 20 },
format: { with: /\A(\+)?[0-9][0-9\-]+[0-9]\z/ }
validates :employment_status,
presence: true
validates :employment_industry,
presence: true
validates :income_range,
presence: true
validates :identification_proof_number,
presence: true,
length: { maximum: 50 }
validates :identification_proof_expiration_date,
presence: true,
timeliness: { on_or_after: :today }
validates :country,
presence: true,
country: true
validates :address,
presence: true,
length: { maximum: 1000 }
validates :address_details,
presence: false,
length: { maximum: 1000 }
validates :city,
presence: true,
length: { maximum: 250 }
validates :state,
presence: true,
length: { maximum: 250 }
validates :postal_code,
presence: true,
length: { maximum: 12 },
format: { with: /\A[a-z0-9][a-z0-9\-\s]{0,10}[a-z0-9]\z/i }
validates :residence_proof_type,
presence: true
validates :verification_code,
presence: true,
format: { with: VERIFICATION_PATTERN }
validates :identification_proof_image,
attached: true,
size: { less_than: IMAGE_SIZE_LIMIT },
content_type: IMAGE_FILE_TYPES
validates :residence_proof_image,
attached: true,
size: { less_than: IMAGE_SIZE_LIMIT },
content_type: IMAGE_FILE_TYPES
validates :identification_pose_image,
attached: true,
size: { less_than: IMAGE_SIZE_LIMIT },
content_type: IMAGE_FILE_TYPES
validates :expiration_date,
if: proc { |kyc| %i[approving approved].member?(kyc.status.to_sym) },
timeliness: { on_or_after: :today }
validates :rejection_reason,
if: proc { |kyc| kyc.status.to_sym == :rejected },
rejection_reason: true
validates :approval_txhash,
presence: false
def expired?
Time.now > expiration_date.to_time
end
class << self
def submit_kyc(user, attrs)
this_user = User.find(user.id)
return [:email_not_set, nil] unless this_user.email
if (this_kyc = this_user.kyc)
kyc_status = this_kyc.status.to_sym
if kyc_status == :pending
return [:active_kyc_submitted, nil]
elsif kyc_status == :approved && !this_kyc.expired?
return [:active_kyc_submitted, nil]
end
end
base_attrs = attrs.except(
:identification_proof_image,
:residence_proof_image,
:identification_pose_image
)
kyc = Kyc.new(base_attrs)
kyc.user_id = this_user.id
kyc.status = :pending
verification_error =
case verify_code(kyc.verification_code)
when :invalid_format then
'has invalid format' # Should not happen
when :latest_block_not_found then
'could not be verified'
when :verification_expired then
'is expired'
when :block_not_found then
'could not be found'
when :invalid_hash then
'is incorrect'
end
if verification_error
kyc.errors.add(:verification_code, verification_error)
return [:invalid_data, kyc.errors]
end
encode_image(kyc, :identification_proof_image, attrs[:identification_proof_image])
encode_image(kyc, :residence_proof_image, attrs[:residence_proof_image])
encode_image(kyc, :identification_pose_image, attrs[:identification_pose_image])
return [:invalid_data, kyc.errors] unless kyc.valid?
return [:database_error, kyc.errors] unless kyc.save
this_kyc&.discard
NotificationMailer.with(kyc: kyc).kyc_submitted.deliver_now
[:ok, kyc]
end
def verify_code(verification_code)
return :invalid_format unless verification_code&.match?(VERIFICATION_PATTERN)
block_number, first_two, last_two =
verification_code.match(VERIFICATION_PATTERN).captures
block_number = block_number.to_i
block_hash = "0x#{block_number.to_s(16)}"
ok_latest, latest_block = EthereumApi.get_latest_block
return :latest_block_not_found unless ok_latest == :ok && latest_block
unless (latest_block.fetch('number', '').to_i - block_number) <= MAX_BLOCK_DELAY
return :verification_expired
end
ok_this, this_block = EthereumApi.get_block_by_block_number(block_hash)
return :block_not_found unless ok_this == :ok && this_block
this_hash = this_block.fetch('hash', '').slice(2..-1)
unless this_hash.slice(0, 2) == first_two &&
this_hash.slice(-2, 2) == last_two
return :invalid_hash
end
:ok
end
def approve_kyc(officer, kyc, attrs)
this_officer = User.find(officer.id)
this_kyc = Kyc.find(kyc.id)
return [:unauthorized_action, nil] if this_kyc.discarded?
return [:unauthorized_action, nil] unless Ability.new(this_officer).can?(:approve, Kyc, kyc)
return [:kyc_not_pending, nil] unless this_kyc.status.to_sym == :pending
unless this_kyc.update_attributes(
status: :approving,
officer: this_officer,
expiration_date: attrs.fetch(:expiration_date, nil)
)
return [:invalid_data, this_kyc.errors] unless this_kyc.valid?
end
Rails.logger.info 'Updating info-server with this approved kyc'
info_result, info_data_or_error = InfoApi.approve_kyc(this_kyc)
unless info_result == :ok
Rails.logger.debug "Failed to updated info-server: #{info_data_or_error}"
end
NotificationMailer.with(kyc: this_kyc).kyc_approved.deliver_now
[:ok, this_kyc]
end
def reject_kyc(officer, kyc, attrs)
this_officer = User.find(officer.id)
this_kyc = Kyc.find(kyc.id)
return [:unauthorized_action, nil] if this_kyc.discarded?
return [:unauthorized_action, nil] unless Ability.new(this_officer).can?(:reject, Kyc, kyc)
return [:kyc_not_pending, nil] unless this_kyc.status.to_sym == :pending
unless this_kyc.update_attributes(
status: :rejected,
officer: this_officer,
rejection_reason: attrs.fetch(:rejection_reason, nil)
)
return [:invalid_data, this_kyc.errors] unless this_kyc.valid?
end
NotificationMailer.with(kyc: this_kyc).kyc_rejected.deliver_now
[:ok, this_kyc]
end
def update_kyc_hashes(hashes)
ActiveRecord::Base.transaction do
hashes.each do |hash|
next unless (user = User.find_by(address: hash.fetch(:address, ''))) &&
(kyc = user.kyc)
kyc.update_attributes(
status: :approved,
approval_txhash: hash.fetch(:txhash, '')
)
DaoServerSchema.subscriptions.trigger(
'kycUpdated',
{},
{ kyc: kyc },
{}
)
end
end
:ok
end
private
def encode_image(kyc, key, image)
attachment = kyc.method(key).call
attachment.attach(
io: StringIO.new(image[:data]),
content_type: image[:content_type],
filename: "#{key}_#{kyc.user.uid}"
)
end
end
end
| 30.986395 | 109 | 0.632602 |
1de4c1f279225462af726d0863e4bca083173450 | 1,513 | #
# Cookbook Name:: openpds
# Recipe:: default
#
# Copyright (C) 2015 Patrick Connolly (patcon)
#
# 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.
#
user 'openpds'
include_recipe 'git'
git node['openpds']['install_dir'] do
repository 'https://github.com/HumanDynamics/openPDS.git'
owner 'openpds'
group 'openpds'
branch 'master'
action :sync
end
include_recipe 'python'
python_virtualenv 'openpds' do
path "#{node['openpds']['install_dir']}/.venv"
owner 'openpds'
group 'openpds'
end
| 32.891304 | 72 | 0.758096 |
4a5ef4260a466ffc95cbb647ce5c303ff3db19cf | 657 | module Markety
# Types of keys that can be used to look up a lead.
# (Other key types exist, but Markety only supports these at this time.)
module LeadKeyType
IDNUM = "IDNUM"
EMAIL = "EMAIL"
COOKIE = "COOKIE"
# LEADOWNEREMAIL = "LEADOWNEREMAIL"
# SFDCACCOUNTID = "SFDCACCOUNTID"
# SFDCCONTACTID = "SFDCCONTACTID"
# SFDCLEADID = "SFDCLEADID"
# SFDCLEADOWNERID = "SFDCLEADOWNERID"
# SFDCOPPTYID = "SFDCOPPTYID"
end
# a parameter type to Markety::Command::SyncLead
module SyncMethod
MARKETO_ID = "MARKETO_ID"
FOREIGN_ID = "FOREIGN_ID"
EMAIL = "EMAIL"
end
end
| 27.375 | 74 | 0.637747 |
08c598a0f8294decec6b43a97cf3f135742f4c09 | 2,353 | module Sessions
class AccountsController < BaseController
rescue_from ActionController::ParameterMissing, with: :handle_missing_params
before_action :set_user, only: :create
def new
return redirect_to(user_path) if logged_in?
example_key = 'request_body_example'
@message = {
problem: 'Client is not authorized.',
solution: "Login. Send a POST to '#{login_path}'. Wrap the request body params as per the example at the key, '#{example_key}'. Successful attempts receive a free cookie.",
example_key => {
session: {
email: '<[email protected]>',
password: '<user_password>'
}
}
}
render('sessions/login', status: 401)
end
def create
if authenticated?
login_authenticated_user
redirect_or_show_success
else
@message = 'Invalid email/password combination.'
render('sessions/login', status: 401)
end
end
private
def set_user
unless params[:session].present?
msg = "Remember to wrap up params in 'session' key"
raise ActionController::ParameterMissing.new(msg)
end
@user = find_user_by_email if email_and_password?
end
def handle_missing_params(e)
json = { text: e }
render(json: json, status: :bad_request)
end
def email_and_password?
email? && password?
end
def email?
params[:session][:email].present?
end
def password?
params[:session][:password].present?
end
def find_user_by_email
email = params[:session][:email].downcase
Users::Account.find_by(email: email)
end
def authenticated?
password = params[:session][:password]
user && user.authenticate(password)
end
def login_authenticated_user
log_in(user)
if remember_me?
remember(user)
else
forget(user)
end
end
def remember_me?
remember_me = params[:session][:remember_me]
remember_me == '1'
end
def redirect_or_show_success
forwarding_url = session[:forwarding_url]
if forwarding_url.present?
redirect_back_or(forwarding_url)
else
@message = 'You have logged in. Have a cookie.'
render('sessions/login')
end
end
end
end
| 23.29703 | 180 | 0.626434 |
1aa9dce017fce84bbea87408f23969ba8518e77f | 426 | cask "flic" do
version "2.1.0"
sha256 "8fceaa6d5eedf4a3013519c9e372e3c640419abc28a2dafc00f0219094933309"
url "https://misc-scl-cdn.s3.amazonaws.com/Flic.#{version}.zip",
verified: "misc-scl-cdn.s3.amazonaws.com/"
name "Flic"
desc "Driver for the Flic bluetooth button"
homepage "https://flic.io/mac-app"
livecheck do
url :homepage
regex(/Flic\.(\d+(?:\.\d+)+)\.zip/i)
end
app "Flic.app"
end
| 23.666667 | 75 | 0.678404 |
bb262241403312e27789c9d0bc91fcbb43036b51 | 602 | require 'linguist/blob_helper'
require 'rugged'
module Linguist
class LazyBlob
include BlobHelper
MAX_SIZE = 128 * 1024
attr_reader :repository
attr_reader :oid
attr_reader :name
attr_reader :mode
def initialize(repo, oid, name, mode = nil)
@repository = repo
@oid = oid
@name = name
@mode = mode
end
def data
load_blob!
@data
end
def size
load_blob!
@size
end
protected
def load_blob!
@data, @size = Rugged::Blob.to_buffer(repository, oid, MAX_SIZE) if @data.nil?
end
end
end
| 15.842105 | 84 | 0.607973 |
28897b5f53a321e2be27b5e4c636a1621158faa6 | 1,271 | require "language/node"
class Eslint < Formula
desc "AST-based pattern checker for JavaScript"
homepage "https://eslint.org"
url "https://registry.npmjs.org/eslint/-/eslint-7.28.0.tgz"
sha256 "8c4078e6527e35556cc7392e4cc6b7e65e5fd63641ee3618689c42531a015374"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "29bb6cd3181059dfeef25b7ff56a8d9861ef963f2502c81b878d0b7af3de4675"
sha256 cellar: :any_skip_relocation, big_sur: "b1277e4acef503fcde6f0600c96bd31fe45d3f8b9417938310d72f589b8f1417"
sha256 cellar: :any_skip_relocation, catalina: "b1277e4acef503fcde6f0600c96bd31fe45d3f8b9417938310d72f589b8f1417"
sha256 cellar: :any_skip_relocation, mojave: "b1277e4acef503fcde6f0600c96bd31fe45d3f8b9417938310d72f589b8f1417"
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/".eslintrc.json").write("{}") # minimal config
(testpath/"syntax-error.js").write("{}}")
# https://eslint.org/docs/user-guide/command-line-interface#exit-codes
output = shell_output("#{bin}/eslint syntax-error.js", 1)
assert_match "Unexpected token }", output
end
end
| 39.71875 | 122 | 0.759245 |
f88b79dc59c1d1828421d41ed38043fbe86709b2 | 825 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'An interactor with .after_rollback callbacks', type: :integration do
let(:interactor_class) do
build_interactor do
after_rollback :test_after_rollback
def perform
context.fail!
end
private
def test_after_rollback; end
end
end
include_examples 'a class with interactor methods'
include_examples 'a class with interactor callback methods'
include_examples 'a class with interactor context methods'
describe '.perform' do
subject { interactor_class.perform }
it { is_expected.to be_a interactor_class.context_class }
it 'is expected to receive #test_after_rollback' do
expect_any_instance_of(interactor_class).to receive(:test_after_rollback)
subject
end
end
end
| 23.571429 | 84 | 0.738182 |
d5fcef1246f2808f382379b7320630b53e7245e2 | 2,472 | require 'spec_helper'
describe ImportExportCleanUpService do
describe '#execute' do
let(:service) { described_class.new }
let(:tmp_import_export_folder) { 'tmp/project_exports' }
context 'when the import/export directory does not exist' do
it 'does not remove any archives' do
path = '/invalid/path/'
stub_repository_downloads_path(path)
expect(service).not_to receive(:clean_up_export_files)
service.execute
end
end
context 'when the import/export directory exists' do
it 'removes old files' do
in_directory_with_files(mtime: 2.days.ago) do |dir, files|
service.execute
files.each { |file| expect(File.exist?(file)).to eq false }
expect(File.directory?(dir)).to eq false
end
end
it 'does not remove new files' do
in_directory_with_files(mtime: 2.hours.ago) do |dir, files|
service.execute
files.each { |file| expect(File.exist?(file)).to eq true }
expect(File.directory?(dir)).to eq true
end
end
end
context 'with uploader exports' do
it 'removes old files' do
upload = create(:import_export_upload,
updated_at: 2.days.ago,
export_file: fixture_file_upload('spec/fixtures/project_export.tar.gz'))
expect { service.execute }.to change { upload.reload.export_file.file.nil? }.to(true)
end
it 'does not remove new files' do
upload = create(:import_export_upload,
updated_at: 1.hour.ago,
export_file: fixture_file_upload('spec/fixtures/project_export.tar.gz'))
expect { service.execute }.not_to change { upload.reload.export_file.file.nil? }
end
end
def in_directory_with_files(mtime:)
Dir.mktmpdir do |tmpdir|
stub_repository_downloads_path(tmpdir)
dir = File.join(tmpdir, tmp_import_export_folder, 'subfolder')
FileUtils.mkdir_p(dir)
files = FileUtils.touch(file_list(dir) + [dir], mtime: mtime.to_time)
yield(dir, files)
end
end
def stub_repository_downloads_path(path)
new_shared_settings = Settings.shared.merge('path' => path)
allow(Settings).to receive(:shared).and_return(new_shared_settings)
end
def file_list(dir)
Array.new(5) do |num|
File.join(dir, "random-#{num}.tar.gz")
end
end
end
end
| 30.146341 | 96 | 0.633091 |
267ca6300a96643f6932aa69c849b56cd86b88e2 | 1,774 | module Elasticsearch
module Model
module Response
# Encapsulates the "hit" returned from the Elasticsearch client
#
# Wraps the raw Hash with in a `Hashie::Mash` instance, providing
# access to the Hash properties by calling Ruby methods.
#
# @see https://github.com/intridea/hashie
#
class Result
# @param attributes [Hash] A Hash with document properties
#
def initialize(attributes={})
@result = HashWrapper.new(attributes)
end
# Return document `_id` as `id`
#
def id
@result['_id']
end
# Return document `_type` as `_type`
#
def type
@result['_type']
end
# Delegate methods to `@result` or `@result._source`
#
def method_missing(name, *arguments)
case
when name.to_s.end_with?('?')
@result.__send__(name, *arguments) || ( @result._source && @result._source.__send__(name, *arguments) )
when @result.respond_to?(name)
@result.__send__ name, *arguments
when @result._source && @result._source.respond_to?(name)
@result._source.__send__ name, *arguments
else
super
end
end
# Respond to methods from `@result` or `@result._source`
#
def respond_to_missing?(method_name, include_private = false)
@result.respond_to?(method_name.to_sym) || \
@result._source && @result._source.respond_to?(method_name.to_sym) || \
super
end
def as_json(options={})
@result.as_json(options)
end
# TODO: #to_s, #inspect, with support for Pry
end
end
end
end
| 27.71875 | 115 | 0.563698 |
bbfa5f9f5eca2ad8ffa6af4cd503cd1a090e3e07 | 1,203 | module Bigid
module Bgcheck
module Auth
class Authentication
def initialize(connection: Connection.new,
username: Bigid::Bgcheck.configuration&.username,
password: Bigid::Bgcheck.configuration&.password,
token_expiration_time_in_seconds: Bigid::Bgcheck::AUTH_ENDPOINT)
@connection = connection
@token_expiration_time_in_seconds = Bigid::Bgcheck::TOKEN_EXPIRATION
@username = username ? username : ENV['BIGID_USERNAME']
@password = password ? password : ENV['BIGID_PASSWORD']
end
def login
res = @connection.post(url: 'Generate', body: login_body)
return res if res.status == 200
raise Bigid::Bgcheck::InvalidCredentialsError if res.status == 401
raise Bigid::Bgcheck::BadRequestError if res.status == 400
raise Bigid::Bgcheck::ServerError if res.status == 500
end
private
def login_body
{
login: @username,
password: @password,
expires: @token_expiration_time_in_seconds.to_i
}.to_json
end
end
end
end
end
| 31.657895 | 86 | 0.60266 |
038db4e66c25bd1ff5a45fcb90f1a626762f5363 | 243 | class CreateBootsyImages < ActiveRecord::Migration[5.1]
def change
create_table :bootsy_images do |t|
t.string :image_file
t.references :image_gallery, index: {name: "bootsy_img_gallery"}
t.timestamps
end
end
end
| 24.3 | 70 | 0.703704 |
38d68d2f65c3916735b77d84d75e267f9822eba4 | 156 | # frozen_string_literal: true
class SpreadsheetController < ApplicationController
def index
send_file Modsulator.template_spreadsheet_path
end
end
| 19.5 | 51 | 0.833333 |
bffa46d7bfcd345a4244a0d7a32ddc57cbd3cb4e | 1,650 | # frozen_string_literal: true
module RSpec
module Oj
module Matchers
class BeJsonEql
include RSpec::Oj::Helpers
include RSpec::Oj::Exclusion
include RSpec::Oj::Messages
attr_reader :expected, :actual
def diffable?
true
end
def initialize(expected_json = nil)
@expected_json = expected_json
@path = nil
end
def matches?(actual_json)
raise 'Expected equivalent JSON not provided' if @expected_json.nil?
@actual = scrub(actual_json, @path)
@expected = scrub(@expected_json)
@actual == @expected
end
def at_path(path)
@path = path
self
end
def to_file(path)
@expected_json = load_json(path)
self
end
def excluding(*keys)
excluded_keys.merge(keys.map(&:to_s))
self
end
def including(*keys)
excluded_keys.subtract(keys.map(&:to_s))
self
end
def failure_message
message_with_path('Expected equivalent JSON')
end
alias failure_message_for_should failure_message
def failure_message_when_negated
message_with_path('Expected inequivalent JSON')
end
alias failure_message_for_should_not failure_message_when_negated
def description
message_with_path('equal JSON')
end
private
def scrub(json, path = nil)
generate_normalized_json(exclude_keys(parse_json(json, path))).chomp + "\n"
end
end
end
end
end
| 22.60274 | 85 | 0.583636 |
f82eada869a802cbb956649970aca35fe51a8459 | 64,508 | # frozen_string_literal: true
require "abstract_unit"
class Map < Hash
def category
"<mus>"
end
end
class CustomEnumerable
include Enumerable
def each
yield "one"
yield "two"
end
end
class FormOptionsHelperTest < ActionView::TestCase
tests ActionView::Helpers::FormOptionsHelper
silence_warnings do
Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments)
Continent = Struct.new("Continent", :continent_name, :countries)
Country = Struct.new("Country", :country_id, :country_name)
Firm = Struct.new("Firm", :time_zone)
Album = Struct.new("Album", :id, :title, :genre)
end
module FakeZones
FakeZone = Struct.new(:name) do
def to_s; name; end
end
module ClassMethods
def [](id); fake_zones ? fake_zones[id] : super; end
def all; fake_zones ? fake_zones.values : super; end
def dummy; :test; end
end
def self.prepended(base)
class << base
mattr_accessor(:fake_zones)
prepend ClassMethods
end
end
end
ActiveSupport::TimeZone.prepend FakeZones
setup do
ActiveSupport::TimeZone.fake_zones = %w(A B C D E).map do |id|
[ id, FakeZones::FakeZone.new(id) ]
end.to_h
@fake_timezones = ActiveSupport::TimeZone.all
end
teardown do
ActiveSupport::TimeZone.fake_zones = nil
end
def test_collection_options
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title")
)
end
def test_collection_options_with_preselected_value
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", "Babe")
)
end
def test_collection_options_with_preselected_value_array
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ])
)
end
def test_collection_options_with_proc_for_selected
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", lambda { |p| p.author_name == "Babe" })
)
end
def test_collection_options_with_disabled_value
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: "Babe")
)
end
def test_collection_options_with_disabled_array
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: [ "Babe", "Cabe" ])
)
end
def test_collection_options_with_preselected_and_disabled_value
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", selected: "Cabe", disabled: "Babe")
)
end
def test_collection_options_with_proc_for_disabled
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: lambda { |p| %w(Babe Cabe).include?(p.author_name) })
)
end
def test_collection_options_with_proc_for_value_method
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, lambda { |p| p.author_name }, "title")
)
end
def test_collection_options_with_proc_for_text_method
assert_dom_equal(
"<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
options_from_collection_for_select(dummy_posts, "author_name", lambda { |p| p.title })
)
end
def test_collection_options_with_element_attributes
assert_dom_equal(
"<option value=\"USA\" class=\"bold\">USA</option>",
options_from_collection_for_select([[ "USA", "USA", { class: "bold" } ]], :first, :second)
)
end
def test_string_options_for_select
options = "<option value=\"Denmark\">Denmark</option><option value=\"USA\">USA</option><option value=\"Sweden\">Sweden</option>"
assert_dom_equal(
options,
options_for_select(options)
)
end
def test_array_options_for_select
assert_dom_equal(
"<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
options_for_select([ "<Denmark>", "USA", "Sweden" ])
)
end
def test_array_options_for_select_with_custom_defined_selected
assert_dom_equal(
"<option selected=\"selected\" type=\"Coach\" value=\"1\">Richard Bandler</option>\n<option type=\"Coachee\" value=\"1\">Richard Bandler</option>",
options_for_select([
["Richard Bandler", 1, { type: "Coach", selected: "selected" }],
["Richard Bandler", 1, { type: "Coachee" }]
])
)
end
def test_array_options_for_select_with_custom_defined_disabled
assert_dom_equal(
"<option disabled=\"disabled\" type=\"Coach\" value=\"1\">Richard Bandler</option>\n<option type=\"Coachee\" value=\"1\">Richard Bandler</option>",
options_for_select([
["Richard Bandler", 1, { type: "Coach", disabled: "disabled" }],
["Richard Bandler", 1, { type: "Coachee" }]
])
)
end
def test_array_options_for_select_with_selection
assert_dom_equal(
"<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>")
)
end
def test_array_options_for_select_with_selection_array
assert_dom_equal(
"<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ])
)
end
def test_array_options_for_select_with_disabled_value
assert_dom_equal(
"<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
options_for_select([ "Denmark", "<USA>", "Sweden" ], disabled: "<USA>")
)
end
def test_array_options_for_select_with_disabled_array
assert_dom_equal(
"<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\" disabled=\"disabled\">Sweden</option>",
options_for_select([ "Denmark", "<USA>", "Sweden" ], disabled: ["<USA>", "Sweden"])
)
end
def test_array_options_for_select_with_selection_and_disabled_value
assert_dom_equal(
"<option value=\"Denmark\" selected=\"selected\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
options_for_select([ "Denmark", "<USA>", "Sweden" ], selected: "Denmark", disabled: "<USA>")
)
end
def test_boolean_array_options_for_select_with_selection_and_disabled_value
assert_dom_equal(
"<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>",
options_for_select([ true, false ], selected: false, disabled: nil)
)
end
def test_range_options_for_select
assert_dom_equal(
"<option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>",
options_for_select(1..3)
)
end
def test_array_options_for_string_include_in_other_string_bug_fix
assert_dom_equal(
"<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
options_for_select([ "ruby", "rubyonrails" ], "rubyonrails")
)
assert_dom_equal(
"<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>",
options_for_select([ "ruby", "rubyonrails" ], "ruby")
)
assert_dom_equal(
%(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>),
options_for_select([ "ruby", "rubyonrails", nil ], "ruby")
)
end
def test_hash_options_for_select
assert_dom_equal(
"<option value=\"Dollar\">$</option>\n<option value=\"<Kroner>\"><DKR></option>",
options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").join("\n")
)
assert_dom_equal(
"<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"<Kroner>\"><DKR></option>",
options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").join("\n")
)
assert_dom_equal(
"<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>",
options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").join("\n")
)
end
def test_ducktyped_options_for_select
quack = Struct.new(:first, :last)
assert_dom_equal(
"<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>",
options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")])
)
assert_dom_equal(
"<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar")
)
assert_dom_equal(
"<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"])
)
end
def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer
albums = [ Album.new(1, "first", "rap"), Album.new(2, "second", "pop")]
assert_dom_equal(
%(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
options_from_collection_for_select(albums, "id", "genre", selected: "1")
)
end
def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string
albums = [ Album.new("1", "first", "rap"), Album.new("2", "second", "pop")]
assert_dom_equal(
%(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
options_from_collection_for_select(albums, "id", "genre", selected: 1)
)
end
def test_collection_options_with_preselected_value_as_string_and_option_value_is_float
albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>),
options_from_collection_for_select(albums, "id", "genre", selected: "2.0")
)
end
def test_collection_options_with_preselected_value_as_nil
albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
options_from_collection_for_select(albums, "id", "genre", selected: nil)
)
end
def test_collection_options_with_disabled_value_as_nil
albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
options_from_collection_for_select(albums, "id", "genre", disabled: nil)
)
end
def test_collection_options_with_disabled_value_as_array
albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")]
assert_dom_equal(
%(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>),
options_from_collection_for_select(albums, "id", "genre", disabled: ["1.0", 2.0])
)
end
def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float
albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop"), Album.new(3.0, "third", "country") ]
assert_dom_equal(
%(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>),
options_from_collection_for_select(albums, "id", "genre", ["1.0", "3.0"])
)
end
def test_option_groups_from_collection_for_select
assert_dom_equal(
"<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk")
)
end
def test_option_groups_from_collection_for_select_with_callable_group_method
group_proc = Proc.new { |c| c.countries }
assert_dom_equal(
"<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
option_groups_from_collection_for_select(dummy_continents, group_proc, "continent_name", "country_id", "country_name", "dk")
)
end
def test_option_groups_from_collection_for_select_with_callable_group_label_method
label_proc = Proc.new { |c| c.continent_name }
assert_dom_equal(
"<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
option_groups_from_collection_for_select(dummy_continents, "countries", label_proc, "country_id", "country_name", "dk")
)
end
def test_option_groups_from_collection_for_select_returns_html_safe_string
assert_predicate option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk"), :html_safe?
end
def test_grouped_options_for_select_with_array
assert_dom_equal(
"<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
grouped_options_for_select([
["North America",
[["United States", "US"], "Canada"]],
["Europe",
[["Great Britain", "GB"], "Germany"]]
])
)
end
def test_grouped_options_for_select_with_array_and_html_attributes
assert_dom_equal(
"<optgroup label=\"North America\" data-foo=\"bar\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\" disabled=\"disabled\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
grouped_options_for_select([
["North America", [["United States", "US"], "Canada"], data: { foo: "bar" }],
["Europe", [["Great Britain", "GB"], "Germany"], disabled: "disabled"]
])
)
end
def test_grouped_options_for_select_with_optional_divider
assert_dom_equal(
"<optgroup label=\"----------\"><option value=\"US\">US</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"----------\"><option value=\"GB\">GB</option>\n<option value=\"Germany\">Germany</option></optgroup>",
grouped_options_for_select([["US", "Canada"], ["GB", "Germany"]], nil, divider: "----------")
)
end
def test_grouped_options_for_select_with_selected_and_prompt
assert_dom_equal(
"<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], "Cowboy Hat", prompt: "Choose a product...")
)
end
def test_grouped_options_for_select_with_selected_and_prompt_true
assert_dom_equal(
"<option value=\"\">Please select</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], "Cowboy Hat", prompt: true)
)
end
def test_grouped_options_for_select_returns_html_safe_string
assert_predicate grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]]), :html_safe?
end
def test_grouped_options_for_select_with_prompt_returns_html_escaped_string
assert_dom_equal(
"<option value=\"\"><Choose One></option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], nil, prompt: "<Choose One>"))
end
def test_optgroups_with_with_options_with_hash
assert_dom_equal(
"<optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup>",
grouped_options_for_select("North America" => ["United States", "Canada"], "Europe" => ["Denmark", "Germany"])
)
end
def test_time_zone_options_no_params
opts = time_zone_options_for_select
assert_dom_equal "<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\">D</option>\n" \
"<option value=\"E\">E</option>",
opts
end
def test_time_zone_options_with_selected
opts = time_zone_options_for_select("D")
assert_dom_equal "<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>",
opts
end
def test_time_zone_options_with_unknown_selected
opts = time_zone_options_for_select("K")
assert_dom_equal "<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\">D</option>\n" \
"<option value=\"E\">E</option>",
opts
end
def test_time_zone_options_with_priority_zones
zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ]
opts = time_zone_options_for_select(nil, zones)
assert_dom_equal "<option value=\"B\">B</option>\n" \
"<option value=\"E\">E</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\">D</option>",
opts
end
def test_time_zone_options_with_selected_priority_zones
zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ]
opts = time_zone_options_for_select("E", zones)
assert_dom_equal "<option value=\"B\">B</option>\n" \
"<option value=\"E\" selected=\"selected\">E</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\">D</option>",
opts
end
def test_time_zone_options_with_unselected_priority_zones
zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ]
opts = time_zone_options_for_select("C", zones)
assert_dom_equal "<option value=\"B\">B</option>\n" \
"<option value=\"E\">E</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"C\" selected=\"selected\">C</option>\n" \
"<option value=\"D\">D</option>",
opts
end
def test_time_zone_options_with_priority_zones_does_not_mutate_time_zones
original_zones = ActiveSupport::TimeZone.all.dup
zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ]
time_zone_options_for_select(nil, zones)
assert_equal original_zones, ActiveSupport::TimeZone.all
end
def test_time_zone_options_returns_html_safe_string
assert_predicate time_zone_options_for_select, :html_safe?
end
def test_select
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest))
)
end
def test_select_without_multiple
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"></select>",
select(:post, :category, "", {}, { multiple: false })
)
end
def test_select_with_grouped_collection_as_nested_array
@post = Post.new
countries_by_continent = [
["<Africa>", [["<South Africa>", "<sa>"], ["Somalia", "so"]]],
["Europe", [["Denmark", "dk"], ["Ireland", "ie"]]],
]
assert_dom_equal(
[
'<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>',
'<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>',
'<option value="ie">Ireland</option></optgroup></select>',
].join("\n"),
select("post", "origin", countries_by_continent)
)
end
def test_select_with_grouped_collection_as_hash
@post = Post.new
countries_by_continent = {
"<Africa>" => [["<South Africa>", "<sa>"], ["Somalia", "so"]],
"Europe" => [["Denmark", "dk"], ["Ireland", "ie"]],
}
assert_dom_equal(
[
'<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>',
'<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>',
'<option value="ie">Ireland</option></optgroup></select>',
].join("\n"),
select("post", "origin", countries_by_continent)
)
end
def test_select_with_boolean_method
@post = Post.new
@post.allow_comments = false
assert_dom_equal(
"<select id=\"post_allow_comments\" name=\"post[allow_comments]\"><option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option></select>",
select("post", "allow_comments", %w( true false ))
)
end
def test_select_under_fields_for
@post = Post.new
@post.category = "<mus>"
output_buffer = fields_for :post, @post do |f|
concat f.select(:category, %w( abe <mus> hest))
end
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
output_buffer
)
end
def test_fields_for_with_record_inherited_from_hash
map = Map.new
output_buffer = fields_for :map, map do |f|
concat f.select(:category, %w( abe <mus> hest))
end
assert_dom_equal(
"<select id=\"map_category\" name=\"map[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
output_buffer
)
end
def test_select_under_fields_for_with_index
@post = Post.new
@post.category = "<mus>"
output_buffer = fields_for :post, @post, index: 108 do |f|
concat f.select(:category, %w( abe <mus> hest))
end
assert_dom_equal(
"<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
output_buffer
)
end
def test_select_under_fields_for_with_auto_index
@post = Post.new
@post.category = "<mus>"
def @post.to_param; 108; end
output_buffer = fields_for "post[]", @post do |f|
concat f.select(:category, %w( abe <mus> hest))
end
assert_dom_equal(
"<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
output_buffer
)
end
def test_select_under_fields_for_with_string_and_given_prompt
@post = Post.new
options = raw("<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>")
output_buffer = fields_for :post, @post do |f|
concat f.select(:category, options, prompt: "The prompt")
end
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n#{options}</select>",
output_buffer
)
end
def test_select_under_fields_for_with_block
@post = Post.new
output_buffer = fields_for :post, @post do |f|
concat(f.select(:category) do
concat content_tag(:option, "hello world")
end)
end
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option>hello world</option></select>",
output_buffer
)
end
def test_select_under_fields_for_with_block_without_options
@post = Post.new
output_buffer = fields_for :post, @post do |f|
concat(f.select(:category) {})
end
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"></select>",
output_buffer
)
end
def test_select_with_multiple_to_add_hidden_input
output_buffer = select(:post, :category, "", {}, { multiple: true })
assert_dom_equal(
"<input type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
)
end
def test_select_with_multiple_and_without_hidden_input
output_buffer = select(:post, :category, "", { include_hidden: false }, { multiple: true })
assert_dom_equal(
"<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
)
end
def test_select_with_multiple_and_with_explicit_name_ending_with_brackets
output_buffer = select(:post, :category, [], { include_hidden: false }, { multiple: true, name: "post[category][]" })
assert_dom_equal(
"<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
)
end
def test_select_with_multiple_and_disabled_to_add_disabled_hidden_input
output_buffer = select(:post, :category, "", {}, { multiple: true, disabled: true })
assert_dom_equal(
"<input disabled=\"disabled\"type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" disabled=\"disabled\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
)
end
def test_select_with_blank
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), include_blank: true)
)
end
def test_select_with_include_blank_false_and_required
@post = Post.new
@post.category = "<mus>"
e = assert_raises(ArgumentError) { select("post", "category", %w( abe <mus> hest), { include_blank: false }, { required: "required" }) }
assert_match(/include_blank cannot be false for a required field./, e.message)
end
def test_select_with_blank_as_string
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), include_blank: "None")
)
end
def test_select_with_blank_as_string_escaped
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><None></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), include_blank: "<None>")
)
end
def test_select_with_default_prompt
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), prompt: true)
)
end
def test_select_no_prompt_when_select_has_value
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), prompt: true)
)
end
def test_select_with_given_prompt
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), prompt: "The prompt")
)
end
def test_select_with_given_prompt_escaped
@post = Post.new
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><The prompt></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), prompt: "<The prompt>")
)
end
def test_select_with_prompt_and_blank
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest), prompt: true, include_blank: true)
)
end
def test_select_with_empty
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>",
select("post", "category", [], prompt: true, include_blank: true)
)
end
def test_select_with_html_options
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select class=\"disabled\" disabled=\"disabled\" name=\"post[category]\" id=\"post_category\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>",
select("post", "category", [], { prompt: true, include_blank: true }, { class: "disabled", disabled: true })
)
end
def test_select_with_nil
@post = Post.new
@post.category = "othervalue"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"othervalue\" selected=\"selected\">othervalue</option></select>",
select("post", "category", [nil, "othervalue"])
)
end
def test_required_select
assert_dom_equal(
%(<select id="post_category" name="post[category]" required="required"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), {}, { required: true })
)
end
def test_required_select_with_include_blank_prompt
assert_dom_equal(
%(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), { include_blank: "Select one" }, { required: true })
)
end
def test_required_select_with_prompt
assert_dom_equal(
%(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), { prompt: "Select one" }, { required: true })
)
end
def test_required_select_display_size_equals_to_one
assert_dom_equal(
%(<select id="post_category" name="post[category]" required="required" size="1"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), {}, { required: true, size: 1 })
)
end
def test_required_select_with_display_size_bigger_than_one
assert_dom_equal(
%(<select id="post_category" name="post[category]" required="required" size="2"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), {}, { required: true, size: 2 })
)
end
def test_required_select_with_multiple_option
assert_dom_equal(
%(<input name="post[category][]" type="hidden" value=""/><select id="post_category" multiple="multiple" name="post[category][]" required="required"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
select("post", "category", %w(abe mus hest), {}, { required: true, multiple: true })
)
end
def test_select_with_integer
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"1\">1</option></select>",
select("post", "category", [1], prompt: true, include_blank: true)
)
end
def test_list_of_lists
@post = Post.new
@post.category = ""
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"number\">Number</option>\n<option value=\"text\">Text</option>\n<option value=\"boolean\">Yes/No</option></select>",
select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], prompt: true, include_blank: true)
)
end
def test_select_with_selected_value
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest ), selected: "abe")
)
end
def test_select_with_index_option
@album = Album.new
@album.id = 1
expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>"
assert_dom_equal(
expected,
select("album[]", "genre", %w[rap rock country], {}, { index: nil })
)
end
def test_select_escapes_options
assert_dom_equal(
'<select id="post_title" name="post[title]"><script>alert(1)</script></select>',
select("post", "title", "<script>alert(1)</script>")
)
end
def test_select_with_selected_nil
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
select("post", "category", %w( abe <mus> hest ), selected: nil)
)
end
def test_select_with_disabled_value
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
select("post", "category", %w( abe <mus> hest ), disabled: "hest")
)
end
def test_select_not_existing_method_with_selected_value
@post = Post.new
assert_dom_equal(
"<select id=\"post_locale\" name=\"post[locale]\"><option value=\"en\">en</option>\n<option value=\"ru\" selected=\"selected\">ru</option></select>",
select("post", "locale", %w( en ru ), selected: "ru")
)
end
def test_select_with_prompt_and_selected_value
@post = Post.new
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"one\">one</option>\n<option selected=\"selected\" value=\"two\">two</option></select>",
select("post", "category", %w( one two ), selected: "two", prompt: true)
)
end
def test_select_with_disabled_array
@post = Post.new
@post.category = "<mus>"
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" disabled=\"disabled\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
select("post", "category", %w( abe <mus> hest ), disabled: ["hest", "abe"])
)
end
def test_select_with_range
@post = Post.new
@post.category = 0
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option></select>",
select("post", "category", 1..3)
)
end
def test_select_with_enumerable
@post = Post.new
assert_dom_equal(
"<select id=\"post_category\" name=\"post[category]\"><option value=\"one\">one</option>\n<option value=\"two\">two</option></select>",
select("post", "category", CustomEnumerable.new)
)
end
def test_collection_select
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
collection_select("post", "author_name", dummy_posts, "author_name", "author_name")
)
end
def test_collection_select_under_fields_for
@post = Post.new
@post.author_name = "Babe"
output_buffer = fields_for :post, @post do |f|
concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
output_buffer
)
end
def test_collection_select_under_fields_for_with_index
@post = Post.new
@post.author_name = "Babe"
output_buffer = fields_for :post, @post, index: 815 do |f|
concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
"<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
output_buffer
)
end
def test_collection_select_under_fields_for_with_auto_index
@post = Post.new
@post.author_name = "Babe"
def @post.to_param; 815; end
output_buffer = fields_for "post[]", @post do |f|
concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
end
assert_dom_equal(
"<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
output_buffer
)
end
def test_collection_select_with_blank_and_style
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true }, { "style" => "width: 200px" })
)
end
def test_collection_select_with_blank_as_string_and_style
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: "No Selection" }, { "style" => "width: 200px" })
)
end
def test_collection_select_with_multiple_option_appends_array_brackets_and_hidden_input
@post = Post.new
@post.author_name = "Babe"
expected = "<input type=\"hidden\" name=\"post[author_name][]\" value=\"\"/><select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>"
# Should suffix default name with [].
assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true }, { multiple: true })
# Shouldn't suffix custom name with [].
assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true, name: "post[author_name][]" }, { multiple: true })
end
def test_collection_select_with_blank_and_selected
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
%{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="<Abe>" selected="selected"><Abe></option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>},
collection_select("post", "author_name", dummy_posts, "author_name", "author_name", include_blank: true, selected: "<Abe>")
)
end
def test_collection_select_with_disabled
@post = Post.new
@post.author_name = "Babe"
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe</option></select>",
collection_select("post", "author_name", dummy_posts, "author_name", "author_name", disabled: "Cabe")
)
end
def test_collection_select_with_proc_for_value_method
@post = Post.new
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option></select>",
collection_select("post", "author_name", dummy_posts, lambda { |p| p.author_name }, "title")
)
end
def test_collection_select_with_proc_for_text_method
@post = Post.new
assert_dom_equal(
"<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option></select>",
collection_select("post", "author_name", dummy_posts, "author_name", lambda { |p| p.title })
)
end
def test_time_zone_select
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone")
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_under_fields_for
@firm = Firm.new("D")
output_buffer = fields_for :firm, @firm do |f|
concat f.time_zone_select(:time_zone)
end
assert_dom_equal(
"<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
output_buffer
)
end
def test_time_zone_select_under_fields_for_with_index
@firm = Firm.new("D")
output_buffer = fields_for :firm, @firm, index: 305 do |f|
concat f.time_zone_select(:time_zone)
end
assert_dom_equal(
"<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
output_buffer
)
end
def test_time_zone_select_under_fields_for_with_auto_index
@firm = Firm.new("D")
def @firm.to_param; 305; end
output_buffer = fields_for "firm[]", @firm do |f|
concat f.time_zone_select(:time_zone)
end
assert_dom_equal(
"<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
output_buffer
)
end
def test_time_zone_select_with_blank
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil, include_blank: true)
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"\"></option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_blank_as_string
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil, include_blank: "No Zone")
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"\">No Zone</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_style
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil, {},
{ "style" => "color: red" })
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {},
{ style: "color: red" })
end
def test_time_zone_select_with_blank_and_style
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil,
{ include_blank: true }, { "style" => "color: red" })
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \
"<option value=\"\"></option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
{ include_blank: true }, { style: "color: red" })
end
def test_time_zone_select_with_blank_as_string_and_style
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil,
{ include_blank: "No Zone" }, { "style" => "color: red" })
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \
"<option value=\"\">No Zone</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
{ include_blank: "No Zone" }, { style: "color: red" })
end
def test_time_zone_select_with_priority_zones
@firm = Firm.new("D")
zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ]
html = time_zone_select("firm", "time_zone", zones)
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_priority_zones_as_regexp
@firm = Firm.new("D")
@fake_timezones.each do |tz|
def tz.=~(re); %(A D).include?(name) end
end
html = time_zone_select("firm", "time_zone", /A|D/)
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_priority_zones_is_not_implemented_with_grep
@firm = Firm.new("D")
# `time_zone_select` can't be written with `grep` because Active Support
# time zones don't support implicit string coercion with `to_str`.
@fake_timezones.each do |tz|
def tz.===(zone); raise Exception; end
end
html = time_zone_select("firm", "time_zone", /A|D/)
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_priority_zones_and_errors
@firm = Firm.new("D")
@firm.extend ActiveModel::Validations
@firm.errors[:time_zone] << "invalid"
zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ]
html = time_zone_select("firm", "time_zone", zones)
assert_dom_equal "<div class=\"field_with_errors\">" \
"<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>" \
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"E\">E</option>" \
"</select>" \
"</div>",
html
end
def test_time_zone_select_with_default_time_zone_and_nil_value
@firm = Firm.new()
@firm.time_zone = nil
html = time_zone_select("firm", "time_zone", nil, default: "B")
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\" selected=\"selected\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_time_zone_select_with_default_time_zone_and_value
@firm = Firm.new("D")
html = time_zone_select("firm", "time_zone", nil, default: "B")
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \
"<option value=\"A\">A</option>\n" \
"<option value=\"B\">B</option>\n" \
"<option value=\"C\">C</option>\n" \
"<option value=\"D\" selected=\"selected\">D</option>\n" \
"<option value=\"E\">E</option>" \
"</select>",
html
end
def test_options_for_select_with_element_attributes
assert_dom_equal(
"<option value=\"<Denmark>\" class=\"bold\"><Denmark></option>\n<option value=\"USA\" onclick=\"alert('Hello World');\">USA</option>\n<option value=\"Sweden\">Sweden</option>\n<option value=\"Germany\">Germany</option>",
options_for_select([ [ "<Denmark>", { class: "bold" } ], [ "USA", { onclick: "alert('Hello World');" } ], [ "Sweden" ], "Germany" ])
)
end
def test_options_for_select_with_data_element
assert_dom_equal(
"<option value=\"<Denmark>\" data-test=\"bold\"><Denmark></option>",
options_for_select([ [ "<Denmark>", { data: { test: "bold" } } ] ])
)
end
def test_options_for_select_with_data_element_with_special_characters
assert_dom_equal(
"<option value=\"<Denmark>\" data-test=\"<bold>\"><Denmark></option>",
options_for_select([ [ "<Denmark>", { data: { test: "<bold>" } } ] ])
)
end
def test_options_for_select_with_element_attributes_and_selection
assert_dom_equal(
"<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
options_for_select([ "<Denmark>", [ "USA", { class: "bold" } ], "Sweden" ], "USA")
)
end
def test_options_for_select_with_element_attributes_and_selection_array
assert_dom_equal(
"<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
options_for_select([ "<Denmark>", [ "USA", { class: "bold" } ], "Sweden" ], [ "USA", "Sweden" ])
)
end
def test_options_for_select_with_special_characters
assert_dom_equal(
"<option value=\"<Denmark>\" onclick=\"alert("<code>")\"><Denmark></option>",
options_for_select([ [ "<Denmark>", { onclick: %(alert("<code>")) } ] ])
)
end
def test_option_html_attributes_with_no_array_element
assert_equal({}, option_html_attributes("foo"))
end
def test_option_html_attributes_without_hash
assert_equal({}, option_html_attributes([ "foo", "bar" ]))
end
def test_option_html_attributes_with_single_element_hash
assert_equal(
{ class: "fancy" },
option_html_attributes([ "foo", "bar", { class: "fancy" } ])
)
end
def test_option_html_attributes_with_multiple_element_hash
assert_equal(
{ :class => "fancy", "onclick" => "alert('Hello World');" },
option_html_attributes([ "foo", "bar", { :class => "fancy", "onclick" => "alert('Hello World');" } ])
)
end
def test_option_html_attributes_with_multiple_hashes
assert_equal(
{ :class => "fancy", "onclick" => "alert('Hello World');" },
option_html_attributes([ "foo", "bar", { class: "fancy" }, { "onclick" => "alert('Hello World');" } ])
)
end
def test_option_html_attributes_with_multiple_hashes_does_not_modify_them
options1 = { class: "fancy" }
options2 = { onclick: "alert('Hello World');" }
option_html_attributes([ "foo", "bar", options1, options2 ])
assert_equal({ class: "fancy" }, options1)
assert_equal({ onclick: "alert('Hello World');" }, options2)
end
def test_grouped_collection_select
@post = Post.new
@post.origin = "dk"
assert_dom_equal(
%Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name)
)
end
def test_grouped_collection_select_with_selected
@post = Post.new
assert_dom_equal(
%Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, selected: "dk")
)
end
def test_grouped_collection_select_with_disabled_value
@post = Post.new
assert_dom_equal(
%Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option disabled="disabled" value="dk">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, disabled: "dk")
)
end
def test_grouped_collection_select_under_fields_for
@post = Post.new
@post.origin = "dk"
output_buffer = fields_for :post, @post do |f|
concat f.grouped_collection_select("origin", dummy_continents, :countries, :continent_name, :country_id, :country_name)
end
assert_dom_equal(
%Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
output_buffer
)
end
private
def dummy_posts
[ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
Post.new("Babe went home", "Babe", "To a little house", "shh!"),
Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ]
end
def dummy_continents
[ Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")]),
Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ]
end
end
| 44.396421 | 351 | 0.633937 |
f887e40f6e5916f08c57de8f179c88b42edae07d | 712 | set :rails_env, 'production'
server 'dash1.code.org', :app, :web, :db, :primary => true
server 'dash5.code.org', :app, :web
server 'dash6.code.org', :app, :web
server 'dash7.code.org', :app, :web
server 'dash8.code.org', :app, :web
server 'dash9.code.org', :app, :web
server 'dash10.code.org', :app, :web
server 'dash11.code.org', :app, :web
server 'dash12.code.org', :app, :web
server 'dash13.code.org', :app, :web
server 'dash14.code.org', :app, :web
server 'dash15.code.org', :app, :web
server 'dash16.code.org', :app, :web
server 'dash17.code.org', :app, :web
server 'dash19.code.org', :app, :web
server 'dash20.code.org', :app, :web
server 'dash23.code.org', :app, :web
server 'dash26.code.org', :app, :web
| 35.6 | 58 | 0.672753 |
e834525cb2a3c52365c0dfe1e48fd3ecc5f9a27e | 534 | module SlackSupport
class Emoji
def initialize(client)
@client = client
end
def get(name)
list[name]
end
alias [] get
def list
@list ||= Rails.cache.fetch('slack_support__emoji#list', expires_in: 30.minutes) do
resp = @client.emoji_list
return {} unless resp['ok']
resp['emoji'].tap do |list|
list.map do |key, value|
list[key] = list[Regexp.last_match(1)] if value =~ /\Aalias:(.+)\z/
end
end
end
end
end
end
| 19.777778 | 89 | 0.552434 |
bb5faea885835fd53924aa32ee65b0d81340a02b | 906 | class Wiki < Formula
desc "Fetch summaries from MediaWiki wikis, like Wikipedia"
homepage "https://github.com/walle/wiki"
url "https://github.com/walle/wiki/archive/v1.4.1.tar.gz"
sha256 "529c6a58b3b5c5eb3faab07f2bf752155868b912e4f753e432d14040ff4f4262"
license "MIT"
bottle do
cellar :any_skip_relocation
sha256 "ff424f6afbc0d2baab91cee289157d9c90623fa19b7d51574b75df455da76cd6" => :catalina
sha256 "316687b381ca23ee0e81eb6e396d2c8c21a5eeaf05a9219ec56dd0024a8d9722" => :mojave
sha256 "bd1b52730bbf5bc503d3fece003b069e248261616d9d02767ef019d87659bdd8" => :high_sierra
end
depends_on "go" => :build
def install
system "go", "build", "-o", bin/"wiki", "cmd/wiki/main.go"
end
test do
assert_match version.to_s, shell_output("#{bin}/wiki --version")
assert_match "Read more: https://en.wikipedia.org/wiki/Go", shell_output("#{bin}/wiki golang")
end
end
| 33.555556 | 98 | 0.754967 |
6299c114467040835b7893d9371d032ea705d5ef | 1,040 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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.
# frozen_string_literal: true
module ElasticAPM
class Config
# @api private
class RegexpList
def call(value)
value = value.is_a?(String) ? value.split(',') : Array(value)
value.map(&Regexp.method(:new))
end
end
end
end
| 33.548387 | 69 | 0.735577 |
91a10778636a50f02beb76b17310a0d87cc249a2 | 14,382 | # frozen_string_literal: true
require 'spec_helper'
describe SFRest::Update do
before :each do
@conn = SFRest.new "http://#{@mock_endpoint}", @mock_user, @mock_pass
end
describe '#status_info' do
path = '/api/v1/status'
it 'can get status' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.status_info
uri = URI res['uri']
expect(uri.path).to eq path
expect(res['method']).to eq 'get'
end
end
describe '#modify_status' do
path = '/api/v1/status'
it 'can set maintenance mode' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.modify_status 'on', 'on', 'on', 'on'
uri = URI res['uri']
expect(uri.path).to eq path
expect(JSON(res['body'])['site_creation']).to eq 'on'
expect(JSON(res['body'])['site_duplication']).to eq 'on'
expect(JSON(res['body'])['domain_management']).to eq 'on'
expect(JSON(res['body'])['bulk_operations']).to eq 'on'
expect(res['method']).to eq 'put'
end
end
describe '#process_theme_notification' do
path = '/api/v1/theme/process'
it 'can process notifications' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.theme.process_theme_notification
uri = URI res['uri']
expect(uri.path).to eq path
expect(res['method']).to eq 'post'
expect(JSON(res['body'])['sitegroup_id']).to eq 0
end
it 'can process sitegroup notifications' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
sid = rand 1000
res = @conn.theme.process_theme_notification sid
uri = URI res['uri']
expect(uri.path).to eq path
expect(res['method']).to eq 'post'
expect(JSON(res['body'])['sitegroup_id']).to eq sid
end
end
describe '#start_update' do
path = '/api/v(1|2)/update'
stacks_path = '/api/v1/stacks'
it 'can start an update' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
ref = SecureRandom.urlsafe_base64
res = @conn.update.start_update ref
uri = URI res['uri']
expect(uri.path).to match path
expect(JSON(res['body'])['scope']).to eq 'sites'
expect(JSON(res['body'])['sites_type']).to eq 'code, db'
expect(JSON(res['body'])['sites_ref']).to eq ref
expect(res['method']).to eq 'post'
end
it 'cannot update a multistack' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
.to_return do |request|
{ status: 200, body: { uri: request.uri, body: request.body, method: request.method }.to_json }
end
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
ref = SecureRandom.urlsafe_base64
expect { @conn.update.start_update ref }.to raise_error SFRest::InvalidApiVersion
end
end
describe '#update' do
path = '/api/v(1|2)/update'
stacks_path = '/api/v1/stacks'
it 'can start a multistack update' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
ref = SecureRandom.urlsafe_base64
res = @conn.update.update sites: [{ name: 'foo', ref: ref }]
uri = URI res['uri']
expect(uri.path).to match path
expect(JSON(res['body'])['sites']).to eq ['name' => 'foo', 'ref' => ref]
expect(res['method']).to eq 'post'
end
it 'can start a single stack update' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
ref = SecureRandom.urlsafe_base64
res = @conn.update.update scope: 'sites', sites_ref: ref, sites_type: 'code, db'
uri = URI res['uri']
expect(uri.path).to match path
expect(JSON(res['body'])['scope']).to eq 'sites'
expect(JSON(res['body'])['sites_type']).to eq 'code, db'
expect(JSON(res['body'])['sites_ref']).to eq ref
end
it 'can not start an update on the wrong version' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
ref = SecureRandom.urlsafe_base64
expect { @conn.update.update sites: [{ name: 'foo', ref: ref }] }.to raise_error SFRest::InvalidDataError
end
end
describe '#update_version' do
path = '/api/v(1|2)/update'
stacks_path = '/api/v1/stacks'
it 'returns v1 if 1 stack' do
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
expect(@conn.update.update_version).to eq 'v1'
end
it 'returns v2 if 2 stacks' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
expect(@conn.update.update_version).to eq 'v2'
end
end
describe '#multi_stack?' do
stacks_path = '/api/v1/stacks'
it 'returns the proper stack status' do
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
expect(@conn.update.multi_stack?).to be false
expect(@conn.update.multi_stack?).to be true
end
# @TODO: this does not ensure multi_stack is singleton
end
describe '#v2_endpoint?' do
path = '/api/v(1|2)/update'
it 'detects a v1 endpoint' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::InvalidResponse.new('Invalid data, status 404'))
expect(@conn.update.v2_endpoint?).to be false
end
it 'detects a v2 endpoint' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
expect(@conn.update.v2_endpoint?).to be true
end
it 'takes exception to other responses' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::InvalidResponse.new)
.to_raise(SFRest::InvalidResponse.new('Invalid data danger danger, status 404'))
.to_raise(SFRest::UnprocessableEntity)
expect { @conn.update.v2_endpoint? }.to raise_error(SFRest::InvalidResponse)
expect { @conn.update.v2_endpoint? }.to raise_error(SFRest::InvalidResponse)
expect { @conn.update.v2_endpoint? }.to raise_error(SFRest::UnprocessableEntity)
end
end
describe '#validate_request' do
path = '/api/v(1|2)/update'
stacks_path = '/api/v1/stacks'
v1_datum = { scope: 'both',
sites_ref: 'tags/1234',
factory_ref: 'tags/2345',
sites_type: 'code',
factory_type: 'code, db',
db_update_arguments: 'arg1 arg2' }
v2_datum = { sites: [{ name: 's3tg42', ref: 'tags/12345', type: 'code', db_update_arguments: 'arg1 arg2' }],
factory: { ref: 'tags/5678', type: 'code' } }
it 'will use a v1 data set' do
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
expect(@conn.update.validate_request(v1_datum)).to be nil
end
it 'will raise if v2 tries to use v1 data' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
expect { @conn.update.validate_request(v1_datum) }.to raise_error SFRest::InvalidDataError
end
it 'will use a v2 data set' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_raise(SFRest::BadRequestError)
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde', 2 => 'fghij' } }.to_json)
expect(@conn.update.validate_request(v2_datum)).to be nil
end
it 'will raise if v1 tries to use v2 data' do
stub_request(:any, /.*#{@mock_endpoint}.*#{stacks_path}/)
.with(headers: @mock_headers)
.to_return(body: { 'stacks' => { 1 => 'abcde' } }.to_json)
expect { @conn.update.validate_request(v2_datum) }.to raise_error SFRest::InvalidDataError
end
end
describe '#list_vcs_refs' do
path = '/api/v1/vcs'
it 'can list vcs refs' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.list_vcs_refs
uri = URI res['uri']
query_hash = URI.decode_www_form(uri.query).to_h
expect(uri.path).to eq path
expect(query_hash['type']).to eq 'sites'
expect(res['method']).to eq 'get'
end
it 'can list refs refs on other stacks' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.list_vcs_refs 'sites', 2
uri = URI res['uri']
query_hash = URI.decode_www_form(uri.query).to_h
expect(uri.path).to eq path
expect(query_hash['type']).to eq 'sites'
expect(query_hash['stack_id']).to eq '2'
expect(res['method']).to eq 'get'
end
it 'can list factory vcs refs' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.list_vcs_refs 'factory'
uri = URI res['uri']
query_hash = URI.decode_www_form(uri.query).to_h
expect(uri.path).to eq path
expect(query_hash['type']).to eq 'factory'
expect(res['method']).to eq 'get'
end
end
describe '#update_list' do
path = '/api/v1/update'
it 'list updates' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.update_list
uri = URI res['uri']
expect(uri.path).to eq path
expect(res['method']).to eq 'get'
end
end
describe '#update_progress' do
path = '/api/v1/update'
it 'get the status of an update' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
upid = rand 1000
res = @conn.update.update_progress upid
uri = URI res['uri']
expect(uri.path).to eq "#{path}/#{upid}/status"
expect(res['method']).to eq 'get'
end
end
describe '#pause_update' do
path = '/api/v1/update'
it 'can pause updates' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.pause_update
uri = URI res['uri']
expect(uri.path).to eq "#{path}/pause"
expect(JSON(res['body'])['pause']).to eq true
expect(res['method']).to eq 'post'
end
end
describe '#resume_update' do
path = '/api/v1/update'
it 'can resume updates' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
res = @conn.update.resume_update
uri = URI res['uri']
expect(uri.path).to eq "#{path}/pause"
expect(JSON(res['body'])['pause']).to eq false
expect(res['method']).to eq 'post'
end
end
end
| 39.95 | 115 | 0.606383 |
2643ebc98c366e17d54859059b7ea799cb1f71a6 | 1,012 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Spree::Tax::OrderAdjuster do
subject(:adjuster) { described_class.new(order) }
describe 'initialization' do
let(:order) { Spree::Order.new }
it 'sets order to adjustable' do
expect(adjuster.order).to eq(order)
end
end
describe '#adjust!' do
let(:order) { Spree::Order.new }
let(:custom_calculator_class) { double }
let(:custom_calculator_instance) { double }
before do
stub_spree_preferences(tax_calculator_class: custom_calculator_class)
end
it 'calls the configured tax calculator' do
expect(custom_calculator_class).to receive(:new).with(order).at_least(:once).and_return(custom_calculator_instance)
expect(custom_calculator_instance).to receive(:calculate).at_least(:once).and_return(
Spree::Tax::OrderTax.new(order_id: order.id, line_item_taxes: [], shipment_taxes: [])
)
adjuster.adjust!
end
end
end
| 28.111111 | 122 | 0.684783 |
ff21452067f509d7fc5669e14c33ec10ada9207c | 5,335 | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "tutorhub_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.090909 | 114 | 0.765323 |
4a2fe6053b1475fed83d0a51322a6d5b6f3cb973 | 8,048 | require 'test_helper'
describe BrNfe::Product::Gateway::WebServiceSVAN do
subject { BrNfe::Product::Gateway::WebServiceSVAN.new(env: :test) }
it "deve herdar da class base" do
subject.class.superclass.must_equal BrNfe::Product::Gateway::Base
end
describe 'STATUS SERVIÇO' do
describe '#wsdl_status_servico' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_status_servico.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeStatusServico2/NfeStatusServico2.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_status_servico.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeStatusServico2/NfeStatusServico2.asmx?wsdl'
end
end
describe '#operation_status_servico' do
it { subject.operation_status_servico.must_equal :nfe_status_servico_nf2 }
end
describe '#version_xml_status_servico' do
it { subject.version_xml_status_servico.must_equal :v3_10 }
end
describe '#url_xmlns_status_servico' do
it { subject.url_xmlns_status_servico.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2' }
end
describe '#ssl_version_status_servico' do
it { subject.ssl_version_status_servico.must_equal :TLSv1 }
end
end
describe 'AUTORIZAÇÃO' do
describe '#wsdl_autorizacao' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_autorizacao.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeAutorizacao/NfeAutorizacao.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_autorizacao.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeAutorizacao/NfeAutorizacao.asmx?wsdl'
end
end
describe '#operation_autorizacao' do
it { subject.operation_autorizacao.must_equal :nfe_autorizacao_lote }
end
describe '#version_xml_autorizacao' do
it { subject.version_xml_autorizacao.must_equal :v3_10 }
end
describe '#url_xmlns_autorizacao' do
it { subject.url_xmlns_autorizacao.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao' }
end
describe '#ssl_version_autorizacao' do
it { subject.ssl_version_autorizacao.must_equal :TLSv1 }
end
end
describe 'RETORNO AUTORIZAÇÃO' do
describe '#wsdl_retorno_autorizacao' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_retorno_autorizacao.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeRetAutorizacao/NfeRetAutorizacao.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_retorno_autorizacao.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeRetAutorizacao/NfeRetAutorizacao.asmx?wsdl'
end
end
describe '#operation_retorno_autorizacao' do
it { subject.operation_retorno_autorizacao.must_equal :nfe_ret_autorizacao_lote }
end
describe '#version_xml_retorno_autorizacao' do
it { subject.version_xml_retorno_autorizacao.must_equal :v3_10 }
end
describe '#url_xmlns_retorno_autorizacao' do
it { subject.url_xmlns_retorno_autorizacao.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeRetAutorizacao' }
end
describe '#ssl_version_retorno_autorizacao' do
it { subject.ssl_version_retorno_autorizacao.must_equal :TLSv1 }
end
end
describe 'CONSULTA PROTOCOLO' do
describe '#wsdl_consulta_protocolo' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_consulta_protocolo.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_consulta_protocolo.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeConsulta2/NfeConsulta2.asmx?wsdl'
end
end
describe '#operation_consulta_protocolo' do
it { subject.operation_consulta_protocolo.must_equal :nfe_consulta_nf2 }
end
describe '#version_xml_consulta_protocolo' do
it { subject.version_xml_consulta_protocolo.must_equal :v3_10 }
end
describe '#url_xmlns_consulta_protocolo' do
it { subject.url_xmlns_consulta_protocolo.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeConsulta2' }
end
describe '#ssl_version_consulta_protocolo' do
it { subject.ssl_version_consulta_protocolo.must_equal :TLSv1 }
end
end
describe 'NFE INUTILIZAÇÃO' do
describe '#wsdl_inutilizacao' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_inutilizacao.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeInutilizacao2/NfeInutilizacao2.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_inutilizacao.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeInutilizacao2/NfeInutilizacao2.asmx?wsdl'
end
end
describe '#operation_inutilizacao' do
it { subject.operation_inutilizacao.must_equal :nfe_inutilizacao_nf2 }
end
describe '#version_xml_inutilizacao' do
it { subject.version_xml_inutilizacao.must_equal :v3_10 }
end
describe '#url_xmlns_inutilizacao' do
it { subject.url_xmlns_inutilizacao.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeInutilizacao2' }
end
describe '#ssl_version_inutilizacao' do
it { subject.ssl_version_inutilizacao.must_equal :TLSv1 }
end
end
describe 'RECEPÇÃO EVENTO' do
describe '#wsdl_recepcao_evento' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_recepcao_evento.must_equal 'https://www.sefazvirtual.fazenda.gov.br/RecepcaoEvento/RecepcaoEvento.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_recepcao_evento.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/RecepcaoEvento/RecepcaoEvento.asmx?wsdl'
end
end
describe '#operation_recepcao_evento' do
it { subject.operation_recepcao_evento.must_equal :nfe_recepcao_evento }
end
describe '#version_xml_recepcao_evento' do
it { subject.version_xml_recepcao_evento.must_equal :v1_00 }
end
describe '#url_xmlns_recepcao_evento' do
it { subject.url_xmlns_recepcao_evento.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/RecepcaoEvento' }
end
describe '#ssl_version_recepcao_evento' do
it { subject.ssl_version_recepcao_evento.must_equal :TLSv1 }
end
end
describe 'DOWNLOAD NF' do
describe '#wsdl_download_nf' do
it "para ambiente de produção" do
subject.env = :production
subject.wsdl_download_nf.must_equal 'https://www.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx?wsdl'
end
it "para ambiente de homologação" do
subject.env = :test
subject.wsdl_download_nf.must_equal 'https://hom.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx?wsdl'
end
end
describe '#operation_download_nf' do
it "para ambiente de produção" do
subject.env = :production
subject.operation_download_nf.must_equal :nfe_download_nf
end
it "para ambiente de homologação" do
subject.env = :test
subject.operation_download_nf.must_equal :nfe_download_nf
end
end
describe '#version_xml_download_nf' do
it "para ambiente de produção" do
subject.env = :production
subject.version_xml_download_nf.must_equal :v1_00
end
it "para ambiente de homologação" do
subject.env = :test
subject.version_xml_download_nf.must_equal :v1_00
end
end
describe '#url_xmlns_download_nf' do
it "para ambiente de produção" do
subject.env = :production
subject.url_xmlns_download_nf.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF'
end
it "para ambiente de homologação" do
subject.env = :test
subject.url_xmlns_download_nf.must_equal 'http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF'
end
end
describe '#ssl_version_download_nf' do
it "para ambiente de produção" do
subject.env = :production
subject.ssl_version_download_nf.must_equal :TLSv1
end
it "para ambiente de homologação" do
subject.env = :test
subject.ssl_version_download_nf.must_equal :TLSv1
end
end
end
end | 33.256198 | 135 | 0.769384 |
edde019e6a93554837a7ccc9d0ede656c710fb11 | 24,782 | # encoding: utf-8
###
#
# for latest updates on new fancies/exclusives see:
# https://updates.cryptokitties.co (official latest updates/timeline)
#
# or see
# https://blog.kotobaza.co/timeline/
#
# or see
# https://kittyhelper.co/price-floor/exclusive/
# https://kittyhelper.co/price-floor/specialedition/
# https://kittyhelper.co/price-floor/fancy/
##
## note:
## for time limits for fancies use:
## e.g. time: { end: '2018-12-07' } # until dec/7
##
## for overflows for limited edition use:
## e.g. overflow: 1 # 888+1 (=889)
RECIPES = {
pepito: { name: 'Pepito',
recipe: {
time: { start: '2020-01-01', end: '2020-01-07' }, count: 443,
traits: ['ragdoll', 'simple', 'meowgarine', 'junglebook'] },
},
chitten: { name: 'Chitten', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-12-21', end: '?' }, count: 829,
traits: ['burmilla', 'calicool', 'hotcocoa', 'tongue'] },
},
puuurrot: { name: 'Puuurrot', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-12-07', end: '?' }, count: 650,
traits: ['chantilly', 'firstblush', 'skyblue', 'tinybox'] },
},
shoopadoop: { name: 'Shoopadoop', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-11-23', end: '?' }, count: 1269,
traits: ['martian', 'wyrm', 'SE03'] },
},
bartholomeow: { name: 'Bartholomeow', date: '2019-11-12', # Page's Warriors series
recipe: {
limit: 10_000, count: 1269,
traits: ['burmilla', 'thunderstruck', 'salmon', 'flamingo', 'rosequartz', 'wasntme'] },
}, ## add shiny-enabled? see https://www.cryptokitties.co/blog/post/ooooooh-shiny
gwendolion: { name: 'Gwendolion', date: '2019-11-10', # Page's Warriors series - starter fancy
recipe: {
limit: 50_000, count: 297,
traits: ['burmilla', 'salmon', 'icy'] },
},
catseye: { name: 'Catseye', date: '2019-11-09',
recipe: {
limit: 30_000, count: 196,
traits: ['burmilla', 'rascal', 'salmon', 'flamingo'] },
},
# Oct 26, 2019 - Skeletonne Fancy Cat is discovered
skeletonne: { name: 'Skeletonne', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-10-26', end: '?' }, count: 752,
traits: ['sphynx', 'scorpius', 'dreamboat', 'satiated'] },
},
# Oct 12, 2019 - Furmione Fancy Cat is discovered
furmione: { name: 'Furmione', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-10-12', end: '?' }, count: 832,
traits: ['spangled', 'firstblush', ['poisonberry', 'mallowflower']] },
},
# Sep 20, 2019 - Purrzival Fancy Cat is discovered
purrzival: { name: 'Purrzival the Paladin', date: '2019-09-20', ## todo/check: was time-limited too?
recipe: {
limit: 30_000, count: 316,
traits: ['thunderstruck', 'rosequartz', 'peach', 'wasntme'] },
},
# Sep 28, 2019 - Jack Fancy Cat is discovered
jack: { name: 'Jack', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-09-28', end: '?' }, count: 721,
traits: ['savannah', 'shadowgrey', 'granitegrey', 'jacked'] },
},
# Sep 14, 2019 - Pawderick the Lancer Fancy Cat is discovered
pawderick: { name: 'Pawderick the Lancer', date: '2019-09-14', ## todo/check: was time-limited too?
recipe: {
limit: 50_000, count: 665,
traits: ['ganado', 'rosequartz', 'wasntme'] },
},
# Aug 31, 2019 - Robin Fancy Cat is discovered
robin: { name: 'Robin', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-08-31', end: '?' }, count: 1837,
traits: ['stunned', 'meowgarine', 'kittencream', 'fetherbrain'] },
},
# Aug 17, 2019 - Kitty Formerly Known as Prince Fancy Cat is discovered
kittyformerlyknownasprince: { name: 'Kitty Formerly Known As Prince', ## todo/check: was time-limited?
recipe: {
time: { start: '2019-08-17', end: '?' }, count: 503,
traits: ['leopard', 'tendertears', 'royalblue', 'pouty'] },
},
# Aug 3, 2019 - DJ Meowlody Fancy Cat is discovered
djmeowlody: { name: 'DJ Meowlody',
recipe: {
time: { start: '2019-08-03', end: '2019-11-30' }, count: 155,
traits: ['happygokitty', 'ragdoll', 'tigerpunk', 'oceanid'] },
},
# Jul 22, 2019 - Poison Orchid Fancy Cat is discovered
poisonorchid: { name: 'Poison Orchid', date: '2019-07-22',
recipe: {
limit: 499,
traits: ['burmilla', 'henna', 'drama', 'onyx', 'wolfgrey', 'dreamboat', 'SE29'] },
desc: 'Ninja Fancy Cat' },
# Jul 18, 2019 - Catyrax Fancy Cat is discovered
catyrax: { name: 'Catyrax', date: '2019-07-18',
recipe: {
limit: 500,
traits: ['lykoi', 'henna', 'bornwithit', 'onyx', 'wolfgrey', 'fallspice', 'SE28'] },
desc: 'Fish-Flinging Ninja Fancy Cat' },
# Jul 6, 2019 - Catamari Fancy Cat is discovered
catamari: { name: 'Catamari',
recipe: {
time: { start: '2019-07-06', end: '2019-07-19' }, count: 378,
traits: ['moonrise', 'cobalt', 'ducky', 'salty'] },
desc: 'Monster Fancy Cat' },
# Jun 22, 2019 - Magmeow Fancy Cat is discovered
magmeow: { name: 'Magmeow',
recipe: {
time: { start: '2019-06-23', end: '2019-06-26' }, count: 736,
traits: ['liger', 'moonrise', 'redvelvet', 'dragontail' ] },
desc: 'Multi-Limbed Magma Monster Fancy Cat' },
# Jun 8, 2019 - Kitijira Fancy Cat is discovered
kitijira: { name: 'Kitijira',
recipe: {
time: { start: '2019-06-08', end: '2019-06-21' }, count: 645,
traits: ['mainecoon', 'moonrise', 'atlantis', 'universe', 'dragontail'] },
desc: 'City-Smashing Lizard Monster Fancy Cat' },
# May 25, 2019 - The Whisper Fancy Cat is discovered
whisper: { name: 'Whisper',
recipe: {
time: { start: '2019-05-25', end: '2019-05-31' }, count: 861,
traits: ['onyx', 'henna', 'wolfgrey', 'sully', 'candyshoppe' ] },
desc: 'Ninja Fancy Cat' },
# May 11, 2019 - Curdlin Fancy Cat is discovered
curdlin: { name: 'Curdlin',
recipe: {
time: { start: '2019-05-11', end: '2019-11-30' }, count: 4,
traits: ['nachocheez', 'saycheese', 'missmuffett', 'dippedcone']},
desc: 'Cheeze Wizard Cat - Celebrating the Launch of the Cheeze Wizards on the Blockchain'
## see https://www.cryptokitties.co/blog/post/things-are-getting-cheezy-in-cryptokitties
},
# Apr 27, 2019 - Krakitten Fancy Cat is discovered
krakitten: { name: 'Krakitten',
recipe: {
time: { start: '2019-04-27', end: '2019-05-06' }, count: 1221,
traits: ['cobalt', 'ducky', 'salty', 'splat']},
## desc: 'Beware the Krakitten in the briny deep.'
},
# Apr 13, 2019 - Furbeard Fancy Cat is discovered
furbeard: { name: 'Furbeard',
recipe: {
time: { start: '2019-04-13', end: '2019-04-26'}, count: 3733,
traits: ['inflatablepool', 'hanauma', 'neckbeard']},
desc: 'Dread Pirate Cat' # Avast Ye! This Old Salt knows a few tricks: how to avoid a meowtiny, how to get out of swabbing the litter deck, and just where the captain's log is buried.
## see https://www.cryptokitties.co/blog/post/pirate-cats-are-plundering-cryptokitties/
},
# Mar 30, 2019
# Glitter Fancy Cat is discovered. Fancy Cat
glitter: { name: 'Glitter',
recipe: {
time: { start: '2019-03-30', end: '2019-11-30'}, count: 658, ## note: ++count NOT FINAL!!!
traits: ['rorschach', 'juju', 'unicorn', 'hyacinth'] }
},
# Mar 16, 2019
# Clover Fancy Cat is discovered. Fancy Cat
clover: { name: 'Clover', date: '2019-03-16',
recipe: {
limit: 2506,
traits: ['shamrock', 'emeraldgreen', 'roadtogold', 'PU27'] },
desc: "Celebrating St. Patrick's Day 2019 (March/19th)"
},
# Mar 2, 2019
# Glasswalker Fancy Cat is discovered. Fancy Cat
glasswalker: { name: 'Glasswalker', date: '2019-03-02',
recipe: {
limit: 1230,
traits: ['cloudwhite', 'henna', 'pearl', 'firedup'] },
desc: "Ninja Fancy Cat"
},
# Feb 21, 2019
# Ande Fancy Cat is discovered. Fancy Cat
ande: { name: 'Ande', date: '2019-02-21',
recipe: {
limit: 440,
traits: ['munchkin', 'cashewmilk', 'moue', 'PU30', 'WE10'] }
},
# Feb 17, 2019
# Al Fancy Cat is discovered. Fancy Cat
al: { name: 'Al',
recipe: {
time: { start: '2019-02-17', end: '2019-12-01'}, count: 3209, ## note: count NOT FINAL!!!
traits: ['munchkin','moue','cashewmilk','brownies'] }
},
# Feb 16, 2019
# Pizzazz Fancy Cat is discovered.Fancy Cat
pizzazz: { name: 'Pizzazz',
recipe: {
time: { start: '2019-02-16', end: '2019-12-01'}, count: 1438, ## note: count NOT FINAL!!!
traits: ['mekong', 'scarlet', 'spangled', 'wonky'] }
},
# Feb 9, 2019
# Miss Purrfect Fancy Cat is discovered.Fancy Cat
misspurrfect: { name: 'Miss Purrfect',
recipe: {
time: { start: '2019-02-09', end: '2019-02-14'}, count: 1298,
traits: ['allyouneed', 'butterscotch', 'asif', 'satiated', 'flapflap']},
desc: "Celebrating St. Valentine's Day 2019 (Feb/14th)"
## see https://www.cryptokitties.co/blog/post/how-to-breed-miss-purrfect/
},
## 2019
## January
# Jan 26, 2019
# Squib Fancy Cat is discovered. Fancy Cat
squib: { name: 'Squib', date: '2019-01-26',
recipe: {
limit: 1443, ## todo/check: check if time-windows?
traits: ['oldlace', 'razzledazzle', 'buzzed', 'rollercoaster']},
desc: 'Celebrating American Football Super Bowl LIII in 2019'
## see https://www.cryptokitties.co/blog/post/how-to-breed-squib/
},
tallythepurrocious: { name: 'Tally The Purrocious',
recipe: {
time: { start: '2019-01-10', end: '2019-01-21' }, count: 3992,
traits: ['selkirk', 'koala', 'arcreactor', 'sully'] },
desc: 'Gods Unchained Promotion - Mystical Cat Talisman'
},
genedough: { name: 'Gene Dough',
recipe: {
time: { start: '2018-12-23', end: '2019-01-07' }, count: 1376,
traits: ['hotcocoa', 'mittens', 'frosting'] }
},
pawrula: { name: 'Pawrula the Bright',
recipe: {
time: { start: '2018-12-15', end: '2019-11-30' }, count: 1952, ## note: count NOT FINAL!!!
traits: ['camo', 'butterscotch', 'fox'] },
desc: 'Neha Narula - Director of the Digital Currency Initiative at the MIT Media Lab'
},
## November
draco: { name: 'Draco',
recipe: {
time: { start: '2018-11-30', end: '2018-12-07' }, count: 1115,
traits: ['toyger', 'martian', 'peppermint', 'dragonwings', 'SE03'] }
},
dracojunior: { name: 'Draco Junior',
recipe: {
time: { start: '2018-11-26', end: '2018-12-07' }, count: 1398,
traits: ['lynx', 'verdigris', 'dragontail', 'SE03']}
},
dreggo: { name: 'Dreggo',
recipe: {
time: { start: '2018-11-21', end: '2018-12-07' }, count: 3624,
traits: ['siberian', 'bananacream', 'SE03'] }
},
pickles: { name: 'Pickles', date: '2018-11-14',
recipe: {
limit: 303,
traits: ['lynx', 'martian', 'highsociety', 'emeraldgreen']}
},
## October
dukecat: { name: 'Dukecat', date: '2018-10-18',
recipe: {
limit: 1366,
traits: ['cymric', 'periwinkle', 'simple', 'tongue']}
},
sheilapurren: { name: 'Sheila Purren', date: '2018-10-04',
recipe: {
limit: 1971,
traits: ['mauveover', 'icy', 'wingtips', 'fangtastic']},
desc: 'Sheila Warren Kitty-fied - Head of Blockchain and Distributed Ledger Technology at the World Economic Forum (WEF)'
},
## September
pawzilla: { name: 'Pawzilla', date: '2018-09-22',
recipe: {
limit: 1185,
traits: ['jaguar', 'universe', 'atlantis', 'littlefoot']}
},
meowstro: { name: 'Meowstro', date: '2018-09-09',
recipe: {
limit: 1698,
traits: ['onyx', 'wowza', 'eclipse']}
},
atlas: { name: 'Atlas', date: '2018-09-07',
recipe: {
limit: 998,
traits: ['highlander', 'kittencream', 'swarley', 'topoftheworld']}
},
## August
purrity: { name: 'Purrity', date: '2018-08-23',
recipe: {
limit: 5984,
traits: ['selkirk', 'chronic', 'cloudwhite', 'cheeky'] }
},
squiddlesworth: { name: 'Squiddlesworth', date: '2018-08-16',
recipe: {
limit: 1510,
traits: ['sphynx', 'redvelvet', 'patrickstarfish', 'dragontail'] },
desc: 'Lava Squid Cat'
},
## July
purrspero: { name: 'Purrspero', date: '2018-07-27',
recipe: {
limit: 4448,
traits: ['dippedcone', 'googly', 'royalpurple', 'beard']}
},
catbury: { name: 'Catbury', date: '2018-07-25',
recipe: {
limit: 76,
traits: ['ragdoll', 'crazy', 'chocolate', 'mintmacaron', 'yokel', 'WE02']}
},
lulu: { name: 'Lulu', date: '2018-07-13',
recipe: {
limit: 999,
traits: ['cyan', 'verdigris', 'turtleback', 'salty']}
},
boot: { name: 'Boot', date: '2018-07-05',
recipe: {
limit: 1440,
traits: ['ganado', 'wiley', 'cerulian', 'rollercoaster'],
variants: {
belgium: { name: 'Belgium', count: 97, traits: [['orangesoda','onyx']]}, ## Base Color: Orangesoda / Onyx
brazil: { name: 'Brazil', count: 195, traits: [['hintomint','bananacream','verdigris']]}, ## Base Color: Hintomint / Bananacream / Verdigris
croatia: { name: 'Croatia', count: 253, traits: [['cottoncandy','mauveover','oldlace']]}, ## Base Color: Cottoncandy / Mauveover / Oldlace
england: { name: 'England', count: 168, traits: [['greymatter','martian']]}, ## Base Color: Greymatter / Martian
france: { name: 'France', count: 317, traits: [['harbourfog','cinderella','lavender']]}, ## Base Color: Harbourfog / Cinderella / Lavender
russia: { name: 'Russia', count: 94, traits: [['shadowgrey','salmon','cloudwhite']]}, ## Base Color: Shadowgrey / Salmon/ Cloudwhite
sweden: { name: 'Sweden', count: 123, traits: [['brownies','dragonfruit','redvelvet']]}, ## Base Color: Brownies / Dragonfruit / Redvelvet
uruguay: { name: 'Uruguay', count: 193, traits: [['aquamarine','nachocheez','koala']]}, ## Base Color: Aquamarine / Nachocheez / Koala
}},
desc: 'Football World Cup',
},
## note: boot - different variants for world cup teams
## Although there are 8 unique Fancies, they're actually each a variant on the same Fancy - Boot.
## Their colours are different, and you can collect all 8 as a set
## June
raspoutine: { name: 'Raspoutine', date: '2018-06-28',
recipe: {
limit: 1867,
traits: ['buzzed', 'nachocheez', 'sandalwood', 'belch']}
},
kittypride: { name: 'Kitty Pride', date: '2018-06-21',
recipe: {
limit: 1316,
traits: ['fabulous','cinderella','garnet']}
},
furrmingo: { name: 'Furrmingo', date: '2018-06-14',
recipe: {
limit: 333,
traits: ['bobtail', 'egyptiankohl', 'flamingo', 'whixtensions']}
},
## May
page: { name: 'Page', date: '2018-05-31',
recipe: {
limit: 50_000, count: 3936, ## note: count NOT FINAL!!!
traits: ['rascal', 'peach', 'wasntme' ]}
},
"schrödingerscat": { name: "Schrödinger's Cat", date: '2018-05-20',
recipe: {
limit: 73,
traits: ['forgetmenot','tinybox','PU20','SE25']}
},
chatplongeur: { name: 'Chat Plongeur', date: '2018-05-19',
recipe: {
limit: 1910,
traits: ['aquamarine', 'skyblue', 'seafoam'] }
},
docpurr: { name: 'Doc Purr', date: '2018-05-16',
recipe: {
limit: 250,
traits: ['persian','spock','raisedbrow','violet','tongue'] }
},
swish: { name: 'Swish', date: '2018-05-08',
recipe: {
limit: 2880,
traits: ['norwegianforest', 'luckystripe', 'thicccbrowz', 'orangesoda'] }
},
## April
flutterbee: { name: 'Flutterbee', date: '2018-04-28',
recipe: {
limit: 275,
traits: ['cloudwhite','jaguar','lemonade','azaleablush','WE14'] }
},
vernon: { name: 'Vernon', date: '2018-04-16',
recipe: {
limit: 320,
traits: ['amur','fabulous','cottoncandy','springcrocus','belleblue','soserious']},
desc: 'Spring Equinox Kitty' ## first, see https://www.cryptokitties.co/kitty/696398
},
## March
berry: { name: 'Berry', date: '2018-03-16',
recipe: {
limit: 200,
traits: ['dragonfruit','thunderstruck','emeraldgreen','apricot','simple'] }
},
pussforprogress: { name: 'Puss For Progress', date: '2018-03-08',
recipe: {
limit: 1920,
traits: ['himalayan','peach','safetyvest','gerbil'] },
desc: "Women's Day"
},
fortunecat: { name: 'Fortune Cat', name_cn: '红包喵', date: '2018-03-08',
recipe: {
limit: 888,
traits: ['harbourfog','calicool','swampgreen','sapphire','beard']}
}, ## todo: check date for china launch specials!!!
liondance: { name: 'Lion Dance', name_cn: '咚咚锵', date: '2018-03-07',
recipe: {
limit: 888, overflow: 1, ## use count 889 ?? - why? why not?
traits: ['manx','royalblue','googly','starstruck']}
},
dogcat: { name: 'Dog Cat', name_cn: '汪星爷', date: '2018-03-02',
recipe: {
limit: 88,
traits: ['tigerpunk','periwinkle','barkbrown','sweetmeloncakes','yokel']},
desc: 'Year of the Dog (Greater China)'
},
## February
tabby: { name: 'Tabby', date: '2018-02-26',
recipe: {
limit: 250,
traits: ['ragamuffin','morningglory','otaku','cheeky'] }
},
yuricatsuki: { name: 'Yuri Catsuki', date: '2018-02-20',
recipe: {
limit: 250,
traits: ['cymric','tiger','neckbeard','elk'] },
desc: 'Figure Scating Kitty - Winter Olympics (Korea)'
},
misterpurrfect: { name: 'Mister Purrfect', date: '2018-02-14',
recipe: {
limit: 1000,
traits: ['chocolate','baddate','strawberry','wuvme'] },
desc: "Valentine's Day"
},
earnie: { name: 'Earnie', date: '2018-02-13',
recipe: {
limit: 500,
traits: ['birman','orangesoda','hotrod','grim'] },
desc: 'Earn.com - Golden Kitty Award (Product Hunt)'
},
## January
'momo-chan': { name: 'Momo-chan', date: '2018-01-31',
recipe: {
limit: 500,
traits: ['onyx','henna','bloodred','wolfgrey','sass'] },
desc: 'Ninja Kitty'
},
negato: { name: 'Negato', date: '2018-01-29',
recipe: {
limit: 500,
traits: ['onyx','henna','wolfgrey','slyboots'] },
desc: 'Ninja Kitty'
},
stitches: { name: 'Stitches', date: '2018-01-10',
recipe: {
limit: 500,
traits: ['hintomint','seafoam','swampgreen','saycheese'] },
desc: 'Zombie Kitty'
},
## 2017
## December
phuziqaat: { name: 'Phu Ziqaat', date: '2017-12-31',
recipe: {
limit: 1000,
traits: ['chartreux','spock','alien','pouty'] },
desc: 'Alien Kitty'
},
santaclaws: { name: 'Santa Claws', date: '2017-12-12',
recipe: {
limit: 1000, overflow: 2,
traits: ['cloudwhite','scarlet','beard','WE12'] },
desc: 'Ho Ho Ho - Santa Claus Kitty'
},
mistletoe: { name: 'Mistletoe', date: '2017-12-09',
recipe: {
limit: 2000,
traits: ['oldlace','crazy','gerbil'] },
desc: "XMas Kitty"
},
dracula: { name: 'Dracula', date: '2017-12-01',
recipe: {
limit: 2000,
traits: ['laperm','spock','strawberry','WE01'] }
},
## November
ducat: { name: 'Du Cat', date: '2017-11-29',
recipe: {
limit: 10_000,
traits: ['cymric','tongue']}
},
shipcat: { name: 'Ship Cat', date: '2017-11-23',
recipe: {
limit: 2000,
traits: ['sphynx','orangesoda','luckystripe','crazy']}
}
}
FANCIES = {}.merge( RECIPES )
.merge( EXCLUSIVES )
.merge( SPECIAL_EDITIONS )
| 44.412186 | 202 | 0.459003 |
1cf142041595411fcb670aa36f84027c218fce64 | 4,395 | require 'spec_helper'
describe 'User updates wiki page' do
let(:user) { create(:user) }
before do
project.add_master(user)
sign_in(user)
end
context 'when wiki is empty' do
before do
visit(project_wikis_path(project))
end
context 'in a user namespace' do
let(:project) { create(:project, namespace: user.namespace) }
it 'redirects back to the home edit page' do
page.within(:css, '.wiki-form .form-actions') do
click_on('Cancel')
end
expect(current_path).to eq project_wiki_path(project, :home)
end
it 'updates a page that has a path', :js do
click_on('New page')
page.within('#modal-new-wiki') do
fill_in(:new_wiki_path, with: 'one/two/three-test')
click_on('Create page')
end
page.within '.wiki-form' do
fill_in(:wiki_content, with: 'wiki content')
click_on('Create page')
end
expect(current_path).to include('one/two/three-test')
expect(find('.wiki-pages')).to have_content('Three')
click_on('Three')
expect(find('.nav-text')).to have_content('Three')
click_on('Edit')
expect(current_path).to include('one/two/three-test')
expect(page).to have_content('Edit Page')
fill_in('Content', with: 'Updated Wiki Content')
click_on('Save changes')
expect(page).to have_content('Updated Wiki Content')
end
end
end
context 'when wiki is not empty' do
let(:project_wiki) { create(:project_wiki, project: project, user: project.creator) }
let!(:wiki_page) { create(:wiki_page, wiki: project_wiki, attrs: { title: 'home', content: 'Home page' }) }
before do
visit(project_wikis_path(project))
end
context 'in a user namespace' do
let(:project) { create(:project, namespace: user.namespace) }
it 'updates a page' do
click_link('Edit')
# Commit message field should have correct value.
expect(page).to have_field('wiki[message]', with: 'Update home')
fill_in(:wiki_content, with: 'My awesome wiki!')
click_button('Save changes')
expect(page).to have_content('Home')
expect(page).to have_content("Last edited by #{user.name}")
expect(page).to have_content('My awesome wiki!')
end
it 'shows a validation error message' do
click_link('Edit')
fill_in(:wiki_content, with: '')
click_button('Save changes')
expect(page).to have_selector('.wiki-form')
expect(page).to have_content('Edit Page')
expect(page).to have_content('The form contains the following error:')
expect(page).to have_content("Content can't be blank")
expect(find('textarea#wiki_content').value).to eq('')
end
it 'shows the autocompletion dropdown', :js do
click_link('Edit')
find('#wiki_content').native.send_keys('')
fill_in(:wiki_content, with: '@')
expect(page).to have_selector('.atwho-view')
end
it 'shows the error message' do
click_link('Edit')
wiki_page.update(content: 'Update')
click_button('Save changes')
expect(page).to have_content('Someone edited the page the same time you did.')
end
it 'updates a page' do
click_on('Edit')
fill_in('Content', with: 'Updated Wiki Content')
click_on('Save changes')
expect(page).to have_content('Updated Wiki Content')
end
it 'cancels edititng of a page' do
click_on('Edit')
page.within(:css, '.wiki-form .form-actions') do
click_on('Cancel')
end
expect(current_path).to eq(project_wiki_path(project, wiki_page))
end
end
context 'in a group namespace' do
let(:project) { create(:project, namespace: create(:group, :public)) }
it 'updates a page' do
click_link('Edit')
# Commit message field should have correct value.
expect(page).to have_field('wiki[message]', with: 'Update home')
fill_in(:wiki_content, with: 'My awesome wiki!')
click_button('Save changes')
expect(page).to have_content('Home')
expect(page).to have_content("Last edited by #{user.name}")
expect(page).to have_content('My awesome wiki!')
end
end
end
end
| 28.354839 | 111 | 0.616382 |
ac1782a9db224abbac89043baaba3499015a362a | 43 | module Swarmclient
VERSION = "0.1.5"
end
| 10.75 | 19 | 0.697674 |
abbd4c0a3d21da13803dbcdec7704447b4764ff9 | 348 | class Kid3 < Cask
# note: "3" is not a version number, but an intrinsic part of the product name (ID3 tags)
url 'http://downloads.sourceforge.net/sourceforge/kid3/kid3-3.0.2-Darwin.dmg'
homepage 'http://kid3.sourceforge.net/'
version '3.0.2'
sha256 'a1b60a4eea11ca62001365dd28d418c595ce2d073dd4e0ba07bd28a94cb5c260'
link 'Kid3.app'
end
| 38.666667 | 91 | 0.755747 |
79421e868d0515ecd814f35b23db263f68f79263 | 4,071 | require "factory_girl"
require 'rspec/collection_matchers'
require "codeclimate-test-reporter"
if ENV["CI"]
CodeClimate::TestReporter.start
end
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
config.include FactoryGirl::Syntax::Methods
FactoryGirl.find_definitions
end
| 43.774194 | 129 | 0.747482 |
6a8568726f6096205c7735b1ad4f3989df68bd47 | 286 | # frozen_string_literal: true
require 'pathname'
require 'tmpdir'
RSpec.shared_context 'with tmpdir' do
let(:tmpdir) { Pathname(Dir.mktmpdir) }
after do
tmpdir.rmtree if tmpdir.exist?
end
end
RSpec.configure do |config|
config.include_context 'with tmpdir', :tmpdir
end
| 16.823529 | 47 | 0.741259 |
1a66f8a7cc2b681573f813e9996ac48a317fd5c6 | 14,607 | describe ResponseController do
let(:assignment) { build(:assignment, instructor_id: 6) }
let(:instructor) { build(:instructor, id: 6) }
let(:participant) { build(:participant, id: 1, user_id: 6, assignment: assignment) }
let(:review_response) { build(:response, id: 1, map_id: 1) }
let(:review_response_round1) { build(:response, id: 1, map_id: 1, round: 1, is_submitted: 0) }
let(:review_response_map) { build(:review_response_map, id: 1, reviewer: participant) }
let(:questionnaire) { build(:questionnaire, id: 1, questions: [question]) }
let(:question) { Criterion.new(id: 1, weight: 2, break_before: true) }
let(:assignment_questionnaire) { build(:assignment_questionnaire) }
let(:answer) { double('Answer') }
let(:assignment_due_date) { build(:assignment_due_date) }
before(:each) do
allow(Assignment).to receive(:find).with('1').and_return(assignment)
stub_current_user(instructor, instructor.role.name, instructor.role)
allow(Response).to receive(:find).with('1').and_return(review_response)
allow(review_response).to receive(:map).and_return(review_response_map)
end
describe '#action_allowed?' do
context 'when params action is edit' do
before(:each) do
controller.params = {id: '1', action: 'edit'}
end
context 'when response is not submitted and current_user is the reviewer of the response' do
it 'allows certain action' do
expect(controller.send(:action_allowed?)).to be true
end
end
context 'when response is submitted' do
it 'does not allow certain action' do
allow(review_response).to receive(:is_submitted).and_return(true)
expect(controller.send(:action_allowed?)).to be false
end
end
end
context 'when params action is delete or update' do
context 'when current_user is the reviewer of the response' do
it 'allows certain action' do
controller.params = {id: '1', action: 'update'}
expect(controller.send(:action_allowed?)).to be true
end
end
end
context 'when params action is view' do
context 'when response_map is a ReviewResponseMap and current user is the instructor of current assignment' do
it 'allows certain action' do
controller.params = {id: '1', action: 'view'}
expect(controller.send(:action_allowed?)).to be true
end
end
end
end
describe '#delete' do
it 'deletes current response and redirects to response#redirect page' do
allow(review_response).to receive(:delete).and_return(review_response)
params = {id: 1}
post :delete, params
expect(response).to redirect_to('/response/redirect?id=1&msg=The+response+was+deleted.')
end
end
describe '#edit' do
it 'renders response#response page' do
allow(Response).to receive(:where).with(map_id: 1).and_return([review_response])
allow(ResponseMap).to receive(:find).with(1).and_return(review_response_map)
allow(review_response_map).to receive(:reviewer_id).and_return(1)
allow(Participant).to receive(:find).with(1).and_return(participant)
allow(assignment).to receive(:review_questionnaire_id).and_return(1)
allow(Questionnaire).to receive(:find).with(1).and_return(questionnaire)
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1, questionnaire_id: 1).and_return([assignment_questionnaire])
allow(Answer).to receive(:where).with(response_id: 1, question_id: 1).and_return([answer])
params = {id: 1, return: 'assignment_edit'}
get :edit, params
expect(controller.instance_variable_get(:@review_scores)).to eq([answer])
expect(controller.instance_variable_get(:@dropdown_or_scale)).to eq('dropdown')
expect(controller.instance_variable_get(:@min)).to eq(0)
expect(controller.instance_variable_get(:@max)).to eq(5)
expect(response).to render_template(:response)
end
end
describe '#update' do
context 'when something is wrong during response updating' do
it 'raise an error and redirects to response#save page' do
allow(review_response).to receive(:update_attribute).with('additional_comment', 'some comments').and_raise('ERROR!')
params = {
id: 1,
review: {
comments: 'some comments'
}
}
session = {user: instructor}
post :update, params, session
expect(response).to redirect_to('/response/save?id=1&msg=Your+response+was+not+saved.+Cause%3A189+ERROR%21&review%5Bcomments%5D=some+comments')
end
end
context 'when response is updated successfully' do
it 'redirects to response#save page' do
allow(ResponseMap).to receive(:find).with(1).and_return(review_response_map)
allow(review_response_map).to receive(:reviewer_id).and_return(1)
allow(Participant).to receive(:find).with(1).and_return(participant)
allow(assignment).to receive(:review_questionnaire_id).and_return(1)
allow(Questionnaire).to receive(:find).with(1).and_return(questionnaire)
allow(Answer).to receive(:create).with(response_id: 1, question_id: 1, answer: '98', comments: 'LGTM').and_return(answer)
allow(answer).to receive(:update_attribute).with(any_args).and_return('OK!')
params = {
id: 1,
review: {
comments: 'some comments'
},
responses: {
'0' => {score: 98, comment: 'LGTM'}
},
isSubmit: 'No'
}
session = {user: instructor}
post :update, params, session
expect(response).to redirect_to('/response/save?id=1&msg=&review%5Bcomments%5D=some+comments')
end
end
end
describe '#new' do
it 'renders response#response page' do
allow(ResponseMap).to receive(:find).with('1').and_return(review_response_map)
allow(SignedUpTeam).to receive(:where).with(team_id: 1, is_waitlisted: 0).and_return([double('SignedUpTeam', topic_id: 1)])
allow(Assignment).to receive(:find).with(1).and_return(assignment)
allow(AssignmentDueDate).to receive(:find_by).with(any_args).and_return(assignment_due_date)
# varying_rubrics_by_round?
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1, used_in_round: 2).and_return([])
# review_questionnaire_id
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1).and_return([assignment_questionnaire])
# set_dropdown_or_scale
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1, questionnaire_id: 1).and_return([assignment_questionnaire])
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1, used_in_round: 1).and_return([assignment_questionnaire])
allow(Questionnaire).to receive(:find).with(any_args).and_return(questionnaire)
allow(Questionnaire).to receive(:questions).and_return(question)
allow(Answer).to receive(:create).and_return(answer)
params = {
id: 1,
feedback: '',
return: ''
}
get :new, params
expect(controller.instance_variable_get(:@dropdown_or_scale)).to eq('dropdown')
expect(controller.instance_variable_get(:@min)).to eq(0)
expect(controller.instance_variable_get(:@max)).to eq(5)
expect(response).to render_template(:response)
end
end
describe '#new_feedback' do
context 'when current response is nil' do
it 'redirects to response#new page' do
allow(AssignmentParticipant).to receive(:where).with(user_id: 6, parent_id: 1).and_return([participant])
allow(FeedbackResponseMap).to receive(:where).with(reviewed_object_id: 1, reviewer_id: 1).and_return([])
params = {id: 1}
session = {user: instructor}
get :new_feedback, params, session
expect(response).to redirect_to('/response/new?id=2&return=feedback')
end
end
context 'when current response is not nil' do
it 'redirects to previous page' do
allow(Response).to receive(:find).with('2').and_return(nil)
params = {id: 2}
session = {user: instructor}
request.env['HTTP_REFERER'] = 'www.google.com'
get :new_feedback, params, session
expect(response).to redirect_to('www.google.com')
end
end
end
describe '#view' do
it 'renders response#view page' do
allow(Response).to receive(:where).with(map_id: 1).and_return([review_response])
allow(ResponseMap).to receive(:find).with(1).and_return(review_response_map)
allow(review_response_map).to receive(:reviewer_id).and_return(1)
allow(Participant).to receive(:find).with(1).and_return(participant)
allow(assignment).to receive(:review_questionnaire_id).and_return(1)
allow(Questionnaire).to receive(:find).with(1).and_return(questionnaire)
allow(AssignmentQuestionnaire).to receive(:where).with(assignment_id: 1, questionnaire_id: 1).and_return([assignment_questionnaire])
allow(Answer).to receive(:where).with(response_id: 1, question_id: 1).and_return([answer])
params = {id: 1, return: 'assignment_edit'}
get :view, params
expect(controller.instance_variable_get(:@dropdown_or_scale)).to eq('dropdown')
expect(controller.instance_variable_get(:@min)).to eq(0)
expect(controller.instance_variable_get(:@max)).to eq(5)
expect(response).to render_template(:view)
end
end
describe '#create' do
it 'creates a new response and redirects to response#save page' do
allow(ResponseMap).to receive(:find).with('1').and_return(review_response_map)
allow(Response).to receive_message_chain(:where, :order).with(map_id: 1, round: 1).with(created_at: :desc).and_return([review_response_round1])
allow(Questionnaire).to receive(:find).with('1').and_return(questionnaire)
allow(Answer).to receive(:create).with(response_id: 1, question_id: 1, answer: '98', comments: 'LGTM').and_return(answer)
allow(answer).to receive(:update_attribute).with(any_args).and_return('OK!')
allow_any_instance_of(Response).to receive(:email).and_return('OK!')
params = {
id: 1,
review: {
questionnaire_id: '1',
round: 1,
comments: 'no comment'
},
responses: {
'0' => {score: 98, comment: 'LGTM'}
},
isSubmit: 'No'
}
post :create, params
expect(response).to redirect_to('/response/save?error_msg=&id=1&msg=Your+response+was+successfully+saved.&review%5Bcomments%5D=no+comment&review%5Bquestionnaire_id%5D=1&review%5Bround%5D=1')
end
end
describe '#save' do
it 'save current response map and redirects to response#redirect page' do
allow(ResponseMap).to receive(:find).with('1').and_return(review_response_map)
allow(review_response_map).to receive(:save).and_return(review_response_map)
params = {
id: 1,
return: ''
}
session = {user: instructor}
post :save, params, session
expect(response).to redirect_to('/response/redirect?id=1&return=')
end
end
describe '#redirect' do
before(:each) do
allow(Response).to receive(:find_by).with(map_id: '1').and_return(review_response)
@params = {id: 1}
end
context 'when params[:return] is feedback' do
it 'redirects to grades#view_my_scores page' do
@params[:return] = 'feedback'
get :redirect, @params
expect(response).to redirect_to('/grades/view_my_scores?id=1')
end
end
context 'when params[:return] is teammate' do
it 'redirects to student_teams#view page' do
@params[:return] = 'teammate'
get :redirect, @params
expect(response).to redirect_to('/student_teams/view?student_id=1')
end
end
context 'when params[:return] is instructor' do
it 'redirects to grades#view page' do
@params[:return] = 'instructor'
get :redirect, @params
expect(response).to redirect_to('/grades/view?id=1')
end
end
context 'when params[:return] is assignment_edit' do
it 'redirects to assignment#edit page' do
@params[:return] = 'assignment_edit'
get :redirect, @params
expect(response).to redirect_to('/assignments/1/edit')
end
end
context 'when params[:return] is selfreview' do
it 'redirects to submitted_content#edit page' do
@params[:return] = 'selfreview'
get :redirect, @params
expect(response).to redirect_to('/submitted_content/1/edit')
end
end
context 'when params[:return] is survey' do
it 'redirects to response#pending_surveys page' do
@params[:return] = 'survey'
get :redirect, @params
expect(response).to redirect_to('/response/pending_surveys')
end
end
context 'when params[:return] is other content' do
it 'redirects to student_review#list page' do
@params[:return] = 'other'
get :redirect, @params
expect(response).to redirect_to('/student_review/list?id=1')
end
end
end
describe '#pending_surveys' do
context 'when session[:user] is nil' do
it 'redirects to root path (/)' do
params = {}
session = {}
get :pending_surveys, params, session
expect(response).to redirect_to('/')
end
end
context 'when session[:user] is not nil' do
it 'renders pending_surveys page' do
allow(CourseParticipant).to receive(:where).with(user_id: 6).and_return([double('CourseParticipant', id: 8, parent_id: 1)])
allow(AssignmentParticipant).to receive(:where).with(user_id: 6).and_return([participant])
survey_deployment = double('SurveyDeployment', id: 1, questionnaire_id: 1, global_survey_id: 1,
start_date: DateTime.now.in_time_zone - 1.day, end_date: DateTime.now.in_time_zone + 1.day)
allow(Questionnaire).to receive(:find).with(1).and_return(questionnaire)
allow(CourseSurveyDeployment).to receive(:where).with(parent_id: 1).and_return([survey_deployment])
participant.parent_id = 1
allow(AssignmentSurveyDeployment).to receive(:where).with(parent_id: 1).and_return([survey_deployment])
params = {}
session = {user: instructor}
get :pending_surveys, params, session
expect(controller.instance_variable_get(:@surveys).size).to eq(2)
expect(response).to render_template(:pending_surveys)
end
end
end
end
| 43.602985 | 196 | 0.67276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.