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
911907cf2f779be724874e148c07040db09b4695
639
describe port(9696) do it { should be_listening } its('processes') { should include 'python' } end describe service('neutron-dhcp-agent') do it { should be_installed } it { should be_enabled } it { should be_running } end describe service('neutron-l3-agent') do it { should be_installed } it { should be_enabled } it { should be_running } end describe service('neutron-metadata-agent') do it { should be_installed } it { should be_enabled } it { should be_running } end describe service('neutron-plugin-linuxbridge-agent') do it { should be_installed } it { should be_enabled } it { should be_running } end
22.034483
55
0.71205
d5053df7afc588aace523ae6ff0fb60736ea71e5
320
require 'rails_helper' describe Doorkeeper::AuthorizedApplicationsController, type: :controller do let(:access_token) { create :access_token } describe '#index' do it 'does not run the extended #authenticate_resource_owner!' do expect do get :index end.not_to raise_error end end end
22.857143
75
0.71875
f896d7e26fd7da3f33d679772edd0c59bac5a139
104
module Podcasts class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end end
17.333333
46
0.769231
26284df65bb37147a437c0f234b7aef2d2de0e20
1,002
#this class will scape using nakgeri class PokemonGame::Scraper def self.nokogiri Nokogiri::HTML(open("https://en.wikipedia.org/wiki/List_of_generation_I_Pok%C3%A9mon")) end def self.scrape(location,get_id) output = [] doc = nokogiri if get_id == true #this gets each pokemon doc.css(location).each do |item| pokemon = item.attributes["id"] # description = item.css('tbody tr td').text #this cuts out unnessesery parts of the list form wikipedia and makes sure its not added to @@all_pokemon if pokemon != nil # puts pokemon output << pokemon end#pokemon if end#css each else#get_id #gets all_pokemon_description doc.css(location).each do |item| description = item.text #this cuts out unnessesery parts of the list form wikipedia and makes sure its not added to @@all_pokemon if description != nil # puts description output << description end#description if end#css each end#get_id if output end#scrape end#class #ignore this will delet later
21.319149
107
0.732535
39db6182db01f842ebe1897fd5f56cae9d693f85
1,792
# Copyright © 2011 MUSC Foundation for Research Development # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Report command, e.g.: # # rails r report list # rails r report run <report> # def report # Require reports dynamically so that reports are not loaded as part # of the regular rails application require 'reports' run_report_command(ARGV) end
54.30303
145
0.792411
ff47fa9745aaa815b4ecbe1e367eccc78c355cac
2,630
require 'spec_helper' module Family def self.const_missing(_name) raise NameError, 'original message' end end describe Fabrication::Support do describe '.class_for' do context 'with a class that exists' do it 'returns the class for a class' do expect(described_class.class_for(Object)).to eq(Object) end it 'returns the class for a class name string' do expect(described_class.class_for('object')).to eq(Object) end it 'returns the class for a class name symbol' do expect(described_class.class_for(:object)).to eq(Object) end end context "with a class that doesn't exist" do it 'returns nil for a class name string' do expect { described_class.class_for('your_mom') } .to raise_error(Fabrication::UnfabricatableError) end it 'returns nil for a class name symbol' do expect { described_class.class_for(:your_mom) } .to raise_error(Fabrication::UnfabricatableError) end end context 'when custom const_missing is defined' do it 'raises an exception with the message from the original exception' do expect { described_class.class_for('Family::Mom') } .to raise_error(Fabrication::UnfabricatableError, /original message/) end end end describe '.variable_name_to_class_name', depends_on: :active_support do before do ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'OCR' end end it 'handles acronyms correctly' do expect(described_class.variable_name_to_class_name('ocr_test')).to eq('OCRTest') end end describe '.hash_class', depends_on: :active_support do subject { described_class.hash_class } before do pending unless defined?(HashWithIndifferentAccess) end context 'with HashWithIndifferentAccess defined' do it { is_expected.to eq(HashWithIndifferentAccess) } end # rubocop:disable Lint/ConstantDefinitionInBlock, RSpec/LeakyConstantDeclaration context 'without HashWithIndifferentAccess defined' do before do TempHashWithIndifferentAccess = HashWithIndifferentAccess described_class.instance_variable_set('@hash_class', nil) Object.send(:remove_const, :HashWithIndifferentAccess) end after do described_class.instance_variable_set('@hash_class', nil) HashWithIndifferentAccess = TempHashWithIndifferentAccess end it { is_expected.to eq(Hash) } end # rubocop:enable Lint/ConstantDefinitionInBlock, RSpec/LeakyConstantDeclaration end end
30.581395
86
0.703802
1d333ee6e5a6f2e49a21da1e19bdf99d97f40817
878
require 'spec_helper' require 'rollbar/truncation' describe Rollbar::Truncation do describe '.truncate' do let(:payload) { {} } context 'if truncation is not needed' do it 'only calls RawStrategy is truncation is not needed' do allow(described_class).to receive(:truncate?).and_return(false) expect(Rollbar::Truncation::RawStrategy).to receive(:call).with(payload) Rollbar::Truncation.truncate(payload) end end context 'if truncation is needed' do it 'calls the next strategy, FramesStrategy' do allow(described_class).to receive(:truncate?).and_return(true, false) expect(Rollbar::Truncation::RawStrategy).to receive(:call).with(payload) expect(Rollbar::Truncation::FramesStrategy).to receive(:call).with(payload) Rollbar::Truncation.truncate(payload) end end end end
31.357143
83
0.694761
1d919808fe3c249a34533b7a8154ea06ede979c1
539
require File.join(File.dirname(__FILE__), 'abstract-php-extension') class Php53Yar < AbstractPhp53Extension init homepage 'http://pecl.php.net/package/yar' url 'http://pecl.php.net/get/yar-1.2.2.tgz' sha1 '882937c7892a4252ec03714f783317c4a1df66f3' def install Dir.chdir "yar-#{version}" ENV.universal_binary if build.universal? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/yar.so" write_config_file if build.with? "config-file" end end
25.666667
67
0.717996
bb9159fe21407f5d1ea43da8c4253e2d57327352
3,447
# -*- coding:binary -*- require 'spec_helper' require 'rex/exploitation/powershell' describe Rex::Exploitation::Powershell::Function do let(:function_name) do Rex::Text.rand_text_alpha(15) end let(:example_function_without_params) do """ { ls HKLM:\SAM\SAM\Domains\Account\Users | where {$_.PSChildName -match \"^[0-9A-Fa-f]{8}$\"} | Add-Member AliasProperty KeyName PSChildName -PassThru | Add-Member ScriptProperty Rid {[Convert]::ToInt32($this.PSChildName, 16)} -PassThru | Add-Member ScriptProperty V {[byte[]]($this.GetValue(\"V\"))} -PassThru | Add-Member ScriptProperty UserName {Get-UserName($this.GetValue(\"V\"))} -PassThru | Add-Member ScriptProperty HashOffset {[BitConverter]::ToUInt32($this.GetValue(\"V\")[0x9c..0x9f],0) + 0xCC} -PassThru }""" end let(:example_function_with_params) do """ { Param ( [OutputType([Type])] [Parameter( Position = 0)] [Type[]] $Parameters = (New-Object Type[](0)), [Parameter( Position = 1 )] [Type] $ReturnType = [Void], [String]$Parpy='hello', [Integer] $puppy = 1, [Array[]] $stuff = Array[], ) $Domain = [AppDomain]::CurrentDomain $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate') $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false) $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters) $ConstructorBuilder.SetImplementationFlags('Runtime, Managed') $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters) $MethodBuilder.SetImplementationFlags('Runtime, Managed') Write-Output $TypeBuilder.CreateType() }""" end describe "::initialize" do it 'should handle a function without params' do function = Rex::Exploitation::Powershell::Function.new(function_name, example_function_without_params) function.name.should eq function_name function.code.should eq example_function_without_params function.to_s.include?("function #{function_name} #{example_function_without_params}").should be_true function.params.should be_kind_of Array function.params.empty?.should be_true end it 'should handle a function with params' do function = Rex::Exploitation::Powershell::Function.new(function_name, example_function_with_params) function.name.should eq function_name function.code.should eq example_function_with_params function.to_s.include?("function #{function_name} #{example_function_with_params}").should be_true function.params.should be_kind_of Array function.params.length.should be == 5 function.params[0].klass.should eq 'Type[]' function.params[0].name.should eq 'Parameters' function.params[1].klass.should eq 'Type' function.params[1].name.should eq 'ReturnType' end end end
40.081395
159
0.67682
62199dbcd6da9064e5c36c2c42b26aa00428957c
290
class LeaderboardController < ApplicationController include DateRange before_action :set_leaderboard, only: [:index] def index render json: @users end private def set_leaderboard @users = User.all.with_total_flights(date_range).order('total_flights DESC') end end
18.125
80
0.755172
1166c4738ec8a4774879c69ec338a04e975c1faa
149
require File.expand_path('../../../../spec_helper', __FILE__) describe "Resolv::IPv4#eql?" do it "needs to be reviewed for spec completeness" end
24.833333
61
0.704698
01b070f0a58d6003fa40d45a74409bc69bbc7d89
693
# == Schema Information # # Table name: tracks # # id :integer not null, primary key # title :string(255) not null # artist_id :integer # album_id :integer # npr_attributes :hstore # external_ids :string(255) # spotify_id :string(255) # created_at :datetime # updated_at :datetime # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :track do sequence(:title) {|n| "dat-song-#{n}"} sequence(:npr_attributes) { |n| {artist_name: "artist-#{n}", album_name: "album-#{n}"} } external_ids { {"isrc"=>"GBJSG1009504"} } sequence(:spotify_id) album end end
25.666667
92
0.621934
e219e8b7b96ebbe2a2b14a0227936f31c9a9d61b
4,911
require 'spec_helper' require 'goliath/runner' describe Goliath::Runner do before(:each) do @r = Goliath::Runner.new([], nil) allow(@r).to receive(:store_pid) @log_mock = double('logger').as_null_object allow(@r).to receive(:setup_logger).and_return(@log_mock) end describe 'server execution' do describe 'daemonization' do it 'daemonizes if specified' do expect(Process).to receive(:fork) @r.daemonize = true @r.run end it "doesn't daemonize if not specified" do expect(Process).not_to receive(:fork) expect(@r).to receive(:run_server) @r.run end end describe 'logging' do before(:each) do @r = Goliath::Runner.new([], nil) end after(:each) do # Runner default env is development. # We do need to revert to test Goliath.env = :test end describe 'without setting up file logger' do before(:each) do allow(@r).to receive(:setup_file_logger) end it 'configures the logger' do log = @r.send(:setup_logger) expect(log).not_to be_nil end [:debug, :warn, :info].each do |type| it "responds to #{type} messages" do log = @r.send(:setup_logger) expect(log.respond_to?(type)).to be true end end describe 'log level' do before(:each) do allow(FileUtils).to receive(:mkdir_p) end it 'sets the default log level' do log = @r.send(:setup_logger) expect(log.level).to eq(Log4r::INFO) end it 'sets debug when verbose' do @r.verbose = true log = @r.send(:setup_logger) expect(log.level).to eq(Log4r::DEBUG) end end describe 'file logger' do it "doesn't configure by default" do expect(@r).not_to receive(:setup_file_logger) log = @r.send(:setup_logger) end it 'configures if -l is provided' do expect(@r).to receive(:setup_file_logger) @r.log_file = 'out.log' log = @r.send(:setup_logger) end end describe 'stdout logger' do it "doesn't configure by default" do expect(@r).not_to receive(:setup_stdout_logger) log = @r.send(:setup_logger) end it 'configures if -s is provided' do expect(@r).to receive(:setup_stdout_logger) @r.log_stdout = true log = @r.send(:setup_logger) end end describe "custom logger" do it "doesn't configure Log4r" do CustomLogger = Struct.new(:info, :debug, :error, :fatal) expect(Log4r::Logger).not_to receive(:new) @r.logger = CustomLogger.new log = @r.send(:setup_logger) end end end it 'creates the log dir if neeed' do allow(Log4r::FileOutputter).to receive(:new) log_mock = double('log').as_null_object expect(FileUtils).to receive(:mkdir_p).with('/my/log/dir') @r.log_file = '/my/log/dir/log.txt' @r.send(:setup_file_logger, log_mock, nil) end end it 'sets up the api if that implements the #setup method' do server_mock = double("Server").as_null_object expect(server_mock.api).to receive(:setup) allow(Goliath::Server).to receive(:new).and_return(server_mock) allow(@r).to receive(:load_config).and_return({}) @r.send(:run_server) end it 'runs the server' do server_mock = double("Server").as_null_object expect(server_mock).to receive(:start) expect(Goliath::Server).to receive(:new).and_return(server_mock) allow(@r).to receive(:load_config).and_return({}) @r.send(:run_server) end it 'configures the server' do server_mock = Goliath::Server.new allow(server_mock).to receive(:start) @r.app = 'my_app' expect(Goliath::Server).to receive(:new).and_return(server_mock) expect(server_mock).to receive(:logger=).with(@log_mock) expect(server_mock).to receive(:app=).with('my_app') @r.send(:run_server) end end end describe Goliath::EnvironmentParser do before(:each) do ENV['RACK_ENV'] = nil end it 'returns the default environment if no other options are set' do expect(Goliath::EnvironmentParser.parse).to eq(Goliath::DEFAULT_ENV) end it 'gives precendence to RACK_ENV over the default' do ENV['RACK_ENV'] = 'rack_env' expect(Goliath::EnvironmentParser.parse).to eq(:rack_env) end it 'gives precendence to command-line flag over RACK_ENV' do ENV['RACK_ENV'] = 'rack_env' args = %w{ -e flag_env } expect(Goliath::EnvironmentParser.parse(args)).to eq(:flag_env) end end
27.589888
72
0.593973
873f440164ecc4bb5cc6b3ebef007997424f3781
186
cask :v1 => 'renamer' do version :latest sha256 :no_check url 'http://creativebe.com/download/renamer' homepage 'http://renamer.com' license :unknown app 'Renamer.app' end
16.909091
46
0.693548
212ee2cb23fb346f56930c66712a7da326209b60
353
class SetServiceDisplayAndRetiredToFalse < ActiveRecord::Migration[5.0] class Service < ActiveRecord::Base self.inheritance_column = :_type_disabled # disable STI end def up Service.where(:retired => nil).update_all(:retired => false) Service.where(:display => nil).update_all(:display => false) end def down # NOP end end
23.533333
71
0.711048
03d7146eb65eaf51aa7888e786943addc94ab1a1
72
class ExperimentEvent < ActiveRecord::Base belongs_to :experiment end
18
42
0.819444
1a028913e934820fc8b365d91affc970335ec3a6
2,720
# frozen_string_literal: true require 'spec_helper' RSpec.describe Security::SecurityOrchestrationPolicies::ProcessScanResultPolicyService do describe '#execute' do let_it_be(:policy_configuration) { create(:security_orchestration_policy_configuration) } let(:approver) { create(:user) } let(:policy) { build(:scan_result_policy, name: 'Test Policy') } let(:policy_yaml) { Gitlab::Config::Loader::Yaml.new(policy.to_yaml).load! } let(:project) { policy_configuration.project } let(:service) { described_class.new(policy_configuration: policy_configuration, policy: policy, policy_index: 0) } before do allow(policy_configuration).to receive(:policy_last_updated_by).and_return(project.owner) end subject { service.execute } context 'when feature flag is disabled' do before do stub_feature_flags(scan_result_policy: false) end it 'does not change approval project rules' do expect { subject }.not_to change { project.approval_rules.count } end end context 'without any require_approval action' do let(:policy) { build(:scan_result_policy, name: 'Test Policy', actions: [{ type: 'another_one' }]) } it 'does not create approval project rules' do expect { subject }.not_to change { project.approval_rules.count } end end context 'without any rule of the scan_finding type' do let(:policy) { build(:scan_result_policy, name: 'Test Policy', rules: [{ type: 'another_one' }]) } it 'does not create approval project rules' do expect { subject }.not_to change { project.approval_rules.count } end end it 'creates a new project approval rule' do expect { subject }.to change { project.approval_rules.count }.by(1) end it 'sets project approval rules names based on policy name', :aggregate_failures do subject scan_finding_rule = project.approval_rules.first first_rule = policy[:rules].first first_action = policy[:actions].first expect(policy[:name]).to include(scan_finding_rule.name) expect(scan_finding_rule.report_type).to eq(Security::ScanResultPolicy::SCAN_FINDING) expect(scan_finding_rule.rule_type).to eq('report_approver') expect(scan_finding_rule.scanners).to eq(first_rule[:scanners]) expect(scan_finding_rule.severity_levels).to eq(first_rule[:severity_levels]) expect(scan_finding_rule.vulnerabilities_allowed).to eq(first_rule[:vulnerabilities_allowed]) expect(scan_finding_rule.vulnerability_states).to eq(first_rule[:vulnerability_states]) expect(scan_finding_rule.approvals_required).to eq(first_action[:approvals_required]) end end end
39.42029
118
0.722794
b962a2ef552214462757fbabd640a0c24b13d414
135
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryBot.define do factory :inst_chapter_module do end end
19.285714
68
0.8
033916fa7b399ebb89d784b8bffc852a9b2a5317
436
require 'tempfile' require 'fileutils' module Helpers def wordlist_tempfile(existing_file=nil) path = Tempfile.new('wordlist').path ::FileUtils.cp(existing_file,path) if existing_file return path end def should_contain_words(path,expected) words = [] ::File.open(path) do |file| file.each_line do |line| words << line.chomp end end words.sort.should == expected.sort end end
18.166667
55
0.672018
acf1acc207898b68b9185f464ab792f8e2da28ea
3,918
class DecksController < ApplicationController get '/decks' do if logged_in? 10.times {u = current_user} erb :'/decks/decks' else flash[:error] = "You must log in to view your decks." redirect '/login' end end get '/decks/new' do if logged_in? erb :'/decks/new_deck' else flash[:error] = "You must log in to make a new deck." redirect '/login' end end post '/decks' do if logged_in? if params[:deck_name] != "" current_user.decks.create(:name => params[:deck_name], :format => params[:deck_format], :magic_card_ids => params[:magic_card_ids]) #@deck.magic_card_ids = params[:cards] #@deck.save redirect '/decks' else flash[:error] = "Your new deck must have a name." redirect '/decks/new' end else flash[:error] = "You must log in to Make a new deck." redirect '/login' end end post '/decks/new' do if logged_in? if params[:card][:name] != "" @card = MagicCard.create(params[:card]) @card.user_id = current_user.id @card.save erb :'/decks/new_deck' else flash[:error] = "Your new card must have a name." erb :'/decks/new_deck' end else flash[:error] = "You must log in to view your cards." redirect '/login' end end get '/decks/:slug' do #needs validation @deck = Deck.find_by_slug(params[:slug]) if logged_in? if validate_user(@deck) erb :'/decks/show_deck' else flash[:error] = "You cannot view another user's deck." redirect '/decks' end else flash[:error] = "You must log in to view a deck." redirect '/login' end end get '/decks/:slug/edit' do #needs validation @deck = Deck.find_by_slug(params[:slug]) if logged_in? if validate_user(@deck) erb :'/decks/edit_deck' else flash[:error] = "You can only edit your own decks." redirect '/decks' end else flash[:error] = "You must log in to edit a deck." redirect '/login' end end post '/decks/:slug/edit' do #needs validations @deck = Deck.find_by_slug(params[:slug]) if logged_in? if params[:card][:name] != "" if validate_user(@deck) @card = MagicCard.create(params[:card]) @card.user_id = current_user.id @card.save erb :'/decks/edit_deck' else flash[:error] = "You can only edit your own deck." redirect '/decks' end else flash[:error] = "Your deck must have a name." erb :'/decks/edit_deck' end else flash[:error] = "You must log in edit a deck." redirect '/login' end end patch '/decks/:slug' do #needs validation @deck = Deck.find_by_slug(params[:slug]) if logged_in? if params[:deck][:name] != "" if validate_user(@deck) @deck.update(params[:deck]) @deck.magic_card_ids = params[:cards] @deck.save redirect to "decks/#{@deck.slug}" else flash[:error] = "You can only edit your own decks." redirect '/decks' end else flash[:error] = "You must have a name for your deck." redirect "/decks/#{@deck.slug}/edit" end #erb :'/decks/show_deck' else flash[:error] = "You must log in to edit a deck." redirect '/login' end end delete '/decks/:slug/delete' do #needs validation @deck = Deck.find_by_slug(params[:slug]) @user = current_user if logged_in? if validate_user(@deck) @deck.delete redirect '/decks' else flash[:error] = "You can only delete your own decks." redirect "/decks/#{@deck.slug}" end else flash[:error] = "You must be logged in to delete a deck." redirect '/login' end end end
25.441558
138
0.572996
18f215eca44af0a5fd9df2ef63687dcf36c7b24a
4,153
module Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_auto_scaling_instances' # Returns a description of each Auto Scaling instance in the # instance_ids list. If a list is not provided, the service returns the # full details of all instances. # # This action supports pagination by returning a token if there are # more pages to retrieve. To get the next page, call this action again # with the returned token as the NextToken parameter. # # ==== Parameters # * options<~Hash>: # * 'InstanceIds'<~Array> - The list of Auto Scaling instances to # describe. If this list is omitted, all auto scaling instances are # described. The list of requested instances cannot contain more # than 50 items. If unknown instances are requested, they are # ignored with no error. # * 'MaxRecords'<~Integer> - The aximum number of Auto Scaling # instances to be described with each call. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeAutoScalingInstancesResponse'<~Hash>: # * 'AutoScalingInstances'<~Array>: # * autoscalinginstancedetails<~Hash>: # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling Group associated with this instance. # * 'AvailabilityZone'<~String> - The availability zone in # which this instance resides. # * 'HealthStatus'<~String> - The health status of this # instance. "Healthy" means that the instance is healthy # and should remain in service. "Unhealthy" means that the # instance is unhealthy. Auto Scaling should terminate and # replace it. # * 'InstanceId'<~String> - The instance's EC2 instance ID. # * 'LaunchConfigurationName'<~String> - The launch # configuration associated with this instance. # * 'LifecycleState'<~String> - The life cycle state of this # instance. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingInstances.html # def describe_auto_scaling_instances(options = {}) if instance_ids = options.delete('InstanceIds') options.merge!(AWS.indexed_param('InstanceIds.member.%d', [*instance_ids])) end request({ 'Action' => 'DescribeAutoScalingInstances', :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingInstances.new }.merge!(options)) end end class Mock def describe_auto_scaling_instances(options = {}) results = { 'AutoScalingInstances' => [] } self.data[:auto_scaling_groups].each do |asg_name, asg_data| asg_data['Instances'].each do |instance| results['AutoScalingInstances'] << { 'AutoScalingGroupName' => asg_name }.merge!(instance) end end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAutoScalingInstancesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end
46.144444
113
0.576692
f7a289c5fd0ff18a565659156927c458c5704755
585
class BackfillScripts2 < ActiveRecord::Migration def up puts "Comments Valorations.." cvts = CommentsValorationsType.find_positive User.find_each( :conditions => "id IN ( SELECT DISTINCT(user_id) FROM comments WHERE id IN ( SELECT distinct(comment_id) from comments_valorations where comments_valorations_type_id IN (2, 3, 4, 8)))") do |u| cvts.each do |cvt| UserEmblemObserver::Emblems.comments_valorations_receiver(cvt, u) end end end def down end end
26.590909
75
0.618803
6a819976d68556f20a5c573ee74e32db88e5af17
135
class QuestionPolicy < ApplicationPolicy def new? record.survey.creator == user && record.survey.published? == false end end
16.875
70
0.718519
281a23d7c0c25a2ae7689652d74eabd3ecc3d31b
93
class Tag < ApplicationRecord has_and_belongs_to_many :poems, join_table: 'poems_tags' end
23.25
58
0.817204
087050efacdb62541bdfb0bcc49de8e08012bef9
3,539
require "rails/generators/named_base" module Administrate module Generators class DashboardGenerator < Rails::Generators::NamedBase ATTRIBUTE_TYPE_MAPPING = { boolean: "Field::Boolean", date: "Field::DateTime", datetime: "Field::DateTime", enum: "Field::String", float: "Field::Number", integer: "Field::Number", time: "Field::DateTime", text: "Field::Text", string: "Field::String", } ATTRIBUTE_OPTIONS_MAPPING = { enum: { searchable: false }, float: { decimals: 2 }, } DEFAULT_FIELD_TYPE = "Field::String.with_options(searchable: false)" COLLECTION_ATTRIBUTE_LIMIT = 4 READ_ONLY_ATTRIBUTES = %w[id created_at updated_at] source_root File.expand_path("../templates", __FILE__) def create_dashboard_definition template( "dashboard.rb.erb", Rails.root.join("app/dashboards/#{file_name}_dashboard.rb"), ) end def create_resource_controller destination = Rails.root.join( "app/controllers/admin/#{file_name.pluralize}_controller.rb", ) template("controller.rb.erb", destination) end private def attributes klass.reflections.keys + klass.attribute_names - redundant_attributes end def form_attributes attributes - READ_ONLY_ATTRIBUTES end def redundant_attributes klass.reflections.keys.flat_map do |relationship| redundant_attributes_for(relationship) end.compact end def redundant_attributes_for(relationship) case association_type(relationship) when "Field::Polymorphic" [relationship + "_id", relationship + "_type"] when "Field::BelongsTo" relationship + "_id" end end def field_type(attribute) type = column_type_for_attribute(attribute.to_s) if type ATTRIBUTE_TYPE_MAPPING.fetch(type, DEFAULT_FIELD_TYPE) + options_string(ATTRIBUTE_OPTIONS_MAPPING.fetch(type, {})) else association_type(attribute) end end def column_type_for_attribute(attr) if enum_column?(attr) :enum else klass.column_types[attr].type end end def enum_column?(attr) klass.respond_to?(:defined_enums) && klass.defined_enums.keys.include?(attr) end def association_type(attribute) relationship = klass.reflections[attribute.to_s] if relationship.has_one? "Field::HasOne" elsif relationship.collection? "Field::HasMany" + relationship_options_string(relationship) elsif relationship.polymorphic? "Field::Polymorphic" else "Field::BelongsTo" + relationship_options_string(relationship) end end def klass @klass ||= Object.const_get(class_name) end def relationship_options_string(relationship) if relationship.class_name != relationship.name.to_s.classify options_string(class_name: relationship.class_name) else "" end end def options_string(options) if options.any? ".with_options(#{inspect_hash_as_ruby(options)})" else "" end end def inspect_hash_as_ruby(hash) hash.map { |key, value| "#{key}: #{value.inspect}" }.join(", ") end end end end
26.810606
77
0.614298
bf8db223ffdc564036e1926515c63c2eb66b0477
536
require 'spec_helper' describe Spree::State, :type => :model do it "can find a state by name or abbr" do state = create(:state, :name => "California", :abbr => "CA") expect(Spree::State.find_all_by_name_or_abbr("California")).to include(state) expect(Spree::State.find_all_by_name_or_abbr("CA")).to include(state) end it "can find all states group by country id" do state = create(:state) expect(Spree::State.states_group_by_country_id).to eq({ state.country_id.to_s => [[state.id, state.name]] }) end end
35.733333
112
0.697761
79725be4cc09693deba8cf3c6b90bca50005d217
407
class CreateFriendlyUrls < ActiveRecord::Migration def change create_table :friendly_urls do |t| t.string :path t.string :slug t.string :controller t.string :action t.string :defaults t.references :article, index: true t.timestamps null: false end add_foreign_key :friendly_urls, :articles add_index :friendly_urls, :slug, unique: true end end
23.941176
50
0.678133
013c4485d75ff6c347b5f46f64227f4f5bfc8197
608
require File.dirname(__FILE__) + '/spec_helper' describe "Chord addition" do describe "adding C and G" do before(:each) do @c = Chord.new(:c, [0,4,7]) @g = Chord.new(:g, [0,4,7]) end it "yields CM9" do @cM9 = Chord.new(:c, [0,4,7,11,14]) result = @c + @g result.should == @cM9 end end describe "adding C and G-" do before(:each) do @c = Chord.new(:c, [0,4,7]) @g = Chord.new(:g, [0,3,7]) end it "yields C9" do @c9 = Chord.new(:c, [0,4,7,10,14]) result = @c + @g result.should == @c9 end end end
19.612903
47
0.503289
e9c21fbe3962ffd39c4abf53568aef25a32ceb65
130
# frozen_string_literal: true json.partial! "hyrax/active_encode/encode_records/encode_record", encode_record: @encode_presenter
32.5
98
0.846154
e2468877fce57f6fe600488f770d58e3c095b427
798
# # Cookbook:: Jk_Book1 # Spec:: default # # Copyright:: 2020, The Authors, All Rights Reserved. require 'spec_helper' describe 'Jk_Book1::default' do context 'When all attributes are default, on Ubuntu 18.04' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'ubuntu', '18.04' it 'converges successfully' do expect { chef_run }.to_not raise_error end end context 'When all attributes are default, on CentOS 7' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'centos', '7' it 'converges successfully' do expect { chef_run }.to_not raise_error end end end
26.6
66
0.705514
4a1dfe1c4a591d111275998e2dd21dc6fa9fc054
122
require "mini_admin/version" module MiniAdmin class Error < StandardError; end def self.greet "Hello" end end
12.2
34
0.721311
61ed71767e737ce1eed0f169221794c10f794b34
407
module NetcashApi class ClientWrapper class << self def method_missing(end_point, params, &block) response = NetcashApi::Client.send(self.to_s.demodulize.underscore.downcase).call(end_point, { message: XmlKeyAdapter.convert_keys(params) }) if block_given? yield response else return response end end end end end
22.611111
102
0.624079
e81037f8aded8b53c530ebdff75d79504c7ab59c
251
# frozen_string_literal: true # https://github.com/rack/rack/issues/1075 class RackMultipartBuffer def initialize(app) @app = app end def call(env) env[Rack::RACK_MULTIPART_BUFFER_SIZE] = 100 * 1024 * 1024 @app.call(env) end end
17.928571
61
0.701195
384a6a81a6cd17e59578ef4e9960ca24045e8484
778
Pod::Spec.new do |spec| spec.name = 'RxComposableArchitectureTests' spec.version = '2.1.1' spec.license = 'MIT' spec.summary = 'A Rx version of ComposableArchitecture.' spec.homepage = 'https://github.com/jrBordet/RxComposableArchitecture.git' spec.author = 'Jean Raphaël Bordet' spec.source = { :git => 'https://github.com/jrBordet/RxComposableArchitecture.git', :tag => spec.version.to_s } spec.source_files = 'RxComposableArchitectureTests/**/*.{swift}' spec.requires_arc = true spec.ios.deployment_target = '10.0' spec.dependency 'RxSwift', '~> 5' spec.dependency 'RxCocoa', '~> 5' spec.dependency 'RxComposableArchitecture', '2.1.1' spec.dependency 'Difference', '0.4' spec.weak_framework = 'XCTest' end
43.222222
119
0.679949
ff7aa0e543a03b5125e28921eaefd6a7c8266a5e
2,100
require_relative 'tests_for_content_sets.rb' gem 'minitest' require 'minitest/autorun' require 'minitest/pride' require 'minitest/mock' require 'mocha/setup' require 'commendo' module Commendo class RedisContentSetTest < Minitest::Test def setup Commendo.config do |config| config.backend = :redis config.host = 'localhost' config.port = 6379 config.database = 15 end Redis.new(host: Commendo.config.host, port: Commendo.config.port, db: Commendo.config.database).flushdb @key_base = 'CommendoTests' @cs = ContentSet.new(key_base: @key_base) end def create_tag_set(kb) Commendo::TagSet.new(key_base: kb) end def create_content_set(key_base, ts = nil) Commendo::ContentSet.new(key_base: key_base, tag_set: ts) end def test_gives_similarity_key_for_resource key_base = 'CommendoTestsFooBarBaz' cs = create_content_set(key_base) assert_equal 'CommendoTestsFooBarBaz:similar:resource-1', cs.similarity_key('resource-1') end def test_calculate_yields_after_each (3..23).each do |group| (3..23).each do |res| @cs.add_by_group(group, res) if res % group == 0 end end expected_keys = ['CommendoTests:resources:3', 'CommendoTests:resources:4', 'CommendoTests:resources:5', 'CommendoTests:resources:6', 'CommendoTests:resources:7', 'CommendoTests:resources:8', 'CommendoTests:resources:9', 'CommendoTests:resources:10', 'CommendoTests:resources:11', 'CommendoTests:resources:12', 'CommendoTests:resources:13', 'CommendoTests:resources:14', 'CommendoTests:resources:15', 'CommendoTests:resources:16', 'CommendoTests:resources:17', 'CommendoTests:resources:18', 'CommendoTests:resources:19', 'CommendoTests:resources:20', 'CommendoTests:resources:21', 'CommendoTests:resources:22', 'CommendoTests:resources:23'] actual_keys = [] @cs.calculate_similarity { |key, index, total| actual_keys << key } assert_equal expected_keys.sort, actual_keys.sort end include TestsForContentSets end end
36.842105
645
0.709524
1d17559efa6b0e01a4612ba0c092f5ec6898ca7d
1,349
module OnTheSpot module Generators class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) desc "This generator installs jEditable and some glue javascript (if rails < 3.1) and installs the locale" #def download_jeditable # # Downloading latest jEditable # get "http://www.appelsiini.net/download/jquery.jeditable.js", "public/javascripts/jquery.jeditable.mini.js" #end def copy_javascripts if ::Rails.version[0..2].to_f >= 3.1 #puts "The javascripts do not need to be installed since Rails 3.1" else copy_file "../../../../../app/assets/javascripts/on_the_spot_code.js", "public/javascripts/on_the_spot.js" copy_file "../../../../../app/assets/javascripts/jquery.jeditable.js", "public/javascripts/jquery.jeditable.js" copy_file "../../../../../app/assets/javascripts/jquery.jeditable.checkbox.js", "public/javascripts/jquery.jeditable.checkbox.js" copy_file "../../../../../app/assets/stylesheets/on_the_spot.css", "public/stylesheets/on_the_spot.css" end end def copy_locales copy_file "on_the_spot.en.yml", "config/locales/on_the_spot.en.yml" copy_file "on_the_spot.fr.yml", "config/locales/on_the_spot.fr.yml" end end end end
43.516129
139
0.66642
037cde278db2319c82d0480b1a551de57e3c140b
3,598
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_04_01 module Models # # Parameters that define the operation to create a connection monitor. # class ConnectionMonitor include MsRestAzure # @return [String] Connection monitor location. attr_accessor :location # @return [Hash{String => String}] Connection monitor tags. attr_accessor :tags # @return [ConnectionMonitorSource] Describes the source of connection # monitor. attr_accessor :source # @return [ConnectionMonitorDestination] Describes the destination of # connection monitor. attr_accessor :destination # @return [Boolean] Determines if the connection monitor will start # automatically once created. Default value: true . attr_accessor :auto_start # @return [Integer] Monitoring interval in seconds. Default value: 60 . attr_accessor :monitoring_interval_in_seconds # # Mapper for ConnectionMonitor class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ConnectionMonitor', type: { name: 'Composite', class_name: 'ConnectionMonitor', model_properties: { location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, source: { client_side_validation: true, required: true, serialized_name: 'properties.source', type: { name: 'Composite', class_name: 'ConnectionMonitorSource' } }, destination: { client_side_validation: true, required: true, serialized_name: 'properties.destination', type: { name: 'Composite', class_name: 'ConnectionMonitorDestination' } }, auto_start: { client_side_validation: true, required: false, serialized_name: 'properties.autoStart', default_value: true, type: { name: 'Boolean' } }, monitoring_interval_in_seconds: { client_side_validation: true, required: false, serialized_name: 'properties.monitoringIntervalInSeconds', default_value: 60, type: { name: 'Number' } } } } } end end end end
30.752137
77
0.503335
ab1104f0ce094d4e804bf5038f3725942d734f08
2,251
class Sys::Setting < Sys::Model::Base::Setting include Sys::Model::Base set_config :common_ssl, :name => "共有SSL", :default => 'disabled', options: [['使用する', 'enabled'], ['使用しない', 'disabled']], form_type: :radio_buttons set_config :pass_reminder_mail_sender, :name => "パスワード変更メール送信元アドレス", :default => 'noreply' set_config :file_upload_max_size, :name => "添付ファイル最大サイズ", :comment => 'MB', :default => 50 set_config :maintenance_mode, :name => "メンテナンスモード", :default => 'disabled', options: [['有効にする', 'enabled'], ['無効にする', 'disabled']], form_type: :radio_buttons validates :name, presence: true def self.use_common_ssl? return false if Sys::Setting.value(:common_ssl) != 'enabled' return false if Sys::Setting.setting_extra_value(:common_ssl, :common_ssl_uri).blank? return true end def self.ext_upload_max_size_list return @ext_upload_max_size_list if @ext_upload_max_size_list csv = Sys::Setting.setting_extra_value(:file_upload_max_size, :extension_upload_max_size).to_s @ext_upload_max_size_list = {} csv.split(/(\r\n|\n)/u).each_with_index do |line, idx| line = line.to_s.gsub(/#.*/, "") line.strip! next if line.blank? data = line.split(/\s*,\s*/) ext = data[0].strip size = data[1].strip @ext_upload_max_size_list[ext.to_s] = size.to_i end return @ext_upload_max_size_list end def self.is_maintenance_mode? return false if Sys::Setting.value(:maintenance_mode) != 'enabled' #return false if Sys::Setting.setting_extra_value(:maintenance_mode).blank? return true end def self.get_maintenance_start_at return nil if Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_start_at).blank? "#{Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_start_at)} から" end def self.get_maintenance_end_at return nil if Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_end_at).blank? "#{Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_end_at)} まで" end def self.get_upload_max_size(ext) ext.gsub!(/^\./, '') list = Sys::Setting.ext_upload_max_size_list return list[ext.to_s] if list.include?(ext.to_s) return nil end end
35.171875
99
0.705464
b90674bc267a1b96861fcb84be095b9691b16349
441
# frozen_string_literal: true module Mutations class UpdateS3Bucket < ::Mutations::BaseMutation argument :id, ID, required: true argument :name, String, required: true argument :access_key_id, String, required: true argument :secret_access_key, String, required: true type Types::S3BucketType def resolve(attributes) S3BucketUpdateService.call(**attributes, user: context[:current_user]) end end end
25.941176
76
0.734694
ed5a0f24ed0679a80bbfb40f69912486bc77a984
1,024
# frozen_string_literal: true class IssuablePolicy < BasePolicy delegate { @subject.project } condition(:locked, scope: :subject, score: 0) { @subject.discussion_locked? } condition(:is_project_member) { @user && @subject.project && @subject.project.team.member?(@user) } desc "User is the assignee or author" condition(:assignee_or_author) do @user && @subject.assignee_or_author?(@user) end condition(:is_author) { @subject&.author == @user } rule { can?(:guest_access) & assignee_or_author }.policy do enable :read_issue enable :update_issue enable :reopen_issue end rule { can?(:read_merge_request) & assignee_or_author }.policy do enable :update_merge_request enable :reopen_merge_request end rule { is_author }.policy do enable :resolve_note end rule { locked & ~is_project_member }.policy do prevent :create_note prevent :admin_note prevent :resolve_note prevent :award_emoji end end IssuablePolicy.prepend_mod_with('IssuablePolicy')
25.6
101
0.72168
26179ddef29db5e222942d86b8e5f85d52e983f9
2,661
# frozen_string_literal: true require 'test_helper' class ObservationStatusTest < ActiveSupport::TestCase setup do @observation = observations(:observation) end test 'starts with a registered status' do assert_nil @observation.value assert_nil @observation.lab_test_value_id assert_equal 'registered', @observation.status end test 'transitions from registered to registered' do @observation.value = nil @observation.lab_test_value_id = nil @observation.evaluate! assert_equal 'registered', @observation.status end test 'transitions from registered to preliminary' do @observation.value = 1 @observation.lab_test_value_id = nil @observation.evaluate! assert_equal 'preliminary', @observation.status, 'Value' @observation.value = nil @observation.lab_test_value_id = 1 @observation.evaluate! assert_equal 'preliminary', @observation.status, 'Value CodeableConcept' end test 'transitions from preliminary to registered' do @observation.value = 1 @observation.evaluate! assert_equal 'preliminary', @observation.status @observation.value = nil @observation.evaluate! assert_equal 'registered', @observation.status end test 'transitions from preliminary to preliminary' do @observation.value = 1 @observation.evaluate! assert_equal 'preliminary', @observation.status @observation.value = 2 @observation.evaluate! assert_equal 'preliminary', @observation.status end test 'does not transition from registered to final' do @observation.value = nil @observation.lab_test_value_id = nil assert_raises AASM::InvalidTransition do @observation.certify! end assert_equal 'registered', @observation.status end test 'transitions a value from preliminary to final' do @observation.value = 1 @observation.lab_test_value_id = nil @observation.evaluate! assert_equal 'preliminary', @observation.status @observation.certify! assert_equal 'final', @observation.status end test 'transitions a CodeableConcept from preliminary to final' do @observation.value = nil @observation.lab_test_value_id = 1 @observation.evaluate! assert_equal 'preliminary', @observation.status @observation.certify! assert_equal 'final', @observation.status end test 'does not transition from final to preliminary' do @observation.value = 1 @observation.evaluate! @observation.certify! assert_equal 'final', @observation.status @observation.value = nil @observation.evaluate! assert_equal 'amended', @observation.status end end
25.342857
76
0.730177
bbd93b99d0a8a4d8a710016fee94fc275494e97b
1,119
module Admin class UsersController < AdminController def index redirect_to admin_path(anchor: 'user_management') end def edit add_breadcrumb 'Edit Users', :edit_users_path @user = User.find(params[:id]) end def show @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.assign_roles_and_email(params) flash[:notice] = 'Successfully updated user.' redirect_to_admin end def send_invitation User.invite!(email: params[:email]) redirect_to_admin end def toggle_approved @user = User.find(params[:id]) @user.approved = [email protected] @user.save redirect_to_admin end def unlock @user = User.find(params[:id]) @user.unlock redirect_to_admin end def destroy @user = User.find(params[:id]) if @user.destroy flash[:notice] = 'Successfully deleted User.' redirect_to_admin end end private def redirect_to_admin redirect_to "#{admin_path}#user_management" end end end
19.982143
55
0.622878
18dc6c28b6e05512d5cfa579f7bb81b1a26bba43
3,923
require 'spec_helper' module Codebreaker describe Game do context "Start game" do let(:game) { Game.new('Dima') } before do game.start end it "saves secret code" do expect(game.instance_variable_get(:@secret_code)).not_to be_empty end it "saves 4 numbers secret code" do expect(game.instance_variable_get(:@secret_code)).to have(4).items end it "saves secret code with numbers from 1 to 6" do expect(game.instance_variable_get(:@secret_code)).to_not include('0','7','8','9') end end context "Setting parametrs" do let(:game) { Game.new('Dima') } before do game.start game.attempts = 10 end it "Setting the number of attempts" do expect(game.instance_variable_get(:@attempts)).to_not be_nil end it "Setting the number of attempts is not more than 10" do expect(game.instance_variable_get(:@attempts)).to be < 11 end it "Comparison of the secret code with user's code" do game.user_code_split '1234' game.instance_variable_set(:@secret_code, ["1","2","3","4"]) expect(game.instance_variable_get(:@secret_code)).to eq(game.instance_variable_get(:@user_code)) end it "Convert string user's code to array user's code" do expect(game.user_code_split('1234')).to eq(["1","2","3","4"]) end end context "Request a hint" do let(:game) { Game.new('Dima') } before do game.start end it "Request a hint return three \"*\"" do requests_hint = game.requests_hint.split '' requests_hint = requests_hint.each_with_object(Hash.new(0)) {|word, hash| hash[word] += 1} expect(requests_hint['*']).to eq(3) end it "If Request a hint else change flag using hint" do game.requests_hint expect(game.hint).to be true end it "If twice call requests_hint returns the same result" do first_call = game.requests_hint expect(game.requests_hint).to eq(first_call) end end context "Return answer" do let(:game) { Game.new('Dima') } before do game.start game.attempts = 1 game.instance_variable_set(:@secret_code, ["1","2","3","4"]) end it "Check return \"+\"" do expect('+').to eq game.comparison_codes('1555') end it "Check return \"++\"" do expect('++').to eq game.comparison_codes('1255') end it "Check return \"+++\"" do expect('+++').to eq game.comparison_codes('1235') end it "Check return \"+++-\"" do expect('++--').to eq game.comparison_codes('1243') end it "Check return \"++-\"" do expect('++-').to eq game.comparison_codes('1245') end it "Check return \"+--\"" do expect('+--').to eq game.comparison_codes('1345') end it "Check return \"+-\"" do expect('+-').to eq game.comparison_codes('1552') end it "Check return \"-\"" do expect('-').to eq game.comparison_codes('6661') end it "Check return \"--\"" do expect('--').to eq game.comparison_codes('6621') end it "Check return \"---\"" do expect('---').to eq game.comparison_codes('6321') end it "Check return \"----\"" do expect('----').to eq game.comparison_codes('4321') end it "Check return \"user's win\"" do expect(true).to eq game.comparison_codes('1234') end it "Check return \"losing user\"" do game.comparison_codes('3333') expect(game.comparison_codes('2341')).to be_falsey end it "Checking the number of attempts to change the counter" do expect{game.comparison_codes '1552' }.to change{ game.instance_variable_get(:@attempts_count) }.to 1 end end end end
26.687075
108
0.585011
036acb9a0c5922a78fa8b7436b7bc1690290cff8
1,666
# -*- coding: utf-8 -*- # Copyright (C) 2010, 2011 Rocky Bernstein <[email protected]> require 'rubygems'; require 'require_relative' require_relative '../command' class Trepan::Command::SaveCommand < Trepan::Command unless defined?(HELP) NAME = File.basename(__FILE__, '.rb') HELP = <<-HELP #{NAME} [--[no-]erase] [--output|-o FILENAME] Save settings to file FILENAME. If FILENAME not given one will be made selected. HELP CATEGORY = 'running' MAX_ARGS = 1 # Need at most this many SHORT_HELP = 'Send debugger state to a file' DEFAULT_OPTIONS = { :erase => true, } end def parse_options(options, args) # :nodoc parser = OptionParser.new do |opts| opts.on("-e", "--[no-]erase", "Add line to erase after reading") do |v| options[:erase] = v end opts.on("-o", "--output FILE", String, "Save file to FILE. ") do |filename| options[:filename] = filename end end parser.parse(args) return options end # This method runs the command def run(args) options = parse_options(DEFAULT_OPTIONS.dup, args[1..-1]) save_filename = @proc.save_commands(options) msg "Debugger commands written to file: #{save_filename}" if save_filename end end if __FILE__ == $0 require_relative '../mock' dbgr, cmd = MockDebugger::setup require 'tmpdir' cmd.run([cmd.name]) # require_relative '../../lib/trepanning'; debugger cmd.run([cmd.name, '--erase', '--output', File.join(Dir.tmpdir, 'save_file.txt')]) # A good test would be to see we can read in those files without error. end
28.237288
73
0.627851
f7f9663f7e262576397eaee7ddee637f1836cee2
2,755
# frozen_string_literal: true module RuboCop # This module holds the RuboCop version information. module Version STRING = '1.22.3' MSG = '%<version>s (using Parser %<parser_version>s, '\ 'rubocop-ast %<rubocop_ast_version>s, ' \ 'running on %<ruby_engine>s %<ruby_version>s %<ruby_platform>s)' CANONICAL_FEATURE_NAMES = { 'Rspec' => 'RSpec' }.freeze # @api private def self.version(debug: false, env: nil) if debug verbose_version = format(MSG, version: STRING, parser_version: Parser::VERSION, rubocop_ast_version: RuboCop::AST::Version::STRING, ruby_engine: RUBY_ENGINE, ruby_version: RUBY_VERSION, ruby_platform: RUBY_PLATFORM) return verbose_version unless env extension_versions = extension_versions(env) return verbose_version if extension_versions.empty? <<~VERSIONS #{verbose_version} #{extension_versions.join("\n")} VERSIONS else STRING end end # @api private def self.extension_versions(env) features = Util.silence_warnings do # Suppress any config issues when loading the config (ie. deprecations, # pending cops, etc.). env.config_store.unvalidated.for_pwd.loaded_features.sort end features.map do |loaded_feature| next unless (match = loaded_feature.match(/rubocop-(?<feature>.*)/)) feature = match[:feature] begin require "rubocop/#{feature}/version" rescue LoadError # Not worth mentioning libs that are not installed else next unless (feature_version = feature_version(feature)) " - #{loaded_feature} #{feature_version}" end end.compact end # Returns feature version in one of two ways: # # * Find by RuboCop core version style (e.g. rubocop-performance, rubocop-rspec) # * Find by `bundle gem` version style (e.g. rubocop-rake) # # @api private def self.feature_version(feature) capitalized_feature = feature.capitalize extension_name = CANONICAL_FEATURE_NAMES.fetch(capitalized_feature, capitalized_feature) # Find by RuboCop core version style (e.g. rubocop-performance, rubocop-rspec) RuboCop.const_get(extension_name)::Version::STRING rescue NameError begin # Find by `bundle gem` version style (e.g. rubocop-rake, rubocop-packaging) RuboCop.const_get(extension_name)::VERSION rescue NameError # noop end end # @api private def self.document_version STRING.match('\d+\.\d+').to_s end end end
32.034884
94
0.629038
1aee1dc3916d3cea66a98c281195c7e0ecc1a913
1,312
class Cocoapods < Formula desc "Dependency manager for Cocoa projects" homepage "https://cocoapods.org/" url "https://github.com/CocoaPods/CocoaPods/archive/1.10.0.tar.gz" sha256 "d44c70047020ea114ca950df6d4499b1f86e5e7bbd3536a46f6fa3e32f1df21e" license "MIT" bottle do sha256 "5fec9be27505bf6858fdbd409f50247987a03471dd0dfe0af15ddb58c267f604" => :big_sur sha256 "e134955d0501635a62e16c9c9b10e01c5f8b9e0ffdeee3d7b778db5845bd88a1" => :catalina sha256 "9977145a066bf2545f5fe3d1ddd41f0360c7efe46523087d56cf06ac305eb069" => :mojave sha256 "783448183d3bb63dc46c8148fe1f3b783b705bfda763fb6f6237760e30b94ff6" => :high_sierra end depends_on "pkg-config" => :build uses_from_macos "libffi", since: :catalina uses_from_macos "ruby", since: :catalina def install if MacOS.version >= :mojave && MacOS::CLT.installed? ENV["SDKROOT"] = ENV["HOMEBREW_SDKROOT"] = MacOS::CLT.sdk_path(MacOS.version) end ENV["GEM_HOME"] = libexec system "gem", "build", "cocoapods.gemspec" system "gem", "install", "cocoapods-#{version}.gem" # Other executables don't work currently. bin.install libexec/"bin/pod", libexec/"bin/xcodeproj" bin.env_script_all_files(libexec/"bin", GEM_HOME: ENV["GEM_HOME"]) end test do system "#{bin}/pod", "list" end end
35.459459
93
0.74314
1d6e990e93feaca486c01a0747b613ff110006bb
225
# frozen_string_literal: true class CreateLocations < ActiveRecord::Migration[5.0] def change create_table :locations do |t| t.string :title t.string :room t.timestamps null: false end end end
17.307692
52
0.68
91dda0da8af0d11f87c2a551665605a17e9fe2ae
702
# frozen_string_literal: true require 'common/client/configuration/soap' require 'emis/configuration' module EMIS # Configuration for {EMIS::MilitaryInformationService} # includes API URL and breakers service name. # class MilitaryInformationConfiguration < Configuration # Military Information Service URL # @return [String] Military Information Service URL def base_path URI.join(Settings.emis.host, Settings.emis.military_information_url.v1).to_s end # :nocov: # Military Information Service breakers name # @return [String] Military Information Service breakers name def service_name 'EmisMilitaryInformation' end # :nocov: end end
26
82
0.74359
ff0523a038f38636aa10cc9f847fdd6eae022bba
1,796
# typed: true # frozen_string_literal: true require "pathname" module Packwerk class PackageSet include Enumerable PACKAGE_CONFIG_FILENAME = "package.yml" class << self def load_all_from(root_path, package_pathspec: nil) package_paths = package_paths(root_path, package_pathspec || "**") packages = package_paths.map do |path| root_relative = path.dirname.relative_path_from(root_path) Package.new(name: root_relative.to_s, config: YAML.load_file(path)) end create_root_package_if_none_in(packages) new(packages) end def package_paths(root_path, package_pathspec) bundle_path_match = Bundler.bundle_path.join("**").to_s glob_patterns = Array(package_pathspec).map do |pathspec| File.join(root_path, pathspec, PACKAGE_CONFIG_FILENAME) end Dir.glob(glob_patterns) .map { |path| Pathname.new(path).cleanpath } .reject { |path| path.realpath.fnmatch(bundle_path_match) } end private def create_root_package_if_none_in(packages) return if packages.any?(&:root?) packages << Package.new(name: Package::ROOT_PACKAGE_NAME, config: nil) end end def initialize(packages) # We want to match more specific paths first sorted_packages = packages.sort_by { |package| -package.name.length } @packages = sorted_packages.each_with_object({}) { |package, hash| hash[package.name] = package } end def each(&blk) @packages.values.each(&blk) end def fetch(name) @packages[name] end def package_from_path(file_path) path_string = file_path.to_s @packages.values.find { |package| package.package_path?(path_string) } end end end
27.212121
103
0.667595
bbeb0054ed15a155d500eb00ebeec97dae445ef1
3,399
require 'rails_helper' RSpec.describe Queries::CCLOW::TargetQuery do before_all do @geography1 = create(:geography, region: 'East Asia & Pacific') @geography2 = create(:geography, region: 'Europe & Central Asia') @geography3 = create(:geography, region: 'Europe & Central Asia') @target1 = create( :target, :published, geography: @geography1, target_type: 'base_year_target', description: 'Assure the development of climate resilience by reducing at least by 50% the climate change', events: [ build(:event, event_type: 'set', date: '2010-01-01'), build(:event, event_type: 'updated', date: '2013-03-01') ] ) @target2 = create( :target, :published, geography: @geography2, target_type: 'base_year_target', description: 'By 2020, the NAP process is completed by 2020', events: [ build(:event, event_type: 'set', date: '2014-12-02') ] ) @target3 = create( :target, :published, geography: @geography3, target_type: 'intensity_target', description: 'To have, by 2020, six regional risk-management plans (covering the entire country)', events: [ build(:event, event_type: 'set', date: '2016-12-02') ] ) @target4 = create( :target, :published, geography: @geography1, target_type: 'trajectory_target', description: 'Some climate target', events: [ build(:event, event_type: 'set', date: '2010-12-02') ] ) # It shouldn't show, so total is 4 not 5 at max! @unpublished_target = create(:target, :draft) end subject { described_class } describe 'call' do it 'should return all targets with no filters' do results = subject.new({}).call expect(results.size).to eq(4) expect(results).not_to include(@unpublished_target) end it 'should use full text search' do results = subject.new(q: 'climate').call expect(results.size).to eq(2) expect(results).to contain_exactly(@target1, @target4) end it 'should filter by type' do results = subject.new(type: %w(intensity_target trajectory_target)).call expect(results.size).to eq(2) expect(results).to contain_exactly(@target3, @target4) end it 'should filter by multiple params' do results = subject.new(q: 'risk', last_change_from: '2014').call expect(results).to contain_exactly(@target3) end it 'should be ordered by last event date' do results = subject.new({}).call expect(results.map(&:id)).to eq([@target3.id, @target2.id, @target1.id, @target4.id]) end it 'should filter by region' do results = subject.new(region: 'Europe & Central Asia').call expect(results.size).to eq(2) expect(results).to contain_exactly(@target2, @target3) end it 'should filter by geography' do results = subject.new(geography: [@geography1.id, @geography3.id]).call expect(results.size).to eq(3) expect(results).to contain_exactly(@target1, @target3, @target4) end it 'should filter by region and geography' do results = subject.new(geography: [@geography2.id], region: 'East Asia & Pacific').call expect(results.size).to eq(3) expect(results).to contain_exactly(@target1, @target2, @target4) end end end
31.183486
113
0.638423
112367fea2e5b115db3abba5b8e29a16b1f4a21c
1,231
# -*- encoding: utf-8 -*- # stub: rouge 3.17.0 ruby lib Gem::Specification.new do |s| s.name = "rouge".freeze s.version = "3.17.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "bug_tracker_uri" => "https://github.com/rouge-ruby/rouge/issues", "changelog_uri" => "https://github.com/rouge-ruby/rouge/blob/master/CHANGELOG.md", "documentation_uri" => "https://rouge-ruby.github.io/docs/", "source_code_uri" => "https://github.com/rouge-ruby/rouge" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Jeanine Adkisson".freeze] s.date = "2020-03-10" s.description = "Rouge aims to a be a simple, easy-to-extend drop-in replacement for pygments.".freeze s.email = ["[email protected]".freeze] s.executables = ["rougify".freeze] s.files = ["bin/rougify".freeze] s.homepage = "http://rouge.jneen.net/".freeze s.licenses = ["MIT".freeze, "BSD-2-Clause".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze) s.rubygems_version = "3.1.2".freeze s.summary = "A pure-ruby colorizer based on pygments".freeze s.installed_by_version = "3.1.2" if s.respond_to? :installed_by_version end
49.24
316
0.697807
ffd1fdf6d34ea8c8d0a38063ac8cd84216974cce
298
# The metric where the mongrel queue time is stored class NewRelic::MetricParser::WebFrontend < NewRelic::MetricParser def short_name if segments.last == 'Average Queue Time' 'Mongrel Average Queue Time' else super end end def legend_name 'Mongrel Wait' end end
21.285714
66
0.701342
e20f4a7d4404c83c636b76345bb131b13a67a7a7
4,166
require "spec_helper" describe Paperclip::Storage::Webdav do let(:original_path) { "/files/original/image.png" } let(:thumb_path) { "/files/thumb/image.png" } [:attachment, :attachment_with_public_url].each do |attachment| let(attachment) do model = double() model.stub(:id).and_return(1) model.stub(:image_file_name).and_return("image.png") options = {} options[:storage] = :webdav options[:path] = "/files/:style/:filename" options[:webdav_servers] = [ {:url => "http://webdav1.example.com"}, {:url => "http://webdav2.example.com"} ] options[:public_url] = "http://public.example.com" if attachment == :attachment_with_public_url attachment = Paperclip::Attachment.new(:image, model, options) attachment.instance_variable_set(:@original_path, original_path) attachment.instance_variable_set(:@thumb_path, thumb_path) attachment end end describe "generate public url" do [:attachment, :attachment_with_public_url].each do |a| context a do [:original, :thumb].each do |style| it "with #{style} style" do attachment.instance_eval do host = "" if a == :attachment host = "http://webdav1.example.com" else host = "http://public.example.com" end should_receive(:public_url).and_return("#{host}/files/#{style}/image.png") public_url style end end end end end end describe "exists?" do it "should returns false if original_name not set" do attachment.stub(:original_filename).and_return(nil) attachment.exists?.should be_false end it "should returns true if file exists on the primary server" do attachment.instance_eval do primary_server.should_receive(:file_exists?).with(@original_path).and_return(true) end attachment.exists?.should be_true end it "accepts an optional style_name parameter to build the correct file pat" do attachment.instance_eval do primary_server.should_receive(:file_exists?).with(@thumb_path).and_return(true) end attachment.exists?(:thumb).should be_true end end describe "flush_writes" do it "store all files on each server" do original_file = double("file") thumb_file = double("file") attachment.instance_variable_set(:@queued_for_write, { :original => double("file"), :thumb => double("file") }) attachment.instance_eval do @queued_for_write.each do |k,v| v.should_receive(:rewind) end servers.each do |server| server.should_receive(:put_file).with(@original_path, @queued_for_write[:original]) server.should_receive(:put_file).with(@thumb_path, @queued_for_write[:thumb]) end end attachment.should_receive(:after_flush_writes).with(no_args) attachment.flush_writes attachment.queued_for_write.should eq({}) end end describe "flush_deletes" do it "deletes files on each servers" do attachment.instance_variable_set(:@queued_for_delete, [original_path, thumb_path]) attachment.instance_eval do servers.each do |server| @queued_for_delete.each do |path| server.should_receive(:delete_file).with(path) end end end attachment.flush_deletes attachment.instance_variable_get(:@queued_for_delete).should eq([]) end end describe "copy_to_local_file" do it "save file" do attachment.instance_eval do primary_server.should_receive(:get_file).with(@original_path, "/local").and_return(nil) end attachment.copy_to_local_file(:original, "/local") end it "save file with custom style" do attachment.instance_eval do primary_server.should_receive(:get_file).with(@thumb_path, "/local").and_return(nil) end attachment.copy_to_local_file(:thumb, "/local") end end end
33.063492
101
0.637782
ac820bc0e1d86c70fbde3f36ff18b82dd203c239
137
require "test_helper" describe CountriesController do it "should get index" do get :index assert_response :success end end
13.7
31
0.737226
e9746825cc4e352080a7793083e6d7064d4c7b17
415
require 'spec_helper' describe Kojo::Commands::SingleCmd do subject { described_class } context "without arguments" do it "shows short usage" do expect { subject.execute %w[single]}.to output_approval('cli/single/usage') end end context "with --help" do it "shows long usage" do expect { subject.execute %w[single --help] }.to output_approval('cli/single/help') end end end
23.055556
88
0.684337
03f99096b71714a3c9c043f22f0d2dcf4f12ef26
34,967
require 'spec_helper_min' require 'support/helpers' require 'helpers/feature_flag_helper' require 'helpers/database_connection_helper' describe Carto::Api::Public::DataObservatoryController do include_context 'users helper' include HelperMethods include FeatureFlagHelper include DatabaseConnectionHelper before(:all) do @master = @user1.api_key @not_granted_token = @user1.api_keys.create_regular_key!(name: 'not_do', grants: [{ type: 'apis', apis: [] }]).token do_grants = [{ type: 'apis', apis: ['do'] }] @granted_token = @user1.api_keys.create_regular_key!(name: 'do', grants: do_grants).token @headers = { 'CONTENT_TYPE' => 'application/json' } @feature_flag = create(:feature_flag, name: 'do-instant-licensing', restricted: true) end after(:all) do @feature_flag.destroy end before(:each) do mock_do_metadata host! "#{@user1.username}.localhost.lan" end shared_examples 'an endpoint validating a DO API key' do before(:all) do @params ||= {} end it 'returns 401 if the API key is wrong' do get_json endpoint_url(@params.merge(api_key: 'wrong')), @headers do |response| expect(response.status).to eq(401) end end it 'returns 403 when using a regular API key without DO grant' do get_json endpoint_url(@params.merge(api_key: @not_granted_token)), @headers do |response| expect(response.status).to eq(403) end end it 'returns 200 when using the master API key' do get_json endpoint_url(@params.merge(api_key: @master)), @headers do |response| expect(response.status).to eq(200) end end it 'returns 200 when using a regular API key with DO grant' do get_json endpoint_url(@params.merge(api_key: @granted_token)), @headers do |response| expect(response.status).to eq(200) end end end def endpoint_url(params = {}) send(@url_helper, params) end describe 'token' do before(:all) do @url_helper = 'api_v4_do_token_url' @expected_body = [{ 'access_token' => 'tokenuco' }] end before(:each) do Cartodb::Central.any_instance.stubs(:get_do_token).returns(@expected_body.to_json) end after(:each) do Cartodb::Central.any_instance.unstub(:get_do_token) end it_behaves_like 'an endpoint validating a DO API key' it 'calls Central to request the token' do Cartodb::Central.any_instance.expects(:get_do_token).with(@user1.username).once.returns(@expected_body.to_json) get_json endpoint_url(api_key: @master), @headers end it 'returns 200 with an access token' do get_json endpoint_url(api_key: @master), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq @expected_body end end it 'returns 500 with an explicit message if the central call fails' do central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json) central_error = CartoDB::CentralCommunicationFailure.new(central_response) Cartodb::Central.any_instance.stubs(:get_do_token).raises(central_error) get_json endpoint_url(api_key: @master), @headers do |response| expect(response.status).to eq(500) expect(response.body).to eq(errors: ["boom"]) end end end describe 'subscriptions' do before(:all) do @url_helper = 'api_v4_do_subscriptions_show_url' @next_year = Time.now + 1.year dataset1 = { dataset_id: 'carto.zzz.table1', expires_at: @next_year, status: 'active', project: 'carto', dataset: 'zzz', table: 'table1' } dataset2 = { dataset_id: 'carto.abc.table2', expires_at: @next_year, status: 'active', project: 'carto', dataset: 'abc', table: 'table2' } dataset3 = { dataset_id: 'opendata.tal.table3', expires_at: @next_year, status: 'active', project: 'opendata', dataset: 'tal', table: 'table3' } dataset4 = { dataset_id: 'carto.abc.expired', expires_at: Time.now - 1.day, status: 'active', project: 'carto', dataset: 'abc', table: 'expired' } dataset5 = { dataset_id: 'carto.abc.requested', expires_at: @next_year, status: 'requested', project: 'carto', dataset: 'abc', table: 'requested' } bq_datasets = [dataset1, dataset2, dataset3, dataset4, dataset5] @redis_key = "do:#{@user1.username}:datasets" $users_metadata.hset(@redis_key, 'bq', bq_datasets.to_json) end after(:all) do $users_metadata.del(@redis_key) end before(:each) do @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:sync).returns({sync_status: 'synced', sync_table: 'my_do_subscription'}) @doss.stubs(:parsed_entity_id).returns({}) end it_behaves_like 'an endpoint validating a DO API key' it 'checks if DO is enabled' do Carto::User.any_instance.expects(:do_enabled?).once get_json endpoint_url(api_key: @master), @headers end it 'returns 200 with the right status' do get_json endpoint_url(api_key: @master), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:status]).to eq 'expired' expect(datasets[1][:status]).to eq 'requested' expect(datasets[2][:status]).to eq 'active' end end it 'returns 200 with an empty array if the user does not have datasets' do host! "#{@user2.username}.localhost.lan" get_json endpoint_url(api_key: @user2.api_key), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 0 end end context 'ordering' do it 'orders by id ascending by default' do get_json endpoint_url(api_key: @master), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:id]).to eq 'carto.abc.expired' expect(datasets[4][:id]).to eq 'opendata.tal.table3' end end it 'orders by id descending' do get_json endpoint_url(api_key: @master, order_direction: 'desc'), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:id]).to eq 'opendata.tal.table3' expect(datasets[1][:id]).to eq 'carto.zzz.table1' end end it 'orders by project descending' do params = { api_key: @master, order: 'project', order_direction: 'desc' } get_json endpoint_url(params), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:id]).to eq 'opendata.tal.table3' end end it 'orders by dataset ascending' do params = { api_key: @master, order: 'dataset', order_direction: 'asc' } get_json endpoint_url(params), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:id]).to eq 'carto.abc.table2' expect(datasets[1][:id]).to eq 'carto.abc.expired' end end it 'orders by table descending' do params = { api_key: @master, order: 'table', order_direction: 'desc' } get_json endpoint_url(params), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 5 expect(datasets[0][:id]).to eq 'opendata.tal.table3' expect(datasets[1][:id]).to eq 'carto.abc.table2' end end end context 'filter by status' do it 'returns only active datasets' do get_json endpoint_url(api_key: @master, status: 'active'), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 3 end end it 'returns only requested dataset' do get_json endpoint_url(api_key: @master, status: 'requested'), @headers do |response| expect(response.status).to eq(200) datasets = response.body[:subscriptions] expect(datasets.count).to eq 1 end end end describe 'sync_info' do before(:each) do @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:sync).returns({sync_status: 'unsynced'}) @doss.stubs(:parsed_entity_id).returns({}) end it 'returns 404 if the subscription_id is not a valid user subscription' do @url_helper = 'api_v4_do_subscription_sync_info_url' get_json endpoint_url(api_key: @master, subscription_id: 'wrong'), @headers do |response| expect(response.status).to eq(404) end end it 'returns 200 with sync info if the subscription_id is valid' do @url_helper = 'api_v4_do_subscription_sync_info_url' get_json endpoint_url(api_key: @master, subscription_id: 'carto.zzz.table1'), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq(sync_status: 'unsynced') end end end describe 'create_sync' do before(:each) do @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:create_sync!).returns({sync_status: 'syncing'}) @doss.stubs(:parsed_entity_id).returns({}) end it 'returns 404 if the subscription_id is not a valid user subscription' do @url_helper = 'api_v4_do_subscription_create_sync_url' post_json endpoint_url(api_key: @master, subscription_id: 'wrong'), @headers do |response| expect(response.status).to eq(404) end end it 'returns 200 with sync info if the subscription_id is valid' do @url_helper = 'api_v4_do_subscription_create_sync_url' post_json endpoint_url(api_key: @master, subscription_id: 'carto.zzz.table1'), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq(sync_status: 'syncing') end end end describe 'destroy_sync' do before(:each) do @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:remove_sync!).returns(nil) @doss.stubs(:parsed_entity_id).returns({}) end it 'returns 404 if the subscription_id is not a valid user subscription' do @url_helper = 'api_v4_do_subscription_destroy_sync_url' delete_json endpoint_url(api_key: @master, subscription_id: 'wrong'), @headers do |response| expect(response.status).to eq(404) end end it 'returns 204 if the subscription_id is valid' do @url_helper = 'api_v4_do_subscription_destroy_sync_url' delete_json endpoint_url(api_key: @master, subscription_id: 'carto.zzz.table1'), @headers do |response| expect(response.status).to eq(204) end end end end describe 'create_sample' do before(:each) do @doss = mock Carto::DoSampleServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:import_sample!).returns(nil) end it 'returns 200 if the dataset_id is valid' do @url_helper = 'api_v4_do_subscription_create_sample_url' post_json endpoint_url(api_key: @master, dataset_id: 'carto.zzz.table1'), @headers do |response| expect(response.status).to eq(204) end end end describe 'subscription' do before(:all) do @url_helper = 'api_v4_do_subscription_show_url' @next_year = (Time.now + 1.year).to_s @datasets = [{ dataset_id: 'carto.zzz.table1', expires_at: @next_year, status: 'active', project: 'carto', dataset: 'zzz', table: 'table1', :type=>"dataset", :id=>"carto.zzz.table1" }] @redis_key = "do:#{@user1.username}:datasets" $users_metadata.hset(@redis_key, 'bq', @datasets.to_json) end after(:all) do $users_metadata.del(@redis_key) end before(:each) do @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:parsed_entity_id).returns({type: 'dataset'}) end it 'checks if DO is enabled' do Carto::User.any_instance.expects(:do_enabled?).once get_json endpoint_url(api_key: @master, subscription_id: 'proj.dat.tab'), @headers end it 'returns 400 if the id param is not valid' do get_json endpoint_url(api_key: @master, subscription_id: 'wrong'), @headers do |response| expect(response.status).to eq(400) end end it 'returns 200 if the subscription_id is valid' do subscription_id = @datasets[0][:dataset_id] get_json endpoint_url(api_key: @master, subscription_id: subscription_id), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq @datasets[0] end end end describe 'subscription_info' do before(:each) do # Cartodb::Central.any_instance.stubs(:check_do_enabled).returns(true) Carto::DoLicensingService.any_instance.stubs(:subscriptions).returns([@params]) end after(:each) do # Cartodb::Central.any_instance.unstub(:check_do_enabled) Carto::DoLicensingService.any_instance.unstub(:subscriptions) end before(:all) do @url_helper = 'api_v4_do_subscription_info_url' @params = { id: 'carto.abc.dataset1', type: 'dataset' } end it 'checks if DO is enabled' do Carto::User.any_instance.expects(:do_enabled?).once get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers end it 'returns 400 if the id param is not valid' do get_json endpoint_url(api_key: @master, id: 'wrong'), @headers do |response| expect(response.status).to eq(400) expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil) end end it 'returns 400 if the type param is not valid' do get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'wrong'), @headers do |response| expect(response.status).to eq(400) expected_response = { errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography", errors_cause: nil } expect(response.body).to eq expected_response end end it 'returns 404 if the dataset metadata does not exist' do id = 'carto.abc.inexistent' get_json endpoint_url(api_key: @master, id: id, type: 'dataset'), @headers do |response| expect(response.status).to eq(404) expect(response.body).to eq(errors: "No metadata found for #{id}", errors_cause: nil) end end context 'with right metadata' do it 'returns 200 with the metadata for a dataset' do get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.dataset1', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end it 'returns 200 with the metadata for a geography' do subscription = { id: 'carto.abc.geography1', type: 'geography' } Carto::DoLicensingService.any_instance.stubs(:subscriptions).returns([subscription]) get_json endpoint_url(subscription.merge(api_key: @master)), @headers do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.geography1', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 90.0, tos: 'tos', tos_link: 'tos_link', type: 'geography' } expect(response.body).to eq expected_response end end it 'returns 200 and null values with the metadata for a dataset with null price and delivery days' do get_json endpoint_url(api_key: @master, id: 'carto.abc.datasetnull', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: nil, id: 'carto.abc.datasetnull', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: nil, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end it 'returns 200 and 0.0 as price with the metadata for a dataset with 0.0 as price' do get_json endpoint_url(api_key: @master, id: 'carto.abc.datasetzero', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.datasetzero', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end it 'returns the default delivery days if estimated_delivery_days is 0 and instant licensing is not enabled' do expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.dataset1', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } with_feature_flag @user1, 'do-instant-licensing', false do get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq expected_response end end end it 'returns 200 with empty array in available_in' do get_json endpoint_url(api_key: @master, id: 'carto.abc.datasetvalidatearrayempty', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) end end it 'returns 200 with a nil in available_in' do get_json endpoint_url(api_key: @master, id: 'carto.abc.datasetvalidatearraynil', type: 'dataset'), @headers do |response| expect(response.status).to eq(200) end end end end describe 'entity_info' do before(:all) do @url_helper = 'api_v4_do_entity_info_url' end before(:each) do # Cartodb::Central.any_instance.stubs(:check_do_enabled).returns(true) @doss = mock Carto::DoSyncServiceFactory.stubs(:get_for_user).returns(@doss) @doss.stubs(:parsed_entity_id).returns({}) end after(:each) do # Cartodb::Central.any_instance.unstub(:check_do_enabled) end it 'returns 200 with dataset info ' do dataset_id = 'carto.zzz.table1' dataset_info = { id: dataset_id, project: 'carto', dataset: 'zzz', table: 'table1', estimated_size: 10000, estimated_row_count: 1000, estimated_columns_count: 1000 } @doss.stubs(:entity_info).with(dataset_id).returns(dataset_info) get_json endpoint_url(api_key: @master, entity_id: dataset_id), @headers do |response| expect(response.status).to eq(200) expect(response.body).to eq(dataset_info) end end it 'returns 404 if the dataset does not exist ' do dataset_id = 'carto.zzz.table1' @doss.stubs(:entity_info).with(dataset_id).returns({ error: 'bad entity id'}) get_json endpoint_url(api_key: @master, entity_id: dataset_id), @headers do |response| expect(response.status).to eq(404) end end end describe 'subscribe' do before(:all) do @url_helper = 'api_v4_do_subscriptions_create_url' @payload = { id: 'carto.abc.dataset1', type: 'dataset' } end it 'returns 400 if the id param is not valid' do post_json endpoint_url(api_key: @master), id: 'wrong' do |response| expect(response.status).to eq(400) expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil) end end it 'returns 400 if the type param is not valid' do post_json endpoint_url(api_key: @master), id: 'carto.abc.dataset1', type: 'wrong' do |response| expect(response.status).to eq(400) expected_response = { errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography", errors_cause: nil } expect(response.body).to eq expected_response end end it 'returns 404 if the dataset metadata does not exist' do post_json endpoint_url(api_key: @master), id: 'carto.abc.inexistent', type: 'dataset' do |response| expect(response.status).to eq(404) expect(response.body).to eq(errors: "No metadata found for carto.abc.inexistent", errors_cause: nil) end end it 'returns 500 with an explicit message if the central call fails' do central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json) central_error = CartoDB::CentralCommunicationFailure.new(central_response) Carto::DoLicensingService.expects(:new).with(@user1.username).once.raises(central_error) post_json endpoint_url(api_key: @master), @payload do |response| expect(response.status).to eq(500) expect(response.body).to eq(errors: ["boom"]) end end it 'subscribes to public dataset' do dataset_id = 'carto.abc.public_dataset' DataObservatoryMailer.expects(:carto_request).never expected_params = { dataset_id: dataset_id, available_in: ['bq'], price: 0.0, created_at: Time.parse('2018/01/01 00:00:00'), expires_at: Time.parse('2019/01/01 00:00:00'), status: 'active' } mock_sync_service = mock Carto::DoSyncServiceFactory.expects(:get_for_user).once.returns(mock_sync_service) mock_sync_service.stubs(:parsed_entity_id).returns(expected_params) mock_service = mock mock_service.expects(:subscribe).with(expected_params).once Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service) Time.stubs(:now).returns(Time.parse('2018/01/01 00:00:00')) post_json endpoint_url(api_key: @master), id: dataset_id, type: 'dataset' do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.public_dataset', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end it 'creates a proper subscription request to premium data' do mailer_mock = stub(:deliver_now) dataset_id = 'carto.abc.geography1' dataset_name = 'CARTO geography 1' provider_name = 'CARTO' DataObservatoryMailer.expects(:user_request).with( @carto_user1, dataset_name, provider_name ).never DataObservatoryMailer.expects(:carto_request).with( @carto_user1, dataset_id, 3.0 ).once.returns(mailer_mock) expected_params = { dataset_id: 'carto.abc.geography1', available_in: ['bq'], price: 90.0, created_at: Time.parse('2018/01/01 00:00:00'), expires_at: Time.parse('2019/01/01 00:00:00'), status: 'requested' } mock_sync_service = mock Carto::DoSyncServiceFactory.expects(:get_for_user).once.returns(mock_sync_service) mock_sync_service.stubs(:parsed_entity_id).returns(expected_params) mock_service = mock mock_service.expects(:subscribe).with(expected_params).once Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service) Time.stubs(:now).returns(Time.parse('2018/01/01 00:00:00')) post_json endpoint_url(api_key: @master), id: 'carto.abc.geography1', type: 'geography' do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 3.0, id: 'carto.abc.geography1', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 90.0, tos: 'tos', tos_link: 'tos_link', type: 'geography' } expect(response.body).to eq expected_response end end it 'subscribes if instant licensing is enabled and delivery time is 0' do with_feature_flag @user1, 'do-instant-licensing', true do expected_params = { dataset_id: 'carto.abc.dataset1', available_in: ['bq'], price: 100.0, created_at: Time.parse('2018/01/01 00:00:00'), expires_at: Time.parse('2019/01/01 00:00:00'), status: 'active' } mock_sync_service = mock Carto::DoSyncServiceFactory.expects(:get_for_user).once.returns(mock_sync_service) mock_sync_service.stubs(:parsed_entity_id).returns(expected_params) mock_service = mock mock_service.expects(:subscribe).with(expected_params).once Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service) Time.stubs(:now).returns(Time.parse('2018/01/01 00:00:00')) post_json endpoint_url(api_key: @master), @payload do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 0.0, id: 'carto.abc.dataset1', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end end it 'creates a proper subscription request when instant licensing is enabled and delivery time is not 0' do with_feature_flag @user1, 'do-instant-licensing', true do mailer_mock = stub(:deliver_now) dataset_id = 'carto.abc.deliver_1day' dataset_name = 'CARTO dataset 1' provider_name = 'CARTO' DataObservatoryMailer.expects(:user_request).with( @carto_user1, dataset_name, provider_name ).never DataObservatoryMailer.expects(:carto_request).with( @carto_user1, dataset_id, 1.0 ).once.returns(mailer_mock) expected_params = { dataset_id: dataset_id, available_in: ['bq'], price: 100.0, created_at: Time.parse('2018/01/01 00:00:00'), expires_at: Time.parse('2019/01/01 00:00:00'), status: 'requested' } mock_sync_service = mock Carto::DoSyncServiceFactory.expects(:get_for_user).once.returns(mock_sync_service) mock_sync_service.stubs(:parsed_entity_id).returns(expected_params) mock_service = mock mock_service.expects(:subscribe).with(expected_params).once Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service) Time.stubs(:now).returns(Time.parse('2018/01/01 00:00:00')) post_json endpoint_url(api_key: @master), id: dataset_id, type: 'dataset' do |response| expect(response.status).to eq(200) expected_response = { estimated_delivery_days: 1.0, id: 'carto.abc.deliver_1day', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', type: 'dataset' } expect(response.body).to eq expected_response end end end end describe 'unsubscribe' do before(:all) do @url_helper = 'api_v4_do_subscriptions_destroy_url' @params = { api_key: @master, id: 'carto.abc.dataset1' } end it 'returns 400 if the id param is not valid' do delete_json endpoint_url(@params.merge(id: 'wrong')) do |response| expect(response.status).to eq(400) expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil) end end it 'returns 204 calls the DoLicensingService with the expected params' do mock_service = mock mock_service.expects(:unsubscribe).with('carto.abc.dataset1').once Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service) delete_json endpoint_url(@params) do |response| expect(response.status).to eq(204) end end end def mock_do_metadata (datasets_provider + cartographies_provider + special_cases_provider).each do |entry| Carto::Api::Public::DataObservatoryController .any_instance.stubs(:request_subscription_metadata).with(entry[:id], entry[:type]).returns(entry[:metadata]) end end def datasets_provider [ { id: 'carto.abc.dataset1', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO dataset 1', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.incomplete', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: nil, name: 'Incomplete dataset', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.datasetvalidatearrayempty', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: nil, name: 'CARTO dataset array empty', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.deliver_1day', type: 'dataset', metadata: { estimated_delivery_days: 1.0, subscription_list_price: 100.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO dataset 1', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.public_dataset', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO dataset 1', is_public_data: true, provider_name: 'CARTO' } } ] end def special_cases_provider [ { id: 'carto.abc.datasetnull', type: 'dataset', metadata: { estimated_delivery_days: nil, subscription_list_price: nil, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO dataset null', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.datasetzero', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO dataset zero', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.datasetvalidatearraynil', type: 'dataset', metadata: { estimated_delivery_days: 0.0, subscription_list_price: 0.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: nil, name: 'CARTO dataset array nil', is_public_data: false, provider_name: 'CARTO' } }, { id: 'carto.abc.inexistent', type: 'dataset', metadata: nil } ] end def cartographies_provider [ { id: 'carto.abc.geography1', type: 'geography', metadata: { estimated_delivery_days: 3.0, subscription_list_price: 90.0, tos: 'tos', tos_link: 'tos_link', licenses: 'licenses', licenses_link: 'licenses_link', rights: 'rights', available_in: %w{bq}, name: 'CARTO geography 1', is_public_data: false, provider_name: 'CARTO' } } ] end end
34.484221
131
0.621386
7a4489677e2fe89085c617c12b20730dca949c81
154
require File.expand_path('../../../../spec_helper', __FILE__) describe "Socket::Ifaddr#inspect" do it "needs to be reviewed for spec completeness" end
25.666667
61
0.720779
e8e3ec499a89d498d0b0e52e76b7d05200ff09e2
258
class AddTunnelblickBundleAndIosBundleAndLinuxBundleToServer < ActiveRecord::Migration def change add_column :servers, :tunnelblick_bundle, :string add_column :servers, :ios_bundle, :string add_column :servers, :linux_bundle, :string end end
32.25
86
0.790698
d56e71f063666cace872849859f2afccd7ae4498
649
require_relative 'serp_api_search' # Ebay Search Result for Ruby powered by SerpApi # # Search API Usage # # ```ruby # parameter = { # _nkw: "query", # api_key: "Your SERP API Key" # } # # search = EbaySearch.new(parameter) # search.params[:ebay_domain] = "ebay.com" # # html_results = search.get_html # hash_results = search.get_hash # json_results = search.get_json # # ``` # # doc: https://serpapi.com/ebay-search-api class EbaySearch < SerpApiSearch def initialize(params = {}) super(params, EBAY_ENGINE) check_params([:_nkw, :engine]) end def get_location raise 'location is not supported by ' + EBAY_ENGINE end end
18.542857
55
0.691834
38f352915c3db3ff350f93c7342a67e22459933f
174
class RemoveNameFromRepos < ActiveRecord::Migration[4.2] def self.up remove_column :repos, :name end def self.down add_column :repos, :name, :string end end
17.4
56
0.706897
bb7b52205b8079d37ec3ad46d1a59a0c0ae06875
1,747
require './lib/board.rb' RSpec.describe 'testing the board' do it 'should show us an empty board' do expect(Board.new.show_board).to eq("+------------------------+\n| 1 - ❔ 2 - ❔ 3 - ❔ | \n| 4 - ❔ 5 - ❔ 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❔ | \n+------------------------+") end it 'should show us an empty board' do expect(Board.new.show_board).not_to eq("+------------------------+\n| 1 - p 2 - ❔ 3 - ❔ | \n| 4 - ❔ 5 - ❔ 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❔ | \n+------------------------+") end context 'update board methods' do it 'should return a board with an input in 5th position' do expect(Board.new.update_board(5, 'x')).not_to eq("+------------------------+\n| 1 - ❔ 2 - x 3 - ❔ | \n| 4 - ❔ 5 - ❌ 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❔ | \n+------------------------+") end it 'should return a board with an input in 5th position' do expect(Board.new.update_board(5, 'x')).to eq("+------------------------+\n| 1 - ❔ 2 - ❔ 3 - ❔ | \n| 4 - ❔ 5 - ❌ 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❔ | \n+------------------------+") end it 'should return a board with an "o" in 5h position if 9th position is x' do board = Board.new board.update_board(9, 'x') expect(board.update_board(5, 'o')).to eq("+------------------------+\n| 1 - ❔ 2 - ❔ 3 - ❔ | \n| 4 - ❔ 5 - ⭕ 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❌ | \n+------------------------+") end it 'should return a board with an "o" in 5h position if 9th position is x' do board = Board.new board.update_board(9, 'x') expect(board.update_board(5, 'o')).not_to eq("+------------------------+\n| 1 - ❔ 2 - ❔ 3 - ❔ | \n| 4 - ❔ 5 - X 6 - ❔ | \n| 7 - ❔ 8 - ❔ 9 - ❌ | \n+------------------------+") end end end
51.382353
190
0.397825
d5fcd91b05d2066a30f5d00972e7a733f0b6fbd3
1,423
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'twilreapi/worker/version' Gem::Specification.new do |spec| spec.name = "twilreapi-worker" spec.version = Twilreapi::Worker::VERSION spec.authors = ["David Wilkie"] spec.email = ["[email protected]"] spec.summary = %q{Workers for Twilreapi} spec.description = %q{A collection of workers for Twilreapi} spec.homepage = "https://github.com/dwilkie/twilreapi-worker" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.11" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "dotenv" spec.add_development_dependency "activejob" end
39.527778
104
0.67955
6ae77ab960cfeb1010134846beeda33829dd272e
2,126
class ProjectsController < ApplicationController include Shared::RespondsController before_filter :authenticate_admin!, except: [:show] expose_decorated(:project, attributes: :project_params) def create if project.save SendMailWithUserJob.perform_async(ProjectMailer, :created, project, current_user.id) respond_on_success project else respond_on_failure project.errors end end def show gon.project = project gon.events = get_events end def update update_associated_memberships archive_project if project.archived_changed?(from: false, to: true) if project.save respond_on_success project else respond_on_failure project.errors end end def destroy if project.destroy redirect_to(dashboard_index_path, notice: I18n.t('projects.success', type: 'delete')) else redirect_to(dashboard_index_path, alert: I18n.t('projects.error', type: 'delete')) end end private def update_associated_memberships Memberships::UpdateStays.new(project.id, project_params[:membership_ids]).call update_booked_memberships end def archive_project Projects::EndCurrentMemberships.new(project).call project.end_at = Date.current.end_of_day end def update_booked_memberships if project.potential_changed?(from: true, to: false) Memberships::UpdateBooked.new(params[:project][:membership_ids]).call(false) end end def project_params params .require(:project) .permit( :name, :starts_at, :end_at, :archived, :potential, :synchronize, :kickoff, :project_type, :toggl_bookmark, :internal, :maintenance_since, :color, :sf_id, membership_ids: [], memberships_attributes: [:id, :stays, :user_id, :role_id, :starts_at, :billable] ) end def get_events project.memberships.map do |m| event = { text: m.user.decorate.name, startDate: m.starts_at.to_date } event[:user_id] = m.user.id.to_s event[:endDate] = m.ends_at.to_date if m.ends_at event[:billable] = m.billable event end end end
26.246914
91
0.704139
1aa58a8d62d976148b4614134bd6a87ad6e1b816
1,927
# frozen_string_literal: true if Rails.env.development? require 'annotate' task set_annotation_options: :environment do # rubocop:disable Metrics/BlockLength # You can override any of these by setting an environment variable of the # same name. Annotate.set_defaults( 'active_admin' => 'false', 'additional_file_patterns' => [], 'routes' => 'false', 'models' => 'true', 'position_in_routes' => 'before', 'position_in_class' => 'before', 'position_in_test' => 'before', 'position_in_fixture' => 'before', 'position_in_factory' => 'before', 'position_in_serializer' => 'before', 'show_foreign_keys' => 'true', 'show_complete_foreign_keys' => 'false', 'show_indexes' => 'true', 'simple_indexes' => 'false', 'model_dir' => 'app/models', 'root_dir' => '', 'include_version' => 'false', 'require' => '', 'exclude_tests' => 'false', 'exclude_fixtures' => 'false', 'exclude_factories' => 'false', 'exclude_serializers' => 'false', 'exclude_scaffolds' => 'true', 'exclude_controllers' => 'true', 'exclude_helpers' => 'true', 'exclude_sti_subclasses' => 'false', 'ignore_model_sub_dir' => 'false', 'ignore_columns' => nil, 'ignore_routes' => nil, 'ignore_unknown_models' => 'false', 'hide_limit_column_types' => 'integer,bigint,boolean', 'hide_default_column_types' => 'json,jsonb,hstore', 'skip_on_db_migrate' => 'false', 'format_bare' => 'false', 'format_rdoc' => 'false', 'format_yard' => 'false', 'format_markdown' => 'true', 'sort' => 'false', 'force' => 'false', 'frozen' => 'false', 'classified_sort' => 'true', 'trace' => 'false', 'wrapper_open' => nil, 'wrapper_close' => nil, 'with_comment' => 'true' ) end Annotate.load_tasks end
32.661017
84
0.586404
abfb234eb906afb41cc3acfd2579ac001fcc7fe7
1,575
cask "microsoft-word" do version "16.49.21050901" sha256 "3b948f9031d337276ef87e9b372a7386ee846efe929cd16714bae596c9336f0c" url "https://officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/Microsoft_Word_#{version}_Installer.pkg", verified: "officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/" name "Microsoft Word" desc "Word processor" homepage "https://products.office.com/en-US/word" livecheck do url "https://go.microsoft.com/fwlink/p/?linkid=525134" strategy :header_match end auto_updates true conflicts_with cask: "microsoft-office" depends_on cask: "microsoft-auto-update" depends_on macos: ">= :sierra" pkg "Microsoft_Word_#{version}_Installer.pkg", choices: [ { "choiceIdentifier" => "com.microsoft.autoupdate", # Office16_all_autoupdate.pkg "choiceAttribute" => "selected", "attributeSetting" => 0, }, ] uninstall pkgutil: [ "com.microsoft.package.Microsoft_Word.app", "com.microsoft.pkg.licensing", ], launchctl: "com.microsoft.office.licensingV2.helper" zap trash: [ "~/Library/Application Scripts/com.microsoft.Word", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.microsoft.word.sfl*", "~/Library/Application Support/CrashReporter/Microsoft Word_*.plist", "~/Library/Containers/com.microsoft.Word", "~/Library/Preferences/com.microsoft.Word.plist", ] end
35.795455
148
0.720635
bb75bee36b546a3d0a716a56b18c0849caebc8b0
2,651
require 'spec_helper' describe 'Admin::AuditLogs', :js do include Select2Helper let(:user) { create(:user) } before do sign_in(create(:admin)) end context 'unlicensed' do before do stub_licensed_features(admin_audit_log: false) end it 'returns 404' do reqs = inspect_requests do visit admin_audit_logs_path end expect(reqs.first.status_code).to eq(404) end end context 'licensed' do before do stub_licensed_features(admin_audit_log: true) end it 'has Audit Log button in head nav bar' do visit admin_audit_logs_path expect(page).to have_link('Audit Log', href: admin_audit_logs_path) end describe 'user events' do before do AuditEventService.new(user, user, with: :ldap) .for_authentication.security_event visit admin_audit_logs_path end it 'filters by user' do filter_by_type('User Events') click_button 'User' wait_for_requests within '.dropdown-menu-user' do click_link user.name end wait_for_requests expect(page).to have_content('Signed in with LDAP authentication') end end describe 'group events' do let(:group_member) { create(:group_member, user: user) } before do AuditEventService.new(user, group_member.group, { action: :create }) .for_member(group_member).security_event visit admin_audit_logs_path end it 'filters by group' do filter_by_type('Group Events') click_button 'Group' find('.group-item-select').click wait_for_requests find('.select2-results').click find('#events-table td', match: :first) expect(page).to have_content('Added user access as Owner') end end describe 'project events' do let(:project_member) { create(:project_member, user: user) } before do AuditEventService.new(user, project_member.project, { action: :destroy }) .for_member(project_member).security_event visit admin_audit_logs_path end it 'filters by project' do filter_by_type('Project Events') click_button 'Project' find('.project-item-select').click wait_for_requests find('.select2-results').click find('#events-table td', match: :first) expect(page).to have_content('Removed user access') end end end def filter_by_type(type) click_button 'Events' within '.dropdown-menu-type' do click_link type end wait_for_requests end end
22.277311
81
0.639759
e9190c8b4da4ef25fe9c1851eed348f025c56312
19,694
# Copyright 2011, Dell # Copyright 2012, SUSE Linux Products GmbH # # 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 # dirty = false # Set up the OS images as well # Common to all OSes admin_net = Barclamp::Inventory.get_network_by_type(node, "admin") admin_ip = admin_net.address domain_name = node[:dns].nil? ? node[:domain] : (node[:dns][:domain] || node[:domain]) web_port = node[:provisioner][:web_port] provisioner_web="http://#{admin_ip}:#{web_port}" append_line = node[:provisioner][:discovery][:append].dup # We'll modify it inline crowbar_node = node_search_with_cache("roles:crowbar").first crowbar_protocol = crowbar_node[:crowbar][:apache][:ssl] ? "https" : "http" crowbar_verify_ssl = !crowbar_node["crowbar"]["apache"]["insecure"] tftproot = node[:provisioner][:root] discovery_dir = "#{tftproot}/discovery" pxe_subdir = "bios" pxecfg_subdir = "bios/pxelinux.cfg" uefi_subdir = "efi" # This is what we could support, but this requires validation discovery_arches = node[:provisioner][:discovery_arches] discovery_arches.select! do |arch| File.exist?("#{discovery_dir}/#{arch}/initrd0.img") && File.exist?("#{discovery_dir}/#{arch}/vmlinuz0") end if ::File.exists?("/etc/crowbar.install.key") crowbar_key = ::File.read("/etc/crowbar.install.key").chomp.strip else crowbar_key = "" end if node[:provisioner][:use_serial_console] append_line += " console=tty0 console=#{node[:provisioner][:serial_tty]}" end if crowbar_key != "" append_line += " crowbar.install.key=#{crowbar_key}" end append_line = append_line.split.join(" ") if node[:provisioner][:sledgehammer_append_line] != append_line node.set[:provisioner][:sledgehammer_append_line] = append_line dirty = true end directory discovery_dir do mode 0o755 owner "root" group "root" action :create end # PXE config discovery_arches.each do |arch| directory "#{discovery_dir}/#{arch}/#{pxecfg_subdir}" do recursive true mode 0o755 owner "root" group "root" action :create end template "#{discovery_dir}/#{arch}/#{pxecfg_subdir}/default" do mode 0o644 owner "root" group "root" source "default.erb" variables(append_line: "#{append_line} crowbar.state=discovery", install_name: "discovery", initrd: "../initrd0.img", kernel: "../vmlinuz0") end end if discovery_arches.include? "x86_64" package "syslinux" ["share", "lib"].each do |d| next unless ::File.exist?("/usr/#{d}/syslinux/pxelinux.0") bash "Install pxelinux.0" do code "cp /usr/#{d}/syslinux/pxelinux.0 #{discovery_dir}/x86_64/#{pxe_subdir}/" not_if "cmp /usr/#{d}/syslinux/pxelinux.0 #{discovery_dir}/x86_64/#{pxe_subdir}/pxelinux.0" end break end end # UEFI config discovery_arches.each do |arch| uefi_dir = "#{discovery_dir}/#{arch}/#{uefi_subdir}" short_arch = arch if arch == "aarch64" short_arch = "aa64" elsif arch == "x86_64" short_arch = "x64" end directory uefi_dir do recursive true mode 0o755 owner "root" group "root" action :create end # we use grub2; steps taken from # https://github.com/openSUSE/kiwi/wiki/Setup-PXE-boot-with-EFI-using-grub2 grub2arch = arch if arch == "aarch64" grub2arch = "arm64" end package "grub2-#{grub2arch}-efi" # Secure Boot Shim if arch == "x86_64" package "shim" shim_code = "cp /usr/lib64/efi/shim.efi boot#{short_arch}.efi; cp /usr/lib64/efi/grub.efi grub.efi" else # aarch64 shim_code = "cp /usr/lib/efi/grub.efi boot#{short_arch}.efi" end directory "#{uefi_dir}/default/boot" do recursive true mode 0o755 owner "root" group "root" action :create end template "#{uefi_dir}/default/grub.cfg" do mode 0o644 owner "root" group "root" source "grub.conf.erb" variables(append_line: "#{append_line} crowbar.state=discovery", install_name: "Crowbar Discovery Image", admin_ip: admin_ip, efi_suffix: arch == "x86_64", initrd: "discovery/#{arch}/initrd0.img", kernel: "discovery/#{arch}/vmlinuz0") end bash "Copy UEFI shim loader with grub2" do cwd "#{uefi_dir}/default/boot" code shim_code action :nothing subscribes :run, resources("template[#{uefi_dir}/default/grub.cfg]"), :immediately end end if node[:platform_family] == "suse" include_recipe "apache2" include_recipe "apache2::mod_authn_core" template "#{node[:apache][:dir]}/vhosts.d/provisioner.conf" do source "base-apache.conf.erb" mode 0o644 variables(docroot: tftproot, port: web_port, admin_ip: admin_ip, admin_subnet: admin_net.subnet, admin_netmask: admin_net.netmask, logfile: "/var/log/apache2/provisioner-access_log", errorlog: "/var/log/apache2/provisioner-error_log") notifies :reload, resources(service: "apache2") end else include_recipe "bluepill" case node[:platform_family] when "debian" package "nginx-light" else package "nginx" end service "nginx" do action :disable end link "/etc/nginx/sites-enabled/default" do action :delete end # Set up our the webserver for the provisioner. file "/var/log/provisioner-webserver.log" do owner "nobody" action :create end template "/etc/nginx/provisioner.conf" do source "base-nginx.conf.erb" variables(docroot: tftproot, port: web_port, logfile: "/var/log/provisioner-webserver.log", pidfile: "/var/run/provisioner-webserver.pid") end file "/var/run/provisioner-webserver.pid" do mode "0644" action :create end template "/etc/bluepill/provisioner-webserver.pill" do source "provisioner-webserver.pill.erb" end bluepill_service "provisioner-webserver" do action [:load, :start] end end # !suse # Set up the TFTP server as well. case node[:platform_family] when "debian" package "tftpd-hpa" bash "stop ubuntu tftpd" do code "service tftpd-hpa stop; killall in.tftpd; rm /etc/init/tftpd-hpa.conf" only_if "test -f /etc/init/tftpd-hpa.conf" end when "rhel" package "tftp-server" when "suse" package "tftp" # work around change in bnc#813226 which breaks # read permissions for nobody and wwwrun user directory tftproot do recursive true mode 0o755 owner "root" group "root" end end cookbook_file "/etc/tftpd.conf" do owner "root" group "root" mode "0644" action :create source "tftpd.conf" end if node[:platform_family] == "suse" if node[:platform] == "suse" && node[:platform_version].to_f < 12.0 service "tftp" do # just enable, don't start (xinetd takes care of it) enabled node[:provisioner][:enable_pxe] ? true : false action node[:provisioner][:enable_pxe] ? "enable" : "disable" end # NOTE(toabctl): stop for tftp does not really help. the process gets started # by xinetd and has a default timeout of 900 seconds which triggers when no # new connections start in this period. So kill the process here execute "kill in.tftpd process" do command "pkill in.tftpd" not_if { node[:provisioner][:enable_pxe] } returns [0, 1] end service "xinetd" do action node[:provisioner][:enable_pxe] ? ["enable", "start"] : ["disable", "stop"] supports reload: true subscribes :reload, resources(service: "tftp"), :immediately end template "/etc/xinetd.d/tftp" do source "tftp.erb" variables(tftproot: tftproot) notifies :reload, resources(service: "xinetd") end else template "/etc/systemd/system/tftp.service" do source "tftp.service.erb" owner "root" group "root" mode "0644" variables(tftproot: tftproot, admin_ip: admin_ip) end service "tftp.service" do if node[:provisioner][:enable_pxe] action ["enable", "start"] subscribes :restart, resources("cookbook_file[/etc/tftpd.conf]") subscribes :restart, resources("template[/etc/systemd/system/tftp.service]") else action ["disable", "stop"] end end # No need for utils_systemd_service_restart: it's handled in the template already bash "reload systemd after tftp.service update" do code "systemctl daemon-reload" action :nothing subscribes :run, resources(template: "/etc/systemd/system/tftp.service"), :immediately end end else template "/etc/bluepill/tftpd.pill" do source "tftpd.pill.erb" variables( tftproot: tftproot ) end bluepill_service "tftpd" do action [:load, :start] end end file "#{tftproot}/validation.pem" do content IO.read("/etc/chef/validation.pem") mode "0644" action :create end # By default, install the same OS that the admin node is running # If the comitted proposal has a default, try it. # Otherwise use the OS the provisioner node is using. if node[:provisioner][:default_os].nil? node.set[:provisioner][:default_os] = "#{node[:platform]}-#{node[:platform_version]}" dirty = true end unless node[:provisioner][:supported_oses].keys.select{ |os| /^(hyperv|windows)/ =~ os }.empty? raise "Binary files (chef-client, curl) need to be added back to the cookbook for Hyper-V support" common_dir="#{tftproot}/windows-common" extra_dir="#{common_dir}/extra" directory "#{extra_dir}" do recursive true mode 0o755 owner "root" group "root" action :create end # Copy the crowbar_join script cookbook_file "#{extra_dir}/crowbar_join.ps1" do owner "root" group "root" mode "0644" action :create source "crowbar_join.ps1" end # Copy the script required for setting the hostname cookbook_file "#{extra_dir}/set_hostname.ps1" do owner "root" group "root" mode "0644" action :create source "set_hostname.ps1" end # Copy the script required for setting the installed state template "#{extra_dir}/set_state.ps1" do owner "root" group "root" mode "0644" source "set_state.ps1.erb" variables(crowbar_key: crowbar_key, admin_ip: admin_ip) end # Also copy the required files to install chef-client and communicate with Crowbar cookbook_file "#{extra_dir}/chef-client-11.4.4-2.windows.msi" do owner "root" group "root" mode "0644" action :create source "chef-client-11.4.4-2.windows.msi" end cookbook_file "#{extra_dir}/curl.exe" do owner "root" group "root" mode "0644" action :create source "curl.exe" end cookbook_file "#{extra_dir}/curl.COPYING" do owner "root" group "root" mode "0644" action :create source "curl.COPYING" end # Create tftp helper directory directory "#{common_dir}/tftp" do mode 0o755 owner "root" group "root" action :create end # Ensure the adk-tools directory exists directory "#{tftproot}/adk-tools" do mode 0o755 owner "root" group "root" action :create end end repositories = Mash.new available_oses = Mash.new node[:provisioner][:supported_oses].each do |os, arches| arches.each do |arch, params| web_path = "#{provisioner_web}/#{os}/#{arch}" install_url = "#{web_path}/install" crowbar_repo_web = "#{web_path}/crowbar-extra" os_dir = "#{tftproot}/#{os}/#{arch}" os_codename = node[:lsb][:codename] role = "#{os}_install" missing_files = false append = params["append"].dup # We'll modify it inline initrd = params["initrd"] kernel = params["kernel"] require_install_dir = params["require_install_dir"].nil? ? true : params["require_install_dir"] if require_install_dir # Don't bother for OSes that are not actually present on the provisioner node. next unless File.directory?(os_dir) && File.directory?("#{os_dir}/install") end # Index known barclamp repositories for this OS repositories[os] ||= Mash.new repositories[os][arch] = Mash.new if File.exist?("#{os_dir}/crowbar-extra") && File.directory?("#{os_dir}/crowbar-extra") Dir.foreach("#{os_dir}/crowbar-extra") do |f| next unless File.symlink? "#{os_dir}/crowbar-extra/#{f}" repositories[os][arch][f] = Hash.new case when os =~ /(ubuntu|debian)/ bin = "deb #{web_path}/crowbar-extra/#{f} /" src = "deb-src #{web_path}/crowbar-extra/#{f} /" repositories[os][arch][f][bin] = true if File.exist? "#{os_dir}/crowbar-extra/#{f}/Packages.gz" repositories[os][arch][f][src] = true if File.exist? "#{os_dir}/crowbar-extra/#{f}/Sources.gz" when os =~ /(redhat|centos|suse)/ bin = "baseurl=#{web_path}/crowbar-extra/#{f}" repositories[os][arch][f][bin] = true else raise ::RangeError.new("Cannot handle repos for #{os}") end end end # If we were asked to use a serial console, arrange for it. if node[:provisioner][:use_serial_console] append << " console=tty0 console=#{node[:provisioner][:serial_tty]}" end # Make sure we get a crowbar install key as well. unless crowbar_key.empty? append << " crowbar.install.key=#{crowbar_key}" end # These should really be made libraries or something. case when /^(open)?suse/ =~ os # Add base OS install repo for suse repositories[os][arch]["base"] = { "baseurl=#{install_url}" => true } ntp_config = Barclamp::Config.load("core", "ntp") ntp_servers = ntp_config["servers"] || [] target_platform_distro = os.gsub(/-.*$/, "") target_platform_version = os.gsub(/^.*-/, "") template "#{os_dir}/crowbar_join.sh" do mode 0o644 owner "root" group "root" source "crowbar_join.suse.sh.erb" variables(admin_ip: admin_ip, web_port: web_port, ntp_servers_ips: ntp_servers, platform: target_platform_distro, target_platform_version: target_platform_version) end repos = Provisioner::Repositories.get_repos(target_platform_distro, target_platform_version, arch) # Need to know if we're doing a storage-only deploy so we can tweak # crowbar_register slightly (same as in update_nodes.rb) storage_available = false cloud_available = false repos.each do |name, repo| storage_available = true if name.include? "Storage" cloud_available = true if name.include? "Cloud" end packages = node[:provisioner][:packages][os] || [] template "#{os_dir}/crowbar_register" do mode 0o644 owner "root" group "root" source "crowbar_register.erb" variables(admin_ip: admin_ip, admin_broadcast: admin_net.broadcast, crowbar_protocol: crowbar_protocol, crowbar_verify_ssl: crowbar_verify_ssl, web_port: web_port, ntp_servers_ips: ntp_servers, os: os, arch: arch, crowbar_key: crowbar_key, domain: domain_name, repos: repos, is_ses: storage_available && !cloud_available, packages: packages, platform: target_platform_distro, target_platform_version: target_platform_version) end missing_files = !File.exist?("#{os_dir}/install/boot/#{arch}/common") when /^(redhat|centos)/ =~ os # Add base OS install repo for redhat/centos if ::File.exist? "#{tftproot}/#{os}/#{arch}/install/repodata" repositories[os][arch]["base"] = { "baseurl=#{install_url}" => true } else repositories[os][arch]["base"] = { "baseurl=#{install_url}/Server" => true } end # Default kickstarts and crowbar_join scripts for redhat. template "#{os_dir}/crowbar_join.sh" do mode 0o644 owner "root" group "root" source "crowbar_join.redhat.sh.erb" variables(admin_web: install_url, os_codename: os_codename, crowbar_repo_web: crowbar_repo_web, admin_ip: admin_ip, provisioner_web: provisioner_web, web_path: web_path) end when /^ubuntu/ =~ os repositories[os][arch]["base"] = { install_url => true } # Default files needed for Ubuntu. template "#{os_dir}/net-post-install.sh" do mode 0o644 owner "root" group "root" variables(admin_web: install_url, os_codename: os_codename, repos: repositories[os][arch], admin_ip: admin_ip, provisioner_web: provisioner_web, web_path: web_path) end template "#{os_dir}/crowbar_join.sh" do mode 0o644 owner "root" group "root" source "crowbar_join.ubuntu.sh.erb" variables(admin_web: install_url, os_codename: os_codename, crowbar_repo_web: crowbar_repo_web, admin_ip: admin_ip, provisioner_web: provisioner_web, web_path: web_path) end when /^(hyperv|windows)/ =~ os # Windows is x86_64-only os_dir = "#{tftproot}/#{os}" template "#{tftproot}/adk-tools/build_winpe_#{os}.ps1" do mode 0o644 owner "root" group "root" source "build_winpe_os.ps1.erb" variables(os: os, admin_ip: admin_ip) end directory "#{os_dir}" do mode 0o755 owner "root" group "root" action :create end # Let's stay compatible with the old code and remove the per-version extra directory if File.directory? "#{os_dir}/extra" directory "#{os_dir}/extra" do recursive true action :delete end end link "#{os_dir}/extra" do action :create to "../windows-common/extra" end missing_files = !File.exist?("#{os_dir}/boot/bootmgr.exe") end available_oses[os] ||= Mash.new available_oses[os][arch] = Mash.new if /^(hyperv|windows)/ =~ os available_oses[os][arch][:kernel] = "#{os}/#{kernel}" available_oses[os][arch][:initrd] = " " available_oses[os][arch][:append_line] = " " else available_oses[os][arch][:kernel] = "#{os}/#{arch}/install/#{kernel}" available_oses[os][arch][:initrd] = "#{os}/#{arch}/install/#{initrd}" available_oses[os][arch][:append_line] = append end available_oses[os][arch][:disabled] = missing_files available_oses[os][arch][:install_name] = role end end if node[:provisioner][:repositories] != repositories node.set[:provisioner][:repositories] = repositories dirty = true end if node[:provisioner][:available_oses] != available_oses node.set[:provisioner][:available_oses] = available_oses dirty = true end # Save this node config. node.save if dirty
29.482036
105
0.63791
bbe48a7302622059b8a756f32618883f8c654a06
1,622
class Cig < Formula desc "CLI app for checking the state of your git repositories" homepage "https://github.com/stevenjack/cig" url "https://github.com/stevenjack/cig/archive/v0.1.5.tar.gz" sha256 "545a4a8894e73c4152e0dcf5515239709537e0192629dc56257fe7cfc995da24" license "MIT" head "https://github.com/stevenjack/cig.git" bottle do rebuild 3 sha256 cellar: :any_skip_relocation, arm64_big_sur: "2d4f345393a0553e40003b46523a07e2bb0162bba0309ca9c0d322f606e73b76" sha256 cellar: :any_skip_relocation, big_sur: "c41c70e517158f1a31bb4b29a6fa01b12570001353b8800d55aadd4ddc99080e" sha256 cellar: :any_skip_relocation, catalina: "3ccce3238efd259041dbb0f0427d5ac06cc4dfafdfbfd336ddd0023e02e9dd7d" sha256 cellar: :any_skip_relocation, mojave: "9cf50d9418885990bed7e23b0c2987918d63bef3e7f3e27589c521b6b73160bf" sha256 cellar: :any_skip_relocation, x86_64_linux: "8a9d6b020869fcad3b544b99c77d8077ac4a787c9c7c843a0f7224fb25c8651c" end depends_on "go" => :build # Patch to remove godep dependency. # Remove when the following PR is merged into release: # https://github.com/stevenjack/cig/pull/44 patch do url "https://github.com/stevenjack/cig/compare/2d834ee..f0e78f0.patch?full_index" sha256 "3aa14ecfa057ec6aba08d6be3ea0015d9df550b4ede1c3d4eb76bdc441a59a47" end def install system "go", "build", *std_go_args end test do repo_path = "#{testpath}/test" system "git", "init", "--bare", repo_path (testpath/".cig.yaml").write <<~EOS test_project: #{repo_path} EOS system "#{bin}/cig", "--cp=#{testpath}" end end
39.560976
122
0.759556
1da74d961b3b402d8b34167ef2d895bd4bd35baf
300
module UsersHelper def gravatar_for(user, options = { size: 80 }) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}" image_tag(gravatar_url, alt: user.name, class: "gravatar") end end
33.333333
70
0.706667
21c65573a16cbfdf41a1129f22df531894f0e212
1,700
class Api::V1::UsersController < ApplicationController def index @users = User.all render json: @users end def show @user = User.find(params[:id]) render json: @user end def create @newuser = User.new(first_name: signup_params[:first_name],last_name: signup_params[:last_name],email: signup_params[:email],dob: signup_params[:dob],password: signup_params[:password]) if @newuser.save token = encode_token(@newuser.id) render json: {user: @newuser, token: token} else render json: {error: @newuser.errors.full_messages, status: 400} end end def update @user = User.find(params[:id]) if @user.update(first_name: update_params[:first_name], last_name: update_params[:last_name], tel: update_params[:tel], address_line_1: update_params[:address_line_1], address_line_2: update_params[:address_line_2], city: update_params[:city], postcode: update_params[:postcode], profile_img: update_params[:profile_img]) render json: @user else render json: {error: @user.errors.full_messages, status: 400} end end # def signin # @user = User.find_by(email: signin_params[:email]) # if (@user && @user.password_digest === signin_params[:password]) # render json: @user # else # render json: {error: 'Incorrect Credentials', status: 400} # end # end private def signup_params params.permit(:first_name, :last_name, :email, :password, :dob) end def update_params params.permit(:id, :first_name, :last_name, :tel, :address_line_1, :address_line_2, :city, :postcode, :user, :profile_img) end # def signin_params # params.permit(:email, :password) # end end
30.357143
325
0.687647
ed32c90f0f02d29b27689623fcee9e6893d884e8
1,333
=begin #Datadog API V1 Collection #Collection of all Datadog Public endpoints. The version of the OpenAPI document: 1.0 Contact: [email protected] Generated by: https://openapi-generator.tech Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020-Present Datadog, Inc. =end require 'date' require 'time' module DatadogAPIClient::V1 class EventAlertType ERROR = "error".freeze WARNING = "warning".freeze INFO = "info".freeze SUCCESS = "success".freeze USER_UPDATE = "user_update".freeze RECOMMENDATION = "recommendation".freeze SNAPSHOT = "snapshot".freeze # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value def self.build_from_hash(value) new.build_from_hash(value) end # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) constantValues = EventAlertType.constants.select { |c| EventAlertType::const_get(c) == value } constantValues.empty? ? DatadogAPIClient::V1::UnparsedObject.new(value) : value end end end
29.622222
107
0.724681
910c555b9883cf03965b11f799a6223751ef31ac
3,288
class UsersController < ApplicationController before_action :authenticate_user! load_and_authorize_resource skip_authorize_resource :only => [:show, :edit, :index, :update] before_action :authorize_admin, only: [:create, :destroy] before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.includes(:role).all respond_with(@users) do |format| format.json { render :json => {:list => @users.as_json, :current_user => current_user.as_json} } format.html end end # GET /users/1 # GET /users/1.json def show respond_with(@user) do |format| format.json { render :json => {:user => @user.as_json, :current_user => current_user.as_json} } format.html end end # GET /users/new def new @user = User.new @minimum_password_length = 8 #roles = Role.all respond_with(@user) do |format| format.json { render :json => {:user => @user.as_json, :is_admin => current_user.admin?, :roles => role_names} } format.html end end # GET /users/1/edit def edit #roles = Role.all respond_with(@user) do |format| format.json { render :json => {:user => @user.as_json, :is_admin => current_user.admin?, :current_user => current_user, :roles => role_names} } format.html end end # POST /users # POST /users.json def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user.as_json, notice: 'User was successfully created.' } @user.send_reset_password_instructions else format.html { render :new } format.json { render json: @user.errors.full_messages, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user.as_json, notice: 'User was successfully updated.' } else format.html { render :edit } format.json { render json: @user.errors.full_messages, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy if @user.admin? respond_to do |format| format.html { redirect_to users_url, alert: 'Admin can not be deleted.' } format.json { head :no_content } end else @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.includes(:role).find(params[:id]) render json: {status: :not_found} unless @user end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :role_id) end end
30.728972
149
0.655109
1c3d4ef0ef17973bbc693b2f9899ad80f861fe10
2,991
class Turtle include Math # turtles understand math methods DEG = Math::PI / 180.0 attr_accessor :track alias run instance_eval def initialize clear end attr_reader :xy, :heading # Place the turtle at [x, y]. The turtle does not draw when it changes # position. def xy=(coords) raise ArgumentError unless is_point?(coords) @xy = coords end # Set the turtle's heading to <degrees>. def heading=(degrees) raise ArgumentError unless degrees.is_a?(Numeric) @heading = degrees % 360 end # Raise the turtle's pen. If the pen is up, the turtle will not draw; # i.e., it will cease to lay a track until a pen_down command is given. def pen_up @pen_is_down = false end # Lower the turtle's pen. If the pen is down, the turtle will draw; # i.e., it will lay a track until a pen_up command is given. def pen_down @pen_is_down = true @track << [@xy] end # Is the pen up? def pen_up? !@pen_is_down end # Is the pen down? def pen_down? @pen_is_down end # Places the turtle at the origin, facing north, with its pen up. # The turtle does not draw when it goes home. def home @heading = 0.0 @xy = [0.0, 0.0] @pen_is_down = false end # Homes the turtle and empties out it's track. def clear @track = [] home end # Turn right through the angle <degrees>. def right(degrees) raise ArgumentError unless degrees.is_a?(Numeric) @heading += degrees @heading %= 360 end # Turn left through the angle <degrees>. def left(degrees) right(-degrees) end # Move forward by <steps> turtle steps. def forward(steps) raise ArgumentError unless steps.is_a?(Numeric) @xy = [@xy.first + sin(@heading * DEG) * steps, @xy.last + cos(@heading * DEG) * steps] @track.last << @xy if @pen_is_down end # Move backward by <steps> turtle steps. def back(steps) forward(-steps) end # Move to the given point. def go(pt) raise ArgumentError unless is_point?(pt) @xy = pt @track.last << @xy if @pen_is_down end # Turn to face the given point. def toward(pt) raise ArgumentError unless is_point?(pt) @heading = (atan2(pt.first - @xy.first, pt.last - @xy.last) / DEG) % 360 end # Return the distance between the turtle and the given point. def distance(pt) raise ArgumentError unless is_point?(pt) return sqrt((pt.first - @xy.first) ** 2 + (pt.last - @xy.last) ** 2) end # Traditional abbreviations for turtle commands. alias fd forward alias bk back alias rt right alias lt left alias pu pen_up alias pd pen_down alias pu? pen_up? alias pd? pen_down? alias set_h heading= alias set_xy xy= alias face toward alias dist distance private def is_point?(pt) pt.is_a?(Array) and pt.length == 2 and pt.first.is_a?(Numeric) and pt.last.is_a?(Numeric) end end
23.367188
93
0.638582
8708e2b02c6c434f1fe305e4c78434c8b8e5d58a
1,152
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-sns' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - Amazon SNS' spec.description = 'Official AWS Ruby gem for Amazon Simple Notification Service (Amazon SNS). This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-sns', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-sns/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.71.0') spec.add_dependency('aws-sigv4', '~> 1.1') end
38.4
141
0.659722
01de161a8cb0ac7e6bbd6a8743b798dd98d8198f
3,766
class Postgresql < Formula desc "Object-relational database system" homepage "https://www.postgresql.org/" url "https://ftp.postgresql.org/pub/source/v11.1/postgresql-11.1.tar.bz2" sha256 "90815e812874831e9a4bf6e1136bf73bc2c5a0464ef142e2dfea40cda206db08" revision 1 head "https://github.com/postgres/postgres.git" bottle do rebuild 1 sha256 "2fbb3a06211b1ca2587920b032a89d7ee759ea536d68ee73f3ad5563038ca843" => :mojave sha256 "5fbe8a446bed7532b1517f5f92356166e4a219b516086364094f00e86cbd1fd3" => :high_sierra sha256 "007ae1c315ec0c01345a9cc754ec927909667697cf35ddd675e7778af39ceebc" => :sierra end depends_on "pkg-config" => :build depends_on "icu4c" depends_on "openssl" depends_on "readline" conflicts_with "postgres-xc", :because => "postgresql and postgres-xc install the same binaries." def install # avoid adding the SDK library directory to the linker search path ENV["XML2_CONFIG"] = "xml2-config --exec-prefix=/usr" ENV.prepend "LDFLAGS", "-L#{Formula["openssl"].opt_lib} -L#{Formula["readline"].opt_lib}" ENV.prepend "CPPFLAGS", "-I#{Formula["openssl"].opt_include} -I#{Formula["readline"].opt_include}" args = %W[ --disable-debug --prefix=#{prefix} --datadir=#{HOMEBREW_PREFIX}/share/postgresql --libdir=#{HOMEBREW_PREFIX}/lib --sysconfdir=#{etc} --docdir=#{doc} --enable-thread-safety --with-bonjour --with-gssapi --with-icu --with-ldap --with-libxml --with-libxslt --with-openssl --with-pam --with-perl --with-uuid=e2fs ] # The CLT is required to build Tcl support on 10.7 and 10.8 because # tclConfig.sh is not part of the SDK args << "--with-tcl" if File.exist?("#{MacOS.sdk_path}/System/Library/Frameworks/Tcl.framework/tclConfig.sh") args << "--with-tclconfig=#{MacOS.sdk_path}/System/Library/Frameworks/Tcl.framework" end system "./configure", *args system "make" system "make", "install-world", "datadir=#{pkgshare}", "libdir=#{lib}", "pkglibdir=#{lib}/postgresql" end def post_install (var/"log").mkpath (var/"postgres").mkpath unless File.exist? "#{var}/postgres/PG_VERSION" system "#{bin}/initdb", "#{var}/postgres" end end def caveats; <<~EOS To migrate existing data from a previous major version of PostgreSQL run: brew postgresql-upgrade-database EOS end plist_options :manual => "pg_ctl -D #{HOMEBREW_PREFIX}/var/postgres start" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/postgres</string> <string>-D</string> <string>#{var}/postgres</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{HOMEBREW_PREFIX}</string> <key>StandardOutPath</key> <string>#{var}/log/postgres.log</string> <key>StandardErrorPath</key> <string>#{var}/log/postgres.log</string> </dict> </plist> EOS end test do system "#{bin}/initdb", testpath/"test" assert_equal "#{HOMEBREW_PREFIX}/share/postgresql", shell_output("#{bin}/pg_config --sharedir").chomp assert_equal "#{HOMEBREW_PREFIX}/lib", shell_output("#{bin}/pg_config --libdir").chomp assert_equal "#{HOMEBREW_PREFIX}/lib/postgresql", shell_output("#{bin}/pg_config --pkglibdir").chomp end end
32.465517
106
0.648168
bb5af56638d75ca5c45f7c610d925581775e455d
777
# coding: utf-8 require 'spec_helper' require_relative '../../lib/berth/form' require_relative '../../lib/berth/monkey_string' class String include MonkeyString end describe Form do class DummyClass attr_accessor :wording, :name, :subject, :content include Form def create_pdf(subject, content) content end end before(:each) do including_class.wording = "A2200" including_class.name = "Fram" including_class.subject = "SUBJ" including_class.content = "CONT" end let(:including_class) { DummyClass.new } it "works" do expect(including_class.choose_form).to eq "Пожалуйста, примите к сведению, что данный танкер прибывает в Новороссийск 15/04/22:00." expect(including_class.choose_form).to be_truthy end end
22.2
135
0.71686
bf2fd828cd214c5e9b6bb7d076624741aab459b0
563
class OpenCompletion < Formula desc "Bash completion for open" homepage "https://github.com/moshen/open-bash-completion" url "https://github.com/moshen/open-bash-completion/archive/v1.0.4.tar.gz" sha256 "23a8a30f9f65f5b3eb60aa6f2d1c60d7d0a858ea753a58f31ddb51d40e16b668" license "MIT" head "https://github.com/moshen/open-bash-completion.git" bottle :unneeded def install bash_completion.install "open" end test do assert_match "-F _open", shell_output("bash -c 'source #{bash_completion}/open && complete -p open'") end end
28.15
82
0.740675
1a4f6adf66944b5946b71bb5b5d6e711a6152e4f
2,982
# Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'api/object' require 'api/type' module Provider # Override a resource property (Api::Type) in api.yaml # TODO(rosbo): Shared common logic with ResourceOverride via a base class. class PropertyOverride < Api::Object include Api::Type::Fields # Apply this override to property inheriting from Api::Type def apply(api_property) ensure_property_fields update_overriden_fields api_property # TODO(nelsonjr): Enable revalidate the object to make sure we did not # break the object during the override process # | api_resource.validate # check if we did not break the object end private # Updates a property field to a new value def update(property, field, value) property.instance_variable_set("@#{field}".to_sym, value) end # Attaches the overridden fields to the property and ensure they are # present on the class. def ensure_property_fields Api::Type.send(:include, overriden) # override ... require_module overriden our_override_modules.each { |mod| require_module mod } # ... and verify end # Copies all overridable properties from ResourceOverride into # Api::Resource. def update_overriden_fields(api_resource) our_override_modules.each do |mod| mod.instance_methods.each do |method| # If we have a variable for it, copy it. prop_name = "@#{method.id2name}".to_sym var_value = instance_variable_get(prop_name) api_resource.instance_variable_set(prop_name, var_value) \ unless var_value.nil? end end end # Returns all modules that contain overridable properties. def our_override_modules self.class.included_modules.select do |mod| mod == Api::Type::Fields \ || mod.name.split(':').last == 'OverrideFields' end end # Ensures that Api::Type includes a module. def require_module(clazz) raise "Api::Type did not include required #{clazz} module" \ unless Api::Type.included_modules.include?(clazz) raise "#{self.class} did not include required #{clazz} module" \ unless self.class.included_modules.include?(clazz) end # Returns the module that provides overriden properties for this provider. def overriden raise "overriden property should be implemented in #{self.class}" end end end
35.5
78
0.701207
798d7862582d4c2130948afd8434d739cbfdd9d2
616
Pod::Spec.new do |spec| spec.name = 'FFViewControlPlaceHoldView' spec.license = { :type => 'MIT' } spec.platform = :ios, '6.0' spec.homepage = 'https://github.com/wujiangwei/FFViewControlPlaceHoldView' spec.authors = 'Kevin.Wu' spec.summary = 'FFViewControlPlaceHoldView' spec.source = {:git => 'https://github.com/wujiangwei/FFViewControlPlaceHoldView.git'} spec.source_files = '{UIViewController+FFViewControllerPlaceholdHelper,FFVCPlaceholdView}.{h,m}' spec.frameworks = 'UIKit' spec.dependency 'MBProgressHUD' spec.ios.deployment_target = '6.0' spec.requires_arc = true end
41.066667
96
0.722403
ac70928e61fb6e9c3cd71f04309a14bea33b3482
2,854
#-*- coding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'new_relic/version' require 'new_relic/latest_changes' Gem::Specification.new do |s| s.name = "newrelic_rpm" s.version = NewRelic::VERSION::STRING s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.authors = [ "Jason Clark", "Sam Goldstein", "Jonan Scheffler", "Ben Weintraub" ] s.date = Time.now.strftime('%Y-%m-%d') s.description = <<-EOS New Relic is a performance management system, developed by New Relic, Inc (http://www.newrelic.com). New Relic provides you with deep information about the performance of your web application as it runs in production. The New Relic Ruby Agent is dual-purposed as a either a Gem or plugin, hosted on http://github.com/newrelic/rpm/ EOS s.email = "[email protected]" s.executables = [ "mongrel_rpm", "newrelic_cmd", "newrelic", "nrdebug" ] s.extra_rdoc_files = [ "CHANGELOG", "LICENSE", "README.md", "GUIDELINES_FOR_CONTRIBUTING.md", "newrelic.yml" ] file_list = `git ls-files`.split build_file_path = 'lib/new_relic/build.rb' file_list << build_file_path if File.exist?(build_file_path) s.files = file_list s.homepage = "http://www.github.com/newrelic/rpm" s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "New Relic Ruby Agent"] s.require_paths = ["lib"] s.rubygems_version = Gem::VERSION s.summary = "New Relic Ruby Agent" s.post_install_message = NewRelic::LatestChanges.read s.add_development_dependency 'rubysl' if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' s.add_development_dependency 'racc' if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' s.add_development_dependency 'rake', '10.1.0' s.add_development_dependency 'minitest', '~> 4.7.5' s.add_development_dependency 'mocha', '~> 0.13.0' s.add_development_dependency 'sdoc-helpers' s.add_development_dependency 'rdoc', '>= 2.4.2' s.add_development_dependency 'rails', '~> 3.2.13' s.add_development_dependency 'sqlite3' unless RUBY_PLATFORM == 'java' s.add_development_dependency 'activerecord-jdbcsqlite3-adapter' if RUBY_PLATFORM == 'java' s.add_development_dependency 'jruby-openssl' if RUBY_PLATFORM == 'java' s.add_development_dependency 'sequel', '~> 3.46.0' s.add_development_dependency 'pry' s.add_development_dependency 'guard', '~> 1.8.3' # Guard 2.0 is Ruby 1.9 only s.add_development_dependency 'guard-test', '~> 1.0.0' s.add_development_dependency 'rb-fsevent', '~> 0.9.1' # Only sign with our private key if you can find it signing_key_path = File.expand_path('~/.ssh/newrelic_rpm-private_key.pem') if File.exists?(signing_key_path) s.signing_key = signing_key_path s.cert_chain = ['gem-public_cert.pem'] end end
42.597015
108
0.722495
871c0dd928bd890efc796ec455eb40318d979526
7,214
# frozen_string_literal: true require 'spec_helper' describe Bosh::AzureCloud::TableManager do let(:azure_config) { mock_azure_config } let(:storage_account_manager) { instance_double(Bosh::AzureCloud::StorageAccountManager) } let(:azure_client) { instance_double(Bosh::AzureCloud::AzureClient) } let(:table_manager) { Bosh::AzureCloud::TableManager.new(azure_config, storage_account_manager, azure_client) } let(:table_name) { 'fake-table-name' } let(:keys) { ['fake-key-1', 'fake-key-2'] } let(:azure_storage_client) { instance_double(Azure::Storage::Common::Client) } let(:table_service) { instance_double(Azure::Storage::Table::TableService) } let(:exponential_retry) { instance_double(Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter) } let(:storage_dns_suffix) { 'fake-storage-dns-suffix' } let(:blob_host) { "https://#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}.blob.#{storage_dns_suffix}" } let(:table_host) { "https://#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}.table.#{storage_dns_suffix}" } let(:storage_account) do { id: 'foo', name: MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, location: 'bar', provisioning_state: 'bar', account_type: 'foo', storage_blob_host: blob_host, storage_table_host: table_host } end let(:request_id) { 'fake-client-request-id' } let(:options) do { request_id: request_id } end before do allow(storage_account_manager).to receive(:default_storage_account) .and_return(storage_account) allow(Azure::Storage::Common::Client).to receive(:create) .and_return(azure_storage_client) allow(Bosh::AzureCloud::AzureClient).to receive(:new) .and_return(azure_client) allow(azure_client).to receive(:get_storage_account_keys_by_name) .and_return(keys) allow(azure_client).to receive(:get_storage_account_by_name) .with(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME) .and_return(storage_account) allow(Azure::Storage::Table::TableService).to receive(:new).with(client: azure_storage_client) .and_return(table_service) allow(Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter).to receive(:new) .and_return(exponential_retry) allow(table_service).to receive(:with_filter).with(exponential_retry) allow(SecureRandom).to receive(:uuid).and_return(request_id) end class MyArray < Array attr_accessor :continuation_token end class MyEntity def initialize @properties = {} yield self if block_given? end attr_accessor :properties end describe '#has_table?' do context 'when the table exists' do before do allow(table_service).to receive(:get_table) .with(table_name, options) end it 'should return true' do expect(table_manager.has_table?(table_name)).to be(true) end end context 'when the table does not exist' do before do allow(table_service).to receive(:get_table) .and_raise('(404)') end it 'returns false' do expect(table_manager.has_table?(table_name)).to be(false) end end context 'when the status code is not 404' do before do allow(table_service).to receive(:get_table) .and_raise('Not-404-Error') end it 'should raise an error' do expect do table_manager.has_table?(table_name) end.to raise_error(/Not-404-Error/) end end end describe '#query_entities' do records_with_token = MyArray.new entity1 = MyEntity.new do |e| e.properties = 'foo' end records_with_token.push(entity1) fake_continuation_token = { next_partition_key: 'p_key', next_row_key: 'r_key' } records_with_token.continuation_token = fake_continuation_token records_without_token = MyArray.new entity2 = MyEntity.new do |e| e.properties = 'bar' end records_without_token.push(entity2) records_without_token.continuation_token = nil before do allow(table_service).to receive(:query_entities) .with(table_name, options) .and_return(records_with_token) allow(table_service).to receive(:query_entities) .with(table_name, continuation_token: fake_continuation_token, request_id: request_id) .and_return(records_without_token) end it 'returns the entities' do expect( table_manager.query_entities(table_name, {}) ).to eq(%w[foo bar]) end end describe '#insert_entity' do entity = MyEntity.new do |e| e.properties = 'foo' end context 'when the specified entity does not exist' do before do allow(table_service).to receive(:insert_entity) .with(table_name, entity, options) end it 'should return true' do expect(table_manager.insert_entity(table_name, entity)).to be(true) end end context 'when the specified entity already exists' do before do allow(table_service).to receive(:insert_entity) .and_raise('(409)') end it 'should return false' do expect(table_manager.insert_entity(table_name, entity)).to be(false) end end context 'when the status code is not 409' do before do allow(table_service).to receive(:insert_entity) .and_raise('Not-409-Error') end it 'should raise an error' do expect do table_manager.insert_entity(table_name, entity) end.to raise_error(/Not-409-Error/) end end end describe '#delete_entity' do let(:partition_key) { 'p_key' } let(:row_key) { 'r_key' } context 'when the specified entity exists' do before do allow(table_service).to receive(:delete_entity) .with(table_name, partition_key, row_key, options) end it 'should not raise an error' do expect do table_manager.delete_entity(table_name, partition_key, row_key) end.not_to raise_error end end context 'when the specified entity does not exist' do before do allow(table_service).to receive(:delete_entity) .and_raise('(404)') end it 'should not raise an error' do expect do table_manager.delete_entity(table_name, partition_key, row_key) end.not_to raise_error end end context 'when the status code is not 404' do before do allow(table_service).to receive(:delete_entity) .and_raise('Not-404-Error') end it 'should raise an error' do expect do table_manager.delete_entity(table_name, partition_key, row_key) end.to raise_error(/Not-404-Error/) end end end describe '#update_entity' do entity = MyEntity.new do |e| e.properties = 'foo' end before do allow(table_service).to receive(:update_entity) .with(table_name, entity, options) end it 'does not raise an error' do expect do table_manager.update_entity(table_name, entity) end.not_to raise_error end end end
29.325203
113
0.665512
6271d5778ad45483ff3cfc4fa839c530b6214b70
1,598
class TestLab # Labfile Error Class class LabfileError < TestLabError; end # Labfile Class # # @author Zachary Patten <zachary AT jovelabs DOT com> class Labfile < ZTK::DSL::Base has_many :dependencies, :class_name => 'TestLab::Dependency' has_many :sources, :class_name => 'TestLab::Source' has_many :nodes, :class_name => 'TestLab::Node' attribute :testlab attribute :config, :default => Hash.new attribute :version def initialize(*args) @ui = TestLab.ui @ui.logger.debug { "Loading Labfile" } super(*args) @ui.logger.debug { "Labfile '#{self.id}' Loaded" } if version.nil? raise LabfileError, 'You must version the Labfile!' else @ui.logger.debug { "Labfile Version: #{version}" } version_arguments = version.split @ui.logger.debug { version_arguments.inspect } if version_arguments.count == 1 if (TestLab::VERSION != version_arguments.first) raise LabfileError, "This Labfile is not compatible with this version of TestLab! (#{version})" end elsif version_arguments.count == 2 if !TestLab::VERSION.send(version_arguments.first, version_arguments.last) raise LabfileError, "This Labfile is not compatible with this version of TestLab! (#{version})" end else raise LabfileError, 'Invalid version!' end end end def config_dir self.testlab.config_dir end def repo_dir self.testlab.repo_dir end end end
28.035088
107
0.624531
bb7ebe0d8efdf3f3311b7cca46dc3275fb9b6ced
4,661
require 'rails_helper' require 'faker' I18n.reload! describe CampsController do let(:email) { Faker::Internet.email } let(:user) { User.create! email: email, password: Faker::Internet.password, ticket_id: '6687' } let(:camp_leader) { Faker::Name.name } let(:camp_attributes){ { name: 'Burn something', subtitle: 'Subtitle', description: 'We will build something and then burn it', electricity: 'Big enough for a big fire', light: 'There sill be need of good ventilation', fire: '2 to build and 3 to burn', noise: 'The fire consumes everything', nature: 'Well - it will burn....', contact_email: '[email protected]', contact_name: camp_leader } } describe "camp creation" do before do sign_in user end it 'got a form' do get :new expect(response).to have_http_status(:success) end it 'creates a camp' do post :create, params: { camp: camp_attributes } c = Camp.find_by_contact_name camp_leader expect( c.name ).to eq 'Burn something' end end context 'update permissions' do let!(:camp) { Camp.create!(camp_attributes.merge(creator: user)) } shared_examples_for 'should fail' do it 'should not succeed updating' do post :update, params: { camp: camp_attributes, id: camp.id } expect(flash[:alert]).to_not be_nil end end shared_examples_for 'should succeed' do it 'should succeed updating' do post :update, params: { camp: camp_attributes, id: camp.id } expect(flash[:alert]).to be_nil expect(flash[:notice]).to be_nil end end describe 'not logged in' do it_behaves_like 'should fail' end context 'logged in' do let(:guide) { false } let(:admin) { false } let(:current_user) { User.create!(email: '[email protected]', password: 'badpassword', guide: guide, admin: admin) } before :each do sign_in current_user end context 'another user' do it_behaves_like 'should fail' end context 'dream owner' do let(:current_user) { user } it_behaves_like 'should succeed' end context 'guide' do let(:guide) { true } it_behaves_like 'should succeed' end context 'admin' do let(:admin) { true } it_behaves_like 'should succeed' end end end describe '#update_grants' do let!(:camp) { Camp.create!(camp_attributes.merge(creator: user)) } before do sign_in user camp.update!(maxbudget_realcurrency: 80, minbudget_realcurrency: 50) end it 'should transfer grants' do expect { patch :update_grants, params: { id: camp.id, grants: 3 } }.to change { Grant.count }.by(1) expect(user.reload.grants).to eq 7 expect(camp.reload.grants_received).to eq 3 expect(Grant.exists?(camp: camp, user: user)) end it 'should transfer grants' do expect { patch :update_grants, params: { id: camp.id, grants: 10 } }.to change { Grant.count }.by(1) expect(user.reload.grants).to eq 2 expect(camp.reload.grants_received).to eq camp.maxbudget expect(camp.fullyfunded).to eq true expect(Grant.exists?(camp: camp, user: user)) expect(Grant.last.amount).to eq camp.maxbudget end it 'should not transfer grants if the user does not have enough' do user.update(grants: 2) expect { patch :update_grants, params: { id: camp.id, grants: 3 } }.to_not change { Grant.count } expect(flash[:alert]).to be_present end it 'should not transfer grants if no max budget is given' do camp.update(maxbudget_realcurrency: nil) expect { patch :update_grants, params: { id: camp.id, grants: 3 } }.to_not change { Grant.count } expect(flash[:alert]).to be_present end it 'should not transfer grants if no grants are given' do expect { patch :update_grants, params: { id: camp.id, grants: 0 } }.to_not change { Grant.count } expect(flash[:alert]).to be_present end it 'should not transfer grants if too many grants are given' do Rails.application.config.x.firestarter_settings["max_grants_per_user_per_dream"] = 7 Grant.create!(user: user, camp: camp, amount: 7) expect { patch :update_grants, params: { id: camp.id, grants: 4 } }.to_not change { Grant.count } expect(flash[:alert]).to be_present Rails.application.config.x.firestarter_settings["max_grants_per_user_per_dream"] = 10 end it 'should allow admins to give any amount of grants' do end end end
30.070968
106
0.641064
1a4417d88e0df377866fede4c368609f870ebe81
3,794
class Erlang < Formula desc "Programming language for highly scalable real-time systems" homepage "https://www.erlang.org/" # Download tarball from GitHub; it is served faster than the official tarball. url "https://github.com/erlang/otp/releases/download/OTP-24.0.3/otp_src_24.0.3.tar.gz" sha256 "64a70fb19da9c94d11f4e756998a2e91d8c8400d7d72960b15ad544af60ebe45" license "Apache-2.0" livecheck do url :stable regex(/^OTP[._-]v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_big_sur: "8ebaae00022e7bb359df1fac2a45ecb371cb5cc96b69d18f6a167040aae3a671" sha256 cellar: :any, big_sur: "3a2620b1a73503d3b30ae868cdd9259e268088a865204eb077778ef41f1978e9" sha256 cellar: :any, catalina: "f7f30f0c895c4ca94db37bf5860b36dbebdef94422628f460eb82ba42d3a1c33" sha256 cellar: :any, mojave: "90129ccd3c3aeea5d09776cd2453e98c39a5facc43c7f834277f729959082a48" sha256 cellar: :any_skip_relocation, x86_64_linux: "1d2bbae52f84051fe554c5a8bdf57ea2f71d9396fb846f2aef08aa2e2f00791e" # linuxbrew-core end head do url "https://github.com/erlang/otp.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "[email protected]" depends_on "wxmac" # for GUI apps like observer resource "html" do url "https://www.erlang.org/download/otp_doc_html_24.0.tar.gz" mirror "https://fossies.org/linux/misc/otp_doc_html_24.0.tar.gz" sha256 "6ceaa2cec97fa5a631779544a3c59afe9e146084e560725b823c476035716e73" end def install # Unset these so that building wx, kernel, compiler and # other modules doesn't fail with an unintelligible error. %w[LIBS FLAGS AFLAGS ZFLAGS].each { |k| ENV.delete("ERL_#{k}") } # Do this if building from a checkout to generate configure system "./otp_build", "autoconf" unless File.exist? "configure" args = %W[ --disable-debug --disable-silent-rules --prefix=#{prefix} --enable-dynamic-ssl-lib --enable-hipe --enable-shared-zlib --enable-smp-support --enable-threads --enable-wx --with-ssl=#{Formula["[email protected]"].opt_prefix} --without-javac ] on_macos do args << "--enable-darwin-64bit" args << "--enable-kernel-poll" if MacOS.version > :el_capitan args << "--with-dynamic-trace=dtrace" if MacOS::CLT.installed? end system "./configure", *args system "make" system "make", "install" # Build the doc chunks (manpages are also built by default) system "make", "docs", "DOC_TARGETS=chunks" system "make", "install-docs" doc.install resource("html") end def caveats <<~EOS Man pages can be found in: #{opt_lib}/erlang/man Access them with `erl -man`, or add this directory to MANPATH. EOS end test do system "#{bin}/erl", "-noshell", "-eval", "crypto:start().", "-s", "init", "stop" (testpath/"factorial").write <<~EOS #!#{bin}/escript %% -*- erlang -*- %%! -smp enable -sname factorial -mnesia debug verbose main([String]) -> try N = list_to_integer(String), F = fac(N), io:format("factorial ~w = ~w\n", [N,F]) catch _:_ -> usage() end; main(_) -> usage(). usage() -> io:format("usage: factorial integer\n"). fac(0) -> 1; fac(N) -> N * fac(N-1). EOS chmod 0755, "factorial" assert_match "usage: factorial integer", shell_output("./factorial") assert_match "factorial 42 = 1405006117752879898543142606244511569936384000000000", shell_output("./factorial 42") end end
32.706897
139
0.640221
9185dfa69ef09ae463afe8ec20e39d44d98c0c81
1,994
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. module Selenium module WebDriver class PortProber def self.above(port) port += 1 until free? port port end def self.random # TODO: Avoid this # # (a) should pick a port that's guaranteed to be free on all interfaces # (b) should pick a random port outside the ephemeral port range # server = TCPServer.new(Platform.localhost, 0) port = server.addr[1] server.close port end IGNORED_ERRORS = [Errno::EADDRNOTAVAIL] IGNORED_ERRORS << Errno::EBADF if Platform.cygwin? IGNORED_ERRORS << Errno::EACCES if Platform.windows? IGNORED_ERRORS.freeze def self.free?(port) Platform.interfaces.each do |host| begin TCPServer.new(host, port).close rescue *IGNORED_ERRORS => ex WebDriver.logger.debug("port prober could not bind to #{host}:#{port} (#{ex.message})") # ignored - some machines appear unable to bind to some of their interfaces end end true rescue SocketError, Errno::EADDRINUSE false end end # PortProber end # WebDriver end # Selenium
32.688525
99
0.666499
2603ee33de2cecb07f1b4f1dfd652d49acaa94eb
4,426
# encoding: utf-8 require "mongoid/matchable/default" require "mongoid/matchable/all" require "mongoid/matchable/and" require "mongoid/matchable/exists" require "mongoid/matchable/gt" require "mongoid/matchable/gte" require "mongoid/matchable/in" require "mongoid/matchable/lt" require "mongoid/matchable/lte" require "mongoid/matchable/ne" require "mongoid/matchable/nin" require "mongoid/matchable/or" require "mongoid/matchable/size" module Mongoid # This module contains all the behavior for ruby implementations of MongoDB # selectors. # # @since 4.0.0 module Matchable extend ActiveSupport::Concern # Hash lookup for the matcher for a specific operation. # # @since 1.0.0 MATCHERS = { "$all" => All, "$and" => And, "$exists" => Exists, "$gt" => Gt, "$gte" => Gte, "$in" => In, "$lt" => Lt, "$lte" => Lte, "$ne" => Ne, "$nin" => Nin, "$or" => Or, "$size" => Size }.with_indifferent_access.freeze # Determines if this document has the attributes to match the supplied # MongoDB selector. Used for matching on embedded associations. # # @example Does the document match? # document.matches?(:title => { "$in" => [ "test" ] }) # # @param [ Hash ] selector The MongoDB selector. # # @return [ true, false ] True if matches, false if not. # # @since 1.0.0 def matches?(selector) selector.each_pair do |key, value| if value.is_a?(Hash) value.each do |item| if item[0].to_s == "$not".freeze item = item[1] return false if matcher(self, key, item).matches?(item) else return false unless matcher(self, key, Hash[*item]).matches?(Hash[*item]) end end else return false unless matcher(self, key, value).matches?(value) end end true end private # Get the matcher for the supplied key and value. Will determine the class # name from the key. # # @api private # # @example Get the matcher. # document.matcher(:title, { "$in" => [ "test" ] }) # # @param [ Document ] document The document to check. # @param [ Symbol, String ] key The field name. # @param [ Object, Hash ] The value or selector. # # @return [ Matcher ] The matcher. # # @since 2.0.0.rc.7 def matcher(document, key, value) Matchable.matcher(document, key, value) end class << self # Get the matcher for the supplied key and value. Will determine the class # name from the key. # # @api private # # @example Get the matcher. # document.matcher(:title, { "$in" => [ "test" ] }) # # @param [ Document ] document The document to check. # @param [ Symbol, String ] key The field name. # @param [ Object, Hash ] The value or selector. # # @return [ Matcher ] The matcher. # # @since 2.0.0.rc.7 def matcher(document, key, value) if value.is_a?(Hash) matcher = MATCHERS[value.keys.first] if matcher matcher.new(extract_attribute(document, key)) else Default.new(extract_attribute(document, key)) end else case key.to_s when "$or" then Or.new(value, document) when "$and" then And.new(value, document) else Default.new(extract_attribute(document, key)) end end end private # Extract the attribute from the key, being smarter about dot notation. # # @api private # # @example Extract the attribute. # strategy.extract_attribute(doc, "info.field") # # @param [ Document ] document The document. # @param [ String ] key The key. # # @return [ Object ] The value of the attribute. # # @since 2.2.1 def extract_attribute(document, key) if (key_string = key.to_s) =~ /.+\..+/ key_string.split('.').inject(document.as_document) do |_attribs, _key| if _attribs.is_a?(::Array) _attribs.map { |doc| doc.try(:[], _key) } else _attribs.try(:[], _key) end end else document.attributes[key_string] end end end end end
28.012658
87
0.567555
ab7f7d47e21f453c4b3b1d177071940337b4ce3f
361
module Gym class Xcode class << self def xcode_path Helper.xcode_path end def xcode_version Helper.xcode_version end # Below Xcode 7 (which offers a new nice API to sign the app) def pre_7? v = xcode_version is_pre = v.split('.')[0].to_i < 7 is_pre end end end end
17.190476
67
0.556787
abc96e1c3f4da20c4816c2a49aadd3f816dee5ab
404
require './config/environment' class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' enable :sessions unless test? set :session_secret, "secret" end get '/' do erb :index end helpers do def logged_in? !!session[:user_id] end def current_user User.find(session[:user_id]) end end end
15.538462
43
0.643564
5dbcd599289a8312e08aee5566c1b00fff3a6ab5
1,943
# frozen_string_literal: true class PasswordResetsController < ApplicationController skip_before_action :authenticated def reset_password user = Marshal.load(Base64.decode64(params[:user])) unless params[:user].nil? if user && params[:password] && params[:confirm_password] && params[:password] == params[:confirm_password] user.password = params[:password] user.save! flash[:success] = "Your password has been reset please login" redirect_to :login else flash[:error] = "Error resetting your password. Please try again." redirect_to :login end end def confirm_token if !params[:token].nil? && is_valid?(params[:token]) flash[:success] = "Password reset token confirmed! Please create a new password." render "password_resets/reset_password" else flash[:error] = "Invalid password reset token. Please try again." redirect_to :login end end def send_forgot_password @user = User.find_by_email(params[:email]) unless params[:email].nil? if @user && password_reset_mailer(@user) flash[:success] = "Password reset email sent to #{params[:email]}" redirect_to :login else flash[:error] = "There was an issue sending password reset email to #{params[:email]}".html_safe unless params[:email].nil? end end private def password_reset_mailer(user) token = generate_token(user.id, user.email) UserMailer.forgot_password(user.email, token).deliver end def generate_token(id, email) hash = Digest::MD5.hexdigest(email) "#{id}-#{hash}" end def is_valid?(token) if token =~ /(?<user>\d+)-(?<email_hash>[A-Z0-9]{32})/i # Fetch the user by their id, and hash their email address @user = User.find_by(id: $~[:user]) email = Digest::MD5.hexdigest(@user.email) # Compare and validate our hashes return true if email == $~[:email_hash] end end end
30.359375
129
0.67473
ff261adf45e8cb5f0923a28970fc7539a8a6d3ab
5,189
require 'spec_helper' module PayuPayments describe Client do it "should be able to create a client" do client = Client.new(:fullName => "John Doe", :email => "[email protected]") client.should_receive(:http_call).with("post", "/payments-api/rest/v4.3/customers", {:fullName => "John Doe", :email => "[email protected]"}).and_return(:fullName => "John Doe", :email => "[email protected]") client.save end it "should validate the required fields" do client = Client.new client.should_not be_valid expect(client.errors.count).to be > 0 expect(client.errors[0][:field]).to eql(:fullName) expect(client.errors[1][:field]).to eql(:email) end it "should validate the format of the email" do client = Client.new(:fullName => "John Doe", :email => "johndoegmail.com") client.should_not be_valid expect(client.errors[0][:field]).to eql(:email) expect(client.errors[0][:message]).to eql("The Email doesn't have the correct format") end it "should be able to find a client with its id" do call = Client.new call.should_receive(:http_call).with("get","/payments-api/rest/v4.3/customers/1").and_return(:fullName => "John Doe", :email => "[email protected]", :id => 1) Client.should_receive(:new).twice.and_return(call) client = Client.find(1) expect(client).to be_an_instance_of(Client) end it "should save a credit card related to the client" do client = Client.new(:id => "123", :fullName => "John Doe", :email => "[email protected]") cc = CreditCard.new CreditCard.should_receive(:new).and_return(cc) cc.stub(:save => true) client.add_credit_card({number: "1234", :name => "John Doe"}) end it "should be able to load credit cards" do response = { id: "2mkls9xekm", fullName: "Pedro Perez", email: "[email protected]", creditCards: [ { token: "da2224a9-58b7-482a-9866-199de911c23f", customerId: "2mkls9xekm", number: "************4242", name: "Usuario Prueba", type: "VISA", address: { line1: "Street 93B", line2: "17 25", line3: "Office 301", city: "Bogota", country: "CO", postalCode: "00000", phone: "300300300" } } ] } Client.should_receive(:find).and_return(Client.new(response)) client = Client.find("2mkls9xekm") expect(client.base.id).to eq("2mkls9xekm") expect(client.credit_cards[0].attr.number).to eql("************4242") end it "should be able to load subscriptions" do response = { id: "2mkls9xekm", fullName: "Pedro Perez", email: "[email protected]", subscriptions: [ { id: "2mlhk3qxji", quantity: "1", installments: "1", currentPeriodStart: "2013-08-30T10:46:41.477-05:00", currentPeriodEnd: "2013-09-29T10:46:41.477-05:00", plan: { id: "414215a2-c990-4525-ba84-072181988d09", planCode: "PLAN-REST-16", description: "Plan rest test", accountId: "1", intervalCount: "1", interval: "MONTH", additionalValues: [ { name: "PLAN_VALUE", value: "20000", currency: "COP" }] } } ] } Client.should_receive(:find).and_return(Client.new(response)) client = Client.find("2mkls9xekm") expect(client.base.id).to eq("2mkls9xekm") expect(client.subscriptions[0].attr.id).to eql("2mlhk3qxji") end end end
47.605505
217
0.413953
623fa16861ad1b7b82765d8216921fac1d0dfce5
687
# Get twilio-ruby from twilio.com/docs/ruby/install require 'rubygems' # This line not needed for ruby > 1.8 require 'twilio-ruby' # Get your Account Sid and Auth Token from twilio.com/user/account account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' @client = Twilio::REST::Client.new account_sid, auth_token # Get an object from its sid. If you do not have a sid, # check out the list resource examples on this page @ip_access_control_list_mapping = @client.account.sip.domains.get('SD32a3c49700934481addd5ce1659f04d2').ip_access_control_list_mappings.get("AL95a47094615fe05b7c17e62a7877836c") puts @ip_access_control_list_mapping.friendly_name
49.071429
177
0.804949
b9ad9ef3373677ee1c96f29e2fd26899255f9846
3,283
# encoding: UTF-8 require 'stringex/localization/conversion_expressions' module Stringex module Localization class Converter include ConversionExpressions attr_reader :ending_whitespace, :options, :starting_whitespace, :string def initialize(string, options = {}) @string = string.dup @options = Stringex::Configuration::StringExtensions.default_settings.merge(options) string =~ /^(\s+)/ @starting_whitespace = $1 unless $1 == '' string =~ /(\s+)$/ @ending_whitespace = $1 unless $1 == '' end def cleanup_accented_html_entities! string.gsub! expressions.accented_html_entity, '\1' end def cleanup_characters! string.gsub! expressions.cleanup_characters, ' ' end def cleanup_html_entities! string.gsub! expressions.cleanup_html_entities, '' end def cleanup_smart_punctuation! expressions.smart_punctuation.each do |expression, replacement| string.gsub! expression, replacement end end def normalize_currency! string.gsub! /(\d+),(\d+)/, '\1\2' end def smart_strip! string.strip! @string = "#{starting_whitespace}#{string}#{ending_whitespace}" end def strip! string.strip! end def strip_html_tags! string.gsub! expressions.html_tag, '' end def translate!(*conversions) conversions.each do |conversion| send conversion end end protected def unreadable_control_characters string.gsub! expressions.unreadable_control_characters, '' end def abbreviations string.gsub! expressions.abbreviation do |x| x.gsub '.', '' end end def apostrophes string.gsub! expressions.apostrophe, '\1\2' end def characters expressions.characters.each do |key, expression| next if key == :slash && options[:allow_slash] replacement = translate(key) replacement = " #{replacement} " unless replacement == '' || key == :dot string.gsub! expression, replacement end end def currencies if has_currencies? [:currencies_complex, :currencies_simple].each do |type| expressions.send(type).each do |key, expression| string.gsub! expression, " #{translate(key, :currencies)} " end end end end def ellipses string.gsub! expressions.characters[:ellipsis], " #{translate(:ellipsis)} " end def html_entities expressions.html_entities.each do |key, expression| string.gsub! expression, translate(key, :html_entities) end string.squeeze! ' ' end def vulgar_fractions expressions.vulgar_fractions.each do |key, expression| string.gsub! expression, translate(key, :vulgar_fractions) end end private def expressions ConversionExpressions end def has_currencies? string =~ CURRENCIES_SUPPORTED end def translate(key, scope = :characters) Localization.translate scope, key end end end end
25.253846
92
0.609199
624ed2b581def3d1d95f132b4076ade3e2ccdefa
456
require "rails/generators" module Ahoy module Stores module Generators class ActiveRecordGenerator < Rails::Generators::Base class_option :database, type: :string, aliases: "-d" class_option :migration_path, type: :string, aliases: "-m" def boom invoke "ahoy:stores:active_record_visits", nil, options invoke "ahoy:stores:active_record_events", nil, options end end end end end
25.333333
66
0.660088
1deced1f03924478c1863e7415dfd28030aadebe
6,302
require_relative '../spec_helper' describe 'bit_field/reference' do include_context 'configuration common' include_context 'register_map common' before(:all) do RgGen.enable(:register_block, :name ) RgGen.enable(:register , :name ) RgGen.enable(:bit_field , :name ) RgGen.enable(:bit_field , :type ) RgGen.enable(:bit_field , :bit_assignment) RgGen.enable(:bit_field , :initial_value ) RgGen.enable(:bit_field , :reference ) RgGen.enable(:bit_field , :type , [:rw, :reserved]) @factory = build_register_map_factory end before(:all) do RgGen.enable(:global, :data_width) ConfigurationDummyLoader.load_data({}) @configuration = build_configuration_factory.create(configuration_file) end after(:all) do clear_enabled_items end let(:configuration) do @configuration end context "入力が空のとき" do let(:load_data) do [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw", "[23:16]", 0, nil], [nil, nil , "bit_field_1", "rw", "[15: 8]", 0, "" ], [nil, nil , "bit_field_2", "rw", "[ 7: 0]", 0 ] ] end let(:register_map) do @factory.create(configuration, register_map_file) end before do RegisterMapDummyLoader.load_data("block_0" => load_data) end describe "#reference" do it "nilを返す" do register_map.bit_fields.each do |bit_field| expect(bit_field.reference).to be_nil end end end describe "#has_reference?" do it "偽を返す" do register_map.bit_fields.each do |bit_field| expect(bit_field).to_not have_reference end end end end context "参照ビットフィールドの指定があるとき" do let(:load_data) do [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw", "[31:16]", 0, "bit_field_1"], [nil, nil , "bit_field_1", "rw", "[15: 0]", 0, "bit_field_0"], [nil, "register_1", "bit_field_2", "rw", "[15: 0]", 0, "bit_field_3"], [nil, "register_2", "bit_field_3", "rw", "[15: 0]", 0, "bit_field_2"] ] end let(:register_map) do @factory.create(configuration, register_map_file) end before do RegisterMapDummyLoader.load_data("block_0" => load_data) end describe "#reference" do it "指定されたビットフィールドオブジェクトを返す" do expect(register_map.bit_fields[0].reference).to eql register_map.bit_fields[1] expect(register_map.bit_fields[1].reference).to eql register_map.bit_fields[0] expect(register_map.bit_fields[2].reference).to eql register_map.bit_fields[3] expect(register_map.bit_fields[3].reference).to eql register_map.bit_fields[2] end end describe "#has_reference?" do it "真を返す" do register_map.bit_fields.each do |bit_field| expect(bit_field).to have_reference end end end end context "入力が自分のビットフィールド名のとき" do let(:load_data) do [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw", "[0]", 0, "bit_field_0"] ] end before do RegisterMapDummyLoader.load_data("block_0" => load_data) end it "RegisterMapErrorを発生させる" do message = "self reference: bit_field_0" expect{ @factory.create(configuration, register_map_file) }.to raise_register_map_error(message, position("block_0", 3, 6)) end end context "入力されたビットフィールド名が存在しないとき" do let(:load_data) do [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw", "[1]", 0, "bit_field_5"], [nil, nil , "bit_field_1", "rw", "[0]", 0, nil ] ] end before do RegisterMapDummyLoader.load_data("block_0" => load_data) end it "RegisterMapErrorを発生させる" do message = "no such reference bit field: bit_field_5" expect{ @factory.create(configuration, register_map_file) }.to raise_register_map_error(message, position("block_0", 3, 6)) end end context "入力されたビットフィールドの属性がreservedのとき" do let(:load_data) do [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw" , "[1]", 0 , "bit_field_1"], [nil, nil , "bit_field_1", "reserved", "[0]", nil, nil ] ] end before do RegisterMapDummyLoader.load_data("block_0" => load_data) end it "RegisterMapErrorを発生させる" do message = "reserved bit field is refered: bit_field_1" expect{ @factory.create(configuration, register_map_file) }.to raise_register_map_error(message, position("block_0", 3, 6)) end end specify "#reference呼び出し時に#validateが呼び出される" do RegisterMapDummyLoader.load_data("block_0" => [ [nil, nil , "block_0" ], [nil, nil , nil ], [nil, nil , nil ], [nil, "register_0", "bit_field_0", "rw", "[0]", 0, ""] ]) register_map = @factory.create(configuration, register_map_file) expect(register_map.bit_fields[0].items[4]).to receive(:validate).with(no_args) register_map.bit_fields[0].reference end end
33.168421
86
0.516503
4ac1944c9745e91f268621b4753bcc3f1b26fa5c
4,169
=begin ########################################################################## # # INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL # __________________ # # (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE # All Rights Reserved. # Product / Project: Flint IT Automation Platform # NOTICE: All information contained herein is, and remains # the property of INFIVERVE TECHNOLOGIES PTE LIMITED. # The intellectual and technical concepts contained # herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED. # Dissemination of this information or any form of reproduction of this material # is strictly forbidden unless prior written permission is obtained # from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE. =end # begin @log.info('Started execution of SMTP script !!') @log.trace("Started execution of 'smtp' flintbit..." + @input.raw.to_s) begin # Flintbit Input Parameters input_type = @input.type # this input parameters are not used if input_type == 'application/xml' # Input type of Request # All mandatory if jdbc_url not provided @connector_name = @input.get('/connector_name/text()') # Name of the SMTP Connector @target = @input.get('/target/text()') # Target for smtp @from = @input.get('/from/text()') # Mail adress of sender @user_name = @input.get('/user_name/text()') # User name of sender @password = @input.get('/password/text()') # Password of sender @to = @input.get('/to/text()') # Mail address of reciver @cc = @input.get('/cc/text()') # cc @bcc = @input.get('/bcc/text()') # bcc @subject = @input.get('/subject/text()') # Subject line of mail @body = @input.get('/body/text()') #Body of mail @attachments = @input.get('/attachments/text()') #Attachments add to mail else # All mandatory if jdbc_url not provided @connector_name = @input.get('connector_name') # Name of the SMTP Connector @target = @input.get('target') # Target for smtp @from = @input.get('from') # Mail adress of sender @user_name = @input.get('username') # User name of sender @password = @input.get('password') # Password of sender @to = @input.get('to') # Mail address of reciver @cc = @input.get('cc') # cc @bcc = @input.get('bcc') # bcc @subject = @input.get('subject') # Subject line of mail @body = @input.get('body') #Body of mail @attachments = @input.get('attachments') #Attachments add to mail end @log.trace('Calling SMTP Connector...') # @log.info("CONNECTOR NAME "+@connector_name.to_s) # @log.info("Target "[email protected]_s) # @log.info("FROM "[email protected]_s) # @log.info("USERNAME "+@user_name.to_s) # @log.info("password "[email protected]_s) # @log.info("TO "[email protected]_s) response = @call.connector(@connector_name) .set('target', @target) .set('from', @from) .set('username', @user_name) .set('password', @password) .set('to', @to) .set('subject', @subject) .set('body', @body) .set('action', 'send') .set("content-type", "text/html") .set('port', 587) .set('timeout', 600000) .sync # SMTP Connector Response Meta Parameters response_exitcode = response.exitcode # Exit status code response_message = response.message # Execution status message # SMTP Connector Response Parameters result = response.get('result') # Response Body if response.exitcode == 0 @log.info("Success in executing SMTP Connector where, exitcode :: #{response_exitcode} | message :: #{response_message}") @log.info("SMTP Response Body ::#{response_message}") @output.set('result', response_message).set('exit-code', 0) else @log.error("Failure in executing SMTP Connector where, exitcode :: #{response_exitcode} | message :: #{response_message}") @log.error('Failed') @output.set('result', response.message).set('exit-code', -1) end rescue Exception => e @log.error(e.message) @output.set('exit-code', 1).set('message', e.message) end @log.info('Finished execution of SMTP script !!') # end
41.69
125
0.636604
5dda71fe37c809973a3dc71da31fbeb6b21d72e9
5,498
require 'spec_helper.rb' describe MarketingCloudSDK::Client do context 'initialized' do it 'with client parameters' do client = MarketingCloudSDK::Client.new 'client' => { 'id' => '1234', 'secret' => 'ssssh', 'signature' => 'hancock' } expect(client.secret).to eq 'ssssh' expect(client.id).to eq '1234' expect(client.signature).to eq 'hancock' end it 'with debug=true' do client = MarketingCloudSDK::Client.new({}, true) expect(client.debug).to be_true end it 'with debug=false' do client = MarketingCloudSDK::Client.new({}, false) expect(client.debug).to be_false end it 'sets the request_token url to parameter if it exists' do client = MarketingCloudSDK::Client.new({ 'request_token_url' => 'fake/url' }, false) expect(client.request_token_url).to eq 'fake/url' end it 'sets the request_token url to a default if it does not exist' do client = MarketingCloudSDK::Client.new({}, false) expect(client.request_token_url).to eq 'https://auth.exacttargetapis.com/v1/requestToken' end it 'creates SoapClient' do client = MarketingCloudSDK::Client.new expect(client).to be_kind_of MarketingCloudSDK::Soap end it '#wsdl defaults to https://webservice.exacttarget.com/etframework.wsdl' do client = MarketingCloudSDK::Client.new expect(client.wsdl).to eq 'https://webservice.exacttarget.com/etframework.wsdl' end it 'creates RestClient' do client = MarketingCloudSDK::Client.new expect(client).to be_kind_of MarketingCloudSDK::Rest end describe 'with a wsdl' do let(:client) { MarketingCloudSDK::Client.new 'defaultwsdl' => 'somewsdl' } it'creates a SoapClient' do expect(client).to be_kind_of MarketingCloudSDK::Soap end it'#wsdl returns default wsdl' do expect(client.wsdl).to eq 'somewsdl' end end end context 'instance can set' do let(:client) { MarketingCloudSDK::Client.new } it 'client id' do client.id = 123 expect(client.id).to eq 123 end it 'client secret' do client.secret = 'sssh' expect(client.secret).to eq 'sssh' end it 'refresh token' do client.refresh_token = 'refresh' expect(client.refresh_token).to eq 'refresh' end it 'debug' do expect(client.debug).to be_false client.debug = true expect(client.debug).to be_true end end describe '#jwt=' do let(:payload) do { 'request' => { 'user' => { 'oauthToken' => 123456789, 'expiresIn' => 3600, 'internalOauthToken' => 987654321, 'refreshToken' => 101010101010, }, 'application' => { 'package' => 'JustTesting', }, }, } end let(:sig) { 'hanckock' } let(:encoded) do JWT.encode(payload, sig) end it 'raises an exception when signature is missing' do expect { MarketingCloudSDK::Client.new.jwt = encoded }.to raise_exception 'Require app signature to decode JWT' end describe 'decodes JWT' do let(:client) do MarketingCloudSDK::Client.new 'client' => { 'id' => '1234', 'secret' => 'ssssh', 'signature' => sig } end it 'making auth token available to client' do client.jwt = encoded expect(client.auth_token).to eq 123456789 end it 'making internal token available to client' do client.jwt = encoded expect(client.internal_token).to eq 987654321 end it 'making refresh token available to client' do client.jwt = encoded expect(client.refresh_token).to eq 101010101010 end end end describe '#refresh_token' do let(:client) { MarketingCloudSDK::Client.new } it 'defaults to nil' do expect(client.refresh_token).to be_nil end it 'can be accessed' do client.refresh_token = '1234567890' expect(client.refresh_token).to eq '1234567890' end end describe '#refresh' do let(:client) { MarketingCloudSDK::Client.new } context 'raises an exception' do it 'when client id and secret are missing' do expect { client.refresh }.to raise_exception 'Require Client Id and Client Secret to refresh tokens' end it 'when client id is missing' do client.secret = 1234 expect { client.refresh }.to raise_exception 'Require Client Id and Client Secret to refresh tokens' end it 'when client secret is missing' do client.id = 1234 expect { client.refresh }.to raise_exception 'Require Client Id and Client Secret to refresh tokens' end end # context 'posts' do # let(:client) { MarketingCloudSDK::Client.new 'client' => { 'id' => 123, 'secret' => 'sssh'} } # it 'accessType=offline' do # client.stub(:post) # .with({'clientId' => 123, 'secret' => 'ssh', 'accessType' => 'offline'}) # .and_return() # end # context 'updates' do # let(:client) { MarketingCloudSDK::Client.new 'client' => { 'id' => 123, 'secret' => 'sssh'} } # it 'access_token' do # #client.stub(:post). # end # end end describe 'includes HTTPRequest' do subject { MarketingCloudSDK::Client.new } it { should respond_to(:get) } it { should respond_to(:post) } it { should respond_to(:patch) } it { should respond_to(:delete) } end end
28.635417
122
0.6255
18d36336a4317ca80da117dc4e3fb8eca4863bab
2,112
# 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: 20171001062926) do create_table "microposts", force: :cascade do |t| t.text "content" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "picture" t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at" t.index ["user_id"], name: "index_microposts_on_user_id" end create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["followed_id"], name: "index_relationships_on_followed_id" t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true t.index ["follower_id"], name: "index_relationships_on_follower_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" t.string "remember_digest" t.boolean "admin", default: false t.string "activation_digest" t.boolean "activated", default: false t.datetime "activated_at" t.string "reset_digest" t.datetime "reset_sent_at" t.index ["email"], name: "index_users_on_email", unique: true end end
40.615385
116
0.736269
7934dae654093d7fb2d1a76870e50adeff064539
1,696
namespace :pentabarf do namespace :import do task default: :all task setup: :environment do require 'pentabarf_import_helper' @import_helper = PentabarfImportHelper.new end desc 'Import conferences' task conferences: :setup do @import_helper.import_conferences end desc 'Import tracks' task tracks: :setup do @import_helper.import_tracks end desc 'Import rooms' task rooms: :setup do @import_helper.import_rooms end desc 'Import people' task people: :setup do @import_helper.import_people end desc 'Import accounts' task accounts: :setup do @import_helper.import_accounts end desc 'Import languages' task languages: :setup do @import_helper.import_languages end desc 'Import events' task events: :setup do @import_helper.import_events end desc 'Import event_ratings' task event_ratings: :setup do @import_helper.import_event_ratings end desc 'Import event_feedbacks' task event_feedbacks: :setup do @import_helper.import_event_feedbacks end desc 'Import event attachments' task event_attachments: :setup do @import_helper.import_event_attachments end desc 'Import event_people' task event_people: :setup do @import_helper.import_event_people end desc 'Import links' task links: :setup do @import_helper.import_links end desc 'Import data from pentabarf' task all: [:setup, :conferences, :tracks, :rooms, :people, :accounts, :languages, :events, :event_feedbacks, :event_ratings, :event_attachments, :event_people, :links] end end
22.918919
171
0.68809
91cd6de48efffff9841bfe406d009b5cedc3a9f9
512
require 'yandex_delivery' YandexDelivery.setup do |config| if File.exist?('config/yandex_delivery.yml') template = ERB.new(File.new('config/yandex_delivery.yml').read) processed = YAML.safe_load(template.result(binding)) processed['YANDEX_DELIVERY_API_KEY'].each do |k, v| config::create_method k.underscore.to_sym config::register "#{k.underscore}_key".to_sym, v end processed['YANDEX_DELIVERY'].each do |k, v| config::register k.underscore.to_sym, v end end end
30.117647
67
0.710938
627aaba3a7bc9a99cb8bd3062a72f0284b088d7d
121,399
# frozen_string_literal: true require "isolation/abstract_unit" require "rack/test" require "env_helpers" require "set" class ::MyMailInterceptor def self.delivering_email(email); email; end end class ::MyOtherMailInterceptor < ::MyMailInterceptor; end class ::MyPreviewMailInterceptor def self.previewing_email(email); email; end end class ::MyOtherPreviewMailInterceptor < ::MyPreviewMailInterceptor; end class ::MyMailObserver def self.delivered_email(email); email; end end class ::MyOtherMailObserver < ::MyMailObserver; end class MyLogRecorder < Logger def initialize @io = StringIO.new super(@io) end def recording @io.string end end module ApplicationTests class ConfigurationTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation include Rack::Test::Methods include EnvHelpers def new_app File.expand_path("#{app_path}/../new_app") end def copy_app FileUtils.cp_r(app_path, new_app) end def app(env = "development") @app ||= begin ENV["RAILS_ENV"] = env require "#{app_path}/config/environment" Rails.application ensure ENV.delete "RAILS_ENV" end end def switch_development_hosts_to(*hosts) old_development_hosts = ENV["RAILS_DEVELOPMENT_HOSTS"] ENV["RAILS_DEVELOPMENT_HOSTS"] = hosts.join(",") yield ensure ENV["RAILS_DEVELOPMENT_HOSTS"] = old_development_hosts end def setup build_app suppress_default_config suppress_sqlite3_warning end def teardown teardown_app FileUtils.rm_rf(new_app) if File.directory?(new_app) end def suppress_default_config FileUtils.mv("#{app_path}/config/environments", "#{app_path}/config/__environments__") end def restore_default_config FileUtils.rm_rf("#{app_path}/config/environments") FileUtils.mv("#{app_path}/config/__environments__", "#{app_path}/config/environments") end def suppress_sqlite3_warning add_to_config "config.active_record.sqlite3_production_warning = false" end def restore_sqlite3_warning remove_from_config ".*config.active_record.sqlite3_production_warning.*\n" end test "Rails.env does not set the RAILS_ENV environment variable which would leak out into rake tasks" do require "rails" switch_env "RAILS_ENV", nil do Rails.env = "development" assert_equal "development", Rails.env assert_nil ENV["RAILS_ENV"] end end test "Rails.env falls back to development if RAILS_ENV is blank and RACK_ENV is nil" do with_rails_env("") do assert_equal "development", Rails.env end end test "Rails.env falls back to development if RACK_ENV is blank and RAILS_ENV is nil" do with_rack_env("") do assert_equal "development", Rails.env end end test "By default logs tags are not set in development" do restore_default_config with_rails_env "development" do app "development" assert_predicate Rails.application.config.log_tags, :blank? end end test "By default logs are tagged with :request_id in production" do restore_default_config with_rails_env "production" do app "production" assert_equal [:request_id], Rails.application.config.log_tags end end test "lib dir is on LOAD_PATH during config" do app_file "lib/my_logger.rb", <<-RUBY require "logger" class MyLogger < ::Logger end RUBY add_to_top_of_config <<-RUBY require "my_logger" config.logger = MyLogger.new STDOUT RUBY app "development" assert_equal "MyLogger", Rails.application.config.logger.class.name end test "raises an error if cache does not support recyclable cache keys" do build_app(initializers: true) add_to_env_config "production", "config.cache_store = Class.new {}.new" add_to_env_config "production", "config.active_record.cache_versioning = true" error = assert_raise(RuntimeError) do app "production" end assert_match(/You're using a cache/, error.message) end test "a renders exception on pending migration" do add_to_config <<-RUBY config.active_record.migration_error = :page_load config.consider_all_requests_local = true config.action_dispatch.show_exceptions = true RUBY app_file "db/migrate/20140708012246_create_user.rb", <<-RUBY class CreateUser < ActiveRecord::Migration::Current def change create_table :users end end RUBY app "development" begin ActiveRecord::Migrator.migrations_paths = ["#{app_path}/db/migrate"] get "/foo" assert_equal 500, last_response.status assert_match "ActiveRecord::PendingMigrationError", last_response.body assert_changes -> { File.exist?(File.join(app_path, "db", "schema.rb")) }, from: false, to: true do output = capture(:stdout) do post "/rails/actions", { error: "ActiveRecord::PendingMigrationError", action: "Run pending migrations", location: "/foo" } end assert_match(/\d{14}\s+CreateUser/, output) end assert_equal 302, last_response.status get "/foo" assert_equal 404, last_response.status ensure ActiveRecord::Migrator.migrations_paths = nil end end test "Rails.groups returns available groups" do require "rails" Rails.env = "development" assert_equal [:default, "development"], Rails.groups assert_equal [:default, "development", :assets], Rails.groups(assets: [:development]) assert_equal [:default, "development", :another, :assets], Rails.groups(:another, assets: %w(development)) Rails.env = "test" assert_equal [:default, "test"], Rails.groups(assets: [:development]) ENV["RAILS_GROUPS"] = "javascripts,stylesheets" assert_equal [:default, "test", "javascripts", "stylesheets"], Rails.groups end test "Rails.application is nil until app is initialized" do require "rails" assert_nil Rails.application app "development" assert_equal AppTemplate::Application.instance, Rails.application end test "Rails.application responds to all instance methods" do app "development" assert_equal Rails.application.routes_reloader, AppTemplate::Application.routes_reloader end test "Rails::Application responds to paths" do app "development" assert_equal ["#{app_path}/app/views"], AppTemplate::Application.paths["app/views"].expanded end test "the application root is set correctly" do app "development" assert_equal Pathname.new(app_path), Rails.application.root end test "the application root can be seen from the application singleton" do app "development" assert_equal Pathname.new(app_path), AppTemplate::Application.root end test "the application root can be set" do copy_app add_to_config <<-RUBY config.root = '#{new_app}' RUBY use_frameworks [] app "development" assert_equal Pathname.new(new_app), Rails.application.root end test "the application root is Dir.pwd if there is no config.ru" do File.delete("#{app_path}/config.ru") use_frameworks [] Dir.chdir("#{app_path}") do app "development" assert_equal Pathname.new("#{app_path}"), Rails.application.root end end test "Rails.root should be a Pathname" do add_to_config <<-RUBY config.root = "#{app_path}" RUBY app "development" assert_instance_of Pathname, Rails.root end test "Rails.public_path should be a Pathname" do add_to_config <<-RUBY config.paths["public"] = "somewhere" RUBY app "development" assert_instance_of Pathname, Rails.public_path end test "config.enable_reloading is !config.cache_classes" do app "development" config = Rails.application.config assert_equal !config.cache_classes, config.enable_reloading [true, false].each do |enabled| config.enable_reloading = enabled assert_equal enabled, config.enable_reloading assert_equal enabled, config.reloading_enabled? assert_equal enabled, !config.cache_classes end [true, false].each do |enabled| config.cache_classes = enabled assert_equal enabled, !config.enable_reloading assert_equal enabled, !config.reloading_enabled? assert_equal enabled, config.cache_classes end end test "does not eager load controllers state actions in development" do app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def index;end def show;end end RUBY app "development" assert_nil PostsController.instance_variable_get(:@action_methods) assert_nil PostsController.instance_variable_get(:@view_context_class) end test "eager loads controllers state in production" do app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def index;end def show;end end RUBY add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY app "production" assert_equal %w(index show).to_set, PostsController.instance_variable_get(:@action_methods) assert_not_nil PostsController.instance_variable_get(:@view_context_class) end test "does not eager load mailer actions in development" do app_file "app/mailers/posts_mailer.rb", <<-RUBY class PostsMailer < ActionMailer::Base def noop_email;end end RUBY app "development" assert_nil PostsMailer.instance_variable_get(:@action_methods) end test "eager loads mailer actions in production" do app_file "app/mailers/posts_mailer.rb", <<-RUBY class PostsMailer < ActionMailer::Base def noop_email;end end RUBY add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY app "production" assert_equal %w(noop_email).to_set, PostsMailer.instance_variable_get(:@action_methods) end test "does not eager load attribute methods in development" do app_file "app/models/post.rb", <<-RUBY class Post < ActiveRecord::Base end RUBY app_file "config/initializers/active_record.rb", <<-RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define(version: 1) do create_table :posts do |t| t.string :title end end RUBY app "development" assert_not_includes Post.instance_methods, :title end test "does not eager load attribute methods in production when the schema cache is empty" do app_file "app/models/post.rb", <<-RUBY class Post < ActiveRecord::Base end RUBY app_file "config/initializers/active_record.rb", <<-RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define(version: 1) do create_table :posts do |t| t.string :title end end RUBY add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY app "production" assert_not_includes Post.instance_methods, :title end test "eager loads attribute methods in production when the schema cache is populated" do app_file "app/models/post.rb", <<-RUBY class Post < ActiveRecord::Base end RUBY app_file "config/initializers/active_record.rb", <<-RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define(version: 1) do create_table :posts do |t| t.string :title end end RUBY add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY app_file "config/initializers/schema_cache.rb", <<-RUBY ActiveRecord::Base.connection.schema_cache.add("posts") RUBY app "production" assert_includes Post.instance_methods, :title end test "does not attempt to eager load attribute methods for models that aren't connected" do app_file "app/models/post.rb", <<-RUBY class Post < ActiveRecord::Base end RUBY app_file "config/initializers/active_record.rb", <<-RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Migration.verbose = false ActiveRecord::Schema.define(version: 1) do create_table :posts do |t| t.string :title end end RUBY add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY app_file "app/models/comment.rb", <<-RUBY class Comment < ActiveRecord::Base establish_connection(adapter: "mysql2", database: "does_not_exist") end RUBY assert_nothing_raised do app "production" end end test "application is always added to eager_load namespaces" do app "development" assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application end test "the application can be eager loaded even when there are no frameworks" do FileUtils.rm_rf("#{app_path}/app/jobs/application_job.rb") FileUtils.rm_rf("#{app_path}/app/models/application_record.rb") FileUtils.rm_rf("#{app_path}/app/mailers/application_mailer.rb") FileUtils.rm_rf("#{app_path}/config/environments") add_to_config <<-RUBY config.enable_reloading = false config.eager_load = true RUBY use_frameworks [] assert_nothing_raised do app "development" end end test "filter_parameters should be able to set via config.filter_parameters" do add_to_config <<-RUBY config.filter_parameters += [ :foo, 'bar', lambda { |key, value| value.reverse! if /baz/.match?(key) }] RUBY assert_nothing_raised do app "development" end end test "filter_parameters should be able to set via config.filter_parameters in an initializer" do app_file "config/initializers/filter_parameters_logging.rb", <<-RUBY Rails.application.config.filter_parameters += [ :password, :foo, 'bar' ] RUBY app "development" assert_equal [:password, :foo, "bar"], Rails.application.env_config["action_dispatch.parameter_filter"] end test "config.to_prepare is forwarded to ActionDispatch" do $prepared = false add_to_config <<-RUBY config.to_prepare do $prepared = true end RUBY assert_not $prepared app "development" get "/" assert $prepared end def assert_utf8 assert_equal Encoding::UTF_8, Encoding.default_external assert_equal Encoding::UTF_8, Encoding.default_internal end test "skipping config.encoding still results in 'utf-8' as the default" do app "development" assert_utf8 end test "config.encoding sets the default encoding" do add_to_config <<-RUBY config.encoding = "utf-8" RUBY app "development" assert_utf8 end test "config.paths.public sets Rails.public_path" do add_to_config <<-RUBY config.paths["public"] = "somewhere" RUBY app "development" assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path end test "In production mode, config.public_file_server.enabled is off by default" do restore_default_config with_rails_env "production" do app "production" assert_not app.config.public_file_server.enabled end end test "In production mode, config.public_file_server.enabled is enabled when RAILS_SERVE_STATIC_FILES is set" do restore_default_config with_rails_env "production" do switch_env "RAILS_SERVE_STATIC_FILES", "1" do app "production" assert app.config.public_file_server.enabled end end end test "In production mode, STDOUT logging is enabled when RAILS_LOG_TO_STDOUT is set" do restore_default_config with_rails_env "production" do switch_env "RAILS_LOG_TO_STDOUT", "1" do app "production" assert ActiveSupport::Logger.logger_outputs_to?(app.config.logger, STDOUT) end end end test "In production mode, config.public_file_server.enabled is disabled when RAILS_SERVE_STATIC_FILES is blank" do restore_default_config with_rails_env "production" do switch_env "RAILS_SERVE_STATIC_FILES", " " do app "production" assert_not app.config.public_file_server.enabled end end end test "EtagWithFlash module doesn't break when the session store is disabled" do make_basic_app do |application| application.config.session_store :disabled end class ::OmgController < ActionController::Base def index stale?(weak_etag: "something") render plain: "else" end end get "/" assert last_response.ok? end test "Use key_generator when secret_key_base is set" do make_basic_app do |application| application.secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" application.config.session_store :disabled end class ::OmgController < ActionController::Base def index cookies.signed[:some_key] = "some_value" render plain: cookies[:some_key] end end get "/" secret = app.key_generator.generate_key("signed cookie") verifier = ActiveSupport::MessageVerifier.new(secret) assert_equal "some_value", verifier.verify(last_response.body) end test "application verifier can be used in the entire application" do make_basic_app do |application| application.secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" application.config.session_store :disabled end message = app.message_verifier(:sensitive_value).generate("some_value") assert_equal "some_value", Rails.application.message_verifier(:sensitive_value).verify(message) secret = app.key_generator.generate_key("sensitive_value") verifier = ActiveSupport::MessageVerifier.new(secret) assert_equal "some_value", verifier.verify(message) end test "application will generate secret_key_base in tmp file if blank in development" do app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.credentials.secret_key_base = nil RUBY # For test that works even if tmp dir does not exist. Dir.chdir(app_path) { FileUtils.remove_dir("tmp") } app "development" assert_not_nil app.secrets.secret_key_base assert File.exist?(app_path("tmp/development_secret.txt")) end test "application will not generate secret_key_base in tmp file if blank in production" do app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.credentials.secret_key_base = nil RUBY assert_raises ArgumentError do app "production" end end test "raises when secret_key_base is blank" do app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.credentials.secret_key_base = nil RUBY error = assert_raise(ArgumentError) do app "production" end assert_match(/Missing `secret_key_base`./, error.message) end test "raise when secret_key_base is not a type of string" do add_to_config <<-RUBY Rails.application.credentials.secret_key_base = 123 RUBY assert_raise(ArgumentError) do app "production" end end test "application verifier can build different verifiers" do make_basic_app do |application| application.config.session_store :disabled end default_verifier = app.message_verifier(:sensitive_value) text_verifier = app.message_verifier(:text) message = text_verifier.generate("some_value") assert_equal "some_value", text_verifier.verify(message) assert_raises ActiveSupport::MessageVerifier::InvalidSignature do default_verifier.verify(message) end assert_equal default_verifier.object_id, app.message_verifier(:sensitive_value).object_id assert_not_equal default_verifier.object_id, text_verifier.object_id end test "secrets.secret_key_base is used when config/secrets.yml is present" do app_file "config/secrets.yml", <<-YAML development: secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 YAML app "development" assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secrets.secret_key_base assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secret_key_base end test "secret_key_base is copied from config to secrets when not set" do remove_file "config/secrets.yml" app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c3" RUBY app "development" assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secrets.secret_key_base end test "custom secrets saved in config/secrets.yml are loaded in app secrets" do app_file "config/secrets.yml", <<-YAML development: secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 aws_access_key_id: myamazonaccesskeyid aws_secret_access_key: myamazonsecretaccesskey YAML app "development" assert_equal "myamazonaccesskeyid", app.secrets.aws_access_key_id assert_equal "myamazonsecretaccesskey", app.secrets.aws_secret_access_key end test "shared secrets saved in config/secrets.yml are loaded in app secrets" do app_file "config/secrets.yml", <<-YAML shared: api_key: 3b7cd727 YAML app "development" assert_equal "3b7cd727", app.secrets.api_key end test "shared secrets will yield to environment specific secrets" do app_file "config/secrets.yml", <<-YAML shared: api_key: 3b7cd727 development: api_key: abc12345 YAML app "development" assert_equal "abc12345", app.secrets.api_key end test "blank config/secrets.yml does not crash the loading process" do app_file "config/secrets.yml", <<-YAML YAML app "development" assert_nil app.secrets.not_defined end test "config.secret_key_base over-writes a blank secrets.secret_key_base" do app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_key_base = "iaminallyoursecretkeybase" RUBY app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML app "development" assert_equal "iaminallyoursecretkeybase", app.secrets.secret_key_base end test "that nested keys are symbolized the same as parents for hashes more than one level deep" do app_file "config/secrets.yml", <<-YAML development: smtp_settings: address: "smtp.example.com" user_name: "[email protected]" password: "697361616320736c6f616e2028656c6f7265737429" YAML app "development" assert_equal "697361616320736c6f616e2028656c6f7265737429", app.secrets.smtp_settings[:password] end test "require_master_key aborts app boot when missing key" do skip "can't run without fork" unless Process.respond_to?(:fork) remove_file "config/master.key" add_to_config "config.require_master_key = true" error = capture(:stderr) do Process.wait(Process.fork { app "development" }) end assert_equal 1, $?.exitstatus assert_match(/Missing.*RAILS_MASTER_KEY/, error) end test "credentials does not raise error when require_master_key is false and master key does not exist" do remove_file "config/master.key" add_to_config "config.require_master_key = false" app "development" assert_not app.credentials.secret_key_base end test "protect from forgery is the default in a new app" do make_basic_app class ::OmgController < ActionController::Base def index render inline: "<%= csrf_meta_tags %>" end end get "/" assert_match(/csrf-param/, last_response.body) end test "default form builder specified as a string" do app_file "config/initializers/form_builder.rb", <<-RUBY class CustomFormBuilder < ActionView::Helpers::FormBuilder def text_field(attribute, *args) label(attribute) + super(attribute, *args) end end Rails.configuration.action_view.default_form_builder = "CustomFormBuilder" RUBY app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model attr_accessor :name end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def index render inline: "<%= begin; form_for(Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" get "/posts" assert_match(/label/, last_response.body) end test "form_with can be configured with form_with_generates_ids" do app_file "config/initializers/form_builder.rb", <<-RUBY Rails.configuration.action_view.form_with_generates_ids = false RUBY app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model attr_accessor :name end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def index render inline: "<%= begin; form_with(model: Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" get "/posts" assert_no_match(/id=('|")post_name('|")/, last_response.body) end test "form_with outputs ids by default" do app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model attr_accessor :name end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def index render inline: "<%= begin; form_with(model: Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" get "/posts" assert_match(/id=('|")post_name('|")/, last_response.body) end test "form_with can be configured with form_with_generates_remote_forms" do app_file "config/initializers/form_builder.rb", <<-RUBY Rails.configuration.action_view.form_with_generates_remote_forms = true RUBY app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model attr_accessor :name end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def index render inline: "<%= begin; form_with(model: Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" get "/posts" assert_match(/data-remote/, last_response.body) end test "form_with generates non remote forms by default" do app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model attr_accessor :name end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def index render inline: "<%= begin; form_with(model: Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" get "/posts" assert_no_match(/data-remote/, last_response.body) end test "default method for update can be changed" do app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model def to_key; [1]; end def persisted?; true; end end RUBY token = "cf50faa3fe97702ca1ae" app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def show render inline: "<%= begin; form_for(Post.new) {}; rescue => e; e.to_s; end %>" end def update render plain: "update" end private def form_authenticity_token(**); token; end # stub the authenticity token end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" params = { authenticity_token: token } get "/posts/1" assert_match(/patch/, last_response.body) patch "/posts/1", params assert_match(/update/, last_response.body) patch "/posts/1", params assert_equal 200, last_response.status put "/posts/1", params assert_match(/update/, last_response.body) put "/posts/1", params assert_equal 200, last_response.status end test "request forgery token param can be changed" do make_basic_app do |application| application.config.action_controller.request_forgery_protection_token = "_xsrf_token_here" end class ::OmgController < ActionController::Base def index render inline: "<%= csrf_meta_tags %>" end end get "/" assert_match "_xsrf_token_here", last_response.body end test "sets ActionDispatch.test_app" do make_basic_app assert_equal Rails.application, ActionDispatch.test_app end test "sets ActionDispatch::Response.default_charset" do make_basic_app do |application| application.config.action_dispatch.default_charset = "utf-16" end assert_equal "utf-16", ActionDispatch::Response.default_charset end test "registers interceptors with ActionMailer" do add_to_config <<-RUBY config.action_mailer.interceptors = MyMailInterceptor RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [::MyMailInterceptor], ::Mail.class_variable_get(:@@delivery_interceptors) end test "registers multiple interceptors with ActionMailer" do add_to_config <<-RUBY config.action_mailer.interceptors = [MyMailInterceptor, "MyOtherMailInterceptor"] RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.class_variable_get(:@@delivery_interceptors) end test "registers preview interceptors with ActionMailer" do add_to_config <<-RUBY config.action_mailer.preview_interceptors = MyPreviewMailInterceptor RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [ActionMailer::InlinePreviewInterceptor, ::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors end test "registers multiple preview interceptors with ActionMailer" do add_to_config <<-RUBY config.action_mailer.preview_interceptors = [MyPreviewMailInterceptor, "MyOtherPreviewMailInterceptor"] RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [ActionMailer::InlinePreviewInterceptor, MyPreviewMailInterceptor, MyOtherPreviewMailInterceptor], ActionMailer::Base.preview_interceptors end test "default preview interceptor can be removed" do app_file "config/initializers/preview_interceptors.rb", <<-RUBY ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [], ActionMailer::Base.preview_interceptors end test "registers observers with ActionMailer" do add_to_config <<-RUBY config.action_mailer.observers = MyMailObserver RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [::MyMailObserver], ::Mail.class_variable_get(:@@delivery_notification_observers) end test "registers multiple observers with ActionMailer" do add_to_config <<-RUBY config.action_mailer.observers = [MyMailObserver, "MyOtherMailObserver"] RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.class_variable_get(:@@delivery_notification_observers) end test "allows setting the queue name for the ActionMailer::MailDeliveryJob" do add_to_config <<-RUBY config.action_mailer.deliver_later_queue_name = 'test_default' RUBY app "development" require "mail" _ = ActionMailer::Base assert_equal "test_default", ActionMailer::Base.class_variable_get(:@@deliver_later_queue_name) end test "ActionMailer::DeliveryJob queue name is :mailers without the Rails defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" require "mail" _ = ActionMailer::Base assert_equal :mailers, ActionMailer::Base.class_variable_get(:@@deliver_later_queue_name) end test "ActionMailer::DeliveryJob queue name is nil by default in 6.1" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" require "mail" _ = ActionMailer::Base assert_nil ActionMailer::Base.class_variable_get(:@@deliver_later_queue_name) end test "valid timezone is setup correctly" do add_to_config <<-RUBY config.root = "#{app_path}" config.time_zone = "Wellington" RUBY app "development" assert_equal "Wellington", Rails.application.config.time_zone end test "raises when an invalid timezone is defined in the config" do add_to_config <<-RUBY config.root = "#{app_path}" config.time_zone = "That big hill over yonder hill" RUBY assert_raise(ArgumentError) do app "development" end end test "valid beginning of week is setup correctly" do add_to_config <<-RUBY config.root = "#{app_path}" config.beginning_of_week = :wednesday RUBY app "development" assert_equal :wednesday, Rails.application.config.beginning_of_week end test "raises when an invalid beginning of week is defined in the config" do add_to_config <<-RUBY config.root = "#{app_path}" config.beginning_of_week = :invalid RUBY assert_raise(ArgumentError) do app "development" end end test "autoloaders" do app "development" assert Rails.autoloaders.zeitwerk_enabled? assert_instance_of Zeitwerk::Loader, Rails.autoloaders.main assert_equal "rails.main", Rails.autoloaders.main.tag assert_instance_of Zeitwerk::Loader, Rails.autoloaders.once assert_equal "rails.once", Rails.autoloaders.once.tag assert_equal [Rails.autoloaders.main, Rails.autoloaders.once], Rails.autoloaders.to_a assert_equal Rails::Autoloaders::Inflector, Rails.autoloaders.main.inflector assert_equal Rails::Autoloaders::Inflector, Rails.autoloaders.once.inflector end test "config.action_view.cache_template_loading with config.enable_reloading default" do add_to_config "config.enable_reloading = false" app "development" require "action_view/base" assert_equal true, ActionView::Resolver.caching? end test "config.action_view.cache_template_loading without config.enable_reloading default" do add_to_config "config.enable_reloading = true" app "development" require "action_view/base" assert_equal false, ActionView::Resolver.caching? end test "config.action_view.cache_template_loading = false" do add_to_config <<-RUBY config.enable_reloading = false config.action_view.cache_template_loading = false RUBY app "development" require "action_view/base" assert_equal false, ActionView::Resolver.caching? end test "config.action_view.cache_template_loading = true" do add_to_config <<-RUBY config.enable_reloading = true config.action_view.cache_template_loading = true RUBY app "development" require "action_view/base" assert_equal true, ActionView::Resolver.caching? end test "config.action_view.cache_template_loading with config.enable_reloading in an environment" do build_app(initializers: true) add_to_env_config "development", "config.enable_reloading = true" # These requires are to emulate an engine loading Action View before the application require "action_view" require "action_view/railtie" require "action_view/base" app "development" assert_equal false, ActionView::Resolver.caching? end test "config.enable_dependency_loading is deprecated" do app "development" assert_deprecated { Rails.application.config.enable_dependency_loading } assert_deprecated { Rails.application.config.enable_dependency_loading = true } end test "ActionController::Base.raise_on_open_redirects is true by default for new apps" do app "development" assert_equal true, ActionController::Base.raise_on_open_redirects end test "ActionController::Base.raise_on_open_redirects is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal false, ActionController::Base.raise_on_open_redirects end test "ActionController::Base.raise_on_open_redirects can be configured in the new framework defaults" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_6_2.rb", <<-RUBY Rails.application.config.action_controller.raise_on_open_redirects = true RUBY app "development" assert_equal true, ActionController::Base.raise_on_open_redirects end test "config.action_dispatch.show_exceptions is sent in env" do make_basic_app do |application| application.config.action_dispatch.show_exceptions = true end class ::OmgController < ActionController::Base def index render plain: request.env["action_dispatch.show_exceptions"] end end get "/" assert_equal "true", last_response.body end test "config.action_controller.wrap_parameters is set in ActionController::Base" do app_file "config/initializers/wrap_parameters.rb", <<-RUBY ActionController::Base.wrap_parameters format: [:json] RUBY app_file "app/models/post.rb", <<-RUBY class Post def self.attribute_names %w(title) end end RUBY app_file "app/controllers/application_controller.rb", <<-RUBY class ApplicationController < ActionController::Base protect_from_forgery with: :reset_session # as we are testing API here end RUBY app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def create render plain: params[:post].inspect end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end RUBY app "development" post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json" assert_equal '#<ActionController::Parameters {"title"=>"foo"} permitted: false>', last_response.body end test "config.action_controller.permit_all_parameters = true" do app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render plain: params[:post].permitted? ? "permitted" : "forbidden" end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end config.action_controller.permit_all_parameters = true RUBY app "development" post "/posts", post: { "title" => "zomg" } assert_equal "permitted", last_response.body end test "config.action_controller.action_on_unpermitted_parameters = :raise" do app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render plain: params.require(:post).permit(:name) end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end config.action_controller.action_on_unpermitted_parameters = :raise RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters post "/posts", post: { "title" => "zomg" } assert_match "We're sorry, but something went wrong", last_response.body end test "config.action_controller.always_permitted_parameters are: controller, action by default" do app "development" require "action_controller/base" require "action_controller/api" assert_equal %w(controller action), ActionController::Parameters.always_permitted_parameters end test "config.action_controller.always_permitted_parameters = ['controller', 'action', 'format']" do add_to_config <<-RUBY config.action_controller.always_permitted_parameters = %w( controller action format ) RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal %w( controller action format ), ActionController::Parameters.always_permitted_parameters end test "config.action_controller.always_permitted_parameters = ['controller','action','format'] does not raise exception" do app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render plain: params.permit(post: [:title]) end end RUBY add_to_config <<-RUBY routes.prepend do resources :posts end config.action_controller.always_permitted_parameters = %w( controller action format ) config.action_controller.action_on_unpermitted_parameters = :raise RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters post "/posts", post: { "title" => "zomg" }, format: "json" assert_equal 200, last_response.status end test "config.action_controller.action_on_unpermitted_parameters is :log by default in development" do app "development" require "action_controller/base" require "action_controller/api" assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_controller.action_on_unpermitted_parameters is :log by default in test" do app "test" require "action_controller/base" require "action_controller/api" assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_controller.action_on_unpermitted_parameters is false by default in production" do app "production" require "action_controller/base" require "action_controller/api" assert_equal false, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_controller.default_protect_from_forgery is true by default" do app "development" assert_equal true, ActionController::Base.default_protect_from_forgery assert_includes ActionController::Base.__callbacks[:process_action].map(&:filter), :verify_authenticity_token end test "config.action_controller.permit_all_parameters can be configured in an initializer" do app_file "config/initializers/permit_all_parameters.rb", <<-RUBY Rails.application.config.action_controller.permit_all_parameters = true RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal true, ActionController::Parameters.permit_all_parameters end test "config.action_controller.always_permitted_parameters can be configured in an initializer" do app_file "config/initializers/always_permitted_parameters.rb", <<-RUBY Rails.application.config.action_controller.always_permitted_parameters = [] RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal [], ActionController::Parameters.always_permitted_parameters end test "config.action_controller.action_on_unpermitted_parameters can be configured in an initializer" do app_file "config/initializers/action_on_unpermitted_parameters.rb", <<-RUBY Rails.application.config.action_controller.action_on_unpermitted_parameters = :raise RUBY app "development" require "action_controller/base" require "action_controller/api" assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_dispatch.ignore_accept_header" do make_basic_app do |application| application.config.action_dispatch.ignore_accept_header = true end class ::OmgController < ActionController::Base def index respond_to do |format| format.html { render plain: "HTML" } format.xml { render plain: "XML" } end end end get "/", {}, { "HTTP_ACCEPT" => "application/xml" } assert_equal "HTML", last_response.body get "/", { format: :xml }, { "HTTP_ACCEPT" => "application/xml" } assert_equal "XML", last_response.body end test "Rails.application#env_config exists and includes some existing parameters" do make_basic_app assert_equal app.env_config["action_dispatch.parameter_filter"], app.config.filter_parameters assert_equal app.env_config["action_dispatch.show_exceptions"], app.config.action_dispatch.show_exceptions assert_equal app.env_config["action_dispatch.logger"], Rails.logger assert_equal app.env_config["action_dispatch.backtrace_cleaner"], Rails.backtrace_cleaner assert_equal app.env_config["action_dispatch.key_generator"], Rails.application.key_generator end test "config.colorize_logging default is true" do make_basic_app assert app.config.colorize_logging end test "config.session_store with :active_record_store with activerecord-session_store gem" do make_basic_app do |application| ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore) application.config.session_store :active_record_store end ensure ActionDispatch::Session.send :remove_const, :ActiveRecordStore end test "config.session_store with :active_record_store without activerecord-session_store gem" do e = assert_raise RuntimeError do make_basic_app do |application| application.config.session_store :active_record_store end end assert_match(/activerecord-session_store/, e.message) end test "default session store initializer does not overwrite the user defined session store even if it is disabled" do make_basic_app do |application| application.config.session_store :disabled end assert_nil app.config.session_store end test "default session store initializer sets session store to cookie store" do session_options = { key: "_myapp_session", cookie_only: true } make_basic_app assert_equal ActionDispatch::Session::CookieStore, app.config.session_store assert_equal session_options, app.config.session_options end test "config.log_level defaults to debug in development" do restore_default_config app "development" assert_equal Logger::DEBUG, Rails.logger.level end test "config.log_level default to info in production" do restore_default_config app "production" assert_equal Logger::INFO, Rails.logger.level end test "config.log_level with custom logger" do make_basic_app do |application| application.config.logger = Logger.new(STDOUT) application.config.log_level = :debug end assert_equal Logger::DEBUG, Rails.logger.level end test "respond_to? accepts include_private" do make_basic_app assert_not_respond_to Rails.configuration, :method_missing assert Rails.configuration.respond_to?(:method_missing, true) end test "config.active_record.dump_schema_after_migration is false on production" do build_app app "production" assert_not ActiveRecord.dump_schema_after_migration end test "config.active_record.dump_schema_after_migration is true by default in development" do app "development" assert ActiveRecord.dump_schema_after_migration end test "config.active_record.verbose_query_logs is false by default in development" do app "development" assert_not ActiveRecord.verbose_query_logs end test "config.active_record.suppress_multiple_database_warning is false by default in development" do app "development" assert_not ActiveRecord.suppress_multiple_database_warning end test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do make_basic_app do |application| application.config.annotations.register_extensions("coffee") do |tag| /#\s*(#{tag}):?\s*(.*)$/ end end assert_not_nil Rails::SourceAnnotationExtractor::Annotation.extensions[/\.(coffee)$/] end test "config.default_log_file returns a File instance" do app "development" assert_instance_of File, app.config.default_log_file assert_equal Rails.application.config.paths["log"].first, app.config.default_log_file.path end test "rake_tasks block works at instance level" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.ran_block = false rake_tasks do config.ran_block = true end end RUBY app "development" assert_not Rails.configuration.ran_block require "rake" require "rake/testtask" require "rdoc/task" Rails.application.load_tasks assert Rails.configuration.ran_block end test "generators block works at instance level" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.ran_block = false generators do config.ran_block = true end end RUBY app "development" assert_not Rails.configuration.ran_block Rails.application.load_generators assert Rails.configuration.ran_block end test "console block works at instance level" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.ran_block = false console do config.ran_block = true end end RUBY app "development" assert_not Rails.configuration.ran_block Rails.application.load_console assert Rails.configuration.ran_block end test "runner block works at instance level" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.ran_block = false runner do config.ran_block = true end end RUBY app "development" assert_not Rails.configuration.ran_block Rails.application.load_runner assert Rails.configuration.ran_block end test "loading the first existing database configuration available" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.paths.add 'config/database', with: 'config/nonexistent.yml' config.paths['config/database'] << 'config/database.yml' end RUBY app "development" assert_kind_of Hash, Rails.application.config.database_configuration end test "autoload paths do not include asset paths" do app "development" ActiveSupport::Dependencies.autoload_paths.each do |path| assert_not_operator path, :end_with?, "app/assets" assert_not_operator path, :end_with?, "app/javascript" end end test "autoload paths will exclude the configured javascript_path" do add_to_config "config.javascript_path = 'webpack'" app_dir("app/webpack") app "development" ActiveSupport::Dependencies.autoload_paths.each do |path| assert_not_operator path, :end_with?, "app/assets" assert_not_operator path, :end_with?, "app/webpack" end end test "autoload paths are not added to $LOAD_PATH if opted-in" do add_to_config "config.add_autoload_paths_to_load_path = true" app "development" # Action Mailer modifies AS::Dependencies.autoload_paths in-place. autoload_paths = ActiveSupport::Dependencies.autoload_paths autoload_paths_from_app_and_engines = autoload_paths.reject do |path| path.end_with?("mailers/previews") end assert_equal true, Rails.configuration.add_autoload_paths_to_load_path assert_empty autoload_paths_from_app_and_engines - $LOAD_PATH # Precondition, ensure we are testing something next. assert_not_empty Rails.configuration.paths.load_paths assert_empty Rails.configuration.paths.load_paths - $LOAD_PATH end test "autoload paths are not added to $LOAD_PATH by default" do app "development" assert_empty ActiveSupport::Dependencies.autoload_paths & $LOAD_PATH # Precondition, ensure we are testing something next. assert_not_empty Rails.configuration.paths.load_paths assert_empty Rails.configuration.paths.load_paths - $LOAD_PATH end test "autoload paths can be set in the config file of the environment" do app_dir "custom_autoload_path" app_dir "custom_autoload_once_path" app_dir "custom_eager_load_path" restore_default_config add_to_env_config "development", <<-RUBY config.autoload_paths << "#{app_path}/custom_autoload_path" config.autoload_once_paths << "#{app_path}/custom_autoload_once_path" config.eager_load_paths << "#{app_path}/custom_eager_load_path" RUBY app "development" Rails.application.config.tap do |config| assert_includes config.autoload_paths, "#{app_path}/custom_autoload_path" assert_includes config.autoload_once_paths, "#{app_path}/custom_autoload_once_path" assert_includes config.eager_load_paths, "#{app_path}/custom_eager_load_path" end end test "load_database_yaml returns blank hash if configuration file is blank" do app_file "config/database.yml", "" app "development" assert_equal({}, Rails.application.config.load_database_yaml) end test "setup_initial_database_yaml does not print a warning if config.active_record.suppress_multiple_database_warning is true" do app_file "config/database.yml", <<-YAML <%= Rails.env %>: username: bobby adapter: sqlite3 database: 'dev_db' YAML add_to_config <<-RUBY config.active_record.suppress_multiple_database_warning = true RUBY app "development" assert_silent do ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml end end test "raises with proper error message if no database configuration found" do FileUtils.rm("#{app_path}/config/database.yml") err = assert_raises RuntimeError do app "development" Rails.application.config.database_configuration end assert_match "config/database", err.message end test "loads database.yml using shared keys" do app_file "config/database.yml", <<-YAML shared: username: bobby adapter: sqlite3 development: database: 'dev_db' YAML app "development" ar_config = Rails.application.config.database_configuration assert_equal "sqlite3", ar_config["development"]["adapter"] assert_equal "bobby", ar_config["development"]["username"] assert_equal "dev_db", ar_config["development"]["database"] end test "loads database.yml using shared keys for undefined environments" do app_file "config/database.yml", <<-YAML shared: username: bobby adapter: sqlite3 database: 'dev_db' YAML app "development" ar_config = Rails.application.config.database_configuration assert_equal "sqlite3", ar_config["development"]["adapter"] assert_equal "bobby", ar_config["development"]["username"] assert_equal "dev_db", ar_config["development"]["database"] end test "config.action_mailer.show_previews defaults to true in development" do app "development" assert Rails.application.config.action_mailer.show_previews end test "config.action_mailer.show_previews defaults to false in production" do app "production" assert_equal false, Rails.application.config.action_mailer.show_previews end test "config.action_mailer.show_previews can be set in the configuration file" do add_to_config <<-RUBY config.action_mailer.show_previews = true RUBY app "production" assert_equal true, Rails.application.config.action_mailer.show_previews end test "config_for loads custom configuration from YAML accessible as symbol or string" do set_custom_config <<~RUBY development: foo: "bar" RUBY app "development" assert_equal "bar", Rails.application.config.my_custom_config[:foo] assert_equal "bar", Rails.application.config.my_custom_config["foo"] end test "config_for loads nested custom configuration from YAML as symbol keys" do set_custom_config <<~RUBY development: foo: bar: baz: 1 RUBY app "development" assert_equal 1, Rails.application.config.my_custom_config[:foo][:bar][:baz] end test "config_for makes all hash methods available" do set_custom_config <<~RUBY development: foo: 0 bar: baz: 1 RUBY app "development" actual = Rails.application.config.my_custom_config assert_equal({ foo: 0, bar: { baz: 1 } }, actual) assert_equal([ :foo, :bar ], actual.keys) assert_equal([ 0, baz: 1], actual.values) assert_equal({ foo: 0, bar: { baz: 1 } }, actual.to_h) assert_equal(0, actual[:foo]) assert_equal({ baz: 1 }, actual[:bar]) end test "config_for does not assume config is a hash" do set_custom_config <<~RUBY development: - foo - bar RUBY app "development" assert_equal %w( foo bar ), Rails.application.config.my_custom_config end test "config_for works with only a shared root array" do set_custom_config <<~RUBY shared: - foo - bar RUBY app "development" assert_equal %w( foo bar ), Rails.application.config.my_custom_config end test "config_for returns only the env array when shared is an array" do set_custom_config <<~RUBY development: - baz shared: - foo - bar RUBY app "development" assert_equal %w( baz ), Rails.application.config.my_custom_config end test "config_for uses the Pathname object if it is provided" do set_custom_config <<~RUBY, "Pathname.new(Rails.root.join('config/custom.yml'))" development: key: 'custom key' RUBY app "development" assert_equal "custom key", Rails.application.config.my_custom_config[:key] end test "config_for raises an exception if the file does not exist" do add_to_config <<-RUBY config.my_custom_config = config_for('custom') RUBY exception = assert_raises(RuntimeError) do app "development" end assert_equal "Could not load configuration. No such file - #{app_path}/config/custom.yml", exception.message end test "config_for without the environment configured returns nil" do set_custom_config <<~RUBY test: key: 'custom key' RUBY app "development" assert_nil Rails.application.config.my_custom_config end test "config_for shared config is overridden" do set_custom_config <<~RUBY shared: foo: :from_shared test: foo: :from_env RUBY app "test" assert_equal :from_env, Rails.application.config.my_custom_config[:foo] end test "config_for shared config is returned when environment is missing" do set_custom_config <<~RUBY shared: foo: :from_shared test: foo: :from_env RUBY app "development" assert_equal :from_shared, Rails.application.config.my_custom_config[:foo] end test "config_for merges shared configuration deeply" do set_custom_config <<~RUBY shared: foo: bar: baz: 1 development: foo: bar: qux: 2 RUBY app "development" assert_equal({ baz: 1, qux: 2 }, Rails.application.config.my_custom_config[:foo][:bar]) end test "config_for with empty file returns nil" do set_custom_config "" app "development" assert_nil Rails.application.config.my_custom_config end test "config_for containing ERB tags should evaluate" do set_custom_config <<~YAML development: key: <%= 'custom key' %> YAML app "development" assert_equal "custom key", Rails.application.config.my_custom_config[:key] end test "config_for with syntax error show a more descriptive exception" do set_custom_config <<~RUBY development: key: foo: RUBY error = assert_raises RuntimeError do app "development" end assert_match "YAML syntax error occurred while parsing", error.message end test "config_for allows overriding the environment" do set_custom_config <<~RUBY, "'custom', env: 'production'" test: key: 'walrus' production: key: 'unicorn' RUBY require "#{app_path}/config/environment" assert_equal "unicorn", Rails.application.config.my_custom_config[:key] end test "config_for handles YAML patches (like safe_yaml) that disable the symbolize_names option" do app_file "config/custom.yml", <<~RUBY development: key: value RUBY app "development" YAML.stub :load, { "development" => { "key" => "value" } } do assert_equal({ key: "value" }, Rails.application.config_for(:custom)) end end test "config_for returns a ActiveSupport::OrderedOptions" do app_file "config/custom.yml", <<~YAML shared: some_key: default development: some_key: value test: YAML app "development" config = Rails.application.config_for(:custom) assert_instance_of ActiveSupport::OrderedOptions, config assert_equal "value", config.some_key config = Rails.application.config_for(:custom, env: :test) assert_instance_of ActiveSupport::OrderedOptions, config assert_equal "default", config.some_key end test "api_only is false by default" do app "development" assert_not Rails.application.config.api_only end test "api_only generator config is set when api_only is set" do add_to_config <<-RUBY config.api_only = true RUBY app "development" Rails.application.load_generators assert Rails.configuration.api_only end test "debug_exception_response_format is :api by default if api_only is enabled" do add_to_config <<-RUBY config.api_only = true RUBY app "development" assert_equal :api, Rails.configuration.debug_exception_response_format end test "debug_exception_response_format can be overridden" do add_to_config <<-RUBY config.api_only = true RUBY app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.debug_exception_response_format = :default end RUBY app "development" assert_equal :default, Rails.configuration.debug_exception_response_format end test "ActiveRecord::Base.has_many_inversing is true by default for new apps" do app "development" assert_equal true, ActiveRecord::Base.has_many_inversing end test "ActiveRecord::Base.has_many_inversing is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, ActiveRecord::Base.has_many_inversing end test "ActiveRecord::Base.has_many_inversing can be configured via config.active_record.has_many_inversing" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_6_1.rb", <<-RUBY Rails.application.config.active_record.has_many_inversing = true RUBY app "development" assert_equal true, ActiveRecord::Base.has_many_inversing end test "ActiveRecord::Base.automatic_scope_inversing is true by default for new apps" do app "development" assert_equal true, ActiveRecord::Base.automatic_scope_inversing end test "ActiveRecord::Base.automatic_scope_inversing is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, ActiveRecord::Base.automatic_scope_inversing end test "ActiveRecord::Base.automatic_scope_inversing can be configured via config.active_record.automatic_scope_inversing" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.active_record.automatic_scope_inversing = true RUBY app "development" assert_equal true, ActiveRecord::Base.automatic_scope_inversing end test "ActiveRecord.verify_foreign_keys_for_fixtures is true by default for new apps" do app "development" assert_equal true, ActiveRecord.verify_foreign_keys_for_fixtures end test "ActiveRecord.verify_foreign_keys_for_fixtures is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, ActiveRecord.verify_foreign_keys_for_fixtures end test "ActiveRecord.verify_foreign_keys_for_fixtures can be configured via config.active_record.verify_foreign_keys_for_fixtures" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.active_record.verify_foreign_keys_for_fixtures = true RUBY app "development" assert_equal true, ActiveRecord.verify_foreign_keys_for_fixtures end test "ActiveSupport::MessageEncryptor.use_authenticated_message_encryption is true by default for new apps" do app "development" assert_equal true, ActiveSupport::MessageEncryptor.use_authenticated_message_encryption end test "ActiveSupport::MessageEncryptor.use_authenticated_message_encryption is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, ActiveSupport::MessageEncryptor.use_authenticated_message_encryption end test "ActiveSupport::MessageEncryptor.use_authenticated_message_encryption can be configured via config.active_support.use_authenticated_message_encryption" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY Rails.application.config.active_support.use_authenticated_message_encryption = true RUBY app "development" assert_equal true, ActiveSupport::MessageEncryptor.use_authenticated_message_encryption end test "ActiveSupport::Digest.hash_digest_class is OpenSSL::Digest::SHA256 by default for new apps" do app "development" assert_equal OpenSSL::Digest::SHA256, ActiveSupport::Digest.hash_digest_class end test "ActiveSupport::Digest.hash_digest_class is OpenSSL::Digest::MD5 by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal OpenSSL::Digest::MD5, ActiveSupport::Digest.hash_digest_class end test "ActiveSupport::Digest.hash_digest_class can be configured via config.active_support.hash_digest_class" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/custom_digest_class.rb", <<-RUBY Rails.application.config.active_support.hash_digest_class = OpenSSL::Digest::SHA256 RUBY app "development" assert_equal OpenSSL::Digest::SHA256, ActiveSupport::Digest.hash_digest_class end test "ActiveSupport::KeyGenerator.hash_digest_class is OpenSSL::Digest::SHA256 by default for new apps" do app "development" assert_equal OpenSSL::Digest::SHA256, ActiveSupport::KeyGenerator.hash_digest_class end test "ActiveSupport::KeyGenerator.hash_digest_class is OpenSSL::Digest::SHA1 by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal OpenSSL::Digest::SHA1, ActiveSupport::KeyGenerator.hash_digest_class end test "ActiveSupport::KeyGenerator.hash_digest_class can be configured via config.active_support.key_generator_hash_digest_class" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/custom_key_generator_digest_class.rb", <<-RUBY Rails.application.config.active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA256 RUBY app "development" assert_equal OpenSSL::Digest::SHA256, ActiveSupport::KeyGenerator.hash_digest_class end test "ActiveSupport.test_parallelization_threshold can be configured via config.active_support.test_parallelization_threshold" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/environments/test.rb", <<-RUBY Rails.application.configure do config.active_support.test_parallelization_threshold = 1234 end RUBY app "test" assert_equal 1234, ActiveSupport.test_parallelization_threshold end test "Digest::UUID.use_rfc4122_namespaced_uuids is enabled by default for new apps" do app "development" assert_equal true, Digest::UUID.use_rfc4122_namespaced_uuids end test "Digest::UUID.use_rfc4122_namespaced_uuids is disabled by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, Digest::UUID.use_rfc4122_namespaced_uuids end test "custom serializers should be able to set via config.active_job.custom_serializers in an initializer" do class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end app_file "config/initializers/custom_serializers.rb", <<-RUBY Rails.application.config.active_job.custom_serializers << DummySerializer RUBY app "development" assert_includes ActiveJob::Serializers.serializers, DummySerializer end test "active record job queue is set" do app "development" assert_equal ActiveSupport::InheritableOptions.new(destroy: :active_record_destroy), ActiveRecord.queues end test "destroy association async job should be loaded in configs" do app "development" assert_equal ActiveRecord::DestroyAssociationAsyncJob, ActiveRecord::Base.destroy_association_async_job end test "ActiveRecord::Base.destroy_association_async_job can be configured via config.active_record.destroy_association_job" do class ::DummyDestroyAssociationAsyncJob; end app_file "config/environments/test.rb", <<-RUBY Rails.application.configure do config.active_record.destroy_association_async_job = DummyDestroyAssociationAsyncJob end RUBY app "test" assert_equal DummyDestroyAssociationAsyncJob, ActiveRecord::Base.destroy_association_async_job end test "destroy association async batch size is nil by default" do app "development" assert_nil ActiveRecord::Base.destroy_association_async_batch_size end test "destroy association async batch size can be set in configs" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.active_record.destroy_association_async_batch_size = 100 end RUBY app "development" assert_equal 100, ActiveRecord::Base.destroy_association_async_batch_size end test "ActionView::Helpers::FormTagHelper.default_enforce_utf8 is false by default" do app "development" assert_equal false, ActionView::Helpers::FormTagHelper.default_enforce_utf8 end test "ActionView::Helpers::FormTagHelper.default_enforce_utf8 is true in an upgraded app" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "5.2"' app "development" assert_equal true, ActionView::Helpers::FormTagHelper.default_enforce_utf8 end test "ActionView::Helpers::FormTagHelper.default_enforce_utf8 can be configured via config.action_view.default_enforce_utf8" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY Rails.application.config.action_view.default_enforce_utf8 = true RUBY app "development" assert_equal true, ActionView::Helpers::FormTagHelper.default_enforce_utf8 end test "ActionView::Helpers::UrlHelper.button_to_generates_button_tag is true by default" do app "development" assert_equal true, ActionView::Helpers::UrlHelper.button_to_generates_button_tag end test "ActionView::Helpers::UrlHelper.button_to_generates_button_tag is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal false, ActionView::Helpers::UrlHelper.button_to_generates_button_tag end test "ActionView::Helpers::UrlHelper.button_to_generates_button_tag can be configured via config.action_view.button_to_generates_button_tag" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.action_view.button_to_generates_button_tag = true RUBY app "development" assert_equal true, ActionView::Helpers::UrlHelper.button_to_generates_button_tag end test "ActionView::Helpers::AssetTagHelper.image_loading is nil by default" do app "development" assert_nil ActionView::Helpers::AssetTagHelper.image_loading end test "ActionView::Helpers::AssetTagHelper.image_loading can be configured via config.action_view.image_loading" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.action_view.image_loading = "lazy" end RUBY app "development" assert_equal "lazy", ActionView::Helpers::AssetTagHelper.image_loading end test "ActionView::Helpers::AssetTagHelper.image_decoding is nil by default" do app "development" assert_nil ActionView::Helpers::AssetTagHelper.image_decoding end test "ActionView::Helpers::AssetTagHelper.image_decoding can be configured via config.action_view.image_decoding" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.action_view.image_decoding = "async" end RUBY app "development" assert_equal "async", ActionView::Helpers::AssetTagHelper.image_decoding end test "ActionView::Helpers::AssetTagHelper.preload_links_header is true by default" do app "development" assert_equal true, ActionView::Helpers::AssetTagHelper.preload_links_header end test "ActionView::Helpers::AssetTagHelper.preload_links_header is nil by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_nil ActionView::Helpers::AssetTagHelper.preload_links_header end test "ActionView::Helpers::AssetTagHelper.preload_links_header can be configured via config.action_view.preload_links_header" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.action_view.preload_links_header = false end RUBY app "development" assert_equal false, ActionView::Helpers::AssetTagHelper.preload_links_header end test "ActionView::Helpers::AssetTagHelper.apply_stylesheet_media_default is true by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal true, ActionView::Helpers::AssetTagHelper.apply_stylesheet_media_default end test "ActionView::Helpers::AssetTagHelper.apply_stylesheet_media_default can be configured via config.action_view.apply_stylesheet_media_default" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.action_view.apply_stylesheet_media_default = false RUBY app "development" assert_equal false, ActionView::Helpers::AssetTagHelper.apply_stylesheet_media_default end test "stylesheet_link_tag sets the Link header by default" do app_file "app/controllers/pages_controller.rb", <<-RUBY class PagesController < ApplicationController def index render inline: "<%= stylesheet_link_tag '/application.css' %>" end end RUBY add_to_config <<-RUBY routes.prepend do root to: "pages#index" end RUBY app "development" get "/" assert_match %r[<link rel="stylesheet" href="/application.css" />], last_response.body assert_equal "</application.css>; rel=preload; as=style; nopush", last_response.headers["Link"] end test "stylesheet_link_tag doesn't set the Link header when disabled" do app_file "config/initializers/action_view.rb", <<-RUBY Rails.application.config.action_view.preload_links_header = false RUBY app_file "app/controllers/pages_controller.rb", <<-RUBY class PagesController < ApplicationController def index render inline: "<%= stylesheet_link_tag '/application.css' %>" end end RUBY add_to_config <<-RUBY routes.prepend do root to: "pages#index" end RUBY app "development" get "/" assert_match %r[<link rel="stylesheet" href="/application.css" />], last_response.body assert_nil last_response.headers["Link"] end test "javascript_include_tag sets the Link header by default" do app_file "app/controllers/pages_controller.rb", <<-RUBY class PagesController < ApplicationController def index render inline: "<%= javascript_include_tag '/application.js' %>" end end RUBY add_to_config <<-RUBY routes.prepend do root to: "pages#index" end RUBY app "development" get "/" assert_match %r[<script src="/application.js"></script>], last_response.body assert_equal "</application.js>; rel=preload; as=script; nopush", last_response.headers["Link"] end test "javascript_include_tag doesn't set the Link header when disabled" do app_file "config/initializers/action_view.rb", <<-RUBY Rails.application.config.action_view.preload_links_header = false RUBY app_file "app/controllers/pages_controller.rb", <<-RUBY class PagesController < ApplicationController def index render inline: "<%= javascript_include_tag '/application.js' %>" end end RUBY add_to_config <<-RUBY routes.prepend do root to: "pages#index" end RUBY app "development" get "/" assert_match %r[<script src="/application.js"></script>], last_response.body assert_nil last_response.headers["Link"] end test "ActiveJob::Base.retry_jitter is 0.15 by default for new apps" do app "development" assert_equal 0.15, ActiveJob::Base.retry_jitter end test "ActiveJob::Base.retry_jitter is 0.0 by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal 0.0, ActiveJob::Base.retry_jitter end test "ActiveJob::Base.retry_jitter can be set by config" do app "development" Rails.application.config.active_job.retry_jitter = 0.22 assert_equal 0.22, ActiveJob::Base.retry_jitter end test "Rails.application.config.action_dispatch.cookies_same_site_protection is :lax by default" do app "production" assert_equal :lax, Rails.application.config.action_dispatch.cookies_same_site_protection end test "Rails.application.config.action_dispatch.cookies_same_site_protection is :lax can be overridden" do app_file "config/environments/production.rb", <<~RUBY Rails.application.configure do config.action_dispatch.cookies_same_site_protection = :strict end RUBY app "production" assert_equal :strict, Rails.application.config.action_dispatch.cookies_same_site_protection end test "Rails.application.config.action_dispatch.cookies_same_site_protection is :lax in 6.1 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal :lax, Rails.application.config.action_dispatch.cookies_same_site_protection end test "Rails.application.config.action_dispatch.ssl_default_redirect_status is 308 in 6.1 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "production" assert_equal 308, Rails.application.config.action_dispatch.ssl_default_redirect_status end test "Rails.application.config.action_dispatch.ssl_default_redirect_status can be configured in an initializer" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app_file "config/initializers/new_framework_defaults_6_1.rb", <<-RUBY Rails.application.config.action_dispatch.ssl_default_redirect_status = 308 RUBY app "production" assert_equal 308, Rails.application.config.action_dispatch.ssl_default_redirect_status end test "Rails.application.config.action_mailer.smtp_settings have open_timeout and read_timeout defined as 5 in 7.0 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config <<-RUBY config.action_mailer.smtp_settings = { domain: "example.com" } config.load_defaults "7.0" RUBY app "development" smtp_settings = { domain: "example.com", open_timeout: 5, read_timeout: 5 } assert_equal smtp_settings, ActionMailer::Base.smtp_settings assert_equal smtp_settings, Rails.configuration.action_mailer.smtp_settings end test "Rails.application.config.action_mailer.smtp_settings does not have open_timeout and read_timeout configured on other versions" do remove_from_config '.*config\.load_defaults.*\n' add_to_config <<-RUBY config.action_mailer.smtp_settings = { domain: "example.com" } RUBY app "development" smtp_settings = { domain: "example.com" } assert_equal smtp_settings, ActionMailer::Base.smtp_settings end test "Rails.application.config.action_mailer.smtp_settings = nil fallback to ActionMailer::Base.smtp_settings" do remove_from_config '.*config\.load_defaults.*\n' add_to_config <<-RUBY ActionMailer::Base.smtp_settings = { domain: "example.com" } config.load_defaults "7.0" RUBY app "development" smtp_settings = { domain: "example.com", open_timeout: 5, read_timeout: 5 } assert_equal smtp_settings, ActionMailer::Base.smtp_settings assert_nil Rails.configuration.action_mailer.smtp_settings end test "Rails.application.config.action_mailer.smtp_settings = nil and ActionMailer::Base.smtp_settings = nil do not configure smtp_timeout" do ActionMailer::Base.smtp_settings = nil remove_from_config '.*config\.load_defaults.*\n' add_to_config <<-RUBY config.action_mailer.smtp_settings = nil config.load_defaults "7.0" RUBY app "development" assert_nil Rails.configuration.action_mailer.smtp_settings assert_nil ActionMailer::Base.smtp_settings end test "ActiveSupport.utc_to_local_returns_utc_offset_times is true in 6.1 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal true, ActiveSupport.utc_to_local_returns_utc_offset_times end test "ActiveSupport.utc_to_local_returns_utc_offset_times is false in 6.0 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_equal false, ActiveSupport.utc_to_local_returns_utc_offset_times end test "ActiveSupport.utc_to_local_returns_utc_offset_times can be configured in an initializer" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app_file "config/initializers/new_framework_defaults_6_1.rb", <<-RUBY ActiveSupport.utc_to_local_returns_utc_offset_times = true RUBY app "development" assert_equal true, ActiveSupport.utc_to_local_returns_utc_offset_times end test "ActiveStorage.queues[:analysis] is :active_storage_analysis by default in 6.0" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_equal :active_storage_analysis, ActiveStorage.queues[:analysis] end test "ActiveStorage.queues[:analysis] is nil by default in 6.1" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_nil ActiveStorage.queues[:analysis] end test "ActiveStorage.queues[:analysis] is nil without Rails 6 defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_nil ActiveStorage.queues[:analysis] end test "ActiveStorage.queues[:purge] is :active_storage_purge by default in 6.0" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_equal :active_storage_purge, ActiveStorage.queues[:purge] end test "ActiveStorage.queues[:purge] is nil by default in 6.1" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_nil ActiveStorage.queues[:purge] end test "ActiveStorage.queues[:purge] is nil without Rails 6 defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_nil ActiveStorage.queues[:purge] end test "ActiveStorage.queues[:mirror] is nil without Rails 6 defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_nil ActiveStorage.queues[:mirror] end test "ActiveStorage.queues[:mirror] is nil by default" do app "development" assert_nil ActiveStorage.queues[:mirror] end test "ActionCable.server.config.cable is set when missing configuration for the current environment" do quietly do app "missing" end assert_kind_of ActiveSupport::HashWithIndifferentAccess, ActionCable.server.config.cable end test "action_text.config.attachment_tag_name is 'action-text-attachment' with Rails 6 defaults" do add_to_config 'config.load_defaults "6.1"' app "development" assert_equal "action-text-attachment", ActionText::Attachment.tag_name end test "action_text.config.attachment_tag_name is 'action-text-attachment' without defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal "action-text-attachment", ActionText::Attachment.tag_name end test "action_text.config.attachment_tag_name is can be overridden" do add_to_config "config.action_text.attachment_tag_name = 'link'" app "development" assert_equal "link", ActionText::Attachment.tag_name end test "ActionMailbox.logger is Rails.logger by default" do app "development" assert_equal Rails.logger, ActionMailbox.logger end test "ActionMailbox.logger can be configured" do app_file "lib/my_logger.rb", <<-RUBY require "logger" class MyLogger < ::Logger end RUBY add_to_config <<-RUBY require "my_logger" config.action_mailbox.logger = MyLogger.new(STDOUT) RUBY app "development" assert_equal "MyLogger", ActionMailbox.logger.class.name end test "ActionMailbox.incinerate_after is 30.days by default" do app "development" assert_equal 30.days, ActionMailbox.incinerate_after end test "ActionMailbox.incinerate_after can be configured" do add_to_config <<-RUBY config.action_mailbox.incinerate_after = 14.days RUBY app "development" assert_equal 14.days, ActionMailbox.incinerate_after end test "ActionMailbox.queues[:incineration] is :action_mailbox_incineration by default in 6.0" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_equal :action_mailbox_incineration, ActionMailbox.queues[:incineration] end test "ActionMailbox.queues[:incineration] is nil by default in 6.1" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_nil ActionMailbox.queues[:incineration] end test "ActionMailbox.queues[:incineration] can be configured" do add_to_config <<-RUBY config.action_mailbox.queues.incineration = :another_queue RUBY app "development" assert_equal :another_queue, ActionMailbox.queues[:incineration] end test "ActionMailbox.queues[:routing] is :action_mailbox_routing by default in 6.0" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.0"' app "development" assert_equal :action_mailbox_routing, ActionMailbox.queues[:routing] end test "ActionMailbox.queues[:routing] is nil by default in 6.1" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_nil ActionMailbox.queues[:routing] end test "ActionMailbox.queues[:routing] can be configured" do add_to_config <<-RUBY config.action_mailbox.queues.routing = :another_queue RUBY app "development" assert_equal :another_queue, ActionMailbox.queues[:routing] end test "ActionMailbox.storage_service is nil by default (default service)" do app "development" assert_nil(ActionMailbox.storage_service) end test "ActionMailbox.storage_service can be configured" do add_to_config <<-RUBY config.active_storage.service_configurations = { email: { root: "#{Dir.tmpdir}/email", service: "Disk" } } config.action_mailbox.storage_service = :email RUBY app "development" assert_equal(:email, ActionMailbox.storage_service) end test "ActionMailer::Base.delivery_job is ActionMailer::MailDeliveryJob by default" do app "development" assert_equal ActionMailer::MailDeliveryJob, ActionMailer::Base.delivery_job end test "ActiveRecord::Base.filter_attributes should equal to filter_parameters" do app_file "config/initializers/filter_parameters_logging.rb", <<-RUBY Rails.application.config.filter_parameters += [ :password, :credit_card_number ] RUBY app "development" assert_equal [ :password, :credit_card_number ], Rails.application.config.filter_parameters assert_equal [ :password, :credit_card_number ], ActiveRecord::Base.filter_attributes end test "ActiveStorage.routes_prefix can be configured via config.active_storage.routes_prefix" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.active_storage.routes_prefix = '/files' end RUBY output = rails("routes", "-g", "active_storage") assert_equal <<~MESSAGE, output Prefix Verb URI Pattern Controller#Action rails_service_blob GET /files/blobs/redirect/:signed_id/*filename(.:format) active_storage/blobs/redirect#show rails_service_blob_proxy GET /files/blobs/proxy/:signed_id/*filename(.:format) active_storage/blobs/proxy#show GET /files/blobs/:signed_id/*filename(.:format) active_storage/blobs/redirect#show rails_blob_representation GET /files/representations/redirect/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/redirect#show rails_blob_representation_proxy GET /files/representations/proxy/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/proxy#show GET /files/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations/redirect#show rails_disk_service GET /files/disk/:encoded_key/*filename(.:format) active_storage/disk#show update_rails_disk_service PUT /files/disk/:encoded_token(.:format) active_storage/disk#update rails_direct_uploads POST /files/direct_uploads(.:format) active_storage/direct_uploads#create MESSAGE end test "ActiveStorage.draw_routes can be configured via config.active_storage.draw_routes" do app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.active_storage.draw_routes = false end RUBY output = rails("routes") assert_not_includes(output, "rails_service_blob") assert_not_includes(output, "rails_blob_representation") assert_not_includes(output, "rails_disk_service") assert_not_includes(output, "update_rails_disk_service") assert_not_includes(output, "rails_direct_uploads") end test "ActiveStorage.video_preview_arguments uses the old arguments without Rails 7 defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal ActiveStorage.video_preview_arguments, "-y -vframes 1 -f image2" end test "ActiveStorage.video_preview_arguments uses the new arguments by default" do app "development" assert_equal ActiveStorage.video_preview_arguments, "-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1'" \ " -frames:v 1 -f image2" end test "ActiveStorage.variant_processor uses mini_magick without Rails 7 defaults" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal :mini_magick, ActiveStorage.variant_processor end test "ActiveStorage.variant_processor uses vips by default" do app "development" assert_equal :vips, ActiveStorage.variant_processor end test "ActiveStorage.supported_image_processing_methods can be configured via config.active_storage.supported_image_processing_methods" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/add_image_processing_methods.rb", <<-RUBY Rails.application.config.active_storage.supported_image_processing_methods = ["write", "set"] RUBY app "development" assert ActiveStorage.supported_image_processing_methods.include?("write") assert ActiveStorage.supported_image_processing_methods.include?("set") end test "ActiveStorage.unsupported_image_processing_arguments can be configured via config.active_storage.unsupported_image_processing_arguments" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/add_image_processing_arguments.rb", <<-RUBY Rails.application.config.active_storage.unsupported_image_processing_arguments = %w( -write -danger ) RUBY app "development" assert ActiveStorage.unsupported_image_processing_arguments.include?("-danger") assert_not ActiveStorage.unsupported_image_processing_arguments.include?("-set") end test "hosts include .localhost in development" do app "development" assert_includes Rails.application.config.hosts, ".localhost" end test "hosts reads multiple values from RAILS_DEVELOPMENT_HOSTS" do host = "agoodhost.com" another_host = "bananapants.com" switch_development_hosts_to(host, another_host) do app "development" assert_includes Rails.application.config.hosts, host assert_includes Rails.application.config.hosts, another_host end end test "hosts reads multiple values from RAILS_DEVELOPMENT_HOSTS and trims white space" do host = "agoodhost.com" host_with_white_space = " #{host} " another_host = "bananapants.com" another_host_with_white_space = " #{another_host}" switch_development_hosts_to(host_with_white_space, another_host_with_white_space) do app "development" assert_includes Rails.application.config.hosts, host assert_includes Rails.application.config.hosts, another_host end end test "hosts reads from RAILS_DEVELOPMENT_HOSTS" do host = "agoodhost.com" switch_development_hosts_to(host) do app "development" assert_includes Rails.application.config.hosts, host end end test "hosts does not read from RAILS_DEVELOPMENT_HOSTS in production" do host = "agoodhost.com" switch_development_hosts_to(host) do app "production" assert_not_includes Rails.application.config.hosts, host end end test "disable_sandbox is false by default" do app "development" assert_equal false, Rails.configuration.disable_sandbox end test "disable_sandbox can be overridden" do add_to_config <<-RUBY config.disable_sandbox = true RUBY app "development" assert Rails.configuration.disable_sandbox end test "rake_eager_load is false by default" do app "development" assert_equal false, Rails.application.config.rake_eager_load end test "rake_eager_load is set correctly" do add_to_config <<-RUBY config.root = "#{app_path}" config.rake_eager_load = true RUBY app "development" assert_equal true, Rails.application.config.rake_eager_load end test "ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization is true by default" do app "development" assert_equal true, ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization end test "ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization is true by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal true, ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization end test "ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization can be configured via config.active_support.fallback_to_marshal_deserialization" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/fallback_to_marshal_deserialization.rb", <<-RUBY Rails.application.config.active_support.fallback_to_marshal_deserialization = false RUBY app "development" assert_equal false, ActiveSupport::JsonWithMarshalFallback.fallback_to_marshal_deserialization end test "ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization is true by default" do app "development" assert_equal true, ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization end test "ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization is true by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal true, ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization end test "ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization can be configured via config.active_support.use_marshal_serialization" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/use_marshal_serialization.rb", <<-RUBY Rails.application.config.active_support.use_marshal_serialization = false RUBY app "development" assert_equal false, ActiveSupport::JsonWithMarshalFallback.use_marshal_serialization end test "ActiveSupport::MessageEncryptor.default_message_encryptor_serializer is :json by default" do app "development" assert_equal :json, ActiveSupport::MessageEncryptor.default_message_encryptor_serializer end test "ActiveSupport::MessageEncryptor.default_message_encryptor_serializer is :marshal by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal :marshal, ActiveSupport::MessageEncryptor.default_message_encryptor_serializer end test "ActiveSupport::MessageEncryptor.default_message_encryptor_serializer can be configured via config.active_support.default_message_encryptor_serializer" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/default_message_encryptor_serializer.rb", <<-RUBY Rails.application.config.active_support.default_message_encryptor_serializer = :hybrid RUBY app "development" assert_equal :hybrid, ActiveSupport::MessageEncryptor.default_message_encryptor_serializer end test "ActiveSupport::MessageVerifier.default_message_verifier_serializer is :json by default for new apps" do app "development" assert_equal :json, ActiveSupport::MessageVerifier.default_message_verifier_serializer end test "ActiveSupport::MessageVerifier.default_message_verifier_serializer is :marshal by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal :marshal, ActiveSupport::MessageVerifier.default_message_verifier_serializer end test "ActiveSupport::MessageVerifier.default_message_verifier_serializer can be configured via config.active_support.default_message_verifier_serializer" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/default_message_verifier_serializer.rb", <<-RUBY Rails.application.config.active_support.default_message_verifier_serializer = :hybrid RUBY app "development" assert_equal :hybrid, ActiveSupport::MessageVerifier.default_message_verifier_serializer end test "unknown_asset_fallback is false by default" do app "development" assert_equal false, Rails.application.config.assets.unknown_asset_fallback end test "ActionDispatch::Request.return_only_media_type_on_content_type is false by default" do app "development" assert_equal false, ActionDispatch::Request.return_only_media_type_on_content_type end test "ActionDispatch::Request.return_only_media_type_on_content_type is true in the 6.1 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "development" assert_equal true, ActionDispatch::Request.return_only_media_type_on_content_type end test "ActionDispatch::Request.return_only_media_type_on_content_type can be configured in the new framework defaults" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.action_dispatch.return_only_request_media_type_on_content_type = false RUBY app "development" assert_equal false, ActionDispatch::Request.return_only_media_type_on_content_type end test "action_dispatch.log_rescued_responses is true by default" do app "development" assert_equal true, Rails.application.env_config["action_dispatch.log_rescued_responses"] end test "action_dispatch.log_rescued_responses can be configured" do add_to_config <<-RUBY config.action_dispatch.log_rescued_responses = false RUBY app "development" assert_equal false, Rails.application.env_config["action_dispatch.log_rescued_responses"] end test "logs a warning when running SQLite3 in production" do restore_sqlite3_warning app_file "config/initializers/active_record.rb", <<~RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") RUBY add_to_config "config.logger = MyLogRecorder.new" app "production" assert_match(/You are running SQLite in production, this is generally not recommended/, Rails.logger.recording) end test "doesn't log a warning when running SQLite3 in production and sqlite3_production_warning=false" do app_file "config/initializers/active_record.rb", <<~RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") RUBY add_to_config "config.logger = MyLogRecorder.new" app "production" assert_no_match(/You are running SQLite in production, this is generally not recommended/, Rails.logger.recording) end test "doesn't log a warning when running MySQL in production" do restore_sqlite3_warning original_configurations = ActiveRecord::Base.configurations ActiveRecord::Base.configurations = { production: { db1: { adapter: "mysql2" } } } app_file "config/initializers/active_record.rb", <<~RUBY ActiveRecord::Base.establish_connection(adapter: "mysql2") RUBY add_to_config "config.logger = MyLogRecorder.new" app "production" assert_no_match(/You are running SQLite in production, this is generally not recommended/, Rails.logger.recording) ensure ActiveRecord::Base.configurations = original_configurations end test "doesn't log a warning when running SQLite3 in development" do restore_sqlite3_warning app_file "config/initializers/active_record.rb", <<~RUBY ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") RUBY add_to_config "config.logger = MyLogRecorder.new" app "development" assert_no_match(/You are running SQLite in production, this is generally not recommended/, Rails.logger.recording) end test "app starts with LocalCache middleware" do app "development" assert(Rails.application.config.middleware.map(&:name).include?("ActiveSupport::Cache::Strategy::LocalCache")) local_cache_index = Rails.application.config.middleware.map(&:name).index("ActiveSupport::Cache::Strategy::LocalCache") logger_index = Rails.application.config.middleware.map(&:name).index("Rails::Rack::Logger") assert local_cache_index < logger_index end test "LocalCache middleware can be moved via app config" do # you can't move Rails.cache.middleware as it doesn't exist yet add_to_config "config.middleware.move_after(Rails::Rack::Logger, ActiveSupport::Cache::Strategy::LocalCache)" app "development" local_cache_index = Rails.application.config.middleware.map(&:name).index("ActiveSupport::Cache::Strategy::LocalCache") logger_index = Rails.application.config.middleware.map(&:name).index("Rails::Rack::Logger") assert local_cache_index > logger_index end test "LocalCache middleware can be moved via initializer" do app_file "config/initializers/move_local_cache_middleware.rb", <<~RUBY Rails.application.config.middleware.move_after(Rails::Rack::Logger, Rails.cache.middleware) RUBY app "development" local_cache_index = Rails.application.config.middleware.map(&:name).index("ActiveSupport::Cache::Strategy::LocalCache") logger_index = Rails.application.config.middleware.map(&:name).index("Rails::Rack::Logger") assert local_cache_index > logger_index end test "LocalCache middleware can be removed via app config" do # you can't delete Rails.cache.middleware as it doesn't exist yet add_to_config "config.middleware.delete(ActiveSupport::Cache::Strategy::LocalCache)" app "development" assert_not(Rails.application.config.middleware.map(&:name).include?("ActiveSupport::Cache::Strategy::LocalCache")) end test "LocalCache middleware can be removed via initializer" do app_file "config/initializers/remove_local_cache_middleware.rb", <<~RUBY Rails.application.config.middleware.delete(Rails.cache.middleware) RUBY app "development" assert_not(Rails.application.config.middleware.map(&:name).include?("ActiveSupport::Cache::Strategy::LocalCache")) end test "custom middleware with overridden names can be added, moved, or deleted" do app_file "config/initializers/add_custom_middleware.rb", <<~RUBY class CustomMiddlewareOne def self.name "1st custom middleware" end def initialize(app, *args); end def new(app); self; end end class CustomMiddlewareTwo def initialize(app, *args); end def new(app); self; end end class CustomMiddlewareThree def self.name "3rd custom middleware" end def initialize(app, *args); end def new(app); self; end end Rails.application.config.middleware.use(CustomMiddlewareOne) Rails.application.config.middleware.use(CustomMiddlewareTwo) Rails.application.config.middleware.use(CustomMiddlewareThree) Rails.application.config.middleware.move_after(CustomMiddlewareTwo, CustomMiddlewareOne) Rails.application.config.middleware.delete(CustomMiddlewareThree) RUBY app "development" custom_middleware_one = Rails.application.config.middleware.map(&:name).index("1st custom middleware") custom_middleware_two = Rails.application.config.middleware.map(&:name).index("CustomMiddlewareTwo") assert custom_middleware_one > custom_middleware_two assert_nil Rails.application.config.middleware.map(&:name).index("3rd custom middleware") end test "ActiveSupport::TimeWithZone.name uses default Ruby implementation by default" do app "development" assert_equal false, ActiveSupport::TimeWithZone.methods(false).include?(:name) end test "ActiveSupport::TimeWithZone.name can be configured in the new framework defaults" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.active_support.remove_deprecated_time_with_zone_name = false RUBY app "development" assert_equal true, ActiveSupport::TimeWithZone.methods(false).include?(:name) end test "can entirely opt out of ActiveSupport::Deprecations" do add_to_config "config.active_support.report_deprecations = false" app "production" assert_equal true, ActiveSupport::Deprecation.silenced assert_equal [ActiveSupport::Deprecation::DEFAULT_BEHAVIORS[:silence]], ActiveSupport::Deprecation.behavior assert_equal [ActiveSupport::Deprecation::DEFAULT_BEHAVIORS[:silence]], ActiveSupport::Deprecation.disallowed_behavior end test "ParamsWrapper is enabled in a new app and uses JSON as the format" do app "production" assert_equal [:json], ActionController::Base._wrapper_options.format end test "ParamsWrapper is enabled in an upgrade and uses JSON as the format" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY Rails.application.config.action_controller.wrap_parameters_by_default = true RUBY app "production" assert_equal [:json], ActionController::Base._wrapper_options.format end test "ParamsWrapper can be changed from the default in the initializer that was created prior to Rails 7" do app_file "config/initializers/wrap_parameters.rb", <<-RUBY ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:xml] end RUBY app "production" assert_equal [:xml], ActionController::Base._wrapper_options.format end test "ParamsWrapper can be turned off" do add_to_config "Rails.application.config.action_controller.wrap_parameters_by_default = false" app "production" assert_equal [], ActionController::Base._wrapper_options.format end test "deprecated #to_s with format works with the Rails 6.1 defaults" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' app "production" assert_deprecated do assert_equal "21 Feb", Date.new(2005, 2, 21).to_s(:short) end assert_deprecated do assert_equal "2005-02-21 14:30:00", DateTime.new(2005, 2, 21, 14, 30, 0, 0).to_s(:db) end assert_deprecated do assert_equal "555-1234", 5551234.to_s(:phone) end assert_deprecated do assert_equal "BETWEEN 'a' AND 'z'", ("a".."z").to_s(:db) end assert_deprecated do assert_equal "2005-02-21 17:44:30", Time.utc(2005, 2, 21, 17, 44, 30.12345678901).to_s(:db) end end test "deprecated #to_s with format does not work with the Rails 6.1 defaults and the config set" do remove_from_config '.*config\.load_defaults.*\n' add_to_config 'config.load_defaults "6.1"' add_to_config <<-RUBY config.active_support.disable_to_s_conversion = true RUBY app "production" assert_raises(ArgumentError) do Date.new(2005, 2, 21).to_s(:short) end assert_raises(ArgumentError) do DateTime.new(2005, 2, 21, 14, 30, 0, 0).to_s(:db) end assert_raises(TypeError) do 5551234.to_s(:phone) end assert_raises(ArgumentError) do ("a".."z").to_s(:db) end assert_raises(ArgumentError) do Time.utc(2005, 2, 21, 17, 44, 30.12345678901).to_s(:db) end end test "deprecated #to_s with format does not work with the Rails 7.0 defaults" do app "production" assert_raises(ArgumentError) do Date.new(2005, 2, 21).to_s(:short) end assert_raises(ArgumentError) do DateTime.new(2005, 2, 21, 14, 30, 0, 0).to_s(:db) end assert_raises(TypeError) do 5551234.to_s(:phone) end assert_raises(ArgumentError) do ("a".."z").to_s(:db) end assert_raises(ArgumentError) do Time.utc(2005, 2, 21, 17, 44, 30.12345678901).to_s(:db) end end test "ActionController::Base.raise_on_missing_callback_actions is false by default for production" do app "production" assert_equal false, ActionController::Base.raise_on_missing_callback_actions end test "ActionController::Base.raise_on_missing_callback_actions is false by default for upgraded apps" do remove_from_config '.*config\.load_defaults.*\n' app "development" assert_equal false, ActionController::Base.raise_on_missing_callback_actions end test "ActionController::Base.raise_on_missing_callback_actions can be configured in the new framework defaults" do remove_from_config '.*config\.load_defaults.*\n' app_file "config/initializers/new_framework_defaults_6_2.rb", <<-RUBY Rails.application.config.action_controller.raise_on_missing_callback_actions = true RUBY app "production" assert_equal true, ActionController::Base.raise_on_missing_callback_actions end private def set_custom_config(contents, config_source = "custom".inspect) app_file "config/custom.yml", contents add_to_config <<~RUBY config.my_custom_config = config_for(#{config_source}) RUBY end end end
32.278383
170
0.695558