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
|
---|---|---|---|---|---|
3838d573563187be9011bc067830ee04fee06ac8 | 6,102 | require 'spec_helper'
describe Puppet::Type.type(:st2_pack).provider(:default) do
let(:name) { 'rspec st2_pack test' }
let(:attributes) { {} }
let(:resource) do
Puppet::Type.type(:st2_pack).new(
{
name: name,
provider: :default,
user: 'st2_user',
password: 'st2_password',
}.merge(attributes),
)
end
let(:provider) do
resource.provider
end
before(:each) do
allow(provider).to receive(:command).with(:st2).and_return('/usr/bin/st2')
end
describe 'st2_authenticate' do
it 'authenticates and receives a token' do
expect(provider).to receive(:exec_st2).with('auth', 'st2_user',
'-t',
'-p', 'st2_password')
.and_return("token\n")
expect(provider.st2_authenticate).to eq('token')
end
it 'caches its token after the first call' do
expect(provider).to receive(:exec_st2).with('auth', 'st2_user',
'-t',
'-p', 'st2_password')
.and_return("cachedtoken\n")
.once
expect(provider.st2_authenticate).to eq('cachedtoken')
expect(provider.st2_authenticate).to eq('cachedtoken')
expect(provider.st2_authenticate).to eq('cachedtoken')
end
end
describe 'create' do
it 'creates a pack' do
expect(provider).to receive(:exec_st2).with('auth', 'st2_user',
'-t',
'-p', 'st2_password')
.and_return('token')
expect(provider).to receive(:exec_st2).with('pack', 'install',
'rspec st2_pack test',
'-t', 'token')
provider.create
end
end
describe 'destroy' do
it 'removes a pack' do
expect(provider).to receive(:exec_st2).with('auth', 'st2_user',
'-t',
'-p', 'st2_password')
.and_return('token')
expect(provider).to receive(:exec_st2).with('pack', 'remove',
'rspec st2_pack test',
'-t', 'token')
provider.destroy
end
end
describe 'apikey is used' do
let(:resource) do
Puppet::Type.type(:st2_pack).new(
{
name: name,
provider: :default,
apikey: 'apikey',
}.merge(attributes),
)
end
it 'creates a pack with apikey' do
expect(provider).to receive(:exec_st2).with('pack', 'install',
'rspec st2_pack test',
'--api-key', 'apikey')
provider.create
end
it 'deletes a pack with apikey' do
expect(provider).to receive(:exec_st2).with('pack', 'remove',
'rspec st2_pack test',
'--api-key', 'apikey')
provider.destroy
end
end
describe 'exists?' do
it 'checks if pack exists' do
expect(provider).to receive(:list_installed_packs).and_return([])
expect(provider.exists?).to be false
end
it 'returns true when pack exists' do
expect(provider).to receive(:list_installed_packs).and_return(['pack1', 'rspec st2_pack test'])
expect(provider.exists?).to be true
end
end
describe 'list_installed_packs' do
it 'returns a list of pack names' do
expect(provider).to receive(:exec_st2).with('auth', 'st2_user',
'-t',
'-p', 'st2_password')
.and_return('token')
expect(provider).to receive(:exec_st2).with('pack', 'list',
'-a', 'ref',
'-j',
'-t', 'token')
.and_return('[{"ref": "pack1"}, {"ref": "pack2"}]')
expect(provider.list_installed_packs).to eq ['pack1', 'pack2']
end
end
describe 'parse_output_json' do
it 'returns empty list when given nil' do
expect(provider.parse_output_json(nil)).to eq []
end
it 'returns empty list when given empty string' do
expect(provider.parse_output_json('')).to eq []
end
it 'extracts pack names from a JSON string' do
expect(provider.parse_output_json('[{"ref": "core"}, {"ref": "examples"}]')).to eq ['core', 'examples']
end
end
describe 'exec_st2' do
it 'executes a command' do
expect(Puppet::Util::Execution).to receive(:execute)
.with('/usr/bin/st2 auth someuser -t -p blah',
override_locale: false,
failonfail: true,
combine: true,
custom_environment: {
'LANG' => 'en_US.UTF-8',
'LC_ALL' => 'en_US.UTF-8',
})
provider.send(:exec_st2, 'auth', 'someuser', '-t', '-p', 'blah')
end
it 'escapes arguments' do
expect(Puppet::Util::Execution).to receive(:execute)
.with('/usr/bin/st2 pack search arg\ with\ spaces \"\ blah\" \)\( \#',
override_locale: false,
failonfail: true,
combine: true,
custom_environment: {
'LANG' => 'en_US.UTF-8',
'LC_ALL' => 'en_US.UTF-8',
})
provider.send(:exec_st2,
'pack', 'search',
'arg with spaces',
'" blah"',
')(',
'#')
end
end
end
| 35.894118 | 109 | 0.460013 |
d505a44e74ae7aebb46190b53373214a938d7dfe | 4,743 | # frozen_string_literal: true
module Spree
class TaxRate < Spree::Base
include Spree::SoftDeletable
# Need to deal with adjustments before calculator is destroyed.
before_destroy :remove_adjustments_from_incomplete_orders
before_discard :remove_adjustments_from_incomplete_orders
include Spree::CalculatedAdjustments
include Spree::AdjustmentSource
belongs_to :zone, class_name: "Spree::Zone", inverse_of: :tax_rates, optional: true
has_many :tax_rate_tax_categories,
class_name: 'Spree::TaxRateTaxCategory',
dependent: :destroy,
inverse_of: :tax_rate
has_many :tax_categories,
through: :tax_rate_tax_categories,
class_name: 'Spree::TaxCategory',
inverse_of: :tax_rates
has_many :adjustments, as: :source
has_many :shipping_rate_taxes, class_name: "Spree::ShippingRateTax"
validates :amount, presence: true, numericality: true
# Finds all tax rates whose zones match a given address
scope :for_address, ->(address) { joins(:zone).merge(Spree::Zone.for_address(address)) }
scope :for_country,
->(country) { for_address(Spree::Tax::TaxLocation.new(country: country)) }
# Finds geographically matching tax rates for a tax zone.
# We do not know if they are/aren't applicable until we attempt to apply these rates to
# the items contained within the Order itself.
# For instance, if a rate passes the criteria outlined in this method,
# but then has a tax category that doesn't match against any of the line items
# inside of the order, then that tax rate will not be applicable to anything.
# For instance:
#
# Zones:
# - Spain
# - France
#
# Tax rates: (note: amounts below do not actually reflect real VAT rates)
# 21% inclusive - "Clothing" - Spain
# 18% inclusive - "Clothing" - France
# 10% inclusive - "Food" - Spain
# 8% inclusive - "Food" - France
# 5% inclusive - "Hotels" - Spain
# 2% inclusive - "Hotels" - France
#
# Order has:
# Line Item #1 - Tax Category: Clothing
# Line Item #2 - Tax Category: Food
#
# Tax rates that should be selected:
#
# 21% inclusive - "Clothing" - Spain
# 10% inclusive - "Food" - Spain
#
# If the order's address changes to one in France, then the tax will be recalculated:
#
# 18% inclusive - "Clothing" - France
# 8% inclusive - "Food" - France
#
# Note here that the "Hotels" tax rates will not be used at all.
# This is because there are no items which have the tax category of "Hotels".
#
# Under no circumstances should negative adjustments be applied for the Spanish tax rates.
#
# Those rates should never come into play at all and only the French rates should apply.
scope :for_zone, ->(zone) do
if zone
where(zone_id: Spree::Zone.with_shared_members(zone).pluck(:id))
else
none
end
end
scope :included_in_price, -> { where(included_in_price: true) }
# Creates necessary tax adjustments for the order.
#
# @deprecated Please use `Spree::Tax::OrderAdjuster#adjust!` instead
def adjust(_order_tax_zone, item)
Spree::Deprecation.warn("`Spree::TaxRate#adjust` is deprecated. Please use `Spree::Tax::OrderAdjuster#adjust!` instead.", caller)
amount = compute_amount(item)
item.adjustments.create!(
source: self,
amount: amount,
order_id: item.order_id,
label: adjustment_label(amount),
included: included_in_price
)
end
# This method is used by Adjustment#update to recalculate the cost.
def compute_amount(item)
calculator.compute(item)
end
def active?
(starts_at.nil? || starts_at < Time.current) &&
(expires_at.nil? || expires_at > Time.current)
end
def adjustment_label(amount)
I18n.t(
translation_key(amount),
scope: "spree.adjustment_labels.tax_rates",
name: name.presence || tax_categories.map(&:name).join(", "),
amount: amount_for_adjustment_label
)
end
def tax_category=(category)
self.tax_categories = [category]
end
def tax_category
tax_categories[0]
end
deprecate :tax_category => :tax_categories, :tax_category= => :tax_categories=, deprecator: Spree::Deprecation
private
def amount_for_adjustment_label
ActiveSupport::NumberHelper::NumberToPercentageConverter.convert(
amount * 100,
locale: I18n.locale
)
end
def translation_key(_amount)
key = included_in_price? ? "vat" : "sales_tax"
key += "_with_rate" if show_rate_in_label?
key.to_sym
end
end
end
| 32.486301 | 135 | 0.664347 |
e825ef454f80c0dd1a9392795f66593ff7c4db03 | 301 | Rails.application.configure do
# http://guides.rubyonrails.org/active_job_basics.html#backends
config.active_job.queue_adapter =
if Rails.env.test?
:inline
elsif defined?(SuckerPunch)
:sucker_punch
else
:inline # no asynchronous background job processing
end
end
| 25.083333 | 65 | 0.72093 |
797fa39701bea41ee29773c630e275d551db1908 | 1,530 | #!/usr/bin/env ruby
# Copyright (c) 2009 Cory Ondrejka. All rights reserved.
# See License.txt for licensing details.
require "#{File.dirname(__FILE__)}/../../../lib/rubyflashbake/core"
require "#{File.dirname(__FILE__)}/../../../lib/rubyflashbake/plugins/weather"
describe RubyFlashbake do
it "should get weather data if @configuration[:INTERNET_ALIVE] is true" do
begin
rfb = RubyFlashbake.new
rfb.load_file("#{File.dirname(__FILE__)}/../../../lib/data/.rubyflashbake_example")
rfb.load_plugins
rfb.configuration[:OUTPUT] = []
rfb.do_internet
rfb.do_location
rfb.do_weather
if rfb.configuration[:INTERNET_ALIVE]
rfb.configuration[:LOCATION_CACHE].scan(/(.*),(.*),(.*)/).should_not == ""
rfb.configuration[:OUTPUT][0].scan(/(.*),(.*),(.*) (.*),(.*)/).should_not == ""
rfb.configuration[:OUTPUT][1].scan(/(\w+) (\w+)/).should_not == ""
end
end
end
it "should fail to get weather data if @configuration[:INTERNET_ALIVE] is false" do
begin
rfb = RubyFlashbake.new
rfb.load_file("#{File.dirname(__FILE__)}/../../../lib/data/.rubyflashbake_example")
rfb.load_plugins
rfb.configuration[:PLUGIN][:INTERNET][:OPTIONAL_HASH][:INTERNET_TEST_URI] = "notavalidwebaddressatall.ca"
rfb.configuration[:OUTPUT] = []
rfb.do_internet
rfb.do_location
rfb.do_weather
rfb.configuration[:LOCATION_CACHE].should == nil
rfb.configuration[:OUTPUT][0].should == "offline"
end
end
end | 37.317073 | 111 | 0.647712 |
e20382dfc23b4dd4798ef46d5bc22dc0d2eb7c0e | 88 | require 'minitest/autorun'
require 'mocha/setup'
require 'pry'
require 'scout_realtime'
| 17.6 | 26 | 0.795455 |
6131c5530994a1fdfd7b61eaa755f769f4f189b7 | 427 | # Option combination generator.
# Copyright (c) 2019 AUTHORS, MIT License.
require "minitest"
require "minitest/autorun"
module Minitest
Minitest.module_eval do
class << self
def <<(klass)
Runnable.runnables << klass unless Runnable.runnables.include? klass
nil
end
end
end
Runnable.instance_eval do
def self.inherited(_klass); end # rubocop:disable Lint/MissingSuper
end
end
| 20.333333 | 76 | 0.700234 |
38dfd8730d3b8988f491c1338d40e4be86935f70 | 1,515 | #
# Copyright:: Copyright 2013-2016, Chef Software 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 "support/shared/integration/integration_helper"
require "support/shared/context/config"
require "chef/knife/data_bag_show"
describe "knife data bag show", :workstation do
include IntegrationSupport
include KnifeSupport
include_context "default config options"
when_the_chef_server "has some data bags" do
before do
data_bag "x", {}
data_bag "canteloupe", {}
data_bag "rocket", { "falcon9" => { heavy: "true" }, "atlas" => {}, "ariane" => {} }
end
it "with an empty data bag" do
knife("data bag show canteloupe").should_succeed "\n"
end
it "with a bag with some items" do
knife("data bag show rocket").should_succeed <<EOM
ariane
atlas
falcon9
EOM
end
it "with a single item" do
knife("data bag show rocket falcon9").should_succeed <<EOM
heavy: true
id: falcon9
EOM
end
end
end
| 28.055556 | 90 | 0.711551 |
f7e86479a85e3b3af07ad7fad3323f161a808512 | 592 | #
# Cookbook Name:: bs-hardening::create_user
# Recipe:: default
#
# Copyright 2015, GSSC C.A
#
# All rights reserved - Do Not Redistribute
#
node['groups'].each do|d|
group d do
action :create
#gid group_id
end
end
node['users_admin'].each do|d|
group d do
action :create
#gid group_id
end
user d do
action :create
shell "/bin/bash"
supports :manage_home => true
#uid 1000+1
gid d
end
end
# Create directory
#directory node['directory'] do
# owner "jbravov"
# group "jbravov"
# mode "0755"
# action :create
#end
| 14.095238 | 43 | 0.621622 |
1db9735391d6d0684b776e0251f7e6c6d5aa09b9 | 142 | require "test_helper"
class ActivitiesControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
| 17.75 | 64 | 0.746479 |
180a71eb0247630bbfe9e1f70a20e885d45ba237 | 3,485 | require 'test_helper'
class FollowJobTest < ActiveSupport::TestCase
def instagram_identity
instagram_identities :default
end
def global_rate_limit
instagram_identity.rate_limits.global.first
end
def hashtag
hashtag = hashtags :default
hashtag.update_attributes!(auto_follow_on: true)
hashtag
end
def rate_limit
instagram_identity.rate_limits.relationships.first
end
def user_id
'1'
end
def test_perform_instagram_identity_id_required
assert_raises RuntimeError do
Instagram::FollowJob.new.perform
end
end
def test_perform_user_id_required
assert_raises RuntimeError do
Instagram::FollowJob.new.perform(instagram_identity_id: instagram_identity.id)
end
end
def test_perform_hashtag_id_required
assert_raises RuntimeError do
Instagram::FollowJob.new.perform(
instagram_identity_id: instagram_identity.id,
user_id: user_id
)
end
end
def test_perform_api_error
user_id = 1
stub_instagram_request(:post, "/users/#{user_id}/relationship", instagram_identity).
with(body: "access_token=#{instagram_identity.token}&action=follow").
to_return(status: 400, body: { error_message: 'haha' }.to_json)
assert_raises RuntimeError do
Instagram::FollowJob.new.perform(
instagram_identity_id: instagram_identity.id,
user_id: user_id,
hashtag_id: hashtag.id
)
assert_nil Relationship.find_by(user: instagram_identity.user, api_user_id: user_id)
end
end
def test_perform_rate_limited
instagram_identity.rate_limits.relationships.first.backoff!
assert_raises RuntimeError do
Instagram::FollowJob.new.perform(
instagram_identity_id: instagram_identity.id,
user_id: user_id,
hashtag_id: hashtag.id
)
end
end
def test_perform
stub_instagram_request(:post, "/users/#{user_id}/relationship", instagram_identity).
with(body: "access_token=#{instagram_identity.token}&action=follow").
to_return(status: 200, body: { code: "200", data: { outgoing_status: "requested" }}.to_json)
Instagram::FollowJob.new.perform(
instagram_identity_id: instagram_identity.id,
user_id: user_id,
hashtag_id: hashtag.id
)
assert_equal 1, Instagram::UnfollowJob.jobs.count
relationship = Relationship.find_by(user: instagram_identity.user, api_user_id: user_id)
assert_equal "requested", relationship.outgoing_status, "should create relationship"
assert_equal 1, rate_limit.requests.count
assert_equal 1, global_rate_limit.requests.count
end
def test_perform_requeue
stub_instagram_request(:post, "/users/#{user_id}/relationship", instagram_identity).
with(body: "access_token=#{instagram_identity.token}&action=follow").
to_return(status: 200, body: { code: "200", data: { outgoing_status: "requested" }}.to_json)
Instagram::FollowJob.new.perform(
instagram_identity_id: instagram_identity.id,
user_id: user_id,
hashtag_id: hashtag.id,
requeue: true
)
assert_equal 1, Instagram::UnfollowJob.jobs.count
assert_equal 1, Instagram::AutoFollowJob.jobs.count
relationship = Relationship.find_by(user: instagram_identity.user, api_user_id: user_id)
assert_equal "requested", relationship.outgoing_status, "should create relationship"
assert_equal 1, rate_limit.requests.count
assert_equal 1, global_rate_limit.requests.count
end
end
| 32.570093 | 98 | 0.736585 |
ac8c8b2b3a59d75cbdc9e6323b9d7038fec2220c | 444 | cask "flying-carpet" do
version "3.0"
sha256 "a38cb60ee732412d03c0372f1b1b3cc46cb83e94f33961c6f677afb4f71d4aaf"
url "https://github.com/spieglt/FlyingCarpet/releases/download/#{version}/Flying.Carpet.Mac.zip"
appcast "https://github.com/spieglt/flyingcarpet/releases.atom"
name "Flying Carpet"
desc "Cross-platform file transfer over ad-hoc wifi"
homepage "https://github.com/spieglt/flyingcarpet"
app "Flying Carpet.app"
end
| 34.153846 | 98 | 0.779279 |
1ab629dd724f46282cbee7763d2998c0865c3977 | 380 | cask 'intellij-idea-12-1' do
version '12.1.8,129.1561'
sha256 '94c2854635f6cfa077de4e3cc71b63242fb652e8c0ef8f6f999e9089eb83d33a'
url "https://download.jetbrains.com/idea/ideaIU-#{version.before_comma}.dmg"
name 'IntelliJ IDEA Ultimate'
homepage 'https://www.jetbrains.com/idea/'
auto_updates true
app 'IntelliJ IDEA 12.app', target: 'IntelliJ IDEA 12.1.app'
end
| 27.142857 | 78 | 0.757895 |
b99361d82c08324b3485d1a43f7db444a3c45b26 | 998 | # 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.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_03_08_075304) do
create_table "tweets", force: :cascade do |t|
t.string "content"
t.integer "user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.string "password_digest"
end
end
| 36.962963 | 86 | 0.759519 |
6a545884f180c755c2365c54a0b5cf8a80b81cb8 | 67,938 | # frozen_string_literal: true
# encoding: utf-8
require "spec_helper"
class FieldWithSerializer
def evolve(object)
Integer.evolve(object)
end
def localized?
false
end
end
describe Mongoid::Criteria::Queryable::Selectable do
let(:query) do
Mongoid::Query.new("id" => "_id")
end
shared_examples_for "returns a cloned query" do
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
shared_examples_for 'requires an argument' do
context "when provided no argument" do
let(:selection) do
query.send(query_method)
end
it "raises ArgumentError" do
expect do
selection.selector
end.to raise_error(ArgumentError)
end
end
end
shared_examples_for 'requires a non-nil argument' do
context "when provided nil" do
let(:selection) do
query.send(query_method, nil)
end
it "raises CriteriaArgumentRequired" do
expect do
selection.selector
end.to raise_error(Mongoid::Errors::CriteriaArgumentRequired, /#{query_method}/)
end
end
end
shared_examples_for 'supports merge strategies' do
context 'when the field is not aliased' do
context "when the strategy is not set" do
let(:selection) do
query.send(query_method, first: [ 1, 2 ]).send(query_method, first: [ 3, 4 ])
end
it "combines the conditions with $and" do
expect(selection.selector).to eq({
"first" => { operator => [ 1, 2 ] },
'$and' => [{'first' => {operator => [3, 4]}}],
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is intersect" do
let(:selection) do
query.send(query_method, first: [ 1, 2 ]).intersect.send(query_method, first: [ 2, 3 ])
end
it "intersects the conditions" do
expect(selection.selector).to eq({
"first" => { operator => [ 2 ] }
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is override" do
let(:selection) do
query.send(query_method, first: [ 1, 2 ]).override.send(query_method, first: [ 3, 4 ])
end
it "overwrites the first condition" do
expect(selection.selector).to eq({
"first" => { operator => [ 3, 4 ] }
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is union" do
let(:selection) do
query.send(query_method, first: [ 1, 2 ]).union.send(query_method, first: [ 3, 4 ])
end
it "unions the conditions" do
expect(selection.selector).to eq({
"first" => { operator => [ 1, 2, 3, 4 ] }
})
end
it_behaves_like "returns a cloned query"
end
end
context 'when the field is aliased' do
context "when the strategy is not set" do
let(:selection) do
query.send(query_method, id: [ 1, 2 ]).send(query_method, _id: [ 3, 4 ])
end
it "combines the conditions with $and" do
expect(selection.selector).to eq({
"_id" => { operator => [ 1, 2 ] },
'$and' => [{'_id' => {operator => [3, 4]}}],
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is intersect" do
let(:selection) do
query.send(query_method, id: [ 1, 2 ]).intersect.send(query_method, _id: [ 2, 3 ])
end
it "intersects the conditions" do
expect(selection.selector).to eq({
"_id" => { operator => [ 2 ] }
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is override" do
let(:selection) do
query.send(query_method, _id: [ 1, 2 ]).override.send(query_method, id: [ 3, 4 ])
end
it "overwrites the first condition" do
expect(selection.selector).to eq({
"_id" => { operator => [ 3, 4 ] }
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is union" do
let(:selection) do
query.send(query_method, _id: [ 1, 2 ]).union.send(query_method, id: [ 3, 4 ])
end
it "unions the conditions" do
expect(selection.selector).to eq({
"_id" => { operator => [ 1, 2, 3, 4 ] }
})
end
it_behaves_like "returns a cloned query"
end
end
context 'when the field uses a serializer' do
let(:query) do
Mongoid::Query.new({}, { "field" => FieldWithSerializer.new })
end
context "when the strategy is not set" do
let(:selection) do
query.send(query_method, field: [ '1', '2' ]).send(query_method, field: [ '3', '4' ])
end
it "combines the conditions with $and" do
expect(selection.selector).to eq({
"field" => { operator => [ 1, 2 ] },
'$and' => [{'field' => {operator => [3, 4]}}],
})
end
it_behaves_like "returns a cloned query"
end
context "when the strategy is set" do
let(:selection) do
query.send(query_method, field: [ '1', '2' ]).intersect.send(query_method, field: [ '2', '3' ])
end
it "intersects the conditions" do
expect(selection.selector).to eq({
"field" => { operator => [ 2 ] }
})
end
it_behaves_like "returns a cloned query"
end
end
context 'when operator value is a Range' do
context "when there is no existing condition and strategy is not specified" do
let(:selection) do
query.send(query_method, foo: 2..4)
end
it 'expands range to array' do
expect(selection.selector).to eq({
"foo" => { operator => [ 2, 3, 4 ] }
})
end
end
context "when there is no existing condition and strategy is specified" do
let(:selection) do
query.union.send(query_method, foo: 2..4)
end
it 'expands range to array' do
expect(selection.selector).to eq({
"foo" => { operator => [ 2, 3, 4 ] }
})
end
end
context "when existing condition has Array value" do
let(:selection) do
query.send(query_method, foo: [ 1, 2 ]).union.send(query_method, foo: 2..4)
end
it 'expands range to array' do
expect(selection.selector).to eq({
"foo" => { operator => [ 1, 2, 3, 4 ] }
})
end
end
context "when existing condition has Range value" do
let(:selection) do
query.send(query_method, foo: 1..2).union.send(query_method, foo: 2..4)
end
it 'expands range to array' do
expect(selection.selector).to eq({
"foo" => { operator => [ 1, 2, 3, 4 ] }
})
end
end
end
end
describe "#all" do
let(:query_method) { :all }
let(:operator) { '$all' }
context "when provided no criterion" do
let(:selection) do
query.all
end
it "does not add any criterion" do
expect(selection.selector).to eq({})
end
it "returns the query" do
expect(selection).to eq(query)
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
context "when no serializers are provided" do
context "when providing an array" do
let(:selection) do
query.all(field: [ 1, 2 ])
end
it "adds the $all selector" do
expect(selection.selector).to eq({
"field" => { "$all" => [ 1, 2 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing a single value" do
let(:selection) do
query.all(field: 1)
end
it "adds the $all selector with wrapped value" do
expect(selection.selector).to eq({
"field" => { "$all" => [ 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when serializers are provided" do
before(:all) do
class Field
def evolve(object)
Integer.evolve(object)
end
def localized?
false
end
end
end
after(:all) do
Object.send(:remove_const, :Field)
end
let!(:query) do
Mongoid::Query.new({}, { "field" => Field.new })
end
context "when providing an array" do
let(:selection) do
query.all(field: [ "1", "2" ])
end
it "adds the $all selector" do
expect(selection.selector).to eq({
"field" => { "$all" => [ 1, 2 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing a single value" do
let(:selection) do
query.all(field: "1")
end
it "adds the $all selector with wrapped value" do
expect(selection.selector).to eq({
"field" => { "$all" => [ 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.all(first: [ 1, 2 ], second: [ 3, 4 ])
end
it "adds the $all selectors" do
expect(selection.selector).to eq({
"first" => { "$all" => [ 1, 2 ] },
"second" => { "$all" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.all(first: [ 1, 2 ]).all(second: [ 3, 4 ])
end
it "adds the $all selectors" do
expect(selection.selector).to eq({
"first" => { "$all" => [ 1, 2 ] },
"second" => { "$all" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
it_behaves_like 'supports merge strategies'
end
end
end
describe "#between" do
let(:query_method) { :between }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single range" do
let(:selection) do
query.between(field: 1..10)
end
it "adds the $gte and $lte selectors" do
expect(selection.selector).to eq({
"field" => { "$gte" => 1, "$lte" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided multiple ranges" do
context "when the ranges are on different fields" do
let(:selection) do
query.between(field: 1..10, key: 5..7)
end
it "adds the $gte and $lte selectors" do
expect(selection.selector).to eq({
"field" => { "$gte" => 1, "$lte" => 10 },
"key" => { "$gte" => 5, "$lte" => 7 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#elem_match" do
let(:query_method) { :elem_match }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
context "when there are no nested complex keys" do
let(:selection) do
query.elem_match(users: { name: "value" })
end
it "adds the $elemMatch expression" do
expect(selection.selector).to eq({
"users" => { "$elemMatch" => { name: "value" }}
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when there are nested complex keys" do
let(:time) do
Time.now
end
let(:selection) do
query.elem_match(users: { :time.gt => time })
end
it "adds the $elemMatch expression" do
expect(selection.selector).to eq({
"users" => { "$elemMatch" => { "time" => { "$gt" => time }}}
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.elem_match(
users: { name: "value" },
comments: { text: "value" }
)
end
it "adds the $elemMatch expression" do
expect(selection.selector).to eq({
"users" => { "$elemMatch" => { name: "value" }},
"comments" => { "$elemMatch" => { text: "value" }}
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
elem_match(users: { name: "value" }).
elem_match(comments: { text: "value" })
end
it "adds the $elemMatch expression" do
expect(selection.selector).to eq({
"users" => { "$elemMatch" => { name: "value" }},
"comments" => { "$elemMatch" => { text: "value" }}
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the fields are the same" do
let(:selection) do
query.
elem_match(users: { name: "value" }).
elem_match(users: { state: "new" })
end
it "overrides the $elemMatch expression" do
expect(selection.selector).to eq({
"users" => { "$elemMatch" => { state: "new" }}
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#exists" do
let(:query_method) { :exists }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
context "when provided a boolean" do
let(:selection) do
query.exists(users: true)
end
it "adds the $exists expression" do
expect(selection.selector).to eq({
"users" => { "$exists" => true }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided a string" do
let(:selection) do
query.exists(users: "yes")
end
it "adds the $exists expression" do
expect(selection.selector).to eq({
"users" => { "$exists" => true }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
context "when providing boolean values" do
let(:selection) do
query.exists(
users: true,
comments: true
)
end
it "adds the $exists expression" do
expect(selection.selector).to eq({
"users" => { "$exists" => true },
"comments" => { "$exists" => true }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing string values" do
let(:selection) do
query.exists(
users: "y",
comments: "true"
)
end
it "adds the $exists expression" do
expect(selection.selector).to eq({
"users" => { "$exists" => true },
"comments" => { "$exists" => true }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
exists(users: true).
exists(comments: true)
end
it "adds the $exists expression" do
expect(selection.selector).to eq({
"users" => { "$exists" => true },
"comments" => { "$exists" => true }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#geo_spacial" do
let(:query_method) { :geo_spacial }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
context "when the geometry is a point intersection" do
let(:selection) do
query.geo_spacial(:location.intersects_point => [ 1, 10 ])
end
it "adds the $geoIntersects expression" do
expect(selection.selector).to eq({
"location" => {
"$geoIntersects" => {
"$geometry" => {
"type" => "Point",
"coordinates" => [ 1, 10 ]
}
}
}
})
end
it_behaves_like "returns a cloned query"
end
context "when the geometry is a line intersection" do
let(:selection) do
query.geo_spacial(:location.intersects_line => [[ 1, 10 ], [ 2, 10 ]])
end
it "adds the $geoIntersects expression" do
expect(selection.selector).to eq({
"location" => {
"$geoIntersects" => {
"$geometry" => {
"type" => "LineString",
"coordinates" => [[ 1, 10 ], [ 2, 10 ]]
}
}
}
})
end
it_behaves_like "returns a cloned query"
end
context "when the geometry is a polygon intersection" do
let(:selection) do
query.geo_spacial(
:location.intersects_polygon => [[[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]]]
)
end
it "adds the $geoIntersects expression" do
expect(selection.selector).to eq({
"location" => {
"$geoIntersects" => {
"$geometry" => {
"type" => "Polygon",
"coordinates" => [[[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]]]
}
}
}
})
end
it_behaves_like "returns a cloned query"
end
context "when the geometry is within a polygon" do
let(:selection) do
query.geo_spacial(
:location.within_polygon => [[[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]]]
)
end
it "adds the $geoIntersects expression" do
expect(selection.selector).to eq({
"location" => {
"$geoWithin" => {
"$geometry" => {
"type" => "Polygon",
"coordinates" => [[[ 1, 10 ], [ 2, 10 ], [ 1, 10 ]]]
}
}
}
})
end
context "when used with the $box operator ($geoWithin query) " do
let(:selection) do
query.geo_spacial(
:location.within_box => [[ 1, 10 ], [ 2, 10 ]]
)
end
it "adds the $geoIntersects expression" do
expect(selection.selector).to eq({
"location" => {
"$geoWithin" => {
"$box" => [
[ 1, 10 ], [ 2, 10 ]
]
}
}
})
end
end
it_behaves_like "returns a cloned query"
end
end
end
describe "#gt" do
let(:query_method) { :gt }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
let(:selection) do
query.gt(field: 10)
end
it "adds the $gt selector" do
expect(selection.selector).to eq({
"field" => { "$gt" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.gt(first: 10, second: 15)
end
it "adds the $gt selectors" do
expect(selection.selector).to eq({
"first" => { "$gt" => 10 },
"second" => { "$gt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.gt(first: 10).gt(second: 15)
end
it "adds the $gt selectors" do
expect(selection.selector).to eq({
"first" => { "$gt" => 10 },
"second" => { "$gt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.gt(first: 10).gt(first: 15)
end
it "overwrites the first $gt selector" do
expect(selection.selector).to eq({
"first" => { "$gt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#gte" do
let(:query_method) { :gte }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
let(:selection) do
query.gte(field: 10)
end
it "adds the $gte selector" do
expect(selection.selector).to eq({
"field" => { "$gte" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.gte(first: 10, second: 15)
end
it "adds the $gte selectors" do
expect(selection.selector).to eq({
"first" => { "$gte" => 10 },
"second" => { "$gte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.gte(first: 10).gte(second: 15)
end
it "adds the $gte selectors" do
expect(selection.selector).to eq({
"first" => { "$gte" => 10 },
"second" => { "$gte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.gte(first: 10).gte(first: 15)
end
it "overwrites the first $gte selector" do
expect(selection.selector).to eq({
"first" => { "$gte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#in" do
let(:query_method) { :in }
let(:operator) { '$in' }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
context "when providing an array" do
let(:selection) do
query.in(field: [ 1, 2 ])
end
it "adds the $in selector" do
expect(selection.selector).to eq({
"field" => { "$in" => [ 1, 2 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing a single value" do
let(:selection) do
query.in(field: 1)
end
it "adds the $in selector with wrapped value" do
expect(selection.selector).to eq({
"field" => { "$in" => [ 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.in(first: [ 1, 2 ], second: 3..4)
end
it "adds the $in selectors" do
expect(selection.selector).to eq({
"first" => { "$in" => [ 1, 2 ] },
"second" => { "$in" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.in(first: [ 1, 2 ]).in(second: [ 3, 4 ])
end
it "adds the $in selectors" do
expect(selection.selector).to eq({
"first" => { "$in" => [ 1, 2 ] },
"second" => { "$in" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
it_behaves_like 'supports merge strategies'
end
end
end
describe "#lt" do
let(:query_method) { :lt }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
let(:selection) do
query.lt(field: 10)
end
it "adds the $lt selector" do
expect(selection.selector).to eq({
"field" => { "$lt" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.lt(first: 10, second: 15)
end
it "adds the $lt selectors" do
expect(selection.selector).to eq({
"first" => { "$lt" => 10 },
"second" => { "$lt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.lt(first: 10).lt(second: 15)
end
it "adds the $lt selectors" do
expect(selection.selector).to eq({
"first" => { "$lt" => 10 },
"second" => { "$lt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.lt(first: 10).lt(first: 15)
end
it "overwrites the first $lt selector" do
expect(selection.selector).to eq({
"first" => { "$lt" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#lte" do
let(:query_method) { :lte }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
let(:selection) do
query.lte(field: 10)
end
it "adds the $lte selector" do
expect(selection.selector).to eq({
"field" => { "$lte" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.lte(first: 10, second: 15)
end
it "adds the $lte selectors" do
expect(selection.selector).to eq({
"first" => { "$lte" => 10 },
"second" => { "$lte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.lte(first: 10).lte(second: 15)
end
it "adds the $lte selectors" do
expect(selection.selector).to eq({
"first" => { "$lte" => 10 },
"second" => { "$lte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.lte(first: 10).lte(first: 15)
end
it "overwrites the first $lte selector" do
expect(selection.selector).to eq({
"first" => { "$lte" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#max_distance" do
let(:query_method) { :max_distance }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
context "when a $near criterion exists on the same field" do
let(:selection) do
query.near(location: [ 1, 1 ]).max_distance(location: 50)
end
it "adds the $maxDistance expression" do
expect(selection.selector).to eq({
"location" => { "$near" => [ 1, 1 ], "$maxDistance" => 50 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#mod" do
let(:query_method) { :mod }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
let(:selection) do
query.mod(value: [ 10, 1 ])
end
it "adds the $mod expression" do
expect(selection.selector).to eq({
"value" => { "$mod" => [ 10, 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.mod(
value: [ 10, 1 ],
comments: [ 10, 1 ]
)
end
it "adds the $mod expression" do
expect(selection.selector).to eq({
"value" => { "$mod" => [ 10, 1 ] },
"comments" => { "$mod" => [ 10, 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
mod(value: [ 10, 1 ]).
mod(result: [ 10, 1 ])
end
it "adds the $mod expression" do
expect(selection.selector).to eq({
"value" => { "$mod" => [ 10, 1 ] },
"result" => { "$mod" => [ 10, 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#ne" do
let(:query_method) { :ne }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
let(:selection) do
query.ne(value: 10)
end
it "adds the $ne expression" do
expect(selection.selector).to eq({
"value" => { "$ne" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.ne(
value: 10,
comments: 10
)
end
it "adds the $ne expression" do
expect(selection.selector).to eq({
"value" => { "$ne" => 10 },
"comments" => { "$ne" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
ne(value: 10).
ne(result: 10)
end
it "adds the $ne expression" do
expect(selection.selector).to eq({
"value" => { "$ne" => 10 },
"result" => { "$ne" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#near" do
let(:query_method) { :near }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
let(:selection) do
query.near(location: [ 20, 21 ])
end
it "adds the $near expression" do
expect(selection.selector).to eq({
"location" => { "$near" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.near(
location: [ 20, 21 ],
comments: [ 20, 21 ]
)
end
it "adds the $near expression" do
expect(selection.selector).to eq({
"location" => { "$near" => [ 20, 21 ] },
"comments" => { "$near" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
near(location: [ 20, 21 ]).
near(comments: [ 20, 21 ])
end
it "adds the $near expression" do
expect(selection.selector).to eq({
"location" => { "$near" => [ 20, 21 ] },
"comments" => { "$near" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#near_sphere" do
let(:query_method) { :near_sphere }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a criterion" do
let(:selection) do
query.near_sphere(location: [ 20, 21 ])
end
it "adds the $nearSphere expression" do
expect(selection.selector).to eq({
"location" => { "$nearSphere" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.near_sphere(
location: [ 20, 21 ],
comments: [ 20, 21 ]
)
end
it "adds the $nearSphere expression" do
expect(selection.selector).to eq({
"location" => { "$nearSphere" => [ 20, 21 ] },
"comments" => { "$nearSphere" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining multiple criteria" do
context "when the fields differ" do
let(:selection) do
query.
near_sphere(location: [ 20, 21 ]).
near_sphere(comments: [ 20, 21 ])
end
it "adds the $nearSphere expression" do
expect(selection.selector).to eq({
"location" => { "$nearSphere" => [ 20, 21 ] },
"comments" => { "$nearSphere" => [ 20, 21 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#nin" do
let(:query_method) { :nin }
let(:operator) { '$nin' }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
context "when providing an array" do
let(:selection) do
query.nin(field: [ 1, 2 ])
end
it "adds the $nin selector" do
expect(selection.selector).to eq({
"field" => { "$nin" => [ 1, 2 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when providing a single value" do
let(:selection) do
query.nin(field: 1)
end
it "adds the $nin selector with wrapped value" do
expect(selection.selector).to eq({
"field" => { "$nin" => [ 1 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.nin(first: [ 1, 2 ], second: [ 3, 4 ])
end
it "adds the $nin selectors" do
expect(selection.selector).to eq({
"first" => { "$nin" => [ 1, 2 ] },
"second" => { "$nin" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.nin(first: [ 1, 2 ]).nin(second: [ 3, 4 ])
end
it "adds the $nin selectors" do
expect(selection.selector).to eq({
"first" => { "$nin" => [ 1, 2 ] },
"second" => { "$nin" => [ 3, 4 ] }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
it_behaves_like 'supports merge strategies'
end
end
end
describe "#with_size" do
let(:query_method) { :with_size }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
context "when provided an integer" do
let(:selection) do
query.with_size(field: 10)
end
it "adds the $size selector" do
expect(selection.selector).to eq({
"field" => { "$size" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided a string" do
let(:selection) do
query.with_size(field: "10")
end
it "adds the $size selector with an integer" do
expect(selection.selector).to eq({
"field" => { "$size" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
context "when provided integers" do
let(:selection) do
query.with_size(first: 10, second: 15)
end
it "adds the $size selectors" do
expect(selection.selector).to eq({
"first" => { "$size" => 10 },
"second" => { "$size" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided strings" do
let(:selection) do
query.with_size(first: "10", second: "15")
end
it "adds the $size selectors" do
expect(selection.selector).to eq({
"first" => { "$size" => 10 },
"second" => { "$size" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.with_size(first: 10).with_size(second: 15)
end
it "adds the $size selectors" do
expect(selection.selector).to eq({
"first" => { "$size" => 10 },
"second" => { "$size" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.with_size(first: 10).with_size(first: 15)
end
it "overwrites the first $size selector" do
expect(selection.selector).to eq({
"first" => { "$size" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#with_type" do
let(:query_method) { :with_type }
it_behaves_like 'requires an argument'
it_behaves_like 'requires a non-nil argument'
context "when provided a single criterion" do
context "when provided an integer" do
let(:selection) do
query.with_type(field: 10)
end
it "adds the $type selector" do
expect(selection.selector).to eq({
"field" => { "$type" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when provided a string" do
let(:selection) do
query.with_type(field: "10")
end
it "adds the $type selector" do
expect(selection.selector).to eq({
"field" => { "$type" => 10 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when provided multiple criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.with_type(first: 10, second: 15)
end
it "adds the $type selectors" do
expect(selection.selector).to eq({
"first" => { "$type" => 10 },
"second" => { "$type" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
context "when chaining the criterion" do
context "when the criterion are for different fields" do
let(:selection) do
query.with_type(first: 10).with_type(second: 15)
end
it "adds the $type selectors" do
expect(selection.selector).to eq({
"first" => { "$type" => 10 },
"second" => { "$type" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
context "when the criterion are on the same field" do
let(:selection) do
query.with_type(first: 10).with_type(first: 15)
end
it "overwrites the first $type selector" do
expect(selection.selector).to eq({
"first" => { "$type" => 15 }
})
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
end
end
describe "#text_search" do
context "when providing a search string" do
let(:selection) do
query.text_search("testing")
end
it "constructs a text search document" do
expect(selection.selector).to eq({ '$text' => { '$search' => "testing" }})
end
it "returns the cloned selectable" do
expect(selection).to be_a(Mongoid::Criteria::Queryable::Selectable)
end
context "when providing text search options" do
let(:selection) do
query.text_search("essais", { :$language => "fr" })
end
it "constructs a text search document" do
expect(selection.selector['$text']['$search']).to eq("essais")
end
it "add the options to the text search document" do
expect(selection.selector['$text'][:$language]).to eq("fr")
end
it_behaves_like "returns a cloned query"
end
end
context 'when given more than once' do
let(:selection) do
query.text_search("one").text_search('two')
end
# MongoDB server can only handle one text expression at a time,
# per https://docs.mongodb.com/manual/reference/operator/query/text/.
# Nonetheless we test that the query is built correctly when
# a user supplies more than one text condition.
it 'merges conditions' do
expect(Mongoid.logger).to receive(:warn)
expect(selection.selector).to eq('$and' => [
{'$text' => {'$search' => 'one'}}
],
'$text' => {'$search' => 'two'},
)
end
end
end
describe "#where" do
let(:query_method) { :where }
context "when provided no criterion" do
let(:selection) do
query.where
end
it "does not add any criterion" do
expect(selection.selector).to eq({})
end
it "returns the query" do
expect(selection).to eq(query)
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
end
it_behaves_like 'requires a non-nil argument'
context "when provided a string" do
let(:selection) do
query.where("this.value = 10")
end
it "adds the $where criterion" do
expect(selection.selector).to eq({ "$where" => "this.value = 10" })
end
it "returns a cloned query" do
expect(selection).to_not equal(query)
end
context 'when multiple calls with string argument are made' do
let(:selection) do
query.where("this.value = 10").where('foo.bar')
end
it 'combines conditions' do
expect(selection.selector).to eq(
"$where" => "this.value = 10", '$and' => [{'$where' => 'foo.bar'}],
)
end
end
context 'when called with string argument and with hash argument' do
let(:selection) do
query.where("this.value = 10").where(foo: 'bar')
end
it 'combines conditions' do
expect(selection.selector).to eq(
"$where" => "this.value = 10", 'foo' => 'bar',
)
end
end
context 'when called with hash argument and with string argument' do
let(:selection) do
query.where(foo: 'bar').where("this.value = 10")
end
it 'combines conditions' do
expect(selection.selector).to eq(
'foo' => 'bar', "$where" => "this.value = 10",
)
end
end
end
context "when provided a single criterion" do
context "when the value needs no evolution" do
let(:selection) do
query.where(name: "Syd")
end
it "adds the criterion to the selection" do
expect(selection.selector).to eq({ "name" => "Syd" })
end
end
context "when the value must be evolved" do
before(:all) do
class Document
def id
13
end
def self.evolve(object)
object.id
end
end
end
after(:all) do
Object.send(:remove_const, :Document)
end
context "when the key needs evolution" do
let(:query) do
Mongoid::Query.new({ "user" => "user_id" })
end
let(:document) do
Document.new
end
let(:selection) do
query.where(user: document)
end
it "alters the key and value" do
expect(selection.selector).to eq({ "user_id" => document.id })
end
end
context 'when the field is a String and the value is a BSON::Regexp::Raw' do
let(:raw_regexp) do
BSON::Regexp::Raw.new('^Em')
end
let(:selection) do
Login.where(_id: raw_regexp)
end
it 'does not convert the bson raw regexp object to a String' do
expect(selection.selector).to eq({ "_id" => raw_regexp })
end
end
end
end
context "when provided complex criterion" do
context "when performing an $all" do
context "when performing a single query" do
let(:selection) do
query.where(:field.all => [ 1, 2 ])
end
it "adds the $all criterion" do
expect(selection.selector).to eq({ "field" => { "$all" => [ 1, 2 ] }})
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
end
context "when performing an $elemMatch" do
context "when the value is not complex" do
let(:selection) do
query.where(:field.elem_match => { key: 1 })
end
it "adds the $elemMatch criterion" do
expect(selection.selector).to eq(
{ "field" => { "$elemMatch" => { key: 1 } }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when the value is complex" do
let(:selection) do
query.where(:field.elem_match => { :key.gt => 1 })
end
it "adds the $elemMatch criterion" do
expect(selection.selector).to eq(
{ "field" => { "$elemMatch" => { "key" => { "$gt" => 1 }}}}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
end
context "when performing an $exists" do
context "when providing boolean values" do
let(:selection) do
query.where(:field.exists => true)
end
it "adds the $exists criterion" do
expect(selection.selector).to eq(
{ "field" => { "$exists" => true }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when providing string values" do
let(:selection) do
query.where(:field.exists => "t")
end
it "adds the $exists criterion" do
expect(selection.selector).to eq(
{ "field" => { "$exists" => true }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
end
context "when performing a $gt" do
let(:selection) do
query.where(:field.gt => 10)
end
it "adds the $gt criterion" do
expect(selection.selector).to eq(
{ "field" => { "$gt" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $gte" do
let(:selection) do
query.where(:field.gte => 10)
end
it "adds the $gte criterion" do
expect(selection.selector).to eq(
{ "field" => { "$gte" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing an $in" do
let(:selection) do
query.where(:field.in => [ 1, 2 ])
end
it "adds the $in criterion" do
expect(selection.selector).to eq({ "field" => { "$in" => [ 1, 2 ] }})
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $lt" do
let(:selection) do
query.where(:field.lt => 10)
end
it "adds the $lt criterion" do
expect(selection.selector).to eq(
{ "field" => { "$lt" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $lte" do
let(:selection) do
query.where(:field.lte => 10)
end
it "adds the $lte criterion" do
expect(selection.selector).to eq(
{ "field" => { "$lte" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $mod" do
let(:selection) do
query.where(:field.mod => [ 10, 1 ])
end
it "adds the $lte criterion" do
expect(selection.selector).to eq(
{ "field" => { "$mod" => [ 10, 1 ]}}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $ne" do
let(:selection) do
query.where(:field.ne => 10)
end
it "adds the $ne criterion" do
expect(selection.selector).to eq(
{ "field" => { "$ne" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $near" do
let(:selection) do
query.where(:field.near => [ 1, 1 ])
end
it "adds the $near criterion" do
expect(selection.selector).to eq(
{ "field" => { "$near" => [ 1, 1 ] }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $nearSphere" do
let(:selection) do
query.where(:field.near_sphere => [ 1, 1 ])
end
it "adds the $nearSphere criterion" do
expect(selection.selector).to eq(
{ "field" => { "$nearSphere" => [ 1, 1 ] }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $nin" do
let(:selection) do
query.where(:field.nin => [ 1, 2 ])
end
it "adds the $nin criterion" do
expect(selection.selector).to eq({ "field" => { "$nin" => [ 1, 2 ] }})
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $not" do
let(:selection) do
query.where(:field.not => /test/)
end
it "adds the $not criterion" do
expect(selection.selector).to eq({ "field" => { "$not" => /test/ }})
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when performing a $size" do
context "when providing an integer" do
let(:selection) do
query.where(:field.with_size => 10)
end
it "adds the $size criterion" do
expect(selection.selector).to eq(
{ "field" => { "$size" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
context "when providing a string" do
let(:selection) do
query.where(:field.with_size => "10")
end
it "adds the $size criterion" do
expect(selection.selector).to eq(
{ "field" => { "$size" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
end
context "when performing a $type" do
let(:selection) do
query.where(:field.with_type => 10)
end
it "adds the $type criterion" do
expect(selection.selector).to eq(
{ "field" => { "$type" => 10 }}
)
end
it "returns a cloned query" do
expect(selection).to_not eq(query)
end
end
end
context 'when using an MQL logical operator manually' do
let(:base_query) do
query.where(test: 1)
end
let(:selection) do
base_query.where(mql_operator => ['hello' => 'world'])
end
shared_examples_for 'adds conditions to existing query' do
it 'adds conditions to existing query' do
selection.selector.should == {
'test' => 1,
mql_operator => ['hello' => 'world'],
}
end
end
shared_examples_for 'adds conditions to existing query with an extra $and' do
it 'adds conditions to existing query' do
selection.selector.should == {
'test' => 1,
# The $and here is superfluous but not wrong.
# To be addressed as part of
# https://jira.mongodb.org/browse/MONGOID-4861.
'$and' => [mql_operator => ['hello' => 'world']],
}
end
end
context '$or' do
let(:mql_operator) { '$or' }
it_behaves_like 'adds conditions to existing query with an extra $and'
end
context '$nor' do
let(:mql_operator) { '$nor' }
it_behaves_like 'adds conditions to existing query with an extra $and'
end
context '$not' do
let(:mql_operator) { '$not' }
it_behaves_like 'adds conditions to existing query'
end
context '$and' do
let(:mql_operator) { '$and' }
it_behaves_like 'adds conditions to existing query'
end
end
end
describe Symbol do
describe "#all" do
let(:key) do
:field.all
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $all" do
expect(key.operator).to eq("$all")
end
end
describe "#elem_match" do
let(:key) do
:field.elem_match
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $elemMatch" do
expect(key.operator).to eq("$elemMatch")
end
end
describe "#exists" do
let(:key) do
:field.exists
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $exists" do
expect(key.operator).to eq("$exists")
end
end
describe "#gt" do
let(:key) do
:field.gt
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $gt" do
expect(key.operator).to eq("$gt")
end
end
describe "#gte" do
let(:key) do
:field.gte
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $gte" do
expect(key.operator).to eq("$gte")
end
end
describe "#in" do
let(:key) do
:field.in
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $in" do
expect(key.operator).to eq("$in")
end
end
describe "#lt" do
let(:key) do
:field.lt
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $lt" do
expect(key.operator).to eq("$lt")
end
end
describe "#lte" do
let(:key) do
:field.lte
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $lte" do
expect(key.operator).to eq("$lte")
end
end
describe "#mod" do
let(:key) do
:field.mod
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $mod" do
expect(key.operator).to eq("$mod")
end
end
describe "#ne" do
let(:key) do
:field.ne
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $ne" do
expect(key.operator).to eq("$ne")
end
end
describe "#near" do
let(:key) do
:field.near
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $near" do
expect(key.operator).to eq("$near")
end
end
describe "#near_sphere" do
let(:key) do
:field.near_sphere
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $nearSphere" do
expect(key.operator).to eq("$nearSphere")
end
end
describe "#nin" do
let(:key) do
:field.nin
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $nin" do
expect(key.operator).to eq("$nin")
end
end
describe "#not" do
let(:key) do
:field.not
end
it "returns a selection key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $not" do
expect(key.operator).to eq("$not")
end
end
describe "#with_size" do
let(:key) do
:field.with_size
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $size" do
expect(key.operator).to eq("$size")
end
end
describe "#with_type" do
let(:key) do
:field.with_type
end
it "returns a selecton key" do
expect(key).to be_a(Mongoid::Criteria::Queryable::Key)
end
it "sets the name as the key" do
expect(key.name).to eq(:field)
end
it "sets the operator as $type" do
expect(key.operator).to eq("$type")
end
end
end
context "when using multiple strategies on the same field" do
context "when using the strategies via methods" do
context "when different operators are specified" do
let(:selection) do
query.gt(field: 5).lt(field: 10).ne(field: 7)
end
it "merges the strategies on the same field" do
expect(selection.selector).to eq(
"field" => { "$gt" => 5, "$lt" => 10, "$ne" => 7 }
)
end
end
context "when the same operator is specified" do
let(:selection) do
query.where(field: 5).where(field: 10)
end
it "combines conditions" do
expect(selection.selector).to eq("field" => 5, '$and' => [{'field' => 10}] )
end
end
end
context "when using the strategies via #where" do
context "when using complex keys with different operators" do
let(:selection) do
query.where(:field.gt => 5, :field.lt => 10, :field.ne => 7)
end
it "merges the strategies on the same field" do
expect(selection.selector).to eq(
"field" => { "$gt" => 5, "$lt" => 10, "$ne" => 7 }
)
end
end
end
end
end
| 23.721369 | 105 | 0.517413 |
18413af9f25867dc7f9ac5e0a55f6101afbaa4fb | 983 | require 'test_helper'
class UsersControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:users)
end
test "should get new" do
get :new
assert_response :success
end
test "should create user" do
assert_difference('User.count') do
post :create, :user => { }
end
assert_redirected_to user_path(assigns(:user))
end
test "should show user" do
get :show, :id => users(:one).to_param
assert_response :success
end
test "should get edit" do
get :edit, :id => users(:one).to_param
assert_response :success
end
test "should update user" do
put :update, :id => users(:one).to_param, :user => { }
assert_redirected_to user_path(assigns(:user))
end
test "should destroy user" do
assert_difference('User.count', -1) do
delete :destroy, :id => users(:one).to_param
end
assert_redirected_to users_path
end
end
| 21.369565 | 58 | 0.672431 |
5dbd0817399e31906b64546f6125ab59046e6caa | 702 |
Pod::Spec.new do |s|
s.name = 'firstPod'
s.version = '0.1.0'
s.summary = 'This library gives you a blinking label . Subclass of UILabel.'
s.description = 'This CocoaPod provides the ability to use a UILabel that may be started and stopped blinking.'
s.homepage = 'https://github.com/iOSDev-khan/firstPod'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Mushrankhan' => '[email protected]' }
s.source = { :git => 'https://github.com/iOSDev-khan/firstPod.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.source_files = 'firstPod/Classes/**/*'
s.frameworks = 'UIKit'
end
| 46.8 | 118 | 0.598291 |
f732236341cd2b0ec53ef4dd196045a3b28fc6a4 | 604 | class Export < ActiveRecord::Base
belongs_to :user
enum file_type: [:ttl, :nt, :xml]
validates_presence_of :default_namespace
before_destroy :delete_dump_file
def finish!(messages)
self.output = messages
self.success = true
self.finished_at = Time.now
save!
end
def fail!(exception)
self.output = exception.to_s + "\n\n" + exception.backtrace.join("\n")
self.finished_at = Time.now
save!
end
def build_filename
File.join(Iqvoc.export_path, "#{token}.#{file_type}")
end
private
def delete_dump_file
File.delete(build_filename)
end
end
| 18.30303 | 74 | 0.688742 |
62a0818e0b50c31f4cf7e41be7d5f3bfd1e9152f | 996 | # 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.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_10_21_072848) do
create_table "tweets", force: :cascade do |t|
t.text "content"
t.integer "user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.string "password_digest"
end
end
| 36.888889 | 86 | 0.759036 |
18f0e12c5acf2d50275b1ff16819c294be7438b2 | 229 | class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.string :body
t.belongs_to :group
t.belongs_to :customer
t.timestamps
end
end
end
| 19.083333 | 46 | 0.655022 |
5db3833b10be0e8e947fde6941c25d85073cea8d | 127 | require 'test_helper'
class EntrezSynonymTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.875 | 49 | 0.716535 |
61475a9d1e117554d69e16e68d8d73bc49b28e79 | 1,386 | require "spec_helper"
describe ProjectsMailer do
it "should send project, with HTML-safe fields and converting new lines to <br>" do
how_much_you_need = "1000 <javascript>"
days = "12"
category = "art <javascript>"
about = "About the project\n<javascript>"
rewards = "Rewards of the project\n<javascript>"
video = "http://vimeo.com/9090 <javascript>"
twitter = "username <javascript>"
facebook = "FB username <javascript>"
blog = "www.lorem.com <javascript>"
links = "Links of the project\n<javascript>"
know_us_via = "My friends\n<javascript>"
contact = "[email protected]"
user = Factory(:user)
email = ProjectsMailer.start_project_email(how_much_you_need, days, category, about, rewards, video, facebook, twitter, blog, links, know_us_via, contact, user, "#{Configuration[:base_url]}#{user_path(user)}").deliver
ActionMailer::Base.deliveries.should_not be_empty
email_body = email.encoded.gsub(/=\r\n/, '')
email_body.should =~ /1000 <javascript>/
email_body.should =~ /About the project\<br\><javascript>/
email_body.should =~ /Rewards of the project\<br\><javascript>/
email_body.should =~ /Links of the project\<br\><javascript>/
email_body.should =~ /[email protected]/
email[:from].to_s.should == "#{Configuration[:company_name]} <#{Configuration[:email_system]}>"
end
end
| 47.793103 | 221 | 0.692641 |
f819037fac39a1135e6919641bdfed54a531bb27 | 2,457 | require 'test_helper'
class SearchTermsTest < ActiveSupport::TestCase
TEST_CASES = {
'simple' => ['foo', 'foo', {}],
'simple_field' => ['one:two', '', { 'one' => 'two' }],
'quotes' => [%(foo:"quoted value"), '', { 'foo' => 'quoted value' }],
'term_with_period' => ['1.5', '1.5', {}],
'multiple_fields' => ['one:two three:four', '', { 'one' => 'two', 'three' => 'four' }],
'key_with_underscore' => ['under_score:foo', '', { 'under_score' => 'foo' }],
'int_parse' => ['id:123', '', { 'id' => 123 }],
'int_parse_leading_letter' => ['id:a01', '', 'id' => 'a01'],
'int_parse_leading_zero' => ['id:001', '', 'id' => '001'],
'int_parse_date' => ['date:2015-01-01', '', 'date' => '2015-01-01'],
'int_parse_date_with_dots' => ['date:10.01.2015', '', 'date' => '10.01.2015'],
'field_with_lower_than' => ['pages:<100', '', 'pages' => '<100'],
'field_with_greater_than' => ['pages:>100', '', 'pages' => '>100'],
'field_with_lower_than_equals' => ['pages:<=100', '', 'pages' => '<=100'],
'field_with_greater_than_equals' => ['pages:>=100', '', 'pages' => '>=100'],
'field_with_greater_than_equals_with_dots' => ['date:>=10.01.2015', '', 'date' => '>=10.01.2015'],
'field_with_incl_range' => ['pages:[10 TO 100]', '', 'pages' => '[10 TO 100]'],
'multiple_fields_with_incl_range' => ['pages:[10 TO 100] other:[1 TO 10]', '', { 'pages' => '[10 TO 100]', 'other' => '[1 TO 10]' }],
'field_with_excl_range' => ['pages:{10 TO 100}', '', 'pages' => '{10 TO 100}'],
'multiple_fields_with_excl_range' => ['pages:{10 TO 100} other:{1 TO 10}', '', { 'pages' => '{10 TO 100}', 'other' => '{1 TO 10}' }],
'multiple_fields_with_mixed_ranges' => ['pages:[10 TO 100] other:{1 TO 10}', '', { 'pages' => '[10 TO 100]', 'other' => '{1 TO 10}' }],
'mixed_fields_terms' => ['one two:three four five:six', 'one four', { 'two' => 'three', 'five' => 'six' }],
'term_in_quotes' => ['"hello world"', '"hello world"', {}],
'term_with_comma' => ['hello,world', 'hello,world', {}]
}
TEST_CASES.each do |name, (input, query, parts)|
test name do
terms = SearchTerms.new(input)
assert_equal query, terms.query
assert_equal parts, terms.parts
end
end
test 'whitelist' do
terms = SearchTerms.new('hello world test:foo something:bad', ['test'])
assert_equal 'hello world something:bad', terms.query
assert_equal ({ 'test' => 'foo' }), terms.parts
end
end
| 54.6 | 139 | 0.559626 |
28c7524de130e2a2f534817a9e07de1abf1db9ec | 2,077 | # encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
require 'helper'
require 'inspec/resource'
describe 'Inspec::Resources::AptRepo' do
it 'check apt on ubuntu' do
resource = MockLoader.new(:ubuntu1504).load_resource('apt', 'http://archive.ubuntu.com/ubuntu/')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on ubuntu with ppa' do
resource = MockLoader.new(:ubuntu1504).load_resource('apt', 'ubuntu-wine/ppa')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on ubuntu with ppa' do
resource = MockLoader.new(:ubuntu1504).load_resource('apt', 'ppa:ubuntu-wine/ppa')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on mint' do
resource = MockLoader.new(:mint18).load_resource('apt', 'http://archive.ubuntu.com/ubuntu/')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on mint with ppa' do
resource = MockLoader.new(:mint18).load_resource('apt', 'ubuntu-wine/ppa')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on mint with ppa' do
resource = MockLoader.new(:mint18).load_resource('apt', 'ppa:ubuntu-wine/ppa')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on debian' do
resource = MockLoader.new(:debian8).load_resource('apt', 'http://archive.ubuntu.com/ubuntu/')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
it 'check apt on unknown os' do
resource = MockLoader.new(:undefined).load_resource('apt', 'ubuntu-wine/ppa')
_(resource.exists?).must_equal false
_(resource.enabled?).must_equal false
end
# check ppa resource
it 'check apt on ubuntu' do
resource = MockLoader.new(:ubuntu1504).load_resource('ppa', 'ubuntu-wine/ppa')
_(resource.exists?).must_equal true
_(resource.enabled?).must_equal true
end
end
| 31.953846 | 100 | 0.709677 |
7a4356fb18c8df64f18c9e11bc15f6b4aff5c635 | 662 | # encoding: UTF-8
require 'spec_helper'
require 'yt/collections/channels'
describe Yt::Collections::Channels, :device_app, :vcr do
subject(:channels) { Yt::Collections::Channels.new auth: test_account }
context 'with a list of parts' do
let(:part) { 'statistics' }
let(:channel) { channels.where(part: part, id: 'UCZDZGN_73I019o6UYD2-4bg').first }
specify 'load ONLY the specified parts of the channels' do
expect(channel.instance_variable_defined? :@snippet).to be false
expect(channel.instance_variable_defined? :@status).to be false
expect(channel.instance_variable_defined? :@statistics_set).to be true
end
end
end
| 34.842105 | 86 | 0.729607 |
62906624a214969c278e92cae1297be7fc8db319 | 370 | class EnsurePlatformUniqueness < ActiveRecord::Migration
def up
add_index :supported_platforms, [:name, :version_constraint], unique: true
remove_column :supported_platforms, :cookbook_version_id
end
def down
add_column :supported_platforms, :cookbook_version_id, :integer
remove_index :supported_platforms, [:name, :version_constraint]
end
end
| 30.833333 | 78 | 0.783784 |
1cd0e81f8d3e530fc242ab06e94a5ddcc3469960 | 1,005 | #Ruby Filter source for Combine value to One string
#06.08.21 zeraf29
#You can use this by calling on Logstash ruby filter
#example call ruby filter on logstash
#filter {
# ruby {
# path => "/etc/logstash/drop_percentage.rb"
# script_params => {
# "max_run" => 10
# "target_event" => "target_event" #logstash event field name what you want to combine
# }
# }
# }
def register(params)
#total event count(how many event values to one string
@maxRun = params["max_run"]
@targetEvent = params["target_event"]
@combinedString = ''
@runCount = 0 #check now running count
end
def filter(event)
if !event.get(@targetEvent).nil? && event.get(@targetEvent)!=''
@combinedString += (@combinedString != '' ? ',' : '') + event.get(@targetEvent)
end
@runCount += 1
if @maxRun == @runCount
event.set('combined_string', @combinedString)
end
@runCount = 0
@combinedString = ''
return [event]
end
| 27.916667 | 96 | 0.618905 |
399aa94d1ac84f33478ef2674bc5b7ce31ec5762 | 2,771 | Rails.application.routes.draw do
root 'items#index'
defaults format: 'json' do
get 'health', to: 'health#index'
end
# Omniauth automatically handles requests to /auth/:provider. We need only
# implement the callback.
get '/login', to: 'sessions#new', as: :login
get '/logout', to: 'sessions#destroy', as: :logout
get '/auth/:provider/callback', to: 'sessions#callback', as: :omniauth_callback
get '/auth/failure', to: 'sessions#failure'
defaults format: 'csv' do
get '/stats/lending(/:date)', to: 'stats#download', as: :stats_download
# TODO: don't include this in production
get '/stats/all_loan_dates', to: 'stats#all_loan_dates', as: :stats_all_loan_dates
end
resources :items, only: :index # index supports both HTML and JSON
resources :items, except: :index, defaults: { format: 'json' }, constraints: ->(req) { req.format == :json }
resources :terms, only: :index, defaults: { format: 'json' }, constraints: ->(req) { req.format == :json }
# Shared constraints
valid_dirname = { directory: Lending::PathUtils::DIRNAME_RAW_RE }
defaults format: 'html' do
# TODO: don't include this in production
get '/stats', to: 'stats#index', as: :stats
get '/profile_stats', to: 'stats#profile_index', as: :stats_profile
# TODO: don't include this in production
get '/profile_index', to: 'lending#profile_index', as: :lending_profile_index
get '/index', to: 'lending#index', as: :index
get '/:directory/edit', to: 'lending#edit', as: :lending_edit, constraints: valid_dirname
get '/:directory', to: 'lending#show', as: :lending_show, constraints: valid_dirname
get '/:directory/view(/:token)', to: 'lending#view', as: :lending_view, constraints: valid_dirname.merge({ token: %r{[^/]+} })
patch '/:directory', to: 'lending#update', as: :lending_update, constraints: valid_dirname
delete '/:directory', to: 'lending#destroy', as: :lending_destroy, constraints: valid_dirname
# TODO: something more RESTful
get '/:directory/checkout', to: 'lending#check_out', as: :lending_check_out, constraints: valid_dirname
get '/:directory/return', to: 'lending#return', as: :lending_return, constraints: valid_dirname
get '/:directory/activate', to: 'lending#activate', as: :lending_activate, constraints: valid_dirname
get '/:directory/deactivate', to: 'lending#deactivate', as: :lending_deactivate, constraints: valid_dirname
get '/:directory/reload', to: 'lending#reload', as: :lending_reload, constraints: valid_dirname
end
# TODO: get Rails to use :directory as the primary key and this all gets a lot simpler
defaults format: 'json' do
get '/:directory/manifest', to: 'lending#manifest', as: :lending_manifest, constraints: valid_dirname
end
end
| 48.614035 | 130 | 0.699747 |
6ab211d1995a0a0ebb7c12aeda770eeddf130e87 | 250 | class CreateConquestWarriorSpecialties < ActiveRecord::Migration[5.1]
def change
create_table :conquest_warrior_specialties do |t|
t.integer :warrior_id
t.integer :type_id
t.integer :slot
t.timestamps
end
end
end
| 20.833333 | 69 | 0.708 |
62cb93fe1ab5b9669ad7dc955bfdf05b719ffe41 | 64 | json.partial! "individuals/individual", individual: @individual
| 32 | 63 | 0.8125 |
872dd263499f02762c47b4622342670ebc7739d0 | 3,196 | # frozen_string_literal: true
RSpec.describe PriceHubble::ValuationRequest do
let(:instance) { build(:valuation_request) }
before { Timecop.freeze(2019, 10, 16, 12, 0, 0) }
after { Timecop.return }
describe 'attributes' do
context 'without sanitization' do
let(:expected) do
{
'deal_type' => :sale,
'valuation_dates' => [Date.current],
'properties' => [build(:property).attributes],
'return_scores' => false,
'country_code' => 'DE'
}
end
it 'serializes the correct data' do
expect(instance.attributes).to be_eql(expected)
end
end
context 'with sanitization' do
let(:expected) do
{
'deal_type' => :sale,
'valuation_dates' => ['2019-10-16'],
'valuation_inputs' => [
{ property: build(:property).attributes(true) }
],
'return_scores' => false,
'country_code' => 'DE'
}
end
it 'serializes the correct data' do
expect(instance.attributes(true)).to be_eql(expected)
end
end
describe 'mass assignment' do
context 'with single property instance' do
let(:instance) { described_class.new(property: build(:property)) }
it 'assigns the correct data' do
expect(instance.properties.first.location.address.street).to \
be_eql('Stresemannstr.')
end
end
context 'with single property attributes' do
let(:instance) do
described_class.new(property: attributes_for(:property))
end
it 'assigns the correct data' do
expect(instance.properties.first.location.address.street).to \
be_eql('Stresemannstr.')
end
end
context 'with multiple property instances' do
let(:instance) do
described_class.new(properties: [build(:property), build(:property)])
end
it 'assigns the correct data' do
expect(instance.properties.count).to be_eql(2)
end
end
context 'with multiple property attribute sets' do
let(:instance) do
described_class.new(properties: [attributes_for(:property),
attributes_for(:property)])
end
it 'assigns the correct data' do
expect(instance.properties.count).to be_eql(2)
end
end
end
end
describe '#perform!' do
let(:action) { instance.perform! }
context 'with valid data', vcr: cassette(:valuation_request) do
it 'returns an array of PriceHubble::Valuation' do
expect(action).to all(be_a(PriceHubble::Valuation))
end
end
context 'with invalid data', vcr: cassette(:valuation_request_bad) do
let(:invalid_property) { build(:property, building_year: 2999) }
let(:instance) do
build(:valuation_request, properties: [invalid_property])
end
it 'raises a PriceHubble::EntityInvalid error' do
expect { action }.to \
raise_error(PriceHubble::EntityInvalid,
/buildingYear: Must be between 1850 and 2022/)
end
end
end
end
| 28.535714 | 79 | 0.597309 |
6aeabd3da847cd860dde1d0262cf57a478b747fb | 196 | Rails.application.routes.draw do
get 'health_check', to: 'health_check#index'
root 'health_check#index'
post 'dns_records', to: 'records#create'
get 'dns_records', to: 'records#index'
end
| 28 | 46 | 0.734694 |
1dba7aa9b12a19875636a1b4857f8180677f02a1 | 2,524 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'rex'
require 'rexml/document'
class Metasploit3 < Msf::Post
include Msf::Post::Windows::UserProfiles
def initialize(info={})
super( update_info( info,
'Name' => 'Windows Gather FTP Explorer (FTPX) Credential Extraction',
'Description' => %q{
This module finds saved login credentials for the FTP Explorer (FTPx)
FTP client for Windows.
},
'License' => MSF_LICENSE,
'Author' => [ 'Brendan Coles <bcoles[at]gmail.com>' ],
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ]
))
end
def run
grab_user_profiles().each do |user|
next if user['AppData'].nil?
xml = get_xml(user['AppData'] + "\\FTP Explorer\\profiles.xml")
unless xml.nil?
parse_xml(xml)
end
end
end
def get_xml(path)
begin
connections = client.fs.file.new(path, 'r')
condata = ''
until connections.eof
condata << connections.read
end
return condata
rescue Rex::Post::Meterpreter::RequestError => e
print_error "Error when reading #{path} (#{e.message})"
return nil
end
end
# Extracts the saved connection data from the XML.
# Reports the credentials back to the database.
def parse_xml(data)
mxml = REXML::Document.new(data).root
mxml.elements.to_a("//FTPx10//Profiles//").each.each do |node|
next if node.elements['Host'].nil?
next if node.elements['Login'].nil?
next if node.elements['Password'].nil?
host = node.elements['Host'].text
port = node.elements['Port'].text
user = node.elements['Login'].text
pass = node.elements['Password'].text
# skip blank passwords
next if !pass or pass.empty?
# show results to the user
print_good("#{session.sock.peerhost}:#{port} (#{host}) - '#{user}:#{pass}'")
# save results to the db
if session.db_record
source_id = session.db_record.id
else
source_id = nil
end
report_auth_info(
:host => host,
:port => port,
:source_id => source_id,
:source_type => "exploit",
:user => user,
:pass => pass
)
end
end
end
| 26.851064 | 84 | 0.597861 |
bb5d5575932d6f298278bf053923644c824568e6 | 1,181 | # these tests are a little concerning b/c they are hacking around the
# modulepath, so these tests will not catch issues that may eventually arise
# related to loading these plugins.
# I could not, for the life of me, figure out how to programatcally set the modulepath
$LOAD_PATH.push(
File.join(
File.dirname(__FILE__),
'..',
'..',
'..',
'fixtures',
'modules',
'inifile',
'lib')
)
require 'spec_helper'
provider_class = Puppet::Type.type(:contrail_vnc_api_config).provider(:ini_setting)
describe provider_class do
it 'should default to the default setting when no other one is specified' do
resource = Puppet::Type::Contrail_vnc_api_config.new(
{:name => 'DEFAULT/foo', :value => 'bar'}
)
provider = provider_class.new(resource)
expect(provider.section).to eq('DEFAULT')
expect(provider.setting).to eq('foo')
end
it 'should allow setting to be set explicitly' do
resource = Puppet::Type::Contrail_vnc_api_config.new(
{:name => 'dude/foo', :value => 'bar'}
)
provider = provider_class.new(resource)
expect(provider.section).to eq('dude')
expect(provider.setting).to eq('foo')
end
end
| 31.078947 | 86 | 0.685859 |
e22d14bdc397b27e3bd309d8d36cdf8f1290673f | 1,157 | require 'faraday'
require 'oga'
require 'logger'
module Iibee
class Broker
CONTEXT_PATH = "/apiv1/properties/"
attr_reader :AdminSecurity, :version, :name, :runMode, :shortDesc, :longDesc,
:platformName, :FixpackCapability, :platformArchitecture, :platformVersion, :operationMode, :buildLevel, :AdminAgentPID, :queueManager
def initialize(document)
document.xpath('properties/basicProperties/property').each do |basicProperty|
propertyName = basicProperty.get('name')
propertyValue = basicProperty.get('value')
instance_variable_set("@#{propertyName}", propertyValue)
end
document.xpath('properties/advancedProperties/property').each do |advancedProperty|
propertyName = advancedProperty.get('name')
propertyValue = advancedProperty.get('value')
instance_variable_set("@#{propertyName}", propertyValue)
end
end
def self.find_by(options: {})
response = Iibee::Connection.new(options: options).get(CONTEXT_PATH)
document = Oga.parse_xml(response.body)
new(document)
end
end
end
| 31.27027 | 139 | 0.675022 |
e95725c29120de159ed709b752b56b2fd64c5d10 | 155 | require 'spec_helper'
RSpec.describe ActiveRecordUpsert do
it 'has a version number' do
expect(ActiveRecordUpsert::VERSION).not_to be nil
end
end
| 19.375 | 53 | 0.774194 |
08e71fe95754fb4c2b2045547ddce0952d23d107 | 1,560 | require 'mongoid/cenit_extension'
module Setup
module CenitUnscoped
extend ActiveSupport::Concern
include Mongoid::CenitDocument
include Mongoid::Timestamps
include Mongoid::CenitExtension
include DateTimeCharts
included do
Setup::Models.regist(self)
end
def copy_hash
share_hash(self.class.copy_options)
end
module ClassMethods
def inherited(subclass)
super
Setup::Models.regist(subclass)
subclass.deny Setup::Models.excluded_actions_for(self)
subclass.build_in_data_type.excluding(build_in_data_type.get_excluding)
subclass.build_in_data_type.embedding(build_in_data_type.get_embedding)
subclass.build_in_data_type.and(build_in_data_type.get_to_merge)
end
def share_options
{
ignore: [:id],
include_blanks: true,
protected: true,
polymorphic: true
}
end
def copy_options
share_options
end
def super_count
count
end
def build_in_data_type
BuildInDataType.regist(self)
end
def allow(*actions)
Setup::Models.included_actions_for self, *actions
end
def deny(*actions)
Setup::Models.excluded_actions_for self, *actions
end
def mongoid_root_class
@mongoid_root_class ||=
begin
root = self
root = root.superclass while root.superclass.include?(Mongoid::Document)
root
end
end
end
end
end
| 21.971831 | 84 | 0.639744 |
e8ceabaeba86398b40a1de8d0c577c7153ab8862 | 4,697 | module ActiveJob
# == Active Job adapters
#
# Active Job has adapters for the following queueing backends:
#
# * {Backburner}[https://github.com/nesquena/backburner]
# * {Delayed Job}[https://github.com/collectiveidea/delayed_job]
# * {Qu}[https://github.com/bkeepers/qu]
# * {Que}[https://github.com/chanks/que]
# * {queue_classic}[https://github.com/QueueClassic/queue_classic]
# * {Resque 1.x}[https://github.com/resque/resque/tree/1-x-stable]
# * {Sidekiq}[http://sidekiq.org]
# * {Sneakers}[https://github.com/jondot/sneakers]
# * {Sucker Punch}[https://github.com/brandonhilkert/sucker_punch]
#
# === Backends Features
#
# | | Async | Queues | Delayed | Priorities | Timeout | Retries |
# |-------------------|-------|--------|------------|------------|---------|---------|
# | Backburner | Yes | Yes | Yes | Yes | Job | Global |
# | Delayed Job | Yes | Yes | Yes | Job | Global | Global |
# | Qu | Yes | Yes | No | No | No | Global |
# | Que | Yes | Yes | Yes | Job | No | Job |
# | queue_classic | Yes | Yes | Yes* | No | No | No |
# | Resque | Yes | Yes | Yes (Gem) | Queue | Global | Yes |
# | Sidekiq | Yes | Yes | Yes | Queue | No | Job |
# | Sneakers | Yes | Yes | No | Queue | Queue | No |
# | Sucker Punch | Yes | Yes | No | No | No | No |
# | Active Job Inline | No | Yes | N/A | N/A | N/A | N/A |
#
# ==== Async
#
# Yes: The Queue Adapter runs the jobs in a separate or forked process.
#
# No: The job is run in the same process.
#
# ==== Queues
#
# Yes: Jobs may set which queue they are run in with queue_as or by using the set
# method.
#
# ==== Delayed
#
# Yes: The adapter will run the job in the future through perform_later.
#
# (Gem): An additional gem is required to use perform_later with this adapter.
#
# No: The adapter will run jobs at the next opportunity and cannot use perform_later.
#
# N/A: The adapter does not support queueing.
#
# NOTE:
# queue_classic supports job scheduling since version 3.1.
# For older versions you can use the queue_classic-later gem.
#
# ==== Priorities
#
# The order in which jobs are processed can be configured differently depending
# on the adapter.
#
# Job: Any class inheriting from the adapter may set the priority on the job
# object relative to other jobs.
#
# Queue: The adapter can set the priority for job queues, when setting a queue
# with Active Job this will be respected.
#
# Yes: Allows the priority to be set on the job object, at the queue level or
# as default configuration option.
#
# No: Does not allow the priority of jobs to be configured.
#
# N/A: The adapter does not support queueing, and therefore sorting them.
#
# ==== Timeout
#
# When a job will stop after the allotted time.
#
# Job: The timeout can be set for each instance of the job class.
#
# Queue: The timeout is set for all jobs on the queue.
#
# Global: The adapter is configured that all jobs have a maximum run time.
#
# N/A: This adapter does not run in a separate process, and therefore timeout
# is unsupported.
#
# ==== Retries
#
# Job: The number of retries can be set per instance of the job class.
#
# Yes: The Number of retries can be configured globally, for each instance or
# on the queue. This adapter may also present failed instances of the job class
# that can be restarted.
#
# Global: The adapter has a global number of retries.
#
# N/A: The adapter does not run in a separate process, and therefore doesn't
# support retries.
module QueueAdapters
extend ActiveSupport::Autoload
autoload :InlineAdapter
autoload :BackburnerAdapter
autoload :DelayedJobAdapter
autoload :QuAdapter
autoload :QueAdapter
autoload :QueueClassicAdapter
autoload :ResqueAdapter
autoload :SidekiqAdapter
autoload :SneakersAdapter
autoload :SuckerPunchAdapter
autoload :TestAdapter
ADAPTER = 'Adapter'.freeze
private_constant :ADAPTER
class << self
# Returns adapter for specified name.
#
# ActiveJob::QueueAdapters.lookup(:sidekiq)
# # => ActiveJob::QueueAdapters::SidekiqAdapter
def lookup(name)
const_get(name.to_s.camelize << ADAPTER)
end
end
end
end
| 36.695313 | 90 | 0.592932 |
4ab6ba32b9f49e012a621c62d0a26d175795c124 | 1,935 | require 'rails_helper'
# So specs will run and not throw scary errors before SessionsController is implemented
begin
SessionsController
rescue
SessionsController = nil
end
RSpec.describe SessionsController, :type => :controller do
let!(:user) { User.create({username: "jack_bruce", password: "abcdef"}) }
describe "GET #new" do
it "renders the new session template" do
get :new
expect(response).to render_template("new")
end
end
describe "POST #create" do
context "with invalid credentials" do
it "returns to sign in with an non-existent user" do
post :create, user: {username: "jill_bruce", password: "abcdef"}
expect(response).to render_template("new")
expect(flash[:errors]).to be_present
end
it "returns to sign in on bad password" do
post :create, user: {username: "jack_bruce", password: "notmypassword"}
expect(response).to render_template("new")
expect(flash[:errors]).to be_present
end
end
context "with valid credentials" do
it "redirects user to links index on success" do
post :create, user: {username: "jack_bruce", password: "abcdef"}
expect(response).to redirect_to(links_url)
end
it "logs in the user" do
post :create, user: {username: "jack_bruce", password: "abcdef"}
user = User.find_by_username("jack_bruce")
expect(session[:session_token]).to eq(user.session_token)
end
end
end
describe "DELETE #destroy" do
before(:each) do
post :create, user: {username: "jack_bruce", password: "abcdef"}
@session_token = User.find_by_username("jack_bruce").session_token
end
it "logs out the current user" do
delete :destroy
expect(session[:session_token]).to be_nil
jack = User.find_by_username("jack_bruce")
expect(jack.session_token).not_to eq(@session_token)
end
end
end
| 29.769231 | 87 | 0.669767 |
f8d84bd5e8617b20827bf9981b00f5be0fcbd4cf | 1,453 | desc 'Install project into INSTALL_DIR'
task :install => %i(compile
install:pre
install:main
install:post)
namespace :install do
task :pre
task :post
task :main
end
desc 'Create build artifacts, e.g., deployable archives & packages'
task :artifacts => %i(install
artifacts:pre
artifacts:main
artifacts:post)
namespace :'artifacts' do
task :pre
task :post
task :main => :setup do
(zip ARTIFACTS_DIR / BUILD_NAME, remove: true) if File.exist? ARTIFACTS_DIR / BUILD_NAME
end
task :'prebuilt-stc' do
archive = ARTIFACTS_DIR / "#{project.app_name}-#{project.app_version}_#{BUILD_TARGET}_prebuilt-stc.zip"
mkdir_p ARTIFACTS_DIR
zip BUILD_DIR / 'stx' / 'stc' , archive: archive, include: STC_BINARY_FILES
end
task :'prebuilt-librun' do
archive = ARTIFACTS_DIR / "#{project.app_name}-#{project.app_version}_#{BUILD_TARGET}_prebuilt-librun.zip"
mkdir_p ARTIFACTS_DIR
zip BUILD_DIR / 'stx' / 'librun' , archive: archive, include: LIBRUN_BINARY_FILES
end
desc 'Create source archive'
task :'source' => :checkout do
archive = ARTIFACTS_DIR / "#{project.app_name}-#{project.app_version}_sources.tar.gz"
mkdir_p ARTIFACTS_DIR
zip ".", archive: archive, exclude: %w(CVS .svn .git .hg *.obj *.o *.dll *.so *.debug *.H *.STH *Init.c *-Test.xml artifacts tmp)
end
end
| 31.586957 | 133 | 0.646249 |
62c9153f5750623fbcdac06ee61b55377421eb03 | 117 | class Material < ApplicationRecord
has_many :compositions
has_many :restored_objects, through: :compositions
end
| 23.4 | 52 | 0.820513 |
1acc000e03c5c4475c91013b8af7d6a353219d2d | 1,410 | Pod::Spec.new do |s|
s.name = "OptimizelySDKShared"
s.version = "1.3.1"
s.summary = "Optimizely server-side testing shared framework."
s.homepage = "http://developers.optimizely.com/server/reference/index.html?language=objectivec"
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" }
s.author = { "Optimizely" => "[email protected]" }
s.platform = :ios, '10.1', :tvos, '10.0'
s.ios.deployment_target = "8.0"
s.tvos.deployment_target = "9.0"
s.source = {
:git => "https://github.com/loyal-tingley-zocdoc/optimizely-sdk.git",
:tag => s.version.to_s
}
s.source_files = "OptimizelySDKShared/OptimizelySDKShared/*.{h,m}"
s.tvos.exclude_files = "OptimizelySDKShared/OptimizelySDKShared/OPTLYDatabase.{h,m}",\
"OptimizelySDKShared/OptimizelySDKShared/OPTLYDatabaseEntity.{h,m}"
s.public_header_files = "OptimizelySDKShared/OptimizelySDKShared/*.h"
s.framework = "Foundation"
s.requires_arc = true
s.xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => "OPTIMIZELY_SDK_SHARED_VERSION=@\\\"#{s.version}\\\"" }
s.dependency 'JSONModel', '1.3.0'
s.dependency 'OptimizelySDKCore', '~> 1.3.0'
s.ios.dependency 'FMDB', '2.6.2'
end
| 54.230769 | 121 | 0.589362 |
337e71e49ac2b2a0b2d2a4f6fc8609024de2c7fd | 1,742 | class FbiServefiles < Formula
include Language::Python::Virtualenv
desc "Serve local files to Nintendo 3DS via FBI remote installer"
homepage "https://github.com/Steveice10/FBI"
url "https://github.com/Steveice10/FBI/archive/2.6.0.tar.gz"
sha256 "4948d4c53d754cc411b51edbf35c609ba514ae21d9d0e8f4b66a26d5c666be68"
license "MIT"
revision OS.mac? ? 2 : 3
bottle do
cellar :any_skip_relocation
sha256 "9383ebc1948e403d7fef0e0613063cb1febb62e5b8142c3fe7ab62bf3f3d5c1d" => :catalina
sha256 "4055c03cc79761271cf0ea70be2f54250fa5b67db91f030f4ac9449e0a2f7307" => :mojave
sha256 "d8d8d483abd92d016d8d1a7f0e4535c51233c83914f1c61d1223b72d750f1b8a" => :high_sierra
sha256 "5fe5372bcb379d644427261a91a9efbe76394a9cd41c09b0db00eec2213a3cb1" => :x86_64_linux
end
depends_on "[email protected]"
def install
venv = virtualenv_create(libexec, Formula["[email protected]"].opt_bin/"python3")
venv.pip_install_and_link buildpath/"servefiles"
end
test do
require "socket"
def test_socket
server = TCPServer.new(5000)
client = server.accept
client.puts "\n"
client_response = client.gets
client.close
server.close
client_response
end
begin
pid = fork do
system "#{bin}/sendurls.py", "127.0.0.1", "https://github.com"
end
assert_match "https://github.com", test_socket
ensure
Process.kill("TERM", pid)
Process.wait(pid)
end
begin
touch "test.cia"
pid = fork do
system "#{bin}/servefiles.py", "127.0.0.1", "test.cia", "127.0.0.1", "8080"
end
assert_match "127.0.0.1:8080/test.cia", test_socket
ensure
Process.kill("TERM", pid)
Process.wait(pid)
end
end
end
| 28.557377 | 94 | 0.695178 |
b952648ffdb58073593477ba400b81819d03d47c | 3,431 | Rails.application.configure do
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = false
# Settings specified here will take precedence over those in config/application.rb.
# 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 JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.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
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# 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 = "rails_app_#{Rails.env}"
# 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
# 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
end
| 41.337349 | 102 | 0.76042 |
e9271bc32f51022889ae966acd4b1831241656d8 | 2,944 | # 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: 20170527224245) do
create_table "assignments", force: :cascade do |t|
t.string "title"
t.text "statement"
t.integer "course_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "start_date"
t.date "end_date"
t.index ["course_id"], name: "index_assignments_on_course_id"
end
create_table "courses", force: :cascade do |t|
t.string "title"
t.string "code"
t.integer "person_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "quota"
t.index ["person_id"], name: "index_courses_on_person_id"
end
create_table "enrollments", force: :cascade do |t|
t.integer "person_id"
t.integer "course_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["course_id"], name: "index_enrollments_on_course_id"
t.index ["person_id"], name: "index_enrollments_on_person_id"
end
create_table "grades", force: :cascade do |t|
t.float "value"
t.integer "person_id"
t.integer "assignment_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["assignment_id"], name: "index_grades_on_assignment_id"
t.index ["person_id"], name: "index_grades_on_person_id"
end
create_table "people", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "is_professor"
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.index ["email"], name: "index_people_on_email", unique: true
t.index ["reset_password_token"], name: "index_people_on_reset_password_token", unique: true
end
end
| 38.736842 | 96 | 0.692595 |
fff894a1b97b8e74115b54564e5753a8a7bf4e2c | 1,320 | require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@user = users(:example)
@admin = users(:example)
@non_admin = users(:archer)
end
test "index including pagination" do
log_in_as(@user)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
User.paginate(page: 1).each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name if user.activated
end
end
test "index as admin including pagination and delete links" do
log_in_as(@admin)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
first_page_of_users = User.paginate(page: 1)
first_page_of_users.each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name if user.activated
unless user == @admin
assert_select 'a[href=?]', user_path(user), text: 'delete' if user.activated
end
end
assert_difference 'User.count', -1 do
delete user_path(@non_admin)
end
end
test "index as non-admin" do
log_in_as(@non_admin)
get users_path
assert_select 'a', text: 'delete', count: 0
end
test 'not showing unactivated users' do
log_in_as(@user)
get user_path(users(:rose))
assert_redirected_to root_path
end
end
| 26.938776 | 84 | 0.683333 |
ed6c4989dcf8f46a9204a86ee92b8982f55609b0 | 517 | require "forwardable"
require "singleton"
module HTTP
module MimeType
# Base encode/decode MIME type adapter
class Adapter
include Singleton
class << self
extend Forwardable
def_delegators :instance, :encode, :decode
end
%w(encode decode).each do |operation|
class_eval <<-RUBY, __FILE__, __LINE__
def #{operation}(*)
fail Error, "\#{self.class} does not supports ##{operation}"
end
RUBY
end
end
end
end
| 20.68 | 72 | 0.601547 |
21d58a474f8c556c25bdd08ed861f6463c7f54dd | 1,551 | #
# Copyright 2012 Wade Alcorn [email protected]
#
# 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.
#
class Coldfusion_dir_traversal_exploit < BeEF::Core::Command
def self.options
return [
{'name' => 'fileToRetrieve', 'ui_label' => 'Retrieve file (in CF /lib dir)', 'value' => 'password.properties'},
{ 'name' => 'os_combobox', 'type' => 'combobox', 'ui_label' => 'CF server OS', 'store_type' => 'arraystore',
'store_fields' => ['os'], 'store_data' => [['Windows'],['Linux/MacOSX/*BSD']],
'valueField' => 'os', 'displayField' => 'os', 'mode' => 'local', 'autoWidth' => true
},
{ 'name' => 'cf_version', 'type' => 'combobox', 'ui_label' => 'ColdFusion version', 'store_type' => 'arraystore',
'store_fields' => ['cf_version'], 'store_data' => [['8'],['9']],
'valueField' => 'cf_version', 'displayField' => 'cf_version', 'mode' => 'local', 'autoWidth' => true
}
]
end
def post_execute
save({'result' => @datastore['result']})
end
end
| 41.918919 | 121 | 0.627982 |
9147a293968a553edec6b4cde9455b3c37bcd33c | 2,255 | Portfolio::Application.routes.draw do
root 'projects#index'
resources :blogs do
collection do
post 'markdown'
end
end
resources :projects do
collection do
post 'markdown'
end
end
get 'manage', to: 'manages#index'
get 'manage/projects', to: 'projects#manage'
get 'manage/blogs', to: 'blogs#manage'
get 'manage/about_me', to: 'about_me#edit'
post 'manage/about_me', to: 'about_me#edit', as: 'edit_about_me'
get 'manage/rspec', to: 'manages#rspec'
get 'about_me', to: 'about_me#index'
get 'projects', to: 'projects#index'
get 'contact_me', to: 'contact_me#send_contact'
post 'send_contact', to: 'contact_me#send_contact'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| 25.91954 | 84 | 0.651885 |
622d95c7052d881116b3639946c2c80e009de776 | 2,694 | # frozen_string_literal: true
module IncidentManagement
module OncallRotations
class EditService < OncallRotations::BaseService
include IncidentManagement::OncallRotations::SharedRotationLogic
# @param rotation [IncidentManagement::OncallRotation]
# @param user [User]
# @param params [Hash<Symbol,Any>]
# @param params - name [String] The name of the on-call rotation.
# @param params - length [Integer] The length of the rotation.
# @param params - length_unit [String] The unit of the rotation length. (One of 'hours', days', 'weeks')
# @param params - starts_at [DateTime] The datetime the rotation starts on.
# @param params - ends_at [DateTime] The datetime the rotation ends on.
# @param params - participants [Array<hash>] An array of hashes defining participants of the on-call rotations.
# @option opts - user [User] The user who is part of the rotation
# @option opts - color_palette [String] The color palette to assign to the on-call user, for example: "blue".
# @option opts - color_weight [String] The color weight to assign to for the on-call user, for example "500". Max 4 chars.
def initialize(oncall_rotation, user, params)
@oncall_rotation = oncall_rotation
@user = user
@project = oncall_rotation.project
@params = params
@participants_params = params.delete(:participants)
end
def execute
return error_no_license unless available?
return error_no_permissions unless allowed?
if participants_params
return error_too_many_participants if participants_params.size > MAXIMUM_PARTICIPANTS
return error_duplicate_participants if duplicated_users?
return error_participants_without_permission if users_without_permissions?
end
# Ensure shift history is up to date before saving new params
IncidentManagement::OncallRotations::PersistShiftsJob.new.perform(oncall_rotation.id)
OncallRotation.transaction do
oncall_rotation.update!(params)
save_participants!
save_current_shift!
success(oncall_rotation.reset)
end
rescue ActiveRecord::RecordInvalid => err
error_in_validation(err.record)
end
private
attr_reader :oncall_rotation, :user, :project, :params, :participants_params
def save_participants!
return if participants_params.nil?
super
oncall_rotation.touch
end
def error_no_permissions
error('You have insufficient permissions to edit an on-call rotation in this project')
end
end
end
end
| 37.943662 | 129 | 0.694135 |
e93cdb007b36718b352c66dee61461aaedf4d5f7 | 711 | Pod::Spec.new do |s|
s.name = 'AWSConnect'
s.version = '2.12.6'
s.summary = 'Amazon Web Services SDK for iOS.'
s.description = 'The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected mobile applications using AWS.'
s.homepage = 'http://aws.amazon.com/mobile/sdk'
s.license = 'Apache License, Version 2.0'
s.author = { 'Amazon Web Services' => 'amazonwebservices' }
s.platform = :ios, '8.0'
s.source = { :git => 'https://github.com/aws/aws-sdk-ios.git',
:tag => s.version}
s.requires_arc = true
s.dependency 'AWSCore', '2.12.6'
s.source_files = 'AWSConnect/*.{h,m}'
end
| 39.5 | 157 | 0.611814 |
4a8b43872596502369984e9b3dba18fdd3952382 | 3,236 | require "topological_inventory/ansible_tower/operations/service_plan"
RSpec.describe TopologicalInventory::AnsibleTower::Operations::ServicePlan do
context "#order" do
let(:subject) { described_class.new(params, identity) }
let(:identity) { {"account_number" => "12345" } }
let(:service_plan) do
TopologicalInventoryApiClient::ServicePlan.new(
:id => "1", :source_id => "1", :source_ref => "2", :service_offering_id => "1", :name => "My Job Template"
)
end
let(:service_offering) do
TopologicalInventoryApiClient::ServiceOffering.new(
:id => "1", :source_id => "1", :source_ref => "2", :name => "My Job Template", :extra => {:type => "job_template"}
)
end
let(:params) do
{
"order_params" => {
"service_plan_id" => 1,
"service_parameters" => {
:name => "Job 1",
:param1 => "Test Topology",
:param2 => 50
},
"provider_control_parameters" => {}
},
"service_plan_id" => 1,
"task_id" => 1
}
end
let(:ansible_tower_client) { TopologicalInventory::AnsibleTower::Operations::Core::AnsibleTowerClient.new('1', params['task_id']) }
it "orders the service plan" do
expect(subject).to receive(:update_task).with(1, :state => "running", :status => "ok")
topology_api_client = double
allow(subject).to receive(:topology_api_client).and_return(topology_api_client)
expect(topology_api_client).to receive(:show_service_plan).with("1")
.and_return(service_plan)
expect(topology_api_client).to receive(:show_service_offering).with("1")
.and_return(service_offering)
expect(subject).to receive(:ansible_tower_client)
.with(service_offering.source_id, params["task_id"], identity)
.and_return(ansible_tower_client)
job = double
allow(job).to receive(:id).and_return(42)
allow(job).to receive(:status).and_return('successful')
allow(ansible_tower_client).to receive(:job_external_url).and_return('https://tower.example.com/job/1')
expect(ansible_tower_client).to receive(:order_service)
.with(service_offering.extra.dig(:type), service_offering.source_ref, params["order_params"])
.and_return(job)
expect(subject).to receive(:update_task)
.with(1,
:context => {
:service_instance => {
:job_status => 'successful',
:url => 'https://tower.example.com/job/1'
}
},
:state => "running",
:status => ansible_tower_client.job_status_to_task_status(job.status),
:source_id => '1',
:target_source_ref => job.id.to_s,
:target_type => 'ServiceInstance'
)
subject.order
end
end
end
| 43.146667 | 135 | 0.541409 |
7aff5ed1b6d20a0415ae765f4c5a4cc58d797266 | 2,914 | require 'rex/parser/winscp'
INI_SECURITY = "[Configuration\\Security]\nUseMasterPassword=1\nMasterPasswordVerifier=\n"
USERNAME = 'username'
HOST = 'server.feralhosting.com'
PASSWORD='A35C7659654B2AB83C292F392E323D31392F392E2A392E723A392E3D3034332F2835323B723F33312F383A2F383A3B2F3B3B3B'
SAMPLE_INI = <<-END
[Sessions\\[email protected]]
HostName=#{HOST}
Timeout=6000
SshProt=3
UserName=#{USERNAME}
UpdateDirectories=0
Utf=1
Password=#{PASSWORD}
Shell=/bin/bash}
END
RSpec.describe Rex::Parser::WinSCP do
let(:target) do
d = Class.new { include Rex::Parser::WinSCP }
d.new
end
context "#parse_protocol" do
it "returns 'Unknown' for unknown protocols" do
expect(target.parse_protocol(nil)).to eq('Unknown')
expect(target.parse_protocol(99)).to eq('Unknown')
expect(target.parse_protocol('stuff')).to eq('Unknown')
end
it "returns 'SSH' for protocol 0" do
expect(target.parse_protocol(0)).to eq('SSH')
end
it "returns 'FTP' for protocol 5" do
expect(target.parse_protocol(5)).to eq('FTP')
end
end
context "#decrypt_next_char" do
it "returns 0 and the pwd if pwd length <= 0" do
r, pwd = target.decrypt_next_char('')
expect(r).to eq(0)
expect(pwd).to eq('')
end
it "strips the first two characters from the return value" do
_, pwd = target.decrypt_next_char('A3')
expect(pwd).to eq('')
end
it "returns 255 for 'A3'" do
r, _ = target.decrypt_next_char('A3')
expect(r).to eq(Rex::Parser::WinSCP::PWDALG_SIMPLE_FLAG)
end
end
context "#decrypt_password" do
it "returns 'sdfsdfgsggg' for the example password" do
expect(target.decrypt_password(PASSWORD, "#{USERNAME}#{HOST}")).to eq('sdfsdfgsggg')
end
end
context "#parse_ini" do
it "raises a RuntimeError if ini is nil or empty" do
expect { target.parse_ini('') }.to raise_error(RuntimeError, /No data/i)
expect { target.parse_ini(nil) }.to raise_error(RuntimeError, /No data/i)
end
it "raises a RuntimeError if UseMasterPassword is 1" do
expect { target.parse_ini(INI_SECURITY) }.to raise_error(RuntimeError, /Master/i)
end
it "parses the example ini" do
r = target.parse_ini(SAMPLE_INI).first
expect(r[:hostname]).to eq(HOST)
expect(r[:password]).to eq('sdfsdfgsggg')
expect(r[:username]).to eq(USERNAME)
expect(r[:protocol]).to eq('SSH')
expect(r[:portnumber]).to eq(22)
end
end
context "#read_and_parse_ini" do
it "returns nil if file is empty or doesn't exist" do
expect(File).to receive(:read).and_return(nil)
expect(target.read_and_parse_ini('blah')).to be nil
end
it "parses the example ini and return a single result" do
expect(File).to receive(:read).and_return(SAMPLE_INI)
expect(target.read_and_parse_ini(SAMPLE_INI).count).to eq 1
end
end
end
| 29.434343 | 113 | 0.684283 |
bb385049548bbd3ef1fd428823e8af7a10534a6e | 5,651 | # frozen_string_literal: true
# rubocop:disable Metrics/ClassLength
module WasteExemptionsEngine
class DataOverviewPresenter < BasePresenter
def initialize(transient_registration)
super(transient_registration, nil)
end
def company_rows
[
operator_rows,
contact_rows
].flatten
end
def registration_rows
[
exemptions_row,
farm_rows,
applicant_rows,
site_location_rows
].flatten
end
private
def operator_rows
rows = [business_type_row, operator_name_row]
rows << company_no_row if company_no_required?
rows << partners_row if partnership?
rows += [location_row, operator_address_row]
rows
end
def contact_rows
rows = [contact_name_row]
rows << contact_position_row if contact_position.present?
rows += [contact_address_row, contact_details_row]
rows
end
def farm_rows
[on_a_farm_row, is_a_farmer_row]
end
def applicant_rows
[applicant_name_row, applicant_phone_row, applicant_email_row]
end
def site_location_rows
if site_address.located_by_grid_reference?
[grid_reference_row, site_description_row]
else
site_address_row
end
end
def business_type_row
formatted_business_type = WasteExemptionsEngine::TransientRegistration::BUSINESS_TYPES.key(business_type)
{
title: I18n.t("#{company_i18n_scope}.business_type.title"),
value: I18n.t("#{company_i18n_scope}.business_type.value.#{formatted_business_type}")
}
end
def operator_name_row
{
title: I18n.t("#{company_i18n_scope}.operator_name.title"),
value: operator_name
}
end
def company_no_row
{
title: I18n.t("#{company_i18n_scope}.company_no.title"),
value: company_no
}
end
def partners_row
partners_value = transient_people.map { |person| "#{person.first_name} #{person.last_name}" }
.join("<br>")
.html_safe
{
title: I18n.t("#{company_i18n_scope}.partners.title"),
value: partners_value
}
end
def location_row
{
title: I18n.t("#{company_i18n_scope}.location.title"),
value: I18n.t("#{company_i18n_scope}.location.value.#{location}")
}
end
def operator_address_row
{
title: I18n.t("#{company_i18n_scope}.operator_address.title"),
value: displayable_address(operator_address)
}
end
def contact_name_row
contact_name = "#{contact_first_name} #{contact_last_name}"
{
title: I18n.t("#{company_i18n_scope}.contact_name.title"),
value: contact_name
}
end
def contact_position_row
{
title: I18n.t("#{company_i18n_scope}.contact_position.title"),
value: contact_position
}
end
def contact_address_row
{
title: I18n.t("#{company_i18n_scope}.contact_address.title"),
value: displayable_address(contact_address)
}
end
def contact_details_row
contact_details_value = [contact_phone, contact_email].join("<br>").html_safe
{
title: I18n.t("#{company_i18n_scope}.contact_details.title"),
value: contact_details_value
}
end
def exemptions_row
exemptions_value = exemptions.map(&:code).join(", ")
{
title: I18n.t("#{reg_i18n_scope}.exemptions.title"),
value: exemptions_value
}
end
def on_a_farm_row
{
title: I18n.t("#{reg_i18n_scope}.on_a_farm.title"),
value: I18n.t("#{reg_i18n_scope}.on_a_farm.value.#{on_a_farm}")
}
end
# rubocop:disable Naming/PredicateName
# Disabling as this is the name of the attribute
def is_a_farmer_row
{
title: I18n.t("#{reg_i18n_scope}.is_a_farmer.title"),
value: I18n.t("#{reg_i18n_scope}.is_a_farmer.value.#{is_a_farmer}")
}
end
# rubocop:enable Naming/PredicateName
def applicant_name_row
applicant_name = "#{applicant_first_name} #{applicant_last_name}"
{
title: I18n.t("#{reg_i18n_scope}.applicant_name.title"),
value: applicant_name
}
end
def applicant_phone_row
{
title: I18n.t("#{reg_i18n_scope}.applicant_phone.title"),
value: applicant_phone
}
end
def applicant_email_row
{
title: I18n.t("#{reg_i18n_scope}.applicant_email.title"),
value: applicant_email
}
end
def site_address_row
{
title: I18n.t("#{reg_i18n_scope}.site_address.title"),
value: displayable_address(site_address)
}
end
def grid_reference_row
{
title: I18n.t("#{reg_i18n_scope}.grid_reference.title"),
value: site_address.grid_reference
}
end
def site_description_row
{
title: I18n.t("#{reg_i18n_scope}.site_description.title"),
value: site_address.description
}
end
def displayable_address(address)
[address.organisation, address.premises, address.street_address,
address.locality, address.city, address.postcode].reject(&:blank?).join("<br>").html_safe
end
def company_i18n_scope
"waste_exemptions_engine.shared.data_overview.company_info"
end
def reg_i18n_scope
"waste_exemptions_engine.shared.data_overview.registration_info"
end
def test_row
{
title: "foo",
value: "bar"
}
end
end
end
# rubocop:enable Metrics/ClassLength
| 24.253219 | 111 | 0.634401 |
61c8409dce4f017d3515d2ce4968f72740ff3af7 | 139 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_logical_session'
| 34.75 | 77 | 0.805755 |
62c5a82cca8b042bf5f7bdd63a97dbe768983d9e | 338 | class Promocode < Sandbox::Script
def main
if @args[0].nil?
@logger.log('Specify promo code')
return
end
begin
code = @game.cmdRedeemPromoCode(@game.config['id'], @args[0])
rescue Trickster::Hackers::RequestError => e
@logger.log(e)
else
@logger.log(code['message'])
end
end
end
| 19.882353 | 67 | 0.60355 |
1d4d298b748a4e6773fc122ee072374e58ef5c89 | 279 | require 'spec_helper.rb'
feature "Looking up recipes", js: true do
scenario "finding recipes" do
visit '/'
fill_in "keywords", with: "baked"
click_on "Search"
expect(page).to have_content("Baked Potato")
expect(page).to have_content("Baked Brussel Sprouts")
end
end | 23.25 | 55 | 0.724014 |
33a40e3b34236f4da11eb8eaaf1faaf404ef8540 | 3,565 | # frozen_string_literal: true
class TimelineEvent < ApplicationRecord
belongs_to :target
belongs_to :improved_timeline_event, class_name: 'TimelineEvent', optional: true
belongs_to :evaluator, class_name: 'Faculty', optional: true
has_many :target_evaluation_criteria, through: :target
has_many :evaluation_criteria, through: :target_evaluation_criteria
has_many :startup_feedback, dependent: :destroy
has_many :timeline_event_files, dependent: :destroy
has_one :improvement_of, class_name: 'TimelineEvent', foreign_key: 'improved_timeline_event_id', dependent: :nullify, inverse_of: :improved_timeline_event
has_many :timeline_event_grades, dependent: :destroy
has_many :timeline_event_owners, dependent: :destroy
has_many :founders, through: :timeline_event_owners
has_one :course, through: :target
serialize :links
delegate :founder_event?, to: :target
delegate :title, to: :target
MAX_DESCRIPTION_CHARACTERS = 500
validates :description, presence: true
scope :from_admitted_startups, -> { joins(:founders).where(founders: { startup: Startup.admitted }) }
scope :not_private, -> { joins(:target).where.not(targets: { role: Target::ROLE_FOUNDER }) }
scope :not_improved, -> { joins(:target).where(improved_timeline_event_id: nil) }
scope :not_auto_verified, -> { joins(:evaluation_criteria).distinct }
scope :auto_verified, -> { where.not(id: not_auto_verified) }
scope :passed, -> { where.not(passed_at: nil) }
scope :pending_review, -> { not_auto_verified.where(evaluator_id: nil) }
scope :evaluated_by_faculty, -> { where.not(evaluator_id: nil) }
scope :from_founders, ->(founders) { joins(:timeline_event_owners).where(timeline_event_owners: { founder: founders }) }
after_initialize :make_links_an_array
def make_links_an_array
self.links ||= []
end
before_save :ensure_links_is_an_array
def ensure_links_is_an_array
self.links = [] if links.nil?
end
# Accessors used by timeline builder form to create TimelineEventFile entries.
# Should contain a hash: { identifier_key => uploaded_file, ... }
attr_accessor :files
def reviewed?
timeline_event_grades.present?
end
def public_link?
links.reject { |l| l[:private] }.present?
end
def founder_or_startup
founder_event? ? founder : startup
end
def improved_event_candidates
founder_or_startup.timeline_events
.where('created_at > ?', created_at)
.where.not(id: id).order('created_at DESC')
end
def share_url
Rails.application.routes.url_helpers.student_timeline_event_show_url(
id: founder.id,
event_id: id,
event_title: title.parameterize,
host: founders.first.school.domains.primary.fqdn
)
end
def overall_grade_from_score
return if score.blank?
{ 1 => 'good', 2 => 'great', 3 => 'wow' }[score.floor]
end
# TODO: Remove TimelineEvent#startup when possible.
def startup
first_founder = founders.first
raise "TimelineEvent##{id} does not have any linked founders" if first_founder.blank?
# TODO: This is a hack. Remove TimelineEvent#startup method after all of its usages have been deleted.
first_founder.startup
end
def founder
founders.first
end
def passed?
passed_at.present?
end
def team_event?
target.team_target?
end
def pending_review?
passed_at.blank? && evaluator_id.blank?
end
def status
if passed_at.blank?
evaluator_id.present? ? :failed : :pending
else
evaluator_id.present? ? :passed : :marked_as_complete
end
end
end
| 29.708333 | 156 | 0.731557 |
5d875c630a05a6bbf4a7bcc57cf52b8eb46ab95c | 1,448 | # frozen_string_literal: true
module DesignManagement
class DeleteDesignsService < DesignService
include RunsDesignActions
include OnSuccessCallbacks
def initialize(project, user, params = {})
super
@designs = params.fetch(:designs)
end
def execute
return error('Forbidden!') unless can_delete_designs?
version = delete_designs!
EventCreateService.new.destroy_designs(designs, current_user)
success(version: version)
end
def commit_message
n = designs.size
<<~MSG
Removed #{n} #{'designs'.pluralize(n)}
#{formatted_file_list}
MSG
end
private
attr_reader :designs
def delete_designs!
DesignManagement::Version.with_lock(project.id, repository) do
run_actions(build_actions)
end
end
def can_delete_designs?
Ability.allowed?(current_user, :destroy_design, issue)
end
def build_actions
designs.map { |d| design_action(d) }
end
def design_action(design)
on_success do
counter.count(:delete)
end
DesignManagement::DesignAction.new(design, :delete)
end
def counter
::Gitlab::UsageDataCounters::DesignsCounter
end
def formatted_file_list
designs.map { |design| "- #{design.full_path}" }.join("\n")
end
end
end
DesignManagement::DeleteDesignsService.prepend_if_ee('EE::DesignManagement::DeleteDesignsService')
| 20.685714 | 98 | 0.674033 |
ace186a9366eae4e9857da12e6b1976b504284ff | 3,150 | class GtkMacIntegration < Formula
desc "Integrates GTK macOS applications with the Mac desktop"
homepage "https://wiki.gnome.org/Projects/GTK+/OSX/Integration"
url "https://download.gnome.org/sources/gtk-mac-integration/2.1/gtk-mac-integration-2.1.3.tar.xz"
sha256 "d5f72302daad1f517932194d72967a32e72ed8177cfa38aaf64f0a80564ce454"
revision 2
bottle do
sha256 "c44aed60d1bddea2a38b4e7d4211dc506695b66170889b104cc9b0f42ae074ed" => :catalina
sha256 "17623aa62198ffb4da0a61b4265d50d3e168170b3e39b33679abea0014d8f773" => :mojave
sha256 "e8f85dbdf092f966838caca1156c836f6a85e9d906276de9eac47dbea4d84adc" => :high_sierra
end
head do
url "https://github.com/jralls/gtk-mac-integration.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gtk-doc" => :build
depends_on "libtool" => :build
end
depends_on "gobject-introspection" => :build
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "gtk+"
depends_on "gtk+3"
depends_on "pygtk"
def install
args = %W[
--disable-dependency-tracking
--disable-silent-rules
--prefix=#{prefix}
--with-gtk2
--with-gtk3
--enable-python=yes
--enable-introspection=yes
]
if build.head?
system "./autogen.sh", *args
else
system "./configure", *args
end
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <gtkosxapplication.h>
int main(int argc, char *argv[]) {
gchar *bundle = gtkosx_application_get_bundle_path();
return 0;
}
EOS
atk = Formula["atk"]
cairo = Formula["cairo"]
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gdk_pixbuf = Formula["gdk-pixbuf"]
gettext = Formula["gettext"]
glib = Formula["glib"]
gtkx = Formula["gtk+"]
harfbuzz = Formula["harfbuzz"]
libpng = Formula["libpng"]
pango = Formula["pango"]
pixman = Formula["pixman"]
flags = %W[
-I#{atk.opt_include}/atk-1.0
-I#{cairo.opt_include}/cairo
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gdk_pixbuf.opt_include}/gdk-pixbuf-2.0
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{gtkx.opt_include}/gtk-2.0
-I#{gtkx.opt_lib}/gtk-2.0/include
-I#{harfbuzz.opt_include}/harfbuzz
-I#{include}/gtkmacintegration
-I#{libpng.opt_include}/libpng16
-I#{pango.opt_include}/pango-1.0
-I#{pixman.opt_include}/pixman-1
-DMAC_INTEGRATION
-D_REENTRANT
-L#{atk.opt_lib}
-L#{cairo.opt_lib}
-L#{gdk_pixbuf.opt_lib}
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{gtkx.opt_lib}
-L#{lib}
-L#{pango.opt_lib}
-latk-1.0
-lcairo
-lgdk-quartz-2.0
-lgdk_pixbuf-2.0
-lgio-2.0
-lglib-2.0
-lgobject-2.0
-lgtk-quartz-2.0
-lgtkmacintegration-gtk2
-lintl
-lpango-1.0
-lpangocairo-1.0
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 27.876106 | 99 | 0.637778 |
bf83ab91e453abe2787ac03369ae9ea1fe8739f6 | 1,905 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'fir/version'
Gem::Specification.new do |spec|
spec.name = 'fir-cli'
spec.version = FIR::VERSION
spec.authors = ['NaixSpirit', 'atpking']
spec.email = ['[email protected]']
spec.date = Time.now.strftime('%Y-%m-%d')
spec.summary = 'fir.im command tool'
spec.description = 'fir.im command tool, support iOS and Android'
spec.homepage = 'https://github.com/FIRHQ/fir-cli'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.post_install_message = %q(
______________ ________ ____
/ ____/ _/ __ \ / ____/ / / _/
/ /_ / // /_/ /_____/ / / / / /
/ __/ _/ // _, _/_____/ /___/ /____/ /
/_/ /___/_/ |_| \____/_____/___/
## 更新记录
- (1.7.2) 修正了无论是否加参数都固定出现二维码图片的bug
- (1.7.1) 增加了 钉钉推送 , 增加了返回指定版本下载地址
- (1.7.0) 过期了ipa_build 功能, 增加了对 android manifest instant run 的兼容
- (1.6.13) 上传图标逻辑修改
- (1.6.12) 修复了部分机器没有默认安装 byebug 的问题
- (1.6.11) 变化了 ruby gem 仓库地址
- [fir-cli](https://github.com/firhq/fir-cli) 已经开源
- 欢迎 fork, issue 和 pull request
)
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'minitest', '~> 5.7'
spec.add_development_dependency 'pry', '~> 0.10'
spec.add_dependency 'thor', '~> 0.19'
spec.add_dependency 'rest-client', '~> 2.0'
spec.add_dependency 'ruby_android_apk', '~> 0.7.7.1'
spec.add_dependency 'rqrcode', '~> 0.7'
spec.add_dependency 'CFPropertyList'
spec.add_dependency 'api_tools', '~> 0.1.0'
end
| 36.634615 | 74 | 0.607874 |
d50405281a089b3d516c007ea10a04fdb2a98a29 | 523 | require 'rails_helper'
RSpec.describe 'news_items/new', type: :view do
let(:news_item) do
NewsItem.new(
body: 'Body',
title: 'Title',
user_id: 1
)
end
before do
assign(:news_item, news_item)
render
end
it 'renders new news_item form' do
assert_select 'form[action=?][method=?]', news_items_path, 'post' do
assert_select 'input#news_item_title[name=?]', 'news_item[title]'
assert_select 'input#trix_input_news_item[name=?]', 'news_item[body]'
end
end
end
| 21.791667 | 75 | 0.65392 |
617ffb2f10cb3b053380befbe928c9db9f5a2791 | 142 | class AddUsernameIndexToCouncillors < ActiveRecord::Migration[5.0]
def change
add_index :councillors, :username, unique: true
end
end
| 23.666667 | 66 | 0.774648 |
e8d9e3d87785adc01a53606c6776599aa8b06ba1 | 29,076 | # encoding: utf-8
require "spec_helper"
def expect_window_with_content(content, window: windows.last)
page.within_window window do
expect(page).to have_content(content)
end
end
def expect_window_without_content(content, window: windows.last)
page.within_window window do
expect(page).not_to have_content(content)
end
end
module Refinery
module Admin
describe "Pages", :type => :feature do
refinery_login
context "when no pages" do
it "invites to create one" do
visit refinery.admin_pages_path
expect(page).to have_content(%q{There are no pages yet. Click "Add new page" to add your first page.})
end
end
describe "action links" do
it "shows add new page link" do
visit refinery.admin_pages_path
within "#actions" do
expect(page).to have_content("Add new page")
expect(page).to have_selector("a[href='/#{Refinery::Core.backend_route}/pages/new']")
end
end
context "when no pages" do
it "doesn't show reorder pages link" do
visit refinery.admin_pages_path
within "#actions" do
expect(page).to have_no_content("Reorder pages")
expect(page).to have_no_selector("a[href='/#{Refinery::Core.backend_route}/pages']")
end
end
end
context "when some pages exist" do
let!(:page_0) { Page.create! title: 'Page 0' }
let!(:page_1) { Page.create! title: 'Page 1' }
it "shows reorder pages link" do
visit refinery.admin_pages_path
within "#actions" do
expect(page).to have_content("Reorder pages")
expect(page).to have_selector("a[href='/#{Refinery::Core.backend_route}/pages']")
end
end
context "when reordering pages" do
let(:reorder_url) { "/#{Refinery::Core.backend_route}/pages/update_positions" }
before do
visit refinery.admin_pages_path
page.driver.post(reorder_url, {
'ul[0][0][id]' => "page_#{page_1.id}",
'ul[0][1][id]' => "page_#{page_0.id}",
})
end
it "shows pages in the new order" do
visit refinery.admin_pages_path
expect(page.body).to match(/Page 1.*Page 0/m)
end
end
end
context "when sub pages exist" do
let!(:company) { Page.create :title => 'Our Company' }
let!(:team) { company.children.create :title => 'Our Team' }
let!(:locations) { company.children.create :title => 'Our Locations' }
let!(:location) { locations.children.create :title => 'New York' }
context "with auto expand option turned off" do
before do
allow(Refinery::Pages).to receive(:auto_expand_admin_tree).and_return(false)
visit refinery.admin_pages_path
end
it "show parent page" do
expect(page).to have_content(company.title)
end
it "doesn't show children" do
expect(page).not_to have_content(team.title)
expect(page).not_to have_content(locations.title)
end
it "expands children", :js do
find("#page_#{company.id} .title.toggle").click
expect(page).to have_content(team.title)
expect(page).to have_content(locations.title)
end
it "expands children when nested multiple levels deep", :js do
find("#page_#{company.id} .title.toggle").click
find("#page_#{locations.id} .title.toggle").click
expect(page).to have_content("New York")
end
end
context "with auto expand option turned on" do
before do
allow(Refinery::Pages).to receive(:auto_expand_admin_tree).and_return(true)
visit refinery.admin_pages_path
end
it "shows children" do
expect(page).to have_content(team.title)
expect(page).to have_content(locations.title)
end
end
end
end
describe "new/create" do
it "Creates a page", js:true do
visit refinery.admin_pages_path
find('a', text: 'Add new page').trigger(:click)
fill_in "Title", :with => "My first page"
expect { click_button "Save" }.to change(Refinery::Page, :count).from(0).to(1)
expect(page).to have_content("'My first page' was successfully added.")
expect(page.body).to match(/Remove this page forever/)
expect(page.body).to match(/Edit this page/)
expect(page.body).to match(%r{/#{Refinery::Core.backend_route}/pages/my-first-page/edit})
expect(page.body).to match(/Add a new child page/)
expect(page.body).to match(%r{/#{Refinery::Core.backend_route}/pages/new\?parent_id=})
expect(page.body).to match(/View this page live/)
expect(page.body).to match(%r{href="/my-first-page"})
end
it "includes menu title field", :js => true do
visit refinery.new_admin_page_path
fill_in "Title", :with => "My first page"
find('#toggle_advanced_options').trigger(:click)
fill_in "Menu title", :with => "The first page"
# For some reason the first click doesn't always work?
begin
click_button "Save"
sleep 0.1
redo unless Refinery::Page.any?
end
expect(page).to have_content("'My first page' was successfully added.")
expect(page.body).to match(%r{/pages/the-first-page})
end
it "allows to easily create nested page" do
parent_page = Page.create! :title => "Rails 4"
visit refinery.admin_pages_path
find("a[href='#{refinery.new_admin_page_path(:parent_id => parent_page.id)}']").click
fill_in "Title", :with => "Parent page"
click_button "Save"
expect(page).to have_content("'Parent page' was successfully added.")
end
end
describe "edit/update" do
before do
Page.create :title => "Update me"
visit refinery.admin_pages_path
expect(page).to have_content("Update me")
end
context 'when saving and returning to index' do
it "updates page", js:true do
find('a[tooltip="Edit this page"]').trigger(:click)
fill_in "Title", :with => "Updated"
find("#submit_button").click
expect(page).to have_content("'Updated' was successfully updated.")
end
end
context 'when saving and continuing to edit' do
before :each do
find('a[tooltip^=Edit]').visible?
find('a[tooltip^=Edit]').click
fill_in "Title", :with => "Updated"
find("#submit_continue_button").click
find('#flash').visible?
end
it "updates page", :js do
expect(page).to have_content("'Updated' was successfully updated.")
end
# Regression test for https://github.com/refinery/refinerycms/issues/1892
context 'when saving to exit (a second time)' do
it 'updates page', :js do
find("#submit_button").click
expect(page).to have_content("'Updated' was successfully updated.")
end
end
end
end
describe 'Previewing', :js do
let(:preview_content) { "Some changes I'm unsure what they will look like".freeze }
context "an existing page" do
before { Page.create :title => 'Preview me' }
it 'will show the preview changes in a new window' do
visit refinery.admin_pages_path
find('a[tooltip^=Edit]').click
fill_in "Title", with: preview_content
window = window_opened_by do
click_button "Preview"
end
expect_window_with_content(preview_content, window: window)
window.close
end
it 'will not show the site bar' do
visit refinery.admin_pages_path
find('a[tooltip^=Edit]').click
fill_in "Title", with: preview_content
window = window_opened_by do
click_button "Preview"
end
expect_window_without_content(
::I18n.t('switch_to_website', scope: 'refinery.site_bar'),
window: window
)
expect_window_without_content(
::I18n.t('switch_to_website_editor', scope: 'refinery.site_bar'),
window: window
)
window.close
end
it 'will not save the preview changes' do
visit refinery.admin_pages_path
find('a[tooltip^=Edit]').click
fill_in "Title", with: preview_content
window = window_opened_by do
click_button "Preview"
end
expect_window_with_content(
preview_content,
window: window
)
window.close
expect(Page.by_title(preview_content)).to be_empty
end
# Regression test for previewing after save-and_continue
it 'will show the preview in a new window after save-and-continue' do
visit refinery.admin_pages_path
find('a[tooltip^=Edit]').click
fill_in "Title", :with => "Save this"
click_button "Save & continue editing"
expect(page).to have_content("'Save this' was successfully updated")
window = window_opened_by do
click_button "Preview"
end
expect_window_with_content("Save this", window: window)
expect_window_without_content(
::I18n.t('switch_to_website', :scope => 'refinery.site_bar'),
window: window
)
window.close
end
it 'will show pages with inherited templates', js:true do
visit refinery.admin_pages_path
find('a[tooltip^=Edit]').click
fill_in 'Title', :with => 'Searchable'
find('#toggle_advanced_options').trigger(:click)
select 'Searchable', :from => 'View template'
Timeout::timeout(5) do
click_button 'Preview'
sleep 0.1 and redo unless windows.many?
expect_window_with_content('Form application/search_form')
end
end
end
context 'a brand new page' do
it "will not save when just previewing", js:true do
visit refinery.admin_pages_path
find('a', text: 'Add new page').trigger(:click)
fill_in "Title", :with => "My first page"
window = window_opened_by do
click_button "Preview"
end
expect_window_with_content("My first page", window: window)
expect(Page.count).to eq(0)
window.close
end
end
context 'a nested page' do
let!(:parent_page) { Page.create :title => "Our Parent Page" }
let!(:nested_page) { parent_page.children.create :title => 'Preview Me' }
it "works like an un-nested page" do
visit refinery.admin_pages_path
within "#page_#{nested_page.id}" do
find('a[tooltip^=Edit]').click
end
fill_in "Title", with: preview_content
window = window_opened_by do
click_button "Preview"
end
expect_window_with_content(preview_content)
end
end
end
describe "destroy" do
context "when page can be deleted", js:true do
before { Page.create :title => "Delete me" }
it "will show delete button" do
visit refinery.admin_pages_path
find('a[tooltip="Remove this page forever"]').trigger(:click)
expect(page).to have_content("'Delete me' was successfully removed.")
expect(Refinery::Page.count).to eq(0)
end
end
context "when page can't be deleted" do
before { Page.create :title => "Indestructible", :deletable => false }
it "wont show delete button" do
visit refinery.admin_pages_path
expect(page).to have_no_content("Remove this page forever")
expect(page).to have_no_selector("a[href='/#{Refinery::Core.backend_route}/pages/indestructible']")
end
end
end
context "duplicate page titles" do
before { Page.create :title => "I was here first" }
it "will append nr to url path" do
visit refinery.new_admin_page_path
fill_in "Title", :with => "I was here first"
click_button "Save"
expect(Refinery::Page.last.url[:path].first).to match(%r{\Ai-was-here-first-.+?})
end
end
context "with translations" do
before do
allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :ru])
# Create a home page in both locales (needed to test menus)
home_page = Globalize.with_locale(:en) do
Page.create :title => 'Home',
:link_url => '/',
:menu_match => "^/$"
end
Globalize.with_locale(:ru) do
home_page.title = 'Домашняя страница'
home_page.save
end
end
describe "add a page with title for default locale", js:true do
before do
visit refinery.admin_pages_path
find('a', text: "Add new page").trigger(:click)
fill_in "Title", :with => "News"
click_button "Save"
end
it "creates a page" do
expect(page).to have_content("'News' was successfully added.")
expect(Refinery::Page.count).to eq(2)
end
it "shows locale flag for page" do
p = ::Refinery::Page.by_slug('news').first
within "#page_#{p.id} .locales" do
expect(page).to have_css('.locale_marker')
expect(page).to have_content('EN')
end
end
it "shows title in the admin menu" do
p = ::Refinery::Page.by_slug('news').first
within "#page_#{p.id}" do
expect(page).to have_content('News')
expect(page.find('a[tooltip="Edit this page"]')[:href]).to include('news')
end
end
it "shows in frontend menu for 'en' locale" do
# page.driver.debug
visit "/"
within "#menu" do
expect(page).to have_content('News')
expect(page).to have_selector("a[href='/news']")
end
end
it "doesn't show in frontend menu for 'ru' locale" do
visit "/ru"
within "#menu" do
# we should only have the home page in the menu
expect(page).to have_css('li', :count => 1)
end
end
end
describe "a page with two locales", js:true do
let(:en_page_title) { 'News' }
let(:en_page_slug) { 'news' }
let(:ru_page_title) { 'Новости' }
let(:ru_page_slug_encoded) { '%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8' }
let!(:news_page) do
allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :ru])
_page = Globalize.with_locale(:en) {
Page.create :title => en_page_title
}
Globalize.with_locale(:ru) do
_page.title = ru_page_title
_page.save
end
_page
end
it "can have a title for each locale" do
news_page.destroy!
visit refinery.admin_pages_path
find('a', text:"Add new page").trigger(:click)
within "#switch_locale_picker" do
find('a', text: "RU").trigger(:click)
end
fill_in "Title", :with => ru_page_title
click_button "Save"
within "#page_#{Page.last.id} .actions" do
find("a[href^='/#{Refinery::Core.backend_route}/pages/#{ru_page_slug_encoded}/edit']").click
end
within "#switch_locale_picker" do
find('a', text: "EN").trigger(:click)
end
fill_in "Title", :with => en_page_title
find("#submit_button").click
expect(page).to have_content("'#{en_page_title}' was successfully updated.")
expect(Refinery::Page.count).to eq(2)
end
it "is shown with both locales in the index" do
visit refinery.admin_pages_path
within "#page_#{news_page.id} .locales" do
expect(page).to have_css('.locale_marker', count: 2)
expect(page).to have_content('EN')
expect(page).to have_content('RU')
end
end
it "shows title in current admin locale in the index" do
visit refinery.admin_pages_path
within "#page_#{news_page.id}" do
expect(page).to have_content(en_page_title)
end
end
it "uses the slug from the default locale in admin" do
visit refinery.admin_pages_path
within "#page_#{news_page.id}" do
expect(page.find('a[tooltip="Edit this page"]')[:href]).to include(en_page_slug)
end
end
it "shows correct language and slugs for default locale" do
visit "/"
within "#menu" do
expect(page.find_link(news_page.title)[:href]).to include(en_page_slug)
end
end
it "shows correct language and slugs for second locale" do
visit "/ru"
within "#menu" do
expect(page.find_link(ru_page_title)[:href]).to include(ru_page_slug_encoded)
end
end
end
describe "add a page with title only for secondary locale", js:true do
let(:ru_page) {
Globalize.with_locale(:ru) {
Page.create :title => ru_page_title
}
}
let(:ru_page_id) { ru_page.id }
let(:ru_page_title) { 'Новости' }
let(:ru_page_slug_encoded) { '%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8' }
before do
ru_page
visit refinery.admin_pages_path
end
it "lets you add a Russian title without an English title" do
ru_page.destroy!
find('a', text: 'Add new page').trigger(:click)
within "#switch_locale_picker" do
find('a', text: "RU").trigger(:click)
end
fill_in "Title", :with => ru_page_title
click_button "Save"
expect(page).to have_content("'#{ru_page_title}' was successfully added.")
expect(Refinery::Page.count).to eq(2)
end
it "shows locale indicator for page" do
within "#page_#{ru_page_id}" do
expect(page).to have_selector('.locale_marker', text: 'RU')
end
end
it "doesn't show locale indicator for primary locale" do
within "#page_#{ru_page_id}" do
expect(page).to_not have_selector('.locale_marker', text: 'EN')
end
end
it "shows title in the admin menu" do
within "#page_#{ru_page_id}" do
expect(page).to have_content(ru_page_title)
end
end
it "uses slug in admin" do
within "#page_#{ru_page_id}" do
expect(page.find('a[tooltip="Edit this page"]')[:href]).to include(ru_page_slug_encoded)
end
end
it "shows in frontend menu for 'ru' locale" do
visit "/ru"
within "#menu" do
expect(page).to have_content(ru_page_title)
expect(page).to have_selector("a[href*='/#{ru_page_slug_encoded}']")
end
end
it "won't show in frontend menu for 'en' locale" do
visit "/"
within "#menu" do
# we should only have the home page in the menu
expect(page).to have_css('li', :count => 1)
end
end
context "when page is a child page", js: true do
it 'succeeds' do
ru_page.destroy!
parent_page = Page.create(:title => "Parent page")
sub_page = Globalize.with_locale(:ru) {
Page.create :title => ru_page_title, :parent_id => parent_page.id
}
expect(sub_page.parent).to eq(parent_page)
visit refinery.admin_pages_path
within "#page_#{sub_page.id}" do
find("a.edit_icon").trigger(:click)
end
fill_in "Title", :with => ru_page_title
click_button "Save"
expect(page).to have_content("'#{ru_page_title}' was successfully updated")
end
end
end
end
describe "new page part", :js do
before do
allow(Refinery::Pages).to receive(:new_page_parts).and_return(true)
end
it "adds new page part" do
visit refinery.new_admin_page_path
find("#add_page_part").trigger(:click)
within "#new_page_part_dialog" do
fill_in "new_page_part_title", :with => "testy"
click_button "Save"
end
within "#page_parts" do
expect(page).to have_content("testy")
end
end
end
describe "delete existing page part", :js do
let!(:some_page) { Page.create! :title => "Some Page" }
before do
some_page.parts.create! :title => "First Part", :slug => "first_part", :position => 1
some_page.parts.create! :title => "Second Part", :slug => "second_part", :position => 2
some_page.parts.create! :title => "Third Part", :slug => "third_part", :position => 3
allow(Refinery::Pages).to receive(:new_page_parts).and_return(true)
end
it "deletes page parts" do
visit refinery.edit_admin_page_path(some_page.id)
within "#page_parts" do
expect(page).to have_content("First Part")
expect(page).to have_content("Second Part")
expect(page).to have_content("Third Part")
end
2.times do
find("#delete_page_part").trigger(:click)
# Poltergeist automatically accepts dialogues.
if Capybara.javascript_driver != :poltergeist
page.driver.browser.switch_to.alert.accept
end
end
within "#page_parts" do
expect(page).to have_no_content("First Part")
expect(page).to have_no_content("Second Part")
expect(page).to have_content("Third Part")
end
click_button "submit_button"
visit refinery.edit_admin_page_path(some_page.id)
within "#page_parts" do
expect(page).to have_no_content("First Part")
expect(page).to have_no_content("Second Part")
expect(page).to have_content("Third Part")
end
end
end
describe 'advanced options' do
describe 'view and layout templates' do
context 'when parent page has templates set' do
before do
allow(Refinery::Pages).to receive(:use_layout_templates).and_return(true)
allow(Refinery::Pages).to receive(:layout_template_whitelist).and_return(['abc', 'refinery'])
allow(Refinery::Pages).to receive(:valid_templates).and_return(['abc', 'refinery'])
parent_page = Page.create :title => 'Parent Page',
:view_template => 'refinery',
:layout_template => 'refinery'
@page = parent_page.children.create :title => 'Child Page'
end
specify 'sub page should inherit them', :js => true do
visit refinery.edit_admin_page_path(@page.id)
find('#toggle_advanced_options').trigger(:click)
within '#page_layout_template' do
expect(page.find('option[value=refinery]')).to be_selected
end
within '#page_view_template' do
expect(page.find('option[value=refinery]')).to be_selected
end
end
end
end
end
# regression spec for https://github.com/refinery/refinerycms/issues/1891
describe "a page part with HTML", js:true do
before do
page = Refinery::Page.create! :title => "test"
Refinery::Pages.default_parts.each_with_index do |default_page_part, index|
page.parts.create(
title: default_page_part,
slug: default_page_part,
body: "<header class='regression'>test</header>",
position: index
)
end
end
specify "should retain the html" do
visit refinery.admin_pages_path
find('a[tooltip="Edit this page"]').trigger(:click)
Capybara.ignore_hidden_elements = false
expect(page).to have_content("header class='regression'")
Capybara.ignore_hidden_elements = true
end
end
end
describe "TranslatePages", :type => :feature do
before { Globalize.locale = :en }
refinery_login
describe "a page with a single locale", js: true do
before do
allow(Refinery::I18n).to receive(:frontend_locales).and_return([:en, :lv])
Page.create :title => 'First Page'
end
it "can have a second locale added to it" do
visit refinery.admin_pages_path
find('a', text: 'Add new page').trigger(:click)
within "#switch_locale_picker" do
find('a', text: "LV").trigger(:click)
end
fill_in "Title", :with => "Brīva vieta reklāmai"
click_button "Save"
expect(page).to have_content("'Brīva vieta reklāmai' was successfully added.")
expect(Refinery::Page.count).to eq(2)
end
end
describe "Pages Link-to Dialog" do
before do
allow(Refinery::I18n).to receive(:frontend_locales).and_return [:en, :ru]
# Create a page in both locales
about_page = Globalize.with_locale(:en) do
Page.create :title => 'About'
end
Globalize.with_locale(:ru) do
about_page.title = 'About Ru'
about_page.save
end
end
let(:about_page) do
page = Refinery::Page.last
# we need page parts so that there's a visual editor
Refinery::Pages.default_parts.each_with_index do |default_page_part, index|
page.parts.create(:title => default_page_part, :body => nil, :position => index)
end
page
end
describe "adding page link" do
describe "with relative urls" do
before { Refinery::Pages.absolute_page_links = false }
it "shows Russian pages if we're editing the Russian locale" do
visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true, :switch_locale => :ru)
expect(page).to have_content("About Ru")
expect(page).to have_selector("a[href='/ru/about-ru']")
end
it "shows default to the default locale if no query string is added" do
visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true)
expect(page).to have_content("About")
expect(page).to have_selector("a[href='/about']")
end
end
describe "with absolute urls" do
before { Refinery::Pages.absolute_page_links = true }
it "shows Russian pages if we're editing the Russian locale" do
visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true, :switch_locale => :ru)
expect(page).to have_content("About Ru")
expect(page).to have_selector("a[href='http://www.example.com/ru/about-ru']")
end
it "shows default to the default locale if no query string is added" do
visit refinery.link_to_admin_pages_dialogs_path(:visual_editor => true)
expect(page).to have_content("About")
expect(page).to have_selector("a[href='http://www.example.com/about']")
end
end
end
end
end
end
end
| 33.96729 | 112 | 0.561253 |
876c71361b2da4b72dd2baffea26e8dad9ecdba3 | 1,630 | # frozen_string_literal: true
context = ChefDK::Generator.context
cookbook_dir = File.join(context.cookbook_root, context.cookbook_name)
recipe_path = File.join(cookbook_dir, 'recipes', "#{context.new_file_basename}.rb")
spec_helper_path = File.join(cookbook_dir, 'spec', 'spec_helper.rb')
spec_dir = File.join(cookbook_dir, 'spec', 'unit', 'recipes')
spec_path = File.join(spec_dir, "#{context.new_file_basename}_spec.rb")
inspec_dir = File.join(cookbook_dir, 'test', 'integration', 'default')
inspec_path = File.join(inspec_dir, "#{context.new_file_basename}_test.rb")
if File.directory?(File.join(cookbook_dir, 'test', 'recipes'))
Chef::Log.deprecation <<~EOH
It appears that you have InSpec tests located at "test/recipes". This location can
cause issues with Foodcritic and has been deprecated in favor of "test/integration/default".
Please move your existing InSpec tests to the newly created "test/integration/default"
directory, and update the 'inspec_tests' value in your kitchen.yml file(s) to
point to "test/integration/default".
EOH
end
# Chefspec
directory spec_dir do
recursive true
end
cookbook_file spec_helper_path do
action :create_if_missing
end
template spec_path do
source 'recipe_spec.rb.erb'
helpers(ChefDK::Generator::TemplateHelper)
action :create_if_missing
end
# Inspec
directory inspec_dir do
recursive true
end
template inspec_path do
source 'inspec_default_test.rb.erb'
helpers(ChefDK::Generator::TemplateHelper)
action :create_if_missing
end
# Recipe
template recipe_path do
source 'recipe.rb.erb'
helpers(ChefDK::Generator::TemplateHelper)
end
| 30.754717 | 96 | 0.77362 |
1dc636bce7f673022de3885e8c33b8679112ddef | 1,053 | require 'serverspec'
set :backend, :exec
puts "os: #{os}"
def mysql_bin
return '/opt/mysql50/bin/mysql' if os[:family] =~ /solaris/
return '/opt/local/bin/mysql' if os[:family] =~ /smartos/
'/usr/bin/mysql'
end
def mysqld_bin
return '/opt/mysql51/bin/mysqld' if os[:family] =~ /solaris/
return '/opt/local/bin/mysqld' if os[:family] =~ /smartos/
return '/usr/libexec/mysqld' if os[:family] =~ /fedora/
return '/usr/libexec/mysqld' if os[:family] =~ /redhat/
'/usr/sbin/mysqld'
end
def mysql_cmd
<<-EOF
#{mysql_bin} \
-h 127.0.0.1 \
-P 3306 \
-u root \
-pilikerandompasswords \
-e "SELECT Host,User,Password FROM mysql.user WHERE User='root' AND Host='%';" \
--skip-column-names
EOF
end
def mysqld_cmd
"#{mysqld_bin} --version"
end
describe command(mysql_cmd) do
its(:exit_status) { should eq 0 }
its(:stdout) { should match(/| % | root | *4C45527A2EBB585B4F5BAC0C29F4A20FB268C591 |/) }
end
describe command(mysqld_cmd) do
its(:exit_status) { should eq 0 }
its(:stdout) { should match(/Ver 5.0/) }
end
| 22.891304 | 91 | 0.662868 |
1de02b6811d35c19eb5e3e9398bdf6b54a9b0e6e | 2,379 | class ApplicationController < ActionController::Base
protect_from_forgery
after_action :store_location
helper_method :current_season, :current_student
before_action do
redirect_to = params[:redirect_to]
redirect_to ||= request.env['omniauth.params']['redirect_to'] if request.env['omniauth.params']
session[:redirect_to] = redirect_to if redirect_to.present?
end
# workaround fix for cancan on rails4 - https://github.com/ryanb/cancan/issues/835
before_action do
resource = controller_path.singularize.gsub('/', '_').to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end
def after_sign_in_path_for(user)
if user.just_created?
edit_user_path(user, welcome: true, redirect_to: session.delete(:redirect_to))
else
session.delete(:previous_url_login_required) || session.delete(:previous_url) || user_path(current_user)
end
end
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: exception.message
end
def cors_preflight
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
headers['Access-Control-Max-Age'] = '1728000'
render text: '', content_type: 'text/plain'
end
end
def cors_set_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = "1728000"
end
def current_season
@season ||= Season.current
end
def current_student
@current_student ||= Student.new(current_user)
end
def require_role(role_name)
redirect_to '/', alert: "#{role_name.capitalize} required" unless current_user && current_user.roles.includes?(role_name)
end
def login_required
store_location key: :previous_url_login_required
redirect_to root_path, alert: 'Please log in with your Github account first' unless current_user
end
def store_location(key: :previous_url)
return unless request.get?
if !request.path.starts_with?('/auth') && \
request.path != "/sign_out" && \
!request.xhr? # don't store ajax calls
session[key] = request.fullpath
end
end
end
| 31.72 | 125 | 0.711223 |
f814038bf5741fe86964fc6bdd3cfb37bda820af | 1,850 | # frozen_string_literal: true
module Spage
# Api Module
#
module Api
# Component resources in the statuspage.io API
#
class Component
include Api
def all(page_id:)
response = client.get("pages/#{page_id}/components")
handle_response(response) do
response.body.map do |component|
Spage::Component.new(component)
end
end
end
def find(page_id:, id:)
response = client.get("pages/#{page_id}/components", id)
handle_response(response) do
Spage::Component.new(response.body)
end
end
def create(component, page_id:)
json = Spage::Serializers::Component.new(component,
update: true).to_json
response = client.post("pages/#{page_id}/components", json)
handle_response(response) do
Spage::Component.new(response.body)
end
end
def update(component, page_id:, id:)
json = Spage::Serializers::Component.new(component,
update: true).to_json
response = client.put("pages/#{page_id}/components", id, json)
handle_response(response) do
Spage::Component.new(response.body)
end
end
def delete(page_id:, id:)
response = client.delete("pages/#{page_id}/components", id)
handle_response(response) do
true
end
end
end
private
def handle_response(response)
case response
when Net::HTTPSuccess
yield
when Net::HTTPUnauthorized
raise(Error, 'Unauthorized: wrong API Key')
else
# Net::HTTPBadRequest, Net::HTTPUnprocessableEntity, Net::HTTPForbidden
raise(Error, response.body)
end
end
end
end
| 25 | 79 | 0.577838 |
b9b077ea099ed28c937ac5f517eb63f8a6fcd93d | 7,610 | require 'helper'
require 'populate_me/document'
class Band < PopulateMe::Document
attr_accessor :name, :awsome, :position
def members; @members ||= []; end
def validate
error_on(:name,"WTF") if self.name=='ZZ Top'
end
end
class Band::Member < PopulateMe::Document
attr_accessor :name
end
require 'populate_me/api'
describe 'PopulateMe::API' do
# This middleware has the CRUD interface for
# managing documents through a JSON-based API
#
# The API needs the Document class to implement these methods:
# - Class.admin_get
# - Needs to be able to accept the ID as a string
# - The class is responsible for conversion
# - So a mix of different classes of IDs is not possible
# - instance.to_h
# - instance.save
# - instance.delete
parallelize_me!
let(:app) {
PopulateMe::API.new
}
let(:json) {
JSON.parse(last_response.body)
}
def assert_not_found
assert_json last_response
assert_equal 404, last_response.status
assert_equal 'pass', last_response.headers['X-Cascade']
refute json['success']
assert_equal 'Not Found', json['message']
end
def assert_successful_creation
assert_json last_response
assert_equal 201, last_response.status
assert json['success']
assert_equal 'Created Successfully', json['message']
end
def assert_successful_sorting
assert_json last_response
assert_predicate last_response, :ok?
assert json['success']
assert_equal 'Sorted Successfully', json['message']
end
def assert_invalid_instance
assert_json last_response
assert_equal 400, last_response.status
refute json['success']
assert_equal 'Invalid Document', json['message']
end
def assert_successful_instance
assert_json last_response
assert_predicate last_response, :ok?
assert json['success']
end
def assert_successful_update
assert_json last_response
assert_predicate last_response, :ok?
assert json['success']
assert_equal 'Updated Successfully', json['message']
end
def assert_successful_deletion
assert_json last_response
assert_predicate last_response, :ok?
assert json['success']
assert_equal 'Deleted Successfully', json['message']
end
describe 'GET /version' do
it 'Returns the PopulateMe version' do
get('/version')
assert_json last_response
assert_predicate last_response, :ok?
assert json['success']
assert_equal PopulateMe::VERSION, json['version']
end
end
describe 'POST /:model' do
it 'Creates successfully' do
post('/band', {data: {id: 'neurosis', name: 'Neurosis'}})
assert_successful_creation
assert_equal 'Neurosis', json['data']['name']
end
it 'Typecasts before creating' do
post('/band', {data: {name: 'Arcade Fire', awsome: 'true'}})
assert_successful_creation
assert json['data']['awsome']
end
it 'Can create a doc even if no data is sent' do
post '/band'
assert_successful_creation
end
it 'Fails if the doc is invalid' do
post('/band', {data: {id: 'invalid_doc_post', name: 'ZZ Top'}})
assert_invalid_instance
assert_equal({'name'=>['WTF']}, json['data'])
assert_nil Band.admin_get('invalid_doc_post')
end
it 'Redirects if destination is given' do
post '/band', {'_destination'=>'http://example.org/anywhere'}
assert_equal 302, last_response.status
assert_equal 'http://example.org/anywhere', last_response.header['Location']
end
end
describe 'PUT /:model' do
it 'Can set indexes for sorting' do
post('/band', {data: {id: 'sortable1', name: 'Sortable 1'}})
post('/band', {data: {id: 'sortable2', name: 'Sortable 2'}})
post('/band', {data: {id: 'sortable3', name: 'Sortable 3'}})
put '/band', {
'action'=>'sort',
'field'=>'position',
'ids'=> ['sortable2','sortable3','sortable1']
}
assert_successful_sorting
assert_equal 0, Band.admin_get('sortable2').position
assert_equal 1, Band.admin_get('sortable3').position
assert_equal 2, Band.admin_get('sortable1').position
end
it 'Redirects after sorting if destination is given' do
post('/band', {data: {id: 'redirectsortable1', name: 'Redirect Sortable 1'}})
post('/band', {data: {id: 'redirectsortable2', name: 'Redirect Sortable 2'}})
post('/band', {data: {id: 'redirectsortable3', name: 'Redirect Sortable 3'}})
put '/band', {
'action'=>'sort',
'field'=>'position',
'ids'=> ['redirectsortable2','redirectsortable3','redirectsortable1'],
'_destination'=>'http://example.org/anywhere'
}
assert_equal 302, last_response.status
assert_equal 'http://example.org/anywhere', last_response.header['Location']
end
end
describe 'GET /:model/:id' do
it 'Sends a not-found when the model is not a class' do
get('/wizz/42')
assert_not_found
end
it 'Sends not-found when the model is a class but not a model' do
get('/string/42')
assert_not_found
end
it 'Sends not-found when the id is not provided' do
get('/band/')
assert_not_found
end
it 'Sends not-found when the instance does not exist' do
get('/band/666')
assert_not_found
end
it 'Sends the instance if it exists' do
post('/band', {data: {id: 'sendable', name: 'Morphine'}})
get('/band/sendable')
assert_successful_instance
assert_equal Band.admin_get('sendable').to_h, json['data']
end
end
describe 'PUT /:model/:id' do
it 'Sends not-found if the instance does not exist' do
put('/band/666')
assert_not_found
end
it 'Fails if the document is invalid' do
post('/band', {data: {id: 'invalid_doc_put', name: 'Valid here'}})
put('/band/invalid_doc_put', {data: {name: 'ZZ Top'}})
assert_invalid_instance
assert_equal({'name'=>['WTF']}, json['data'])
refute_equal 'ZZ Top', Band.admin_get('invalid_doc_put').name
end
it 'Updates documents' do
post('/band', {data: {id: 'updatable', name: 'Updatable'}})
put('/band/updatable', {data: {awsome: 'yes'}})
assert_successful_update
obj = Band.admin_get('updatable')
assert_equal 'yes', obj.awsome
assert_equal 'Updatable', obj.name
end
# it 'Updates nested documents' do
# obj = Band.admin_get('3')
# put('/band/3', {data: {members: [
# {id: obj.members[0].id, _class: 'Band::Member', name: 'Joey Ramone'},
# {id: obj.members[1].id, _class: 'Band::Member'},
# ]}})
# assert_successful_update
# obj = Band.admin_get('3')
# assert_equal 'yes', obj.awsome
# assert_equal 'The Ramones', obj.name
# assert_equal 2, obj.members.size
# assert_equal 'Joey Ramone', obj.members[0].name
# assert_equal 'Deedee Ramone', obj.members[1].name
# end
end
describe 'DELETE /:model/:id' do
it 'Sends not-found if the instance does not exist' do
delete('/band/666')
assert_not_found
end
it 'Returns a deletion response when the instance exists' do
post('/band', {data: {id: 'deletable', name: '1D'}})
delete('/band/deletable')
assert_successful_deletion
assert_instance_of Hash, json['data']
end
it 'Redirects if destination is given' do
delete('/band/2', {'_destination'=>'http://example.org/anywhere'})
assert_equal 302, last_response.status
assert_equal 'http://example.org/anywhere', last_response.header['Location']
end
end
end
| 30.809717 | 83 | 0.652825 |
ac317cb2dfc621bb1f5c01868b2ebb2b0acf3d73 | 145 | class AddDeletedToAssessors < ActiveRecord::Migration[4.2]
def change
add_column :assessors, :deleted, :boolean, default: :false
end
end
| 24.166667 | 62 | 0.751724 |
5d4515ce72ef0606a255420fe9b7fff57e0972f5 | 29 | class Captivity < Event ;end
| 14.5 | 28 | 0.758621 |
f8b638b8e10d7a9f352f1f136e3e877d3fc822bf | 1,821 | ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require 'test_keys'
class ActiveSupport::TestCase
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
# Every Active Record database supports transactions except MyISAM tables
# in MySQL. Turn off transactional fixtures in this case; however, if you
# don't care one way or the other, switching from MyISAM to InnoDB tables
# is recommended.
#
# The only drawback to using transactional fixtures is when you actually
# need to test transactions. Since your test is bracketed by a transaction,
# any transactions started in your code will be automatically rolled back.
self.use_transactional_fixtures = true
# Instantiated fixtures are slow, but give you @david where otherwise you
# would need people(:david). If you don't want to migrate your existing
# test cases which use the @david style and don't mind the speed hit (each
# instantiated fixtures translates to a database query per test method),
# then set this back to true.
self.use_instantiated_fixtures = false
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end
| 44.414634 | 89 | 0.75508 |
18469da82543709d21509310501d367179dce736 | 240 | class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}")
end
end | 24 | 90 | 0.691667 |
bf470ab56695820f84d50e33f4d77145a88aa5fd | 942 | require 'rails/generators'
require 'rails/generators/migration'
module IsPublished
module Generators
class InstallGenerator < ::Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc "Add the migrations for IsPublished"
argument :model_name, type: :string, default: 'post'
def self.next_migration_number(path)
next_migration_number = current_migration_number(path) + 1
ActiveRecord::Migration.next_migration_number(next_migration_number)
end
def copy_migrations
migration_template "create_migration.erb",
"db/migrate/create_#{model_name.underscore.pluralize}.rb"
end
def create_model
create_file "app/models/#{model_name.underscore}.rb", "
class #{model_name.capitalize} < ApplicationRecord
extend IsPublished::Scopes
end
"
end
end
end
end | 30.387097 | 84 | 0.703822 |
0116459d9149b0be0e767c2ff62976768c5b0d4e | 3,231 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
#@user.name = " "
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should be present" do
#@user.email = " "
@user.email = "a" * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
valid_addresses = %w[[email protected] [email protected] [email protected]
[email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test "email validation should reject invalid addresses" do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "email addresses should be saved as lower-case" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
test "authenticated? should return false for a user with nil digest" do
#assert_not @user.authenticated?('')
assert_not @user.authenticated?(:remember, '')
end
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
test "should follow and unfollow a user" do
michael = users(:michael)
archer = users(:archer)
assert_not michael.following?(archer)
michael.follow(archer)
assert michael.following?(archer)
assert archer.followers.include?(michael)
michael.unfollow(archer)
assert_not michael.following?(archer)
end
test "feed should have the right posts" do
michael = users(:michael)
archer = users(:archer)
lana = users(:lana)
# Posts from followed user
lana.microposts.each do |post_following|
assert michael.feed.include?(post_following)
end
# Posts from self
michael.microposts.each do |post_self|
assert michael.feed.include?(post_self)
end
# Posts from unfollowed user
archer.microposts.each do |post_unfollowed|
assert_not michael.feed.include?(post_unfollowed)
end
end
end
| 29.108108 | 78 | 0.67688 |
e9b7980b037dfd61a8ea63eaa6e9d8d0882e7fef | 337 | class DynamicWorker < Packet::Worker
set_worker_name :dynamic_worker
set_no_auto_load true
def worker_init
p "Starting dynamic worker"
p worker_options
end
def receive_data data_obj
eval_data = eval(data_obj[:data])
data_obj[:data] = eval_data
data_obj[:type] = :response
send_data(data_obj)
end
end
| 21.0625 | 37 | 0.727003 |
ed3116f348b3ca128fd530a3df60ae620a6d361c | 7,849 | module StudiesHelper
def search_value(search_params, key)
if !search_params.nil? and search_params.has_key?(key)
return search_params[key]
end
end
def determine_contacts(trial)
contact_suffix = @system_info.contact_email_suffix
if !trial.contact_override.blank?
# Always use the override, if available.
return [{
email: trial.contact_override,
first_name: trial.contact_override_first_name,
last_name: trial.contact_override_last_name
}]
elsif !contact_suffix.nil? and (
( !trial.contact_email.nil? and trial.contact_email.include?(contact_suffix) ) or
( !trial.contact_backup_email.nil? and trial.contact_backup_email.include?(contact_suffix) )
)
contacts = []
if !trial.contact_email.nil? && trial.contact_email.include?(contact_suffix)
contacts << {
email: trial.contact_email,
first_name: trial.contact_first_name,
last_name: trial.contact_last_name
}
end
if !trial.contact_backup_email.nil? && trial.contact_backup_email.include?(contact_suffix)
contacts << {
email: trial.contact_backup_email,
first_name: trial.contact_backup_first_name,
last_name: trial.contact_backup_last_name
}
end
return contacts
elsif (!trial.contact_email.nil? or !trial.contact_backup_email.nil?) and contact_suffix.nil?
# Use the overall contacts, if appropriate.
contacts = []
if !trial.contact_email.nil?
contacts << {
email: trial.contact_email,
first_name: trial.contact_first_name,
last_name: trial.contact_last_name
}
end
if !trial.contact_backup_email.nil?
contacts << {
email: trial.contact_backup_email,
first_name: trial.contact_backup_first_name,
last_name: trial.contact_backup_last_name
}
end
return contacts
elsif !trial.trial_locations.empty? && !contact_suffix.nil?
# Overall contacts didn't work, search within locations.
contacts = contacts_by_location(trial.trial_locations)
if !contacts.empty?
return contacts
else
return default_email
end
else
# Return the default email specified in the administrator.
return default_email
end
end
def determine_contact_method(trial)
if !trial.contact_url_override.blank? || !trial.contact_url.blank?
return 'url'
else
return 'email'
end
end
def render_contact_url(trial)
unless trial.contact_url_override.blank?
return trial.contact_url_override
else
return trial.contact_url
end
end
def default_email
return [{
email: @system_info.default_email
}]
end
def contacts_by_location(locations)
location_contacts = []
locations.each do |x|
if !x.email.nil? && x.email.include?(@system_info.contact_email_suffix)
location_contacts << {
email: x.email,
last_name: x.last_name
}
end
if !x.backup_email.nil? && x.backup_email.include?(@system_info.contact_email_suffix)
location_contacts << {
email: x.backup_email,
last_name: x.backup_last_name
}
end
end
return location_contacts
end
def remove_category_param
p = params.dup
p[:search] = p[:search].except('category')
return "#{request.path}?#{p.to_unsafe_h.to_query}"
end
def eligibility_display(gender)
unless gender.blank?
if gender == 'Both'
'Male or Female'
else
gender
end
end
end
def render_healthy_volunteers(study)
return nil if study.healthy_volunteers.nil?
rendered = '<div class="healthy-message" data-toggle="popover" data-title="Healthy Volunteer" data-content="A person who does not have the condition or disease being studied." data-placement="top">'
if study.healthy_volunteers == true
rendered = rendered + '<i class="fa fa-check-circle"></i>This study is also accepting healthy volunteers <i class="fa fa-question-circle"></i>'
else
rendered = rendered + '<i class="fa fa-exclamation-triangle"></i>This study is NOT accepting healthy volunteers <i class="fa fa-question-circle"></i>'
end
rendered = rendered + '</div>'
return rendered.html_safe
end
def render_age_display(study)
return nil if study.min_age_unit.nil? && study.max_age_unit.nil?
if (study.respond_to?(:min_age_unit) && study.respond_to?(:max_age_unit))
age_display_units(study.min_age_unit, study.max_age_unit)
else
age_display(study.min_age, study.max_age)
end
end
def age_display_units(min_age_unit, max_age_unit)
if min_age_unit == 'N/A' and max_age_unit != 'N/A'
return "up to #{max_age_unit} old"
elsif min_age_unit != 'N/A' and max_age_unit == 'N/A'
return "#{min_age_unit} and over"
elsif min_age_unit == 'N/A' and max_age_unit == 'N/A'
return "Not specified"
else
return "#{min_age_unit} to #{max_age_unit} old"
end
end
def age_display(min_age, max_age)
age = ''
unless (min_age.nil? and max_age.nil?) or (min_age == 0 and max_age == 1000)
unless min_age.nil? or min_age == 0
unless (min_age % 1).zero?
# There is a decimal value. Let's convert it.
age << "#{(min_age * 12).round} month(s)"
else
age << "#{min_age.to_i} year(s)"
end
else
age << 'up to '
end
unless max_age.nil? or max_age == 1000
unless age.include?('to')
age << " to "
end
unless (max_age % 1).zero?
# There is a decimal value. Let's convert it.
age << "#{(max_age * 12).round} month(s) old"
else
age << "#{max_age.to_i} year(s) old"
end
else
age << ' and over'
end
else
age << 'Not specified'
end
age
end
def contacts_display(c)
contacts = ''
c.each do |contact|
unless contact[:first_name].nil?
contacts << "#{contact[:first_name]} "
end
unless contact[:last_name].nil?
contacts << "#{contact[:last_name]} - "
end
contacts << "#{contact[:email]}<br>"
end
contacts.html_safe
end
def site(site)
site_name = site.site_name
unless site.city.blank?
site_name = site_name + ' - ' + site.city
end
unless site.state.blank?
site_name = site_name + ', ' + site.state
end
return site_name
end
def render_attribute(settings, key, page, attribute, new_line = false)
setting = settings.select{|x|x.attribute_key == key}.first
rendered = ''
return rendered if setting.nil?
open_tag = (new_line == false ? '<span class="nomargin">' : '<p class="nomargin">')
close_tag = (new_line == false ? '</span>' : '</p>')
if page == 'show' && setting.display_on_show && !(setting.display_if_null_on_show == false && (attribute.nil? || attribute.blank?))
#configured to show up on the page unless attribute is nil
rendered = rendered + '<label class="nomargin strong">' + setting.attribute_label + '</label> ' if setting.display_label_on_show
rendered = rendered + open_tag + attribute.to_s + close_tag
elsif page == 'list' && setting.display_on_list && !(setting.display_if_null_on_list == false && (attribute.nil? || attribute.blank?))
rendered = rendered + '<label class="nomargin strong">' + setting.attribute_label + '</label> ' if setting.display_label_on_list
rendered = rendered + open_tag + attribute.to_s + close_tag
end
rendered = '<div data-attribute-name=' + setting.attribute_key + '>' + rendered + '</div>' unless rendered == ''
return rendered.html_safe
end
end | 31.146825 | 202 | 0.639827 |
79c97a1b693a2336a819c2f83e46c79edbafce99 | 1,853 | #
# Copyright:: Copyright 2017, Chef Software, 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 "spec_helper"
describe Chef::HTTP::APIVersions do
class TestVersionClient < Chef::HTTP
use Chef::HTTP::APIVersions
end
before do
Chef::ServerAPIVersions.instance.reset!
end
let(:method) { "GET" }
let(:url) { "http://dummy.com" }
let(:headers) { {} }
let(:data) { false }
let(:request) {}
let(:return_value) { "200" }
# Test Variables
let(:response_body) { "Thanks for checking in." }
let(:response_headers) do
{
"x-ops-server-api-version" => { "min_version" => 0, "max_version" => 2 },
}
end
let(:response) do
m = double("HttpResponse", :body => response_body)
allow(m).to receive(:key?).with("x-ops-server-api-version").and_return(true)
allow(m).to receive(:[]) do |key|
response_headers[key]
end
m
end
let(:middleware) do
client = TestVersionClient.new(url)
client.middlewares[0]
end
def run_api_version_handler
middleware.handle_request(method, url, headers, data)
middleware.handle_response(response, request, return_value)
end
it "correctly stores server api versions" do
run_api_version_handler
expect(Chef::ServerAPIVersions.instance.min_server_version).to eq(0)
end
end
| 26.471429 | 80 | 0.695629 |
1855d4c7b6ee64e6a1714eb9eab6bbbef5ddcd3e | 48 | json.partial! "sayings/saying", saying: @saying
| 24 | 47 | 0.75 |
398226a2312468485bc31aaea3b8d1a37394db60 | 43 | module FlickrOAuth
VERSION = "0.0.2"
end
| 10.75 | 19 | 0.697674 |
e2abd1238c57c50b3760a8b9c2f5bf3de0c70da3 | 2,907 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Projects::Pipelines::TestsController do
let(:user) { create(:user) }
let(:project) { create(:project, :public, :repository) }
let(:pipeline) { create(:ci_pipeline, project: project) }
before do
sign_in(user)
end
describe 'GET #summary.json' do
context 'when pipeline has build report results' do
let(:pipeline) { create(:ci_pipeline, :with_report_results, project: project) }
it 'renders test report summary data' do
get_tests_summary_json
expect(response).to have_gitlab_http_status(:ok)
expect(json_response['total_count']).to eq(2)
end
end
context 'when pipeline does not have build report results' do
it 'renders test report summary data' do
get_tests_summary_json
expect(response).to have_gitlab_http_status(:ok)
expect(json_response['total_count']).to eq(0)
end
end
context 'when feature is disabled' do
before do
stub_feature_flags(build_report_summary: false)
end
it 'returns 404' do
get_tests_summary_json
expect(response).to have_gitlab_http_status(:not_found)
expect(response.body).to be_empty
end
end
end
describe 'GET #show.json' do
context 'when pipeline has build report results' do
let(:pipeline) { create(:ci_pipeline, :with_report_results, project: project) }
let(:suite_name) { 'test' }
let(:build_ids) { pipeline.latest_builds.pluck(:id) }
it 'renders test suite data' do
get_tests_show_json(build_ids)
expect(response).to have_gitlab_http_status(:ok)
expect(json_response['name']).to eq('test')
end
end
context 'when pipeline does not have build report results' do
let(:pipeline) { create(:ci_empty_pipeline) }
let(:suite_name) { 'test' }
it 'renders 404' do
get_tests_show_json([])
expect(response).to have_gitlab_http_status(:not_found)
expect(response.body).to be_empty
end
end
context 'when feature is disabled' do
let(:suite_name) { 'test' }
before do
stub_feature_flags(build_report_summary: false)
end
it 'returns 404' do
get_tests_show_json([])
expect(response).to have_gitlab_http_status(:not_found)
expect(response.body).to be_empty
end
end
end
def get_tests_summary_json
get :summary,
params: {
namespace_id: project.namespace,
project_id: project,
pipeline_id: pipeline.id
},
format: :json
end
def get_tests_show_json(build_ids)
get :show,
params: {
namespace_id: project.namespace,
project_id: project,
pipeline_id: pipeline.id,
suite_name: suite_name,
build_ids: build_ids
},
format: :json
end
end
| 25.725664 | 85 | 0.651531 |
398af035216eb5639a8b25f65b0765cf8d571767 | 2,351 | # frozen_string_literal: true
# == Schema Information
#
# Table name: inboxes
#
# id :integer not null, primary key
# channel_type :string
# email_address :string
# enable_auto_assignment :boolean default(TRUE)
# greeting_enabled :boolean default(FALSE)
# greeting_message :string
# name :string not null
# out_of_office_message :string
# timezone :string default("UTC")
# working_hours_enabled :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
# account_id :integer not null
# channel_id :integer not null
#
# Indexes
#
# index_inboxes_on_account_id (account_id)
#
class Inbox < ApplicationRecord
include Reportable
include Avatarable
include OutOfOffisable
validates :account_id, presence: true
validates :timezone, inclusion: { in: TZInfo::Timezone.all_identifiers }
belongs_to :account
belongs_to :channel, polymorphic: true, dependent: :destroy
has_many :contact_inboxes, dependent: :destroy
has_many :contacts, through: :contact_inboxes
has_many :inbox_members, dependent: :destroy
has_many :members, through: :inbox_members, source: :user
has_many :conversations, dependent: :destroy
has_many :messages, through: :conversations
has_one :agent_bot_inbox, dependent: :destroy
has_one :agent_bot, through: :agent_bot_inbox
has_many :webhooks, dependent: :destroy
has_many :hooks, dependent: :destroy, class_name: 'Integrations::Hook'
after_destroy :delete_round_robin_agents
scope :order_by_name, -> { order('lower(name) ASC') }
def add_member(user_id)
member = inbox_members.new(user_id: user_id)
member.save!
end
def remove_member(user_id)
member = inbox_members.find_by(user_id: user_id)
member.try(:destroy)
end
def facebook?
channel.class.name.to_s == 'Channel::FacebookPage'
end
def web_widget?
channel.class.name.to_s == 'Channel::WebWidget'
end
def inbox_type
channel.name
end
def webhook_data
{
id: id,
name: name
}
end
private
def delete_round_robin_agents
::RoundRobin::ManageService.new(inbox: self).clear_queue
end
end
| 25.835165 | 74 | 0.668226 |
7a5374478e5572ad6f19cb7ae10c7afe24970932 | 574 | require 'test_helper'
class TalkTest < ActiveSupport::TestCase
def setup
@talk = Talk.create
10.times do |t|
user = users("user_#{t}".to_sym)
@talk.memberships.create(user: user)
@talk.messages.create(user: user, content: Faker::Lorem.sentence(5))
end
end
test "assosiated memberships should be destroyed" do
assert_difference "Membership.count", -10 do
@talk.destroy
end
end
test "assosiated messages should be destroyed" do
assert_difference "Message.count", -10 do
@talk.destroy
end
end
end
| 22.076923 | 74 | 0.667247 |
f741b5c76a64280da877a98b4c1bade421a78996 | 1,338 | class Cowsay < Formula
desc "Configurable talking characters in ASCII art"
# Historical homepage: https://web.archive.org/web/20120225123719/www.nog.net/~tony/warez/cowsay.shtml
homepage "https://github.com/tnalpgge/rank-amateur-cowsay"
url "https://github.com/tnalpgge/rank-amateur-cowsay/archive/cowsay-3.04.tar.gz"
sha256 "d8b871332cfc1f0b6c16832ecca413ca0ac14d58626491a6733829e3d655878b"
license "GPL-3.0"
revision 1
bottle do
cellar :any_skip_relocation
sha256 "422c58f10fc2441a62a90864d01b83176ebda627f9a8c29b34f89f4f1f86618e" => :big_sur
sha256 "dc3cb88861e89bb415d3b1be1b5314514174349bb44338551e80badc4da94542" => :arm64_big_sur
sha256 "c1f4af994e038a18492c8afe0f6b97cfd1c475fe62eafe68762cf5d734dc214d" => :catalina
sha256 "faebbfa7a9379fd4efddc43dc167fda055989d2936b0430e404c252a555439cc" => :mojave
sha256 "4cdddb22ad76cf14527347e58317caf1495dc88fdf5d6c729ac72fa2fe19dd81" => :high_sierra
end
def install
# Remove offensive content
%w[cows/sodomized.cow cows/telebears.cow].each do |file|
rm file
inreplace "Files.base", file, ""
end
system "/bin/sh", "install.sh", prefix
mv prefix/"man", share
end
test do
output = shell_output("#{bin}/cowsay moo")
assert_match "moo", output # bubble
assert_match "^__^", output # cow
end
end
| 37.166667 | 104 | 0.760837 |
4a30398df795c0020494159423f33ab778f922a3 | 6,104 | # frozen_string_literal: true
# Copyright 2019 OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
require 'test_helper'
describe OpenTelemetry::SDK::Trace::Samplers do
Samplers = OpenTelemetry::SDK::Trace::Samplers
describe '.ALWAYS_ON' do
it 'samples' do
_(call_sampler(Samplers::ALWAYS_ON)).must_be :sampled?
end
end
describe '.ALWAYS_OFF' do
it 'does not sample' do
_(call_sampler(Samplers::ALWAYS_OFF)).wont_be :sampled?
end
end
describe '.ALWAYS_PARENT' do
it 'samples if parent is sampled' do
context = OpenTelemetry::Trace::SpanContext.new(
trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(1)
)
_(call_sampler(Samplers::ALWAYS_PARENT, parent_context: context)).must_be :sampled?
end
it 'does not sample if parent is not sampled' do
context = OpenTelemetry::Trace::SpanContext.new(
trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(0)
)
_(call_sampler(Samplers::ALWAYS_PARENT, parent_context: context)).wont_be :sampled?
end
it 'does not sample root spans' do
_(call_sampler(Samplers::ALWAYS_PARENT, parent_context: nil)).wont_be :sampled?
end
end
describe '.probability' do
let(:sampler) { Samplers.probability(Float::MIN) }
let(:context) do
OpenTelemetry::Trace::SpanContext.new(
trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(1)
)
end
it 'respects parent sampling' do
result = call_sampler(sampler, parent_context: context)
_(result).must_be :sampled?
end
it 'ignores parent sampling if ignore_parent' do
sampler = Samplers.probability(Float::MIN, ignore_parent: true)
result = call_sampler(sampler, parent_context: context, trace_id: trace_id(123))
_(result).wont_be :sampled?
end
it 'returns a result' do
result = call_sampler(sampler, trace_id: trace_id(123))
_(result).must_be_instance_of(Result)
end
it 'samples if probability is 1' do
positive = Samplers.probability(1)
result = call_sampler(positive, trace_id: 'f' * 32)
_(result).must_be :sampled?
end
it 'does not sample if probability is 0' do
sampler = Samplers.probability(0)
result = call_sampler(sampler, trace_id: trace_id(1))
_(result).wont_be :sampled?
end
it 'does not sample a remote parent if apply_probability_to == :root_spans' do
context = OpenTelemetry::Trace::SpanContext.new(
trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(0),
remote: true
)
sampler = Samplers.probability(1, apply_probability_to: :root_spans)
result = call_sampler(sampler, parent_context: context)
_(result).wont_be :sampled?
end
it 'samples a local child span if apply_probability_to == :all_spans' do
sampler = Samplers.probability(1, apply_probability_to: :all_spans)
result = call_sampler(sampler, parent_context: context, trace_id: trace_id(1))
_(result).must_be :sampled?
end
it 'samples a remote parent if apply_probability_to == :root_spans_and_remote_parent' do
context = OpenTelemetry::Trace::SpanContext.new(
trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(0),
remote: true
)
sampler = Samplers.probability(1, apply_probability_to: :root_spans_and_remote_parent)
result = call_sampler(sampler, parent_context: context)
_(result).must_be :sampled?
end
it 'does not sample a local child span if apply_probability_to == :root_spans_and_remote_parent' do
context = OpenTelemetry::Trace::SpanContext.new(trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(0))
sampler = Samplers.probability(1, apply_probability_to: :root_spans_and_remote_parent)
result = call_sampler(sampler, parent_context: context, trace_id: trace_id(1))
_(result).wont_be :sampled?
end
it 'does not sample a local child span if apply_probability_to == :root_spans' do
context = OpenTelemetry::Trace::SpanContext.new(trace_flags: OpenTelemetry::Trace::TraceFlags.from_byte(0))
sampler = Samplers.probability(1, apply_probability_to: :root_spans)
result = call_sampler(sampler, parent_context: context, trace_id: trace_id(1))
_(result).wont_be :sampled?
end
it 'does not allow invalid symbols in apply_probability_to' do
_(proc { Samplers.probability(1, apply_probability_to: :foo) }).must_raise(ArgumentError)
end
it 'samples the smallest probability larger than the smallest trace_id' do
probability = 2.0 / (2**64 - 1)
sampler = Samplers.probability(probability)
result = call_sampler(sampler, trace_id: trace_id(1))
_(result).must_be :sampled?
end
it 'does not sample the largest trace_id with probability less than 1' do
probability = 1.0.prev_float
sampler = Samplers.probability(probability)
result = call_sampler(sampler, trace_id: trace_id(0xffff_ffff_ffff_ffff))
_(result).wont_be :sampled?
end
it 'ignores the high bits of the trace_id for sampling' do
sampler = Samplers.probability(0.5)
result = call_sampler(sampler, trace_id: trace_id(0x1_0000_0000_0000_0001))
_(result).must_be :sampled?
end
it 'limits probability to the range (0...1)' do
_(proc { Samplers.probability(-1) }).must_raise(ArgumentError)
_(Samplers.probability(0)).wont_be_nil
_(Samplers.probability(0.5)).wont_be_nil
_(Samplers.probability(1)).wont_be_nil
_(proc { Samplers.probability(2) }).must_raise(ArgumentError)
end
end
def trace_id(id)
format('%032x', id)
end
def call_sampler(sampler, trace_id: nil, span_id: nil, parent_context: nil, links: nil, name: nil, kind: nil, attributes: nil)
sampler.call(
trace_id: trace_id || OpenTelemetry::Trace.generate_trace_id,
span_id: span_id || OpenTelemetry::Trace.generate_span_id,
parent_context: parent_context,
links: links,
name: name,
kind: kind,
attributes: attributes
)
end
end
| 36.118343 | 128 | 0.70036 |
6af35510d19032807fcbbc1a95f5ac96229f9a0a | 23,372 | # -*- coding: utf-8 -*-
# Copyright (C) iWeb Technologies 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.
#
# Author: Francois Charlier <[email protected]>
# Author: David Moreau Simard <[email protected]>
# Author: Andrew Woodward <xarses>
require 'spec_helper'
describe 'ceph::repo' do
describe 'Debian' do
let :facts do
{
:osfamily => 'Debian',
:lsbdistid => 'Debian',
:lsbdistcodename => 'jessie',
:lsbdistrelease => '8',
}
end
describe "with default params" do
it { is_expected.to contain_apt__key('ceph').with(
:id => '08B73419AC32B4E966C1A330E84AC2C0460F3994',
:source => 'https://download.ceph.com/keys/release.asc',
:before => 'Apt::Source[ceph]',
) }
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://download.ceph.com/debian-mimic/',
:release => 'jessie',
) }
end
describe "when overriding ceph mirror" do
let :params do
{
:ceph_mirror => 'http://myserver.com/debian-mimic/'
}
end
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://myserver.com/debian-mimic/',
:release => 'jessie',
) }
end
describe "when overriding ceph release" do
let :params do
{
:release => 'firefly'
}
end
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://download.ceph.com/debian-firefly/',
:release => 'jessie',
) }
end
end
describe 'Ubuntu' do
let :facts do
{
:osfamily => 'Debian',
:lsbdistid => 'Ubuntu',
:lsbdistcodename => 'trusty',
:lsbdistrelease => '14.04',
:hardwaremodel => 'x86_64',
}
end
describe "with default params" do
it { is_expected.to contain_apt__key('ceph').with(
:id => '08B73419AC32B4E966C1A330E84AC2C0460F3994',
:source => 'https://download.ceph.com/keys/release.asc',
:before => 'Apt::Source[ceph]',
) }
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://download.ceph.com/debian-mimic/',
:release => 'trusty',
) }
end
describe "when overriding ceph release" do
let :params do
{
:release => 'firefly'
}
end
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://download.ceph.com/debian-firefly/',
:release => 'trusty',
) }
end
describe "when wanting fast-cgi" do
let :params do
{
:fastcgi => true
}
end
it { is_expected.to contain_apt__key('ceph-gitbuilder').with(
:id => 'FCC5CB2ED8E6F6FB79D5B3316EAEAE2203C3951A',
:server => 'keyserver.ubuntu.com',
) }
it { is_expected.to contain_apt__source('ceph').with(
:location => 'http://download.ceph.com/debian-mimic/',
:release => 'trusty',
) }
it { is_expected.to contain_apt__source('ceph-fastcgi').with(
:ensure => 'present',
:location => 'http://gitbuilder.ceph.com/libapache-mod-fastcgi-deb-trusty-x86_64-basic/ref/master',
:release => 'trusty',
:require => 'Apt::Key[ceph-gitbuilder]'
) }
end
describe "with ensure => absent to disable" do
let :params do
{
:ensure => 'absent',
:fastcgi => true
}
end
it { is_expected.to contain_apt__source('ceph').with(
:ensure => 'absent',
:location => 'http://download.ceph.com/debian-mimic/',
:release => 'trusty',
) }
it { is_expected.to contain_apt__source('ceph-fastcgi').with(
:ensure => 'absent',
:location => 'http://gitbuilder.ceph.com/libapache-mod-fastcgi-deb-trusty-x86_64-basic/ref/master',
:release => 'trusty',
:require => 'Apt::Key[ceph-gitbuilder]'
) }
end
end
describe 'RHEL7' do
let :facts do
{
:osfamily => 'RedHat',
:operatingsystem => 'RedHat',
:operatingsystemmajrelease => '7',
}
end
describe "with default params" do
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
end
describe "when overriding ceph release" do
let :params do
{
:release => 'firefly'
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph firefly',
:name => 'ext-ceph-firefly',
:baseurl => 'http://download.ceph.com/rpm-firefly/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-firefly-noarch',
:baseurl => 'http://download.ceph.com/rpm-firefly/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
end
describe "when disabling EPEL" do
let :params do
{
:enable_epel => false,
}
end
it { is_expected.to_not contain_yumrepo('ext-epel-7') }
end
describe "when using a proxy for yum repositories" do
let :params do
{
:proxy => 'http://someproxy.com:8080/',
:proxy_username => 'proxyuser',
:proxy_password => 'proxypassword'
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
:proxy => 'http://someproxy.com:8080/',
:proxy_username => 'proxyuser',
:proxy_password => 'proxypassword',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10',
:proxy => 'http://someproxy.com:8080/',
:proxy_username => 'proxyuser',
:proxy_password => 'proxypassword',
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10',
:proxy => 'http://someproxy.com:8080/',
:proxy_username => 'proxyuser',
:proxy_password => 'proxypassword',
) }
end
describe "with ensure => absent to disable" do
let :params do
{
:ensure => 'absent',
:fastcgi => true
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '0',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '0',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '0',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-fastcgi').with(
:enabled => '0',
:descr => 'FastCGI basearch packages for Ceph',
:name => 'ext-ceph-fastcgi',
:baseurl => 'http://gitbuilder.ceph.com/mod_fastcgi-rpm-rhel7-x86_64-basic/ref/master',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/autobuild.asc',
:mirrorlist => 'absent',
:priority => '20'
) }
end
describe "with ceph fast-cgi" do
let :params do
{
:fastcgi => true
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-fastcgi').with(
:enabled => '1',
:descr => 'FastCGI basearch packages for Ceph',
:name => 'ext-ceph-fastcgi',
:baseurl => 'http://gitbuilder.ceph.com/mod_fastcgi-rpm-rhel7-x86_64-basic/ref/master',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/autobuild.asc',
:mirrorlist => 'absent',
:priority => '20'
) }
end
end
describe 'CentOS7' do
let :facts do
{
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:operatingsystemmajrelease => '7',
}
end
describe "with default params" do
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
end
describe "when overriding ceph release" do
let :params do
{
:release => 'firefly'
}
end
it { is_expected.to contain_file_line('exclude base').with(
:ensure => 'present',
:path => '/etc/yum.repos.d/CentOS-Base.repo',
:after => '^\[base\]$',
:line => 'exclude=python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph firefly',
:name => 'ext-ceph-firefly',
:baseurl => 'http://download.ceph.com/rpm-firefly/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-firefly-noarch',
:baseurl => 'http://download.ceph.com/rpm-firefly/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
end
describe "when using CentOS SIG repository" do
let :params do
{
:enable_sig => true,
}
end
it { is_expected.to_not contain_file_line('exclude base') }
it { is_expected.to_not contain_yumrepo('ext-epel-7') }
it { is_expected.to_not contain_yumrepo('ext-ceph') }
it { is_expected.to_not contain_yumrepo('ext-ceph-noarch') }
it { is_expected.to contain_yumrepo('ceph-luminous-sig').with_ensure('absent') }
it { is_expected.to contain_yumrepo('ceph-storage-sig').with(
:baseurl => 'https://buildlogs.centos.org/centos/7/storage/x86_64/ceph-mimic/',
) }
end
describe "when using CentOS SIG repository from a mirror" do
let :params do
{
:enable_sig => true,
:ceph_mirror => 'https://mymirror/luminous/',
}
end
it { is_expected.to_not contain_file_line('exclude base') }
it { is_expected.to_not contain_yumrepo('ext-epel-7') }
it { is_expected.to_not contain_yumrepo('ext-ceph') }
it { is_expected.to_not contain_yumrepo('ext-ceph-noarch') }
it { is_expected.to contain_yumrepo('ceph-luminous-sig').with_ensure('absent') }
it { is_expected.to contain_yumrepo('ceph-storage-sig').with(
:baseurl => 'https://mymirror/luminous/',
) }
end
describe "with ensure => absent to disable" do
let :params do
{
:ensure => 'absent',
:fastcgi => true
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '0',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '0',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '0',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-fastcgi').with(
:enabled => '0',
:descr => 'FastCGI basearch packages for Ceph',
:name => 'ext-ceph-fastcgi',
:baseurl => 'http://gitbuilder.ceph.com/mod_fastcgi-rpm-rhel7-x86_64-basic/ref/master',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/autobuild.asc',
:mirrorlist => 'absent',
:priority => '20'
) }
end
describe "with ceph fast-cgi" do
let :params do
{
:fastcgi => true
}
end
it { is_expected.not_to contain_file_line('exclude base') }
it { is_expected.to contain_yumrepo('ext-epel-7').with(
:enabled => '1',
:descr => 'External EPEL 7',
:name => 'ext-epel-7',
:baseurl => 'absent',
:gpgcheck => '1',
:gpgkey => 'https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7',
:mirrorlist => 'http://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch',
:priority => '20',
:exclude => 'python-ceph-compat python-rbd python-rados python-cephfs',
) }
it { is_expected.to contain_yumrepo('ext-ceph').with(
:enabled => '1',
:descr => 'External Ceph mimic',
:name => 'ext-ceph-mimic',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/$basearch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-noarch').with(
:enabled => '1',
:descr => 'External Ceph noarch',
:name => 'ext-ceph-mimic-noarch',
:baseurl => 'http://download.ceph.com/rpm-mimic/el7/noarch',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/release.asc',
:mirrorlist => 'absent',
:priority => '10'
) }
it { is_expected.to contain_yumrepo('ext-ceph-fastcgi').with(
:enabled => '1',
:descr => 'FastCGI basearch packages for Ceph',
:name => 'ext-ceph-fastcgi',
:baseurl => 'http://gitbuilder.ceph.com/mod_fastcgi-rpm-rhel7-x86_64-basic/ref/master',
:gpgcheck => '1',
:gpgkey => 'https://download.ceph.com/keys/autobuild.asc',
:mirrorlist => 'absent',
:priority => '20'
) }
end
end
end
| 33.921626 | 107 | 0.535898 |
4abc1b74c937bc39e2c7aa083db91491577b8764 | 1,204 | cask 'wine-devel' do
version '3.12'
sha256 '46604a64f7651df883030ea578b1039cbabb7c93bf7e030de713967f17f455b1'
url "https://dl.winehq.org/wine-builds/macosx/pool/winehq-devel-#{version}.pkg"
appcast 'https://dl.winehq.org/wine-builds/macosx/download.html'
name 'WineHQ-devel'
homepage 'https://wiki.winehq.org/MacOS'
depends_on x11: true
pkg "winehq-devel-#{version}.pkg",
choices: [
{
'choiceIdentifier' => 'choice3',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
]
uninstall pkgutil: [
'org.winehq.wine-devel',
'org.winehq.wine-devel-deps',
'org.winehq.wine-devel-deps64',
'org.winehq.wine-devel32',
'org.winehq.wine-devel64',
],
delete: '/Applications/Wine Devel.app'
caveats <<~EOS
#{token} installs support for running 64 bit applications in Wine, which is considered experimental.
If you do not want 64 bit support, you should download and install the #{token} package manually.
EOS
end
| 34.4 | 104 | 0.570598 |
1ac634ce1cdb07fcdb42196bfafb0fc67565923e | 627 | module Glysellin
class Property < ActiveRecord::Base
self.table_name = 'glysellin_properties'
has_many :variant_properties, class_name: 'Glysellin::VariantProperty',
dependent: :destroy, inverse_of: :variant
has_many :variants, class_name: 'Glysellin::Variant',
through: :variant_properties
has_many :sellables, through: :variants
belongs_to :property_type, class_name: 'Glysellin::PropertyType'
validates :value, presence: true
def name
[property_type.try(:name).presence, value.presence].compact.join(' - ')
end
end
end
| 29.857143 | 77 | 0.666667 |
21725bb0074149e21503af3079db5b0c25809e63 | 228 | # frozen_string_literal: true
class Speciality < ApplicationRecord
has_many :diseases, dependent: :destroy
belongs_to :user
has_many :doctors
validates :name, presence: true
validates :created_by, presence: true
end
| 20.727273 | 41 | 0.776316 |
62ed7fe69b06b3e625eb2246560616dfa14167af | 3,945 | require 'gisele'
module Gisele
#
# Gisele - A Process Analyzer Toolset
#
# SYNOPSIS
# gisele [--version] [--help]
# gisele [--ast | --graph] PROCESS_FILE
#
# OPTIONS
# #{summarized_options}
#
# DESCRIPTION
# The Gisele process analyzer toolset provides tools and technique to model and analyze
# complex process models such as care processes.
#
# When --no-sugar is specified, syntactic sugar is first removed before making any other
# transformation. For now, this rewrites all `if` statements as explicit `case` guarded
# commands.
#
# When --ast is used, the command parses the process file and prints its Abstract Syntax
# Tree (AST) on standard output. By default, this option prints the AST for manual
# debugging, that is with colors and extra information. Use --ast=ruby to get a ruby
# array for automatic processing.
#
# When --graph is used, the command parses the process file. It then converts the AST into
# a directed graph representing the process as a box-and-arrow workflow and outputs it on
# standard output. For now, the only output format available is dot (from graphviz).
#
class Gisele::Command < Quickl::Command(__FILE__, __LINE__)
# Install options
options do |opt|
@sugar = true
opt.on('--no-sugar', 'Apply syntactic sugar removal') do
@sugar = false
end
@compile_mode = [:ast, "debug"]
opt.on('--ast=[MODE]',
'Compile as an abstract syntax tree (debug,ruby)') do |value|
@compile_mode = [:ast, (value || "debug").to_sym]
end
opt.on('--graph=[MODE]',
'Compile as a workflow graph (dot)') do |value|
@compile_mode = [:graph, (value || "dot").to_sym]
end
opt.on('--glts=[MODE]',
'Compile as guarded labeled transition system (dot)') do |value|
@compile_mode = [:glts, (value || "dot").to_sym]
end
opt.on('-d', '--deterministic',
'Determinize gtls output?') do
@determinize = true
end
opt.on('-e', '--explicit',
'Explicit guards in gtls output?') do
@explicit = true
end
opt.on('-s', '--separate',
'Split guards from events in glts output?') do
@separate = true
end
opt.on_tail('--help', "Show this help message") do
raise Quickl::Help
end
opt.on_tail('--version', 'Show version and exit') do
raise Quickl::Exit, "gisele #{Gisele::VERSION} (c) The University of Louvain"
end
end
def execute(args)
raise Quickl::Help unless args.size == 1
unless (file = Path(args.first)).exist?
raise Quickl::IOAccessError, "File does not exists: #{file}"
end
ast = Gisele.ast(file)
ast = Language::SugarRemoval.call(ast) unless @sugar
send :"compile_#{@compile_mode.first}", ast, *@compile_mode[1..-1]
end
private
def compile_ast(ast, option)
require 'awesome_print'
options = {}
options = {index: false, plain: true} if option == :ruby
ap ast, options
end
def compile_graph(ast, option)
graph = Analysis::Compiling::Ast2Graph.call(ast)
puts graph.to_dot
end
def compile_glts(ast, mode)
session = Analysis::Compiling::Ast2Session.call(ast)
glts = Analysis::Compiling::Ast2Glts.call(session, ast)
glts = glts.determinize if @determinize
glts = glts.separate if @separate
glts = glts.explicit_guards! if @explicit
case mode
when :dot then puts glts.to_dot
when :ruby then puts glts.to_ruby_literal
when :text then puts glts.to_relation.to_text
when :rash then puts glts.to_relation.to_rash
else
raise "Unrecognized --glts output mode `mode`"
end
ensure
session.close if session
end
end # class Command
end # module Gisele | 32.875 | 94 | 0.619772 |
bf0de4bd98e4077bba69f8d66a0104cff860518c | 274 | class CreateApplicationTexts < ActiveRecord::Migration
def self.up
create_table :application_texts do |t|
t.integer :application_for_offering_id
t.string :title
t.timestamps
end
end
def self.down
drop_table :application_texts
end
end
| 18.266667 | 54 | 0.718978 |
911ced90650fcb339d2db7cbecaae58dddc1bba3 | 2,046 | class Libmagic < Formula
desc "Implementation of the file(1) command"
homepage "https://www.darwinsys.com/file/"
url "https://astron.com/pub/file/file-5.39.tar.gz"
sha256 "f05d286a76d9556243d0cb05814929c2ecf3a5ba07963f8f70bfaaa70517fad1"
livecheck do
url "https://astron.com/pub/file/"
regex(/href=.*?file[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 arm64_big_sur: "e588a1adec77deda36340e9cce3375fde9ffcdabcd79ba86a429dbd14ea542fe"
sha256 big_sur: "2a09f46305a9457a2bfae1069cbf8f6a473d77f69a6370e67f67c0decc96ca0a"
sha256 catalina: "90b17cb74e853804227abdd32c6810ff535fb98e8862f946c49860b697faece0"
sha256 mojave: "f32eb14fbef470d28a041ddefec932e8d96870b4a13dbac3f61d8c6de6e50f29"
sha256 high_sierra: "110d2db0b588dc5a379124d024b228e8ee8aae58c95a6a0510e68dc36426a86a"
sha256 x86_64_linux: "fa24ab8447b58ec9cc2e1313ddbf3ccb75e626d2b0c63edf9d06a2e7dc65911d"
end
uses_from_macos "zlib"
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--enable-fsect-man5",
"--enable-static"
system "make", "install"
(share/"misc/magic").install Dir["magic/Magdir/*"]
# Don't dupe this system utility
rm bin/"file"
rm man1/"file.1"
end
test do
(testpath/"test.c").write <<~EOS
#include <assert.h>
#include <stdio.h>
#include <magic.h>
int main(int argc, char **argv) {
magic_t cookie = magic_open(MAGIC_MIME_TYPE);
assert(cookie != NULL);
assert(magic_load(cookie, NULL) == 0);
// Prints the MIME type of the file referenced by the first argument.
puts(magic_file(cookie, argv[1]));
}
EOS
system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lmagic", "-o", "test"
cp test_fixtures("test.png"), "test.png"
assert_equal "image/png", shell_output("./test test.png").chomp
end
end
| 35.894737 | 92 | 0.653959 |
bf0f5bbbd37ed2eac3fdb14d5d65a23c32be1cc0 | 3,999 | # frozen_string_literal: true
module DOTIW
class TimeHash
TIME_FRACTIONS = %i[seconds minutes hours days weeks months years].freeze
attr_reader :distance, :smallest, :largest, :from_time, :to_time
def initialize(distance, from_time, to_time = nil, options = {})
@output = {}
@options = options
@distance = distance
@from_time = from_time || Time.current
@to_time = to_time || (@to_time_not_given = true && @from_time + distance.seconds)
@smallest, @largest = [@from_time, @to_time].minmax
@to_time += 1.hour if @to_time_not_given && smallest.dst? && !largest.dst?
@to_time -= 1.hour if @to_time_not_given && !smallest.dst? && largest.dst?
@smallest, @largest = [@from_time, @to_time].minmax
@distance ||= begin
d = largest - smallest
d -= 1.hour if smallest.dst? && !largest.dst?
d += 1.hour if !smallest.dst? && largest.dst?
d
end
build_time_hash
end
def to_hash
output
end
private
attr_reader :options, :output
ONE_MINUTE = 1.minute.freeze
ONE_HOUR = 1.hour.freeze
ONE_DAY = 1.day.freeze
ONE_WEEK = 7.days.freeze
FOUR_WEEKS = 28.days.freeze
def build_time_hash
if accumulate_on = options.delete(:accumulate_on)
accumulate_on = accumulate_on.to_sym
return build_time_hash if accumulate_on == :years
TIME_FRACTIONS.index(accumulate_on).downto(0) { |i| send("build_#{TIME_FRACTIONS[i]}") }
else
while distance > 0
if distance < ONE_MINUTE
build_seconds
elsif distance < ONE_HOUR
build_minutes
elsif distance < ONE_DAY
build_hours
elsif distance < ONE_WEEK
build_days
elsif distance < FOUR_WEEKS
build_weeks
else # greater than a week
build_years_months_weeks_days
end
end
end
output
end
def build_seconds
output[:seconds] = distance.to_i
@distance = 0
end
def build_minutes
output[:minutes], @distance = distance.divmod(ONE_MINUTE.to_i)
end
def build_hours
output[:hours], @distance = distance.divmod(ONE_HOUR.to_i)
end
def build_days
output[:days], @distance = distance.divmod(ONE_DAY.to_i) unless output[:days]
end
def build_weeks
output[:weeks], @distance = distance.divmod(ONE_WEEK.to_i) unless output[:weeks]
end
def build_months
build_years_months_weeks_days
if (years = output.delete(:years)) > 0
output[:months] += (years * 12)
end
end
def build_years_months_weeks_days
months = (largest.year - smallest.year) * 12 + (largest.month - smallest.month)
years, months = months.divmod(12)
days = largest.day - smallest.day
weeks, days = days.divmod(7)
# Will otherwise incorrectly say one more day if our range goes over a day.
days -= 1 if largest.hour < smallest.hour
if days < 0
# Convert a week to days and add to total
weeks -= 1
days += 7
end
if weeks < 0
# Convert the last month to a week and add to total
months -= 1
last_month = largest.advance(months: -1)
days_in_month = Time.days_in_month(last_month.month, last_month.year)
weeks += days_in_month / 7
days += days_in_month % 7
if days >= 7
days -= 7
weeks += 1
end
if weeks == -1
months -= 1
weeks = 4
days -= 4
end
end
if months < 0
# Convert a year to months
years -= 1
months += 12
end
output[:years] = years
output[:months] = months
output[:weeks] = weeks
output[:days] = days
total_days, @distance = distance.abs.divmod(ONE_DAY.to_i)
[total_days, @distance]
end
end # TimeHash
end # DOTIW
| 26.309211 | 96 | 0.593148 |
d51c65882526a9f580083e42b12ee7bc1c59a2c0 | 1,784 | #! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/indirector/file_metadata/file'
describe Puppet::Indirector::FileMetadata::File do
it "should be registered with the file_metadata indirection" do
Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file).should equal(Puppet::Indirector::FileMetadata::File)
end
it "should be a subclass of the DirectFileServer terminus" do
Puppet::Indirector::FileMetadata::File.superclass.should equal(Puppet::Indirector::DirectFileServer)
end
describe "when creating the instance for a single found file" do
before do
@metadata = Puppet::Indirector::FileMetadata::File.new
@path = File.expand_path('/my/local')
@uri = Puppet::Util.path_to_uri(@path).to_s
@data = mock 'metadata'
@data.stubs(:collect)
FileTest.expects(:exists?).with(@path).returns true
@request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil)
end
it "should collect its attributes when a file is found" do
@data.expects(:collect)
Puppet::FileServing::Metadata.expects(:new).returns(@data)
@metadata.find(@request).should == @data
end
end
describe "when searching for multiple files" do
before do
@metadata = Puppet::Indirector::FileMetadata::File.new
@path = File.expand_path('/my/local')
@uri = Puppet::Util.path_to_uri(@path).to_s
@request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil)
end
it "should collect the attributes of the instances returned" do
FileTest.expects(:exists?).with(@path).returns true
@metadata.expects(:path2instances).returns( [mock("one", :collect => nil), mock("two", :collect => nil)] )
@metadata.search(@request)
end
end
end
| 34.980392 | 123 | 0.695628 |
1cc1683322c87a4ce59221ff7bbf2f2bd19feea1 | 668 | desc 'capistrano COMMAND', 'Run a capistrano command on all deploy targets'
long_desc <<-LONGDESC
Example: `geordi capistrano deploy`
LONGDESC
def capistrano(*args)
targets = Dir['config/deploy/*.rb'].map { |file| File.basename(file, '.rb') }.sort
note 'Found the following deploy targets:'
puts targets
prompt('Continue?', 'n', /y|yes/) or fail 'Cancelled.'
targets << nil if targets.empty? # default target
targets.each do |stage|
announce 'Target: ' + (stage || '(default)')
command = "bundle exec cap #{stage} " + args.join(' ')
note_cmd command
Util.system!(command, :fail_message => 'Capistrano failed. Have a look!')
end
end
| 27.833333 | 84 | 0.676647 |
ab39b697c1201e57d4299d237e339f9b07872d08 | 2,816 | require 'set'
require 'benchmark'
require 'ostruct'
#require 'audit_data'
module CassandraAudits
module Adapters
module ActiveRecord
# Audit saves the changes to ActiveRecord models. It has the following attributes:
#
# * <tt>auditable</tt>: the ActiveRecord model that was changed
# * <tt>user</tt>: the user that performed the change; a string or an ActiveRecord model
# * <tt>action</tt>: one of create, update, or delete
# * <tt>audited_changes</tt>: a serialized hash of all the changes
# * <tt>comment</tt>: a comment set with the audit
# * <tt>created_at</tt>: Time that the change was performed
#
class AuditWrapper
include ::ActiveModel::Observing
include ::ActiveSupport::Callbacks
def self.before_create(arg)
end
attr_accessor :audit_data
def initialize(audit_data = {}, decode = false)
self.audit_data = OpenStruct.new(audit_data)
if decode
["audit_destination_data", "audit_source_data", "audited_changes", "superior_data"].each do |field|
send(:decode_field, field)
end
end
end
def save
notify_observers(:before_create)
begin
CassandraMigrations::Cassandra.write!(table_name,
audit_data.marshal_dump.merge(partition_key))
rescue Cql::QueryError => e
::ActiveRecord::Base.logger.debug("Cql::QueryError")
::ActiveRecord::Base.logger.debug(e.inspect)
::ActiveRecord::Base.logger.debug( audit_data.marshal_dump)
end
end
def method_missing(method_name, *arguments, &block)
audit_data.send(method_name)
end
def respond_to_missing?(method_name, include_private = false)
audit_data.send(method_name).present? || super
end
# All audits made during the block called will be recorded as made
# by +user+. This method is hopefully threadsafe, making it ideal
# for background operations that require audit information.
def as_user(user, &block)
Thread.current[:audited_user] = user
yield
ensure
Thread.current[:audited_user] = nil
end
protected
private
def set_audit_user
self.user = Thread.current[:audited_user] if Thread.current[:audited_user]
nil # prevent stopping callback chains
end
def decode_field(field)
self.audit_data
.send("#{field}=", self.audit_data.send(field).present? ? JSON.parse(self.audit_data.send(field)) : {})
end
def table_name
raise "not implemented"
end
end
end
end
end
| 31.288889 | 113 | 0.611151 |
338eaed47694ac4f2c7febff1a4e0a73989ff4bd | 303 | # encoding: utf-8
require_relative "../spec_helper"
describe Rango do
describe ".environment" do
it "should have environment" do
Rango.should respond_to(:environment)
end
it "should be development by default" do
Rango.environment.should eql("development")
end
end
end
| 18.9375 | 49 | 0.69967 |
39178193b3b1af822880596dca4448d045c0db1f | 1,163 | require './config/environment'
require 'sinatra/flash'
class ApplicationController < Sinatra::Base
register Sinatra::Flash
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "notsureyet"
end
get '/' do
if !logged_in?
erb :index
else
redirect '/consoles'
end
end
helpers do
def logged_in?
!!current_user
end
def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
def login(username, password)
user = User.find_by(:username => username)
if user && user.authenticate(password)
session[:user_id] = user.id
redirect to '/consoles'
else
flash[:login_error] = "Your username or password doesn't match our records, please try again!"
redirect '/login'
end
end
def duplicate_console?(name)
!!current_user.consoles.map{|console| console.name.delete(" ").downcase}.include?(name.delete(" ").downcase)
end
def duplicate_user?(name)
!!User.all.map {|user| user.username}.include?(name)
end
end
end
| 21.943396 | 114 | 0.640585 |
e8246d940d8c800040828625f9a6ea72f1690536 | 559 | module RedisRateLimit
class Minute < Period
# Create an instance of Minute
# @param [String] name A unique namespace that identify the subject to track : users, emails, ip ...
# @param [Hash] options Options hash
# @option options [Integer] :limit (60) How many transactions to perform during the defined interval
# @option options [Redis] :redis (nil) Redis client
# @return [Minute] Minute instance
def initialize(name, options = {})
super(name, options.merge(format: '%Y-%m-%dT%H:%M', interval: 60))
end
end
end
| 39.928571 | 104 | 0.677996 |
bfee6e1352c86c8f888b2666fe25d781367f05dd | 1,807 | class LinkGrammar < Formula
desc "Carnegie Mellon University's link grammar parser"
homepage "https://www.abisource.com/projects/link-grammar/"
url "https://www.abisource.com/downloads/link-grammar/5.8.0/link-grammar-5.8.0.tar.gz"
sha256 "ad65a6b47ca0665b814430a5a8ff4de51f4805f7fb76642ced90297b4e7f16ed"
license "LGPL-2.1"
revision 1
livecheck do
url :homepage
regex(/href=.*?link-grammar[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 arm64_big_sur: "2ff86c07dc50539754a20b35fbd548c421f9822b39ab43053f2721ee6841fd43"
sha256 big_sur: "6416c4a870cf3a11a345ffc0d1fecfb64e402dc264648febe89c6b9cb903f514"
sha256 catalina: "d2125eec68c573874249d6b3629b54b9c55c7c378343f9ae969440dfdbb3497d"
sha256 mojave: "5c6e347b0c82683ae1a3c8838bec8bf9b840c06fbe33e59a494ea3495256b0e0"
sha256 high_sierra: "64a9aa4bebc23fe23063f436cd18bca518e11f3be4322ca60d2d710c9ed6cd8c"
end
depends_on "ant" => :build
depends_on "autoconf" => :build
depends_on "autoconf-archive" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "[email protected]" => :build
uses_from_macos "sqlite"
def install
ENV["PYTHON_LIBS"] = "-undefined dynamic_lookup"
inreplace "bindings/python/Makefile.am",
"$(PYTHON_LDFLAGS) -module -no-undefined",
"$(PYTHON_LDFLAGS) -module"
inreplace "link-grammar/link-grammar.def", "regex_tokenizer_test\n", ""
system "autoreconf", "-fiv"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-regexlib=c"
system "make", "install"
end
test do
system "#{bin}/link-parser", "--version"
end
end
| 36.14 | 92 | 0.693968 |
ed473d75b0eb55b7922882a92ea6a667cb2d858f | 1,977 | class Event < ActiveRecord::Base
geocoded_by :location # can also be an IP address
after_validation :geocode # auto-fetch coordinates
after_update :notify_system
before_save :check_over
belongs_to :user
belongs_to :category
has_many :donations, as: :donatable
has_many :votes, as: :votable
has_many :comments
has_many :participations
has_many :participants, through: :participations, source: :event
has_many :notifications, dependent: :destroy
validates :category, presence: true
scope :enable, -> { where(enable: true) }
scope :featured, -> { enable.joins(:votes).group("events.id").order('count(events.id) DESC') }
scope :near_me, -> (lat, lon) { Event.near([lat, lon], 100).limit(10) }
def vote_by!(user)
# create a new vote associating user and photo
raise "Already voted" if voted_by?(user)
votes.find_or_create_by!(voter: user)
end
def unvote_by!(user)
raise "Not yet voted" unless voted_by?(user)
votes.where(voter: user).first.destroy
end
def voted_by?(user)
votes.exists?(voter: user)
end
def vote_count
votes.size
end
def send_sms
message = "\nXin chúc mừng:\n"
message += "Ý tưởng của bạn đã quyên góp đủ số tiền.\n"
message += "\nÝ tưởng: #{name}"
message += "\nTổng số tiền nhận được: #{donations.sum(:amount)} VNĐ"
message += "\n\nHãy thực hiện ý tưởng của bạn vì cộng đồng"
@client = Twilio::REST::Client.new "AC1f944d7f633a1bd6d3a87d6ca62ef497", "d323885b3cfdcb0aaa079ba5b60998c3"
@client.messages.create(
from: "+12017318643",
to: "+841289816416",
body: message
)
end
def is_valid?
donations.sum(:amount) >= required_amount
end
private
def notify_system
if changes['enable']
notifications.create(message: "vừa được khởi tạo")
end
end
def check_over
if success
SendSmsWorker.new.perform(id)
SendEmailEventCloseWorker.new.perform(id)
end
true
end
end
| 25.675325 | 111 | 0.68083 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.