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
e930d78cc613ca865ef70610d174daa83d717f8c
882
# frozen_string_literal: true # Container for Vox components. module Vox # Default ETF adapter for vox's gateway component. module ETF # @!parse [ruby] # # Encode an object to an ETF term. This method accepts, `Integer`, `Float`, # # `String`, `Symbol`, `Hash`, `Array`, `nil`, `true`, and `false` objects. # # It also allows any object that responds to `#to_hash => Hash`. # # @param input [Object, #to_hash] The object to be encoded as an ETF term. # # @return [String] The ETF term encoded as a packed string. # def self.encode(input) # end # @!parse [ruby] # # Decode an ETF term from a string. # # @param input [String] The ETF term to be decoded. # # @return [Object] The ETF term decoded to an object. # def self.decode(input) # end # Gem version VERSION = '0.1.9' end end
32.666667
83
0.608844
d5466b287a55d10fd7221af882addc9083d24cfa
368
# Preview all emails at http://localhost:3000/rails/mailers/contact class ContactPreview < ActionMailer::Preview def automatic_answer_preview ContactMailer.automatic_answer(Contact.first) end def manual_answer(contact, answer, subject_answer, admin) ContactMailer.manual_answer(Contact.first, 'Body Test', 'Subject Test', Admin.first) end end
28.307692
88
0.771739
f8ee4c8ff07c5d01f9219db3aa5d9bd2930042cb
3,398
# Static Loader contains constants, basic data types and other types required for the system # to boot. # module Puppet::Pops module Loader class StaticLoader < Loader BUILTIN_TYPE_NAMES = %w{ Component Exec File Filebucket Group Node Notify Package Resources Schedule Service Stage Tidy User Whit }.freeze BUILTIN_TYPE_NAMES_LC = Set.new(BUILTIN_TYPE_NAMES.map { |n| n.downcase }).freeze BUILTIN_ALIASES = { 'Data' => 'Variant[ScalarData,Undef,Hash[String,Data],Array[Data]]', 'RichDataKey' => 'Variant[String,Numeric]', 'RichData' => 'Variant[Scalar,SemVerRange,Binary,Sensitive,Type,TypeSet,URI,Object,Undef,Default,Hash[RichDataKey,RichData],Array[RichData]]', # Backward compatible aliases. 'Puppet::LookupKey' => 'RichDataKey', 'Puppet::LookupValue' => 'RichData' }.freeze attr_reader :loaded def initialize @loaded = {} @runtime_3_initialized = false create_built_in_types end def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY) # Static loader only contains runtime types return EMPTY_ARRAY unless type == :type && name_authority == name_authority = Pcore::RUNTIME_NAME_AUTHORITY #rubocop:disable Lint/AssignmentInCondition typed_names = type == :type && name_authority == Pcore::RUNTIME_NAME_AUTHORITY ? @loaded.keys : EMPTY_ARRAY block_given? ? typed_names.select { |tn| yield(tn) } : typed_names end def load_typed(typed_name) load_constant(typed_name) end def get_entry(typed_name) load_constant(typed_name) end def set_entry(typed_name, value, origin = nil) @loaded[typed_name] = Loader::NamedEntry.new(typed_name, value, origin) end def find(name) # There is nothing to search for, everything this loader knows about is already available nil end def parent nil # at top of the hierarchy end def to_s() "(StaticLoader)" end def loaded_entry(typed_name, check_dependencies = false) @loaded[typed_name] end def runtime_3_init unless @runtime_3_initialized @runtime_3_initialized = true create_resource_type_references end nil end def register_aliases aliases = BUILTIN_ALIASES.map { |name, string| add_type(name, Types::PTypeAliasType.new(name, Types::TypeFactory.type_reference(string), nil)) } aliases.each { |type| type.resolve(self) } end private def load_constant(typed_name) @loaded[typed_name] end def create_built_in_types origin_uri = URI("puppet:Puppet-Type-System/Static-Loader") type_map = Puppet::Pops::Types::TypeParser.type_map type_map.each do |name, type| set_entry(TypedName.new(:type, name), type, origin_uri) end end def create_resource_type_references() # These needs to be done quickly and we do not want to scan the file system for these # We are also not interested in their definition only that they exist. # These types are in all environments. # BUILTIN_TYPE_NAMES.each { |name| create_resource_type_reference(name) } end def add_type(name, type) set_entry(TypedName.new(:type, name), type) type end def create_resource_type_reference(name) add_type(name, Types::TypeFactory.resource(name)) end def synchronize(&block) yield end end end end
25.742424
155
0.704532
e829b1e432a55acca1107d93bcefa53eda1274ed
2,777
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' require 'rex' require 'msf/core/post/windows/railgun' $:.push "test/lib" unless $:.include? "test/lib" require 'module_test' class Metasploit3 < Msf::Post include Msf::ModuleTest::PostTest include Msf::Post::Windows::Railgun def initialize(info={}) super( update_info( info, 'Name' => 'railgun_testing', 'Description' => %q{ This module will test railgun code used in post modules}, 'License' => MSF_LICENSE, 'Author' => [ 'kernelsmith'], 'Platform' => [ 'windows' ] )) register_options( [ OptInt.new("ERR_CODE", [ false, "Error code to reverse lookup" ]), OptInt.new("WIN_CONST", [ false, "Windows constant to reverse lookup" ]), OptRegexp.new("WCREGEX", [ false, "Regexp to apply to constant rev lookup" ]), OptRegexp.new("ECREGEX", [ false, "Regexp to apply to error code lookup" ]), ], self.class) end def test_static it "should return a constant name given a const and a filter" do ret = true results = select_const_names(4, /^SERVICE/) ret &&= !!(results.kind_of? Array) # All of the returned values should match the filter and have the same value results.each { |const| ret &&= !!(const =~ /^SERVICE/) ret &&= !!(session.railgun.constant_manager.parse(const) == 4) } # Should include things that match the filter and the value ret &&= !!(results.include? "SERVICE_RUNNING") # Should NOT include things that match the value but not the filter ret &&= !!(not results.include? "CLONE_FLAG_ENTITY") ret end it "should return an error string given an error code" do ret = true results = lookup_error(0x420, /^ERROR_SERVICE/) ret &&= !!(results.kind_of? Array) ret &&= !!(results.length == 1) ret end end def test_datastore if (datastore["WIN_CONST"]) it "should look up arbitrary constants" do ret = true results = select_const_names(datastore['WIN_CONST'], datastore['WCREGEX']) #vprint_status("RESULTS: #{results.class} #{results.pretty_inspect}") ret end end if (datastore["ERR_CODE"]) it "should look up arbitrary error codes" do ret = true results = lookup_error(datastore['ERR_CODE'], datastore['ECREGEX']) #vprint_status("RESULTS: #{results.class} #{results.inspect}") ret end end end end
28.336735
88
0.624415
1adce33f851796597ddc0b54b513fa04644f2b71
1,903
# # Be sure to run `pod lib lint Verifiedly.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'Verifiedly' s.version = '1.0.0' s.summary = 'Identity verification and fraud prevention for fast growing startups' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = 'Verifiedly allows companies to embed identity verification and fraud prevention products in their applications' s.homepage = 'https://github.com/Samuelail/Verifiedly' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Samuel Ailemen' => '[email protected]' } s.source = { :git => 'https://github.com/Samuelail/Verifiedly.git', :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/verfiedly' s.ios.deployment_target = '10.0' s.swift_versions = ['4.0'] s.source_files = 'Resources/*.swift' s.resources = 'Resources/**/*.{png,storyboard,json}' #s.resource_bundles = { # 'Verifiedly' => ['Verifiedly/Resources/*/**'] #} # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'ActiveLabel' s.dependency 'Alamofire' s.dependency 'SwiftyJSON' s.dependency 'RappleProgressHUD' s.dependency 'SwiftMessages' s.dependency 'SwiftPublicIP' s.dependency 'lottie-ios' end
38.836735
135
0.676301
1ae1b487bfbf6a4f48d41dfcc13a75533fb3b1b0
306
cask 'dd-utility' do version '1.11' sha256 '1c33a998b7c9b7a9fa59222d2e7cc0410f0cec85650e8647308c33ee0af1e956' url "https://github.com/thefanclub/dd-utility/raw/master/DMG/ddUtility-#{version}.dmg" name 'dd Utility' homepage 'https://github.com/thefanclub/dd-utility' app 'dd Utility.app' end
27.818182
88
0.764706
8724b4a778a072de34ba215c4648da05ef7a4b26
1,023
require 'simp/cli/config/items/action/warn_client_yum_config_action' require_relative '../spec_helper' describe Simp::Cli::Config::Item::WarnClientYumConfigAction do before :each do @ci = Simp::Cli::Config::Item::WarnClientYumConfigAction.new @ci.silent = true # uncomment out this line to see log message end describe "#apply" do it "sets applied_status to deferred" do @ci.apply expect( @ci.applied_status ).to eq :deferred expected_summary =<<EOM Checking YUM configuration for SIMP clients deferred: Your SIMP client YUM configuration requires manual verification EOM expect( @ci.apply_summary ).to eq expected_summary.strip end end describe "#apply_summary" do it 'reports unattempted status when #apply not called' do expect(@ci.apply_summary).to eq( 'Checking YUM configuration for SIMP clients unattempted') end end it_behaves_like "an Item that doesn't output YAML" it_behaves_like 'a child of Simp::Cli::Config::Item' end
31.96875
71
0.72825
03f811d25347d8f01be6700021721fb713ac9d66
1,471
# # Cookbook Name:: iptables-ng # Recipe:: install # # Copyright 2013, Chris Aumann # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # include_recipe 'iptables-ng::manage' # Make sure iptables is installed Array(node['iptables-ng']['packages']).each { |pkg| package pkg } # Make sure ufw is not installed on Ubuntu/Debian, as it might interfere package 'ufw' do action :remove only_if { node['platform_family'] == 'debian' } end # Create directories directory '/etc/iptables.d' do mode 00700 end node['iptables-ng']['rules'].each do |table, chains| directory "/etc/iptables.d/#{table}" do mode 00700 end # Create default policies unless they exist chains.each do |chain, policy| iptables_ng_chain "default-policy-#{table}-#{chain}" do chain chain table table policy policy['default'] action :create_if_missing end end end
28.288462
72
0.721958
181a2d37ae4d49c4a095aa8c05da4f8112e712f6
308
module Types class OpinionType < Types::BaseObject field :id, ID, null: false field :text, String, null: true field :author_id, Integer, null: true field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :updated_at, GraphQL::Types::ISO8601DateTime, null: false end end
30.8
67
0.714286
ac02239a14f8e9a7c4315852050a114bd8bf0aca
6,863
module Kontena # The observable value is nil when initialized, and Observers will wait for it to become ready. # Once the observable is first updated, then Observers will return/yield the initial value. # When the observable is later updated, Observers will return/yield the updated value. # If the observable already has a value, then observing that value will return/yield the immediate value. # If the observable crashes, then any Observers will immediately raise. # # TODO: are you allowed to reset an observable after crashing it, allowing observers to restart and re-observe? # # @attr observers [Hash{Kontena::Observer => Boolean}] stored value is the persistent? flag class Observable require_relative './observable/registry' # @return [Celluloid::Proxy::Cell<Kontena::Observable::Registry>] system registry actor def self.registry Celluloid::Actor[:observable_registry] || fail(Celluloid::DeadActorError, "Observable registry actor not running") end include Kontena::Logging attr_reader :logging_prefix # customize Kontena::Logging#logging_prefix by instance class Message attr_reader :observer, :observable, :value # @param observer [Kontena::Observer] # @param observable [Kontena::Observable] # @param value [Object, nil, Exception] def initialize(observer, observable, value) @observer = observer @observable = observable @value = value end end # mixin for Celluloid actor classes module Helper # Create a new Observable using the including class name as the subject. # Register the Observable with the Kontena::Observable::Registry. # Links to the registry to crash the Observable if the owning actor crashes. # # @return [Kontena::Observable] def observable return @observable if @observable # the register can suspend this task, so other calls might get the observable before it gets registered # shouldn't be a problem, unless the register/linking somehow fails and crashes this actor without crashing the # observable? @observable = Kontena::Observable.new(self.class.name) observable_registry = Kontena::Observable.registry observable_registry.register(@observable, self.current_actor) self.links << observable_registry # registry monitors owner @observable end end # @param subject [Object] used to identify the Observable for logging purposes def initialize(subject = nil) @subject = subject @mutex = Thread::Mutex.new @observers = {} @value = nil # include the subject (owning actor class, other resource) in log messages @logging_prefix = "#{self}" end # @return [String] def to_s "#{self.class.name}<#{@subject}>" end # @return [Object, nil] last updated value, or nil if not ready? def get @value end # Observable has updated, and has not reset. It might be crashed? # # @return [Boolean] def ready? !!@value end # Observable has an exception set. # # Calls to `add_observer` will raise. # def crashed? Exception === @value end # Observable has observers. # # NOTE: dead observers will only get cleaned out on the next update # # @return [Boolean] def observed? [email protected]? end # The Observable has a value. Propagate it to any observers. # # This will notify any Observers, causing them to yield/return if ready. # # The value must be immutable and threadsafe: it must remain valid for use by other threads # both after this update, and after any other future updates. Do not send a mutable object # that gets invalidated in between updates. # # TODO: automatically freeze the value? # # @param value [Object] # @raise [RuntimeError] Observable crashed # @raise [ArgumentError] Update with nil value def update(value) raise RuntimeError, "Observable crashed: #{@value}" if crashed? raise ArgumentError, "Update with nil value" if value.nil? debug { "update: #{value}" } set_and_notify(value) end # Reset the observable value back into the initialized state. # This will notify any Observers, causing them to wait until we update again. # def reset debug { "reset" } set_and_notify(nil) end # @param reason [Exception] def crash(reason) raise ArgumentError, "Crash with non-exception: #{reason.class.name}" unless Exception === reason debug { "crash: #{reason}" } set_and_notify(reason) end # Observer is observing this Observable's value. # Raises if observable has crashed. # Returns current value, or nil if not yet ready. # Subscribes observer for updates if persistent, or if not yet ready (returning nil). # # The observer will be dropped once no longer alive?. # # @param observer [Kontena::Observer] # @param persistent [Boolean] false => either return immediate value, or return nil and subscribe for a single notification # @raise [Exception] # @return [Object, nil] current value if ready def add_observer(observer, persistent: true) @mutex.synchronize do if !@value # subscribe for future udpates, no value to return @observers[observer] = persistent elsif Exception === @value # raise with immediate value, no future updates to subscribe to raise @value elsif persistent # return with immediate value, also subscribe for future updates @observers[observer] = persistent else # return with immediate value, do not subscribe for future updates end return @value end end # Send Message with given value to each Kontena::Observer that is still alive. # Future calls to `add_observer` will also return the same value. # Drops any observers that are dead or non-persistent. # # TODO: automatically clean out all observers when the observable crashes? # # @param value [Object, nil, Exception] def set_and_notify(value) @mutex.synchronize do @value = value @observers.each do |observer, persistent| if !observer.alive? debug { "dead: #{observer}" } @observers.delete(observer) elsif !persistent debug { "notify and drop: #{observer} <- #{value}" } observer << Message.new(observer, self, value) @observers.delete(observer) else debug { "notify: #{observer} <- #{value}" } observer << Message.new(observer, self, value) end end end end end end
32.372642
127
0.658458
08dccf7030ba78b5f4cd523068e8de88dc5bffe4
6,936
=begin #Xero Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.3.1 =end require 'time' require 'date' module WorkflowMaxRuby::Accounting require 'bigdecimal' class InvoiceReminders attr_accessor :invoice_reminders # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'invoice_reminders' => :'InvoiceReminders' } end # Attribute type mapping. def self.openapi_types { :'invoice_reminders' => :'Array<InvoiceReminder>' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `WorkflowMaxRuby::Accounting::InvoiceReminders` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `WorkflowMaxRuby::Accounting::InvoiceReminders`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'invoice_reminders') if (value = attributes[:'invoice_reminders']).is_a?(Array) self.invoice_reminders = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && invoice_reminders == o.invoice_reminders end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [invoice_reminders].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(parse_date(value)) when :Date Date.parse(parse_date(value)) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BigDecimal BigDecimal(value.to_s) when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model WorkflowMaxRuby::Accounting.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash(downcase: false) hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? key = downcase ? attr : param hash[key] = _to_hash(value, downcase: downcase) end hash end # Returns the object in the form of hash with snake_case def to_attributes to_hash(downcase: true) end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value, downcase: false) if value.is_a?(Array) value.map do |v| v.to_hash(downcase: downcase) end elsif value.is_a?(Hash) {}.tap do |hash| value.map { |k, v| hash[k] = _to_hash(v, downcase: downcase) } end elsif value.respond_to? :to_hash value.to_hash(downcase: downcase) else value end end def parse_date(datestring) if datestring.include?('Date') date_pattern = /\/Date\((-?\d+)(\+\d+)?\)\// original, date, timezone = *date_pattern.match(datestring) date = (date.to_i / 1000) Time.at(date).utc.strftime('%Y-%m-%dT%H:%M:%S%z').to_s else # handle date 'types' for small subset of payroll API's Time.parse(datestring).strftime('%Y-%m-%dT%H:%M:%S').to_s end end end end
31.103139
223
0.632209
5d7d06c84903db173ea00ad3945f1f4a758d5b54
540
module RunnersHelper def runner_status_icon(runner) unless runner.contacted_at return content_tag :i, nil, class: "fa fa-warning-sign", title: "New runner. Has not connected yet" end status = if runner.active? runner.contacted_at > 3.hour.ago ? :online : :offline else :paused end content_tag :i, nil, class: "fa fa-circle runner-status-#{status}", title: "Runner is #{status}, last contact was #{time_ago_in_words(runner.contacted_at)} ago" end end
25.714286
98
0.635185
2867fa6725c1b97a7c016eb39476817f0fca1e24
623
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'evt-dependency' s.version = '2.1.0.0' s.summary = 'Declare dependencies that have null object or substitute default values' s.description = ' ' s.authors = ['The Eventide Project'] s.email = '[email protected]' s.homepage = 'https://github.com/eventide-project/dependency' s.licenses = ['MIT'] s.require_paths = ['lib'] s.files = Dir.glob('{lib}/**/*') s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.3.3' s.add_runtime_dependency 'evt-subst_attr' s.add_development_dependency 'test_bench' end
28.318182
87
0.680578
628c11f11bbe9f78c27a0621341e6c0ffb6ace0c
1,373
class Pygments < Formula include Language::Python::Virtualenv desc "Generic syntax highlighter" homepage "https://pygments.org/" url "https://files.pythonhosted.org/packages/e1/86/8059180e8217299079d8719c6e23d674aadaba0b1939e25e0cc15dcf075b/Pygments-2.7.4.tar.gz" sha256 "df49d09b498e83c1a73128295860250b0b7edd4c723a32e9bc0d295c7c2ec337" license "BSD-2-Clause" head "https://github.com/pygments/pygments.git" livecheck do url :stable end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "a03ce270d1a5bc2b1b0b59b07939f041a433873fb89c3cb48df1d89ef9df8443" sha256 cellar: :any_skip_relocation, big_sur: "ba143cb212e8a0e5065d46784c113d120b620dfc03bf01de940aea49c024b18f" sha256 cellar: :any_skip_relocation, catalina: "9725becf19d65286936b2a260b4c9da4edc17240d7f91b896993393b227f08fd" sha256 cellar: :any_skip_relocation, mojave: "60e2749b874ba3bf69c7034d2ecbe00b340f2eae14a5ca5c9362e3f1ea1695ab" end depends_on "[email protected]" def install bash_completion.install "external/pygments.bashcomp" => "pygmentize" virtualenv_install_with_resources end test do (testpath/"test.py").write <<~EOS import os print(os.getcwd()) EOS system bin/"pygmentize", "-f", "html", "-o", "test.html", testpath/"test.py" assert_predicate testpath/"test.html", :exist? end end
35.205128
136
0.766934
1c9603a5cb7a85e69290f19e3389cd125781453f
2,620
class Song attr_accessor :url def self.find(id) self.new(id: id).tap { |song| song.document } end def initialize(kwargs = {}) @id = kwargs.delete(:id) @artist = kwargs.delete(:artist) @title = kwargs.delete(:title) self.url = "songs/#{@id}" end def response document["response"]["song"] end def artist @artist ||= Artist.new( name: response["primary_artist"]["name"], id: response["primary_artist"]["id"], type: :primary ) end def featured_artists @featured_artists ||= response["featured_artists"].map do |artist| Artist.new( name: artist["name"], id: artist["id"], type: :featured ) end end def url response["url"] end def producer_artists @producer_artists ||= response["producer_artists"].map do |artist| Artist.new( name: artist["name"], id: artist["id"], type: :producer ) end end def artists [artist] + featured_artists + producer_artists end def title @title ||= response["title"] end def description @description ||= document["response"]["song"]["description"]["plain"] end def images @images ||= keys_with_images.map do |key| node = response[key] if node.is_a? Array node.map { |subnode| subnode["image_url"] } elsif node.is_a? Hash node["image_url"] else return end end.flatten end def pyongs response["pyongs_count"] end def hot? response["stats"]["hot"] end def views response["stats"]["pageviews"] end def concurrent_viewers response["stats"]["concurrents"] end def media response["media"].map do |m| Media.new(type: m["type"], provider: m["provider"], url: m["url"]) end end def lines @lines ||= response["lyrics"]["dom"]["children"].map do |node| parse_lines(node) end.flatten.compact end private def parse_lines(node) if node.is_a?(Array) node.map { |subnode| parse_lines(subnode) } elsif node.is_a?(String) Line.new( song: Song.new(id: @id), lyric: node ) elsif node.is_a?(Hash) && node["tag"] == "p" parse_lines(node["children"]) elsif node.is_a?(Hash) && node["tag"] == "a" Line.new( song: Song.new(id: @id), lyric: node["children"].select {|l| l.is_a? String }.join("\n"), id: node["data"]["id"] ) else return end end def keys_with_images %w{featured_artists producer_artists primary_artist} end end
20
74
0.575954
2124c723186d01eaa19f240d6860313a01300ca0
768
provides :varnish_repo, platform_family: 'debian' property :major_version, Float, equal_to: [2.1, 3.0, 4.0, 4.1, 5, 6.0], default: lazy { node['varnish']['major_version'] } property :fetch_gpg_key, [TrueClass, FalseClass], default: true action :configure do # packagecloud repos omit dot from major version major_version_no_dot = new_resource.major_version.to_s.tr('.', '') apt_repository "varnish-cache_#{new_resource.major_version}" do uri "https://packagecloud.io/varnishcache/varnish#{major_version_no_dot}/#{node['platform']}/" distribution node['lsb']['codename'] components ['main'] key "https://packagecloud.io/varnishcache/varnish#{major_version_no_dot}/gpgkey" if new_resource.fetch_gpg_key deb_src true action :add end end
42.666667
122
0.739583
3933d7d0ea717ce263aad8b85f8ba7725bac4e38
3,526
class Admin::StatisticsAnnouncementsController < Admin::BaseController before_action :find_statistics_announcement, only: %i[show edit update cancel publish_cancellation cancel_reason] before_action :redirect_to_show_if_cancelled, only: %i[cancel publish_cancellation] helper_method :unlinked_announcements_count, :show_unlinked_announcements_warning? def index @filter = Admin::StatisticsAnnouncementFilter.new(filter_params) @statistics_announcements = @filter.statistics_announcements end def show @edition_taxons = EditionTaxonsFetcher.new(@statistics_announcement.content_id).fetch end def new @statistics_announcement = build_statistics_announcement(organisation_ids: [current_user.organisation.try(:id)]) @statistics_announcement.build_current_release_date(precision: StatisticsAnnouncementDate::PRECISION[:two_month]) end def create @statistics_announcement = build_statistics_announcement(statistics_announcement_params) if @statistics_announcement.save redirect_to [:admin, @statistics_announcement], notice: "Announcement published successfully" else render :new end end def edit; end def update @statistics_announcement.attributes = statistics_announcement_params if @statistics_announcement.save redirect_to [:admin, @statistics_announcement], notice: "Announcement updated successfully" else render :edit end end def cancel; end def publish_cancellation if @statistics_announcement.cancel!(params[:statistics_announcement][:cancellation_reason], current_user) redirect_to [:admin, @statistics_announcement], notice: "Announcement has been cancelled" else render :cancel end end private def find_statistics_announcement @statistics_announcement = StatisticsAnnouncement.friendly.find(params[:id]) end def redirect_to_show_if_cancelled redirect_to [:admin, @statistics_announcement] if @statistics_announcement.cancelled? end def build_statistics_announcement(attributes = {}) if attributes[:current_release_date_attributes] attributes[:current_release_date_attributes][:creator_id] = current_user.id end current_user.statistics_announcements.new(attributes) end def statistics_announcement_params params .require(:statistics_announcement) .permit( :title, :summary, :publication_type_id, :publication_id, :cancellation_reason, organisation_ids: [], topic_ids: [], current_release_date_attributes: %i[id release_date precision confirmed] ) end def filter_params params.permit!.to_h .slice(:title, :page, :per_page, :organisation_id, :dates, :unlinked_only) .reverse_merge(filter_defaults) end def filter_defaults { organisation_id: current_user.organisation.try(:id), dates: "future", user_id: current_user.id, } end def show_unlinked_announcements_warning? !filtering_imminent_unlinked_announcements? && unlinked_announcements_count.positive? end def filtering_imminent_unlinked_announcements? @filter.options[:dates] == "imminent" && @filter.options[:unlinked_only] == "1" end def unlinked_announcements_count unlinked_announcements_filter.statistics_announcements.total_count end def unlinked_announcements_filter @unlinked_announcements_filter ||= Admin::StatisticsAnnouncementFilter.new(dates: "imminent", unlinked_only: "1", organisation_id: filter_params[:organisation_id]) end end
32.348624
167
0.77198
08f89868f555a12111e710ed3ab3b6a62a5fc539
194
describe OrderRepositoryMemory do let(:repo) { described_class.new } it '.save' do order = instance_double('Order') repo.save(order) expect(repo.orders.size).to eq(1) end end
19.4
37
0.685567
79cae906eef3948b9c1cad007b18f038417bb065
1,793
#-- # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others. # All rights reserved. # See LICENSE.txt for permissions. #++ class Gem::Ext::Builder def self.class_name name =~ /Ext::(.*)Builder/ $1.downcase end def self.make(dest_path, results) unless File.exist? 'Makefile' then raise Gem::InstallError, "Makefile not found:\n\n#{results.join "\n"}" end # try to find make program from Ruby configure arguments first RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/ make_program = $1 || ENV['MAKE'] || ENV['make'] unless make_program then make_program = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make' end destdir = '"DESTDIR=%s"' % ENV['DESTDIR'] if RUBY_VERSION > '2.0' ['', 'install'].each do |target| # Pass DESTDIR via command line to override what's in MAKEFLAGS cmd = [ make_program, destdir, target ].join(' ').rstrip run(cmd, results, "make #{target}".rstrip) end end def self.redirector '2>&1' end def self.run(command, results, command_name = nil) verbose = Gem.configuration.really_verbose begin # TODO use Process.spawn when ruby 1.8 support is dropped. rubygems_gemdeps, ENV['RUBYGEMS_GEMDEPS'] = ENV['RUBYGEMS_GEMDEPS'], nil if verbose puts(command) system(command) else results << command results << `#{command} #{redirector}` end ensure ENV['RUBYGEMS_GEMDEPS'] = rubygems_gemdeps end unless $?.success? then results << "Building has failed. See above output for more information on the failure." if verbose raise Gem::InstallError, "#{command_name || class_name} failed:\n\n#{results.join "\n"}" end end end
26.367647
104
0.62744
e25f3c3898e4b3f2373bdb8c49cf7b12fcdf39fb
340
gem 'paper_trail', '~> 2' after_bundler do generate "paper_trail:install" end __END__ name: Paper Trail description: Plugin for tracking changes to your models' data. Good for auditing or versioning. category: persistence exclusive: activerecord_versioning tags: [activerecord_versioning] # TODO eycloud partner version of same name
20
95
0.797059
911df921b0af48f315cbd5a2199794e8172b5863
4,449
require 'rails_helper' # require './app/models/parsers/xml/reports/policy_link_type' module Parsers::Xml::Reports describe PolicyLinkType do let(:namespace) { 'http://openhbx.org/api/terms/1.0' } let(:policy_xml) { "<n1:policy xmlns:n1=\"#{namespace}\">\"#{policy_id}#{enrollees}#{employer}\"</n1:policy>" } let(:policy_id) { "<n1:id>http://localhost:3000/api/v1/policies/8461</n1:id>" } let(:enrollees) { "<n1:enrollees><n1:enrollee>\"#{benefit}\"</n1:enrollee></n1:enrollees>" } let(:benefit) { "<n1:benefit>\"#{begin_date}#{end_date}\"</n1:benefit>" } let(:begin_date) { "<n1:begin_date>20140301</n1:begin_date>" } let(:end_date) { "<n1:end_date>20141212</n1:end_date>"} let(:employer) { "<n1:employer></n1:employer>" } it 'should parse policy id' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.id).to eq 'http://localhost:3000/api/v1/policies/8461' end context '#individual_market' do context 'when employer not present' do let(:employer) { nil } it 'should return true' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.individual_market?).to eq true end end context 'when employer present' do it 'should return false' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.individual_market?).to eq false end end end context '#begin_date' do context 'when not present' do let(:begin_date) { nil } it 'should return nil' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.begin_date).to eq nil end end context 'when present' do it 'should return date' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.begin_date).to eq Date.strptime('20140301', '%Y%m%d') end end end context '#end_date' do context 'when not present' do let(:end_date) { nil } it 'should return nil' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.end_date).to eq nil end end context 'when present' do it 'should return date' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.end_date).to eq Date.strptime('20141212', '%Y%m%d') end end end context '#state' do context 'when begin date and end dates are same' do let(:end_date) { "<n1:end_date>20140301</n1:end_date>" } it 'should return inactive' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.state).to eq 'inactive' end end context 'when begin date is after renewal year start date' do let(:begin_date) { "<n1:begin_date>20150101</n1:begin_date>" } it 'should return inactive' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.state).to eq 'inactive' end end context 'when begin date is before renewal year start date and' do context 'end date not present' do let(:end_date) { nil } it 'should return active' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.state).to eq 'active' end end context 'end date is after renewal year start date' do let(:end_date) { "<n1:end_date>20150101</n1:end_date>" } it 'should return true' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.state).to eq 'active' end end context 'end date is before renewal year start date' do it 'should return false' do policy = Nokogiri::XML(policy_xml) subject = PolicyLinkType.new(policy.root) expect(subject.state).to eq 'inactive' end end end end end end
34.757813
115
0.598337
87dfd43a14d8e9a0cbaa847fb607e60d27a937c4
1,251
require 'pry' class TasksController < ApplicationController get '/tasks' do @tasks = Task.all erb :"/tasks/index" end get '/tasks/new' do @categories = Category.all erb :'/tasks/new' end post '/tasks/new' do if params[:name] == "" || params[:summary] == "" redirect '/tasks/new' else @task = Task.create(name: params[:name], summary: params[:summary], category_ids: params[:category_ids]) if !params["categories"]["name"].empty? @task.categories << Category.new(name: params["categories"]["name"]) end redirect "/tasks/#{@task.id}" end end get '/tasks/:id' do @task = Task.find(params[:id]) erb :'/tasks/show' end get '/tasks/:id/edit' do @task = Task.find(params[:id]) erb :'/tasks/edit' end patch '/tasks/:id/' do @task = Task.find(params[:id]) @task.update(name: params[:name], summary: params[:summary], category_ids: params[:category_ids]) if !params["categories"]["name"].empty? @task.categories << Category.new(name: params["categories"]["name"]) end redirect "/tasks/#{@task.id}" end get '/tasks/:id/delete' do @task = Task.find(params[:id]) @task.delete redirect '/tasks' end end
23.166667
110
0.601119
26b3b43ff321f5d26c2ae7c1b451b14bee04630a
2,082
# -*- encoding: utf-8 -*- require 'spec_helper' describe "Humanize" do require_relative 'tests' after(:each) do Humanize.reset_config end TESTS.each do |num, human| it "#{num} is #{human}" do expect(num.humanize).to eql(human) end end describe 'locale option' do it 'uses default locale' do Humanize.config.default_locale = :fr expect(42.humanize).to eql('quarante-deux') end it 'uses locale passed as argument if given' do Humanize.config.default_locale = :en expect(42.humanize(:locale => :fr)).to eql('quarante-deux') end describe 'french specific rules' do it 'one thousand and two equals "mille deux"' do expect(1002.humanize(:locale => :fr)).to eql('mille deux') end it 'two thousand and one equals "deux mille un"' do expect(2001.humanize(:locale => :fr)).to eql('deux mille un') end it 'ten thousand equals "dix mille"' do expect(10000.humanize(:locale => :fr)).to eql('dix mille') end end describe 'turkish specific rules' do it 'one thousand and two equals "bin iki"' do expect(1002.humanize(:locale => :tr)).to eql('bin iki') end it 'two thousand and one equals "iki bin bir' do expect(2001.humanize(:locale => :tr)).to eql('iki bin bir') end it 'ten thousand equals "on bin"' do expect(10000.humanize(:locale => :tr)).to eql('on bin') end end end describe 'decimals_as option' do it 'uses value from configuration' do Humanize.config.decimals_as = :number expect(0.42.humanize).to eql('zero point forty-two') end it 'uses value passed as argument if given' do Humanize.config.decimals_as = :number expect(0.42.humanize(:decimals_as => :digits)).to eql('zero point four two') end end describe 'both options work together' do it 'work together' do expect( 0.42.humanize(:locale => :fr, :decimals_as => :number) ).to eql('zéro virgule quarante-deux') end end end
23.393258
82
0.621998
e8f073a1e596287bd59a1fc63890c69c110feec4
1,085
class Lxc < Formula desc "CLI client for interacting with LXD" homepage "https://linuxcontainers.org" url "https://linuxcontainers.org/downloads/lxd/lxd-4.8.tar.gz" sha256 "de4f096c71448ceb358c0d0d63e34d17ea8e49c15eb9d4f8af5030ce0535337f" license "Apache-2.0" livecheck do url "https://linuxcontainers.org/lxd/downloads/" regex(/href=.*?lxd[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do cellar :any_skip_relocation sha256 "8675b214d8d8dba0cea05084104952fce09f25ef43e0a3b1759d2b736823cda5" => :catalina sha256 "9a8303d460b15e9fd4c95ff980df5485efa2011fc96170f50fbf851c3158b3da" => :mojave sha256 "ebd08abe30cd9d0e27cad7b494b0b850c552f98770d7bf4181f7093fb09926d5" => :high_sierra sha256 "930ed9be5cb11a462af8e4d75adb6574fca1618c8402d1fddb7dc1c4e48416e6" => :x86_64_linux end depends_on "go" => :build def install ENV["GOPATH"] = buildpath ENV["GOBIN"] = bin ln_s buildpath/"_dist/src", buildpath/"src" system "go", "install", "-v", "github.com/lxc/lxd/lxc" end test do system "#{bin}/lxc", "--version" end end
31
94
0.730876
f79ea288b4270fc7fa7790398df4994aad58868a
1,159
# -*- coding: utf-8 -*- # usage: ruby checkfix#.rb [file] # ------------------- # Author:: Jean-Michel Bruel (mailto:[email protected]) # Copyright:: Copyright (c) 2020 JMB # License:: Distributes under the same terms as Ruby # ------------------- README = ARGV[0] ? ARGV[0] : "../README.adoc" fixNb = __FILE__.scan(/\d+/) File.open(README) { |f| result = true content = f.read lastName = content.scan(/\{lastName\}:: (\w+)/) firstName = content.scan(/\{firstName\}:: ([\w|\-]+)/) groupNb = content.scan(/\- \[[x|X]\] ([\w|\{|\}]+)/) print "----------------------------------\n" print "Looking for fix #" + fixNb[0] + " rules...\n" # Checking Name if (lastName[0][0] == "BRUEL") && (firstName[0][0] == "Jean-Michel") result = false else print "SUCCESS: Last Name = " + lastName[0][0] + "\n" print "SUCCESS: First Name = " + firstName[0][0] + "\n" end # Checking Group if groupNb[0][0] != "{Enseignants}" print "SUCCESS: Group = " + groupNb[0][0] + "\n" else result = false end if !result print "/!\\FAILURE: Your info need to be updated in " + README + "\n" exit 1 end exit 0 }
26.340909
75
0.529767
0883f9d2445f2faad2c71744a50212c04e51123a
132
# frozen_string_literal: true Rails.application.routes.draw do devise_for :users resources :players root 'players#index' end
16.5
32
0.780303
2854120f1d5994a00b97f382bc7cdab46b6be1c5
516
h_shirts = ['Brad','Joe','Tristan','Tom', 'Matt', 'Jim', 'David', 'Myron'] normal_shirts = ['Dylan', 'Sonju', 'Kate', 'Isaac', 'Chris', 'Eric'] h_shirts.pop normal_shirts.pop h_shirts.push('James') normal_shirts.push('Angie') h_shirts.each do |i| puts i end normal_shirts.each do |i| puts i end class Hawaiian(shirt,color,name) def initialize @shirt = shirt @color = color @name = name end def to_s(person) puts person.to_s end end person = Hawaiian.new('true', 'red', 'Brad')
16.645161
74
0.643411
bf008262573915febb1303cd2957f2f5ea9aa148
98,008
require 'spec_helper' module VCAP::CloudController RSpec.describe VCAP::CloudController::AppsController do let(:admin_user) { User.make } let(:non_admin_user) { User.make } let(:app_event_repository) { Repositories::AppEventRepository.new } before do set_current_user(non_admin_user) CloudController::DependencyLocator.instance.register(:app_event_repository, app_event_repository) end describe 'Query Parameters' do it { expect(VCAP::CloudController::AppsController).to be_queryable_by(:name) } it { expect(VCAP::CloudController::AppsController).to be_queryable_by(:space_guid) } it { expect(VCAP::CloudController::AppsController).to be_queryable_by(:organization_guid) } it { expect(VCAP::CloudController::AppsController).to be_queryable_by(:diego) } it { expect(VCAP::CloudController::AppsController).to be_queryable_by(:stack_guid) } end describe 'query by org_guid' do let(:process) { ProcessModelFactory.make } it 'filters apps by org_guid' do set_current_user_as_admin get "/v2/apps?q=organization_guid:#{process.organization.guid}" expect(last_response.status).to eq(200) expect(decoded_response['resources'][0]['entity']['name']).to eq(process.name) end end describe 'querying by stack guid' do let(:stack1) { Stack.make } let(:stack2) { Stack.make } let(:process1) { ProcessModel.make } let(:process2) { ProcessModel.make } before do process1.app.lifecycle_data.update(stack: stack1.name) process2.app.lifecycle_data.update(stack: stack2.name) end it 'filters apps by stack guid' do set_current_user_as_admin get "/v2/apps?q=stack_guid:#{stack1.guid}" expect(last_response.status).to eq(200) expect(decoded_response['resources'].length).to eq(1) expect(decoded_response['resources'][0]['entity']['name']).to eq(process1.name) end end describe 'Attributes' do it do expect(VCAP::CloudController::AppsController).to have_creatable_attributes( { enable_ssh: { type: 'bool' }, buildpack: { type: 'string' }, command: { type: 'string' }, console: { type: 'bool', default: false }, debug: { type: 'string' }, disk_quota: { type: 'integer' }, environment_json: { type: 'hash', default: {} }, health_check_http_endpoint: { type: 'string' }, health_check_timeout: { type: 'integer' }, health_check_type: { type: 'string', default: 'port' }, instances: { type: 'integer', default: 1 }, memory: { type: 'integer' }, name: { type: 'string', required: true }, production: { type: 'bool', default: false }, state: { type: 'string', default: 'STOPPED' }, space_guid: { type: 'string', required: true }, stack_guid: { type: 'string' }, diego: { type: 'bool' }, docker_image: { type: 'string', required: false }, docker_credentials: { type: 'hash', default: {} }, ports: { type: '[integer]', default: nil } }) end it do expect(VCAP::CloudController::AppsController).to have_updatable_attributes( { enable_ssh: { type: 'bool' }, buildpack: { type: 'string' }, command: { type: 'string' }, console: { type: 'bool' }, debug: { type: 'string' }, disk_quota: { type: 'integer' }, environment_json: { type: 'hash' }, health_check_http_endpoint: { type: 'string' }, health_check_timeout: { type: 'integer' }, health_check_type: { type: 'string' }, instances: { type: 'integer' }, memory: { type: 'integer' }, name: { type: 'string' }, production: { type: 'bool' }, state: { type: 'string' }, space_guid: { type: 'string' }, stack_guid: { type: 'string' }, diego: { type: 'bool' }, docker_image: { type: 'string' }, docker_credentials: { type: 'hash' }, ports: { type: '[integer]' } }) end end describe 'Associations' do it do expect(VCAP::CloudController::AppsController).to have_nested_routes( { events: [:get, :put, :delete], service_bindings: [:get], routes: [:get], route_mappings: [:get], }) end describe 'events associations (via AppEvents)' do before { set_current_user_as_admin } it 'does not return events with inline-relations-depth=0' do process = ProcessModel.make get "/v2/apps/#{process.app.guid}?inline-relations-depth=0" expect(entity).to have_key('events_url') expect(entity).to_not have_key('events') end it 'does not return events with inline-relations-depth=1 since app_events dataset is relatively expensive to query' do process = ProcessModel.make get "/v2/apps/#{process.app.guid}?inline-relations-depth=1" expect(entity).to have_key('events_url') expect(entity).to_not have_key('events') end end end describe 'create app' do let(:space) { Space.make } let(:space_guid) { space.guid.to_s } let(:initial_hash) do { name: 'maria', space_guid: space_guid } end let(:decoded_response) { MultiJson.load(last_response.body) } let(:user_audit_info) { UserAuditInfo.from_context(SecurityContext) } describe 'events' do before do allow(UserAuditInfo).to receive(:from_context).and_return(user_audit_info) end it 'records app create' do set_current_user(admin_user, admin: true) expected_attrs = AppsController::CreateMessage.decode(initial_hash.to_json).extract(stringify_keys: true) allow(app_event_repository).to receive(:record_app_create).and_call_original post '/v2/apps', MultiJson.dump(initial_hash) process = ProcessModel.last expect(app_event_repository).to have_received(:record_app_create).with(process, process.space, user_audit_info, expected_attrs) end end context 'when the org is suspended' do before do space.organization.update(status: 'suspended') end it 'does not allow user to create new app (spot check)' do post '/v2/apps', MultiJson.dump(initial_hash) expect(last_response.status).to eq(403) end end context 'when allow_ssh is enabled globally' do before do TestConfig.override(allow_app_ssh_access: true) end context 'when allow_ssh is enabled on the space' do before do space.allow_ssh = true space.save end it 'allows enable_ssh to be set to true' do set_current_user_as_admin post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: true)) expect(last_response.status).to eq(201) end it 'allows enable_ssh to be set to false' do set_current_user_as_admin post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: false)) expect(last_response.status).to eq(201) end end context 'when allow_ssh is disabled on the space' do before do space.allow_ssh = false space.save end it 'allows enable_ssh to be set to false' do set_current_user_as_admin post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: false)) expect(last_response.status).to eq(201) end context 'and the user is an admin' do it 'allows enable_ssh to be set to true' do set_current_user_as_admin post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: true)) expect(last_response.status).to eq(201) end end context 'and the user is not an admin' do it 'errors when attempting to set enable_ssh to true' do set_current_user(non_admin_user) post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: true)) expect(last_response.status).to eq(400) end end end end context 'when allow_ssh is disabled globally' do before do set_current_user_as_admin TestConfig.override(allow_app_ssh_access: false) end context 'when allow_ssh is enabled on the space' do before do space.allow_ssh = true space.save end it 'errors when attempting to set enable_ssh to true' do post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: true)) expect(last_response.status).to eq(400) end it 'allows enable_ssh to be set to false' do post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: false)) expect(last_response.status).to eq(201) end end context 'when allow_ssh is disabled on the space' do before do space.allow_ssh = false space.save end it 'errors when attempting to set enable_ssh to true' do post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: true)) expect(last_response.status).to eq(400) end it 'allows enable_ssh to be set to false' do post '/v2/apps', MultiJson.dump(initial_hash.merge(enable_ssh: false)) expect(last_response.status).to eq(201) end end context 'when diego is set to true' do context 'when no custom ports are specified' do it 'sets the ports to 8080' do post '/v2/apps', MultiJson.dump(initial_hash.merge(diego: true)) expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([8080]) expect(decoded_response['entity']['diego']).to be true end end context 'when custom ports are specified' do it 'sets the ports to as specified in the request' do post '/v2/apps', MultiJson.dump(initial_hash.merge(diego: true, ports: [9090, 5222])) expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([9090, 5222]) expect(decoded_response['entity']['diego']).to be true end end context 'when the custom port is not in the valid range 1024-65535' do it 'return an error' do post '/v2/apps', MultiJson.dump(initial_hash.merge(diego: true, ports: [9090, 500])) expect(last_response.status).to eq(400) expect(decoded_response['description']).to include('Ports must be in the 1024-65535 range.') end end end end it 'creates the app' do request = { name: 'maria', space_guid: space.guid, environment_json: { 'KEY' => 'val' }, buildpack: 'http://example.com/buildpack', health_check_http_endpoint: '/healthz', health_check_type: 'http', } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) v2_app = ProcessModel.last expect(v2_app.health_check_type).to eq('http') expect(v2_app.health_check_http_endpoint).to eq('/healthz') end it 'creates the app' do request = { name: 'maria', space_guid: space.guid, environment_json: { 'KEY' => 'val' }, buildpack: 'http://example.com/buildpack' } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) v2_app = ProcessModel.last expect(v2_app.name).to eq('maria') expect(v2_app.space).to eq(space) expect(v2_app.environment_json).to eq({ 'KEY' => 'val' }) expect(v2_app.stack).to eq(Stack.default) expect(v2_app.buildpack.url).to eq('http://example.com/buildpack') v3_app = v2_app.app expect(v3_app.name).to eq('maria') expect(v3_app.space).to eq(space) expect(v3_app.environment_variables).to eq({ 'KEY' => 'val' }) expect(v3_app.lifecycle_type).to eq(BuildpackLifecycleDataModel::LIFECYCLE_TYPE) expect(v3_app.lifecycle_data.stack).to eq(Stack.default.name) expect(v3_app.lifecycle_data.buildpacks).to eq(['http://example.com/buildpack']) expect(v3_app.desired_state).to eq(v2_app.state) expect(v3_app.guid).to eq(v2_app.guid) end context 'creating a buildpack app' do it 'creates the app correctly' do stack = Stack.make(name: 'stack-name') request = { name: 'maria', space_guid: space.guid, stack_guid: stack.guid, buildpack: 'http://example.com/buildpack' } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) v2_app = ProcessModel.last expect(v2_app.stack).to eq(stack) expect(v2_app.buildpack.url).to eq('http://example.com/buildpack') end context 'when custom buildpacks are disabled and the buildpack attribute is being changed' do before do TestConfig.override({ disable_custom_buildpacks: true }) set_current_user(admin_user, admin: true) end let(:request) do { name: 'maria', space_guid: space.guid, } end it 'does NOT allow a public git url' do post '/v2/apps', MultiJson.dump(request.merge(buildpack: 'http://example.com/buildpack')) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does NOT allow a public http url' do post '/v2/apps', MultiJson.dump(request.merge(buildpack: 'http://example.com/foo')) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does allow a buildpack name' do admin_buildpack = Buildpack.make post '/v2/apps', MultiJson.dump(request.merge(buildpack: admin_buildpack.name)) expect(last_response.status).to eq(201) end it 'does not allow a private git url' do post '/v2/apps', MultiJson.dump(request.merge(buildpack: 'https://username:[email protected]/johndoe/my-buildpack.git')) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does not allow a private git url with ssh schema' do post '/v2/apps', MultiJson.dump(request.merge(buildpack: 'ssh://[email protected]:foo.git')) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end end end context 'creating a docker app' do it 'creates the app correctly' do request = { name: 'maria', space_guid: space.guid, docker_image: 'some-image:latest', } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) v2_app = ProcessModel.last expect(v2_app.docker_image).to eq('some-image:latest') expect(v2_app.package_hash).to eq('some-image:latest') package = v2_app.latest_package expect(package.image).to eq('some-image:latest') end context 'when the package is invalid' do before do allow(VCAP::CloudController::PackageCreate).to receive(:create_without_event). and_raise(VCAP::CloudController::PackageCreate::InvalidPackage.new('oops')) end it 'returns an UnprocessableEntity error' do request = { name: 'maria', space_guid: space.guid, docker_image: 'some-image:latest', } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) expect(last_response.status).to eq(422) expect(last_response.body).to match /UnprocessableEntity/ expect(last_response.body).to match /oops/ end end end context 'when starting an app without a package' do it 'raises an error' do request = { name: 'maria', space_guid: space.guid, state: 'STARTED' } set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump(request) expect(last_response.status).to eq(400) expect(last_response.body).to include('bits have not been uploaded') end end context 'when the space does not exist' do it 'returns 404' do set_current_user(admin_user, admin: true) post '/v2/apps', MultiJson.dump({ name: 'maria', space_guid: 'no-existy' }) expect(last_response.status).to eq(404) end end end describe 'docker image credentials' do let(:space) { Space.make } let(:space_guid) { space.guid.to_s } let(:initial_hash) do { name: 'maria', space_guid: space_guid } end let(:decoded_response) { MultiJson.load(last_response.body) } let(:user) { 'user' } let(:password) { 'password' } let(:docker_credentials) do { username: user, password: password, } end let(:body) do MultiJson.dump(initial_hash.merge(docker_image: 'someimage', docker_credentials: docker_credentials)) end let(:redacted_message) { '***' } def create_app post '/v2/apps', body expect(last_response).to have_status_code(201) decoded_response['metadata']['guid'] end def read_app app_guid = create_app get "/v2/apps/#{app_guid}" expect(last_response).to have_status_code(200) end def update_app app_guid = create_app put "/v2/apps/#{app_guid}", body expect(last_response).to have_status_code(201) end before do set_current_user_as_admin end context 'create app' do it 'redacts the credentials' do create_app expect(decoded_response['entity']['docker_credentials']['password']).to eq redacted_message end end context 'read app' do it 'redacts the credentials' do read_app expect(decoded_response['entity']['docker_credentials']['password']).to eq redacted_message end end context 'update app' do it 'redacts the credentials' do update_app expect(decoded_response['entity']['docker_credentials']['password']).to eq redacted_message end end end describe 'update app' do let(:update_hash) { {} } let(:process) { ProcessModelFactory.make(diego: false, instances: 1) } let(:developer) { make_developer_for_space(process.space) } before do set_current_user(developer) allow_any_instance_of(V2::AppStage).to receive(:stage).and_return(nil) end describe 'app_scaling feature flag' do context 'when the flag is enabled' do before { FeatureFlag.make(name: 'app_scaling', enabled: true) } it 'allows updating memory' do put "/v2/apps/#{process.app.guid}", '{ "memory": 2 }' expect(last_response.status).to eq(201) end end context 'when the flag is disabled' do before { FeatureFlag.make(name: 'app_scaling', enabled: false, error_message: nil) } it 'fails with the proper error code and message' do put "/v2/apps/#{process.app.guid}", '{ "memory": 2 }' expect(last_response.status).to eq(403) expect(decoded_response['error_code']).to match(/FeatureDisabled/) expect(decoded_response['description']).to match(/app_scaling/) end end end context 'switch from dea to diego' do let(:process) { ProcessModelFactory.make(instances: 1, diego: false, type: 'web') } let(:developer) { make_developer_for_space(process.space) } let(:route) { Route.make(space: process.space) } let(:route_mapping) { RouteMappingModel.make(app: process.app, route: route) } it 'sets ports to 8080' do expect(process.ports).to be_nil put "/v2/apps/#{process.app.guid}", '{ "diego": true }' expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([8080]) expect(decoded_response['entity']['diego']).to be true end end context 'switch from diego to dea' do let(:process) { ProcessModelFactory.make(instances: 1, diego: true, ports: [8080, 5222]) } it 'updates the backend of the app and returns 201 with warning' do put "/v2/apps/#{process.app.guid}", '{ "diego": false}' expect(last_response).to have_status_code(201) expect(decoded_response['entity']['diego']).to be false warning = CGI.unescape(last_response.headers['X-Cf-Warnings']) expect(warning).to include('App ports have changed but are unknown. The app should now listen on the port specified by environment variable PORT') end end context 'when app is diego app' do let(:process) { ProcessModelFactory.make(instances: 1, diego: true, ports: [9090, 5222]) } it 'sets ports to user specified values' do put "/v2/apps/#{process.app.guid}", '{ "ports": [1883,5222] }' expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([1883, 5222]) expect(decoded_response['entity']['diego']).to be true end context 'when not updating ports' do it 'should keep previously specified custom ports' do put "/v2/apps/#{process.app.guid}", '{ "instances":2 }' expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([9090, 5222]) expect(decoded_response['entity']['diego']).to be true end end context 'when the user sets ports to an empty array' do it 'should keep previously specified custom ports' do put "/v2/apps/#{process.app.guid}", '{ "ports":[] }' expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([9090, 5222]) expect(decoded_response['entity']['diego']).to be true end end context 'when updating an app with existing route mapping' do let(:route) { Route.make(space: process.space) } let!(:route_mapping) { RouteMappingModel.make(app: process.app, route: route, app_port: 9090) } let!(:route_mapping2) { RouteMappingModel.make(app: process.app, route: route, app_port: 5222) } context 'when new app ports contains all existing route port mappings' do it 'updates the ports' do put "/v2/apps/#{process.app.guid}", '{ "ports":[9090, 5222, 1234] }' expect(last_response.status).to eq(201) expect(decoded_response['entity']['ports']).to match([9090, 5222, 1234]) end end context 'when new app ports partially contains existing route port mappings' do it 'returns 400' do put "/v2/apps/#{process.app.guid}", '{ "ports":[5222, 1234] }' expect(last_response.status).to eq(400) expect(decoded_response['description']).to include('App ports may not be removed while routes are mapped to them.') end end context 'when new app ports do not contain existing route mapping port' do it 'returns 400' do put "/v2/apps/#{process.app.guid}", '{ "ports":[1234] }' expect(last_response.status).to eq(400) expect(decoded_response['description']).to include('App ports may not be removed while routes are mapped to them.') end end end end describe 'events' do let(:update_hash) { { instances: 2, foo: 'foo_value' } } context 'when the update succeeds' do it 'records app update with whitelisted attributes' do allow_any_instance_of(ErrorPresenter).to receive(:raise_500?).and_return(false) allow(app_event_repository).to receive(:record_app_update).and_call_original expect(app_event_repository).to receive(:record_app_update) do |recorded_app, recorded_space, user_audit_info, attributes| expect(recorded_app.guid).to eq(process.app.guid) expect(recorded_app.instances).to eq(2) expect(user_audit_info.user_guid).to eq(SecurityContext.current_user.guid) expect(user_audit_info.user_name).to eq(SecurityContext.current_user_email) expect(attributes).to eq({ 'instances' => 2 }) end put "/v2/apps/#{process.app.guid}", MultiJson.dump(update_hash) end end context 'when the update fails' do before do allow_any_instance_of(ProcessModel).to receive(:save).and_raise('Error saving') allow(app_event_repository).to receive(:record_app_update) end it 'does not record app update' do expect { put "/v2/apps/#{process.app.guid}", MultiJson.dump(update_hash) }.to raise_error RuntimeError, /Error saving/ expect(app_event_repository).to_not have_received(:record_app_update) end end end it 'updates the app' do v2_app = ProcessModel.make v3_app = v2_app.app stack = Stack.make(name: 'stack-name') request = { name: 'maria', environment_json: { 'KEY' => 'val' }, stack_guid: stack.guid, buildpack: 'http://example.com/buildpack', } set_current_user(admin_user, admin: true) put "/v2/apps/#{v2_app.app.guid}", MultiJson.dump(request) expect(last_response.status).to eq(201) v2_app.reload v3_app.reload expect(v2_app.name).to eq('maria') expect(v2_app.environment_json).to eq({ 'KEY' => 'val' }) expect(v2_app.stack).to eq(stack) expect(v2_app.buildpack.url).to eq('http://example.com/buildpack') expect(v3_app.name).to eq('maria') expect(v3_app.environment_variables).to eq({ 'KEY' => 'val' }) expect(v3_app.lifecycle_type).to eq(BuildpackLifecycleDataModel::LIFECYCLE_TYPE) expect(v3_app.lifecycle_data.stack).to eq('stack-name') expect(v3_app.lifecycle_data.buildpacks).to eq(['http://example.com/buildpack']) end context 'when custom buildpacks are disabled and the buildpack attribute is being changed' do before do TestConfig.override({ disable_custom_buildpacks: true }) set_current_user(admin_user, admin: true) process.app.lifecycle_data.update(buildpacks: [Buildpack.make.name]) end let(:process) { ProcessModel.make } it 'does NOT allow a public git url' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: 'http://example.com/buildpack' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does NOT allow a public http url' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: 'http://example.com/foo' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does allow a buildpack name' do admin_buildpack = Buildpack.make put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: admin_buildpack.name }) expect(last_response.status).to eq(201) end it 'does not allow a private git url' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: '[email protected]:foo.git' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end it 'does not allow a private git url with ssh schema' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: 'ssh://[email protected]:foo.git' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Custom buildpacks are disabled') end end describe 'setting stack' do let(:new_stack) { Stack.make } it 'changes the stack' do set_current_user(admin_user, admin: true) process = ProcessModelFactory.make expect(process.stack).not_to eq(new_stack) put "/v2/apps/#{process.app.guid}", MultiJson.dump({ stack_guid: new_stack.guid }) expect(last_response.status).to eq(201) expect(process.reload.stack).to eq(new_stack) end context 'when the app is already staged' do let(:process) do ProcessModelFactory.make( instances: 1, state: 'STARTED') end it 'marks the app for re-staging' do expect(process.needs_staging?).to eq(false) put "/v2/apps/#{process.app.guid}", MultiJson.dump({ stack_guid: new_stack.guid }) expect(last_response.status).to eq(201) process.reload expect(process.needs_staging?).to eq(true) expect(process.staged?).to eq(false) end end context 'when the app needs staged' do let(:process) { ProcessModelFactory.make(state: 'STARTED') } before do PackageModel.make(app: process.app, package_hash: 'some-hash', state: PackageModel::READY_STATE) process.reload end it 'keeps app as needs staging' do expect(process.staged?).to be false expect(process.needs_staging?).to be true put "/v2/apps/#{process.app.guid}", MultiJson.dump({ stack_guid: new_stack.guid }) expect(last_response.status).to eq(201) process.reload expect(process.staged?).to be false expect(process.needs_staging?).to be true end end context 'when the app was never staged' do let(:process) { ProcessModel.make } it 'does not mark the app for staging' do expect(process.staged?).to be_falsey expect(process.needs_staging?).to be_nil put "/v2/apps/#{process.app.guid}", MultiJson.dump({ stack_guid: new_stack.guid }) expect(last_response.status).to eq(201) process.reload expect(process.staged?).to be_falsey expect(process.needs_staging?).to be_nil end end end describe 'changing lifecycle types' do context 'when changing from docker to buildpack' do let(:process) { ProcessModel.make(app: AppModel.make(:docker)) } it 'raises an error setting buildpack' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ buildpack: 'https://buildpack.example.com' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Lifecycle type cannot be changed') end it 'raises an error setting stack' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ stack_guid: 'phat-stackz' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Lifecycle type cannot be changed') end end context 'when changing from buildpack to docker' do let(:process) { ProcessModel.make(app: AppModel.make(:buildpack)) } it 'raises an error' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ docker_image: 'repo/great-image' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('Lifecycle type cannot be changed') end end end describe 'updating docker_image' do before do set_current_user(admin_user, admin: true) end it 'creates a new docker package' do process = ProcessModelFactory.make(app: AppModel.make(:docker), docker_image: 'repo/original-image') original_package = process.latest_package expect(process.docker_image).not_to eq('repo/new-image') put "/v2/apps/#{process.app.guid}", MultiJson.dump({ docker_image: 'repo/new-image' }) expect(last_response.status).to eq(201) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['entity']['docker_image']).to eq('repo/new-image') expect(parsed_response['entity']['docker_credentials']).to eq({ 'username' => nil, 'password' => nil }) expect(process.reload.docker_image).to eq('repo/new-image') expect(process.latest_package).not_to eq(original_package) end context 'when credentials are requested' do let(:docker_credentials) do { 'username' => 'fred', 'password' => 'derf' } end it 'creates a new docker package with those credentials' do process = ProcessModelFactory.make(app: AppModel.make(:docker), docker_image: 'repo/original-image') original_package = process.latest_package expect(process.docker_image).not_to eq('repo/new-image') put "/v2/apps/#{process.app.guid}", MultiJson.dump({ docker_image: 'repo/new-image', docker_credentials: docker_credentials }) expect(last_response.status).to eq(201) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['entity']['docker_image']).to eq('repo/new-image') expect(parsed_response['entity']['docker_credentials']).to eq({ 'username' => 'fred', 'password' => '***' }) expect(process.reload.docker_image).to eq('repo/new-image') expect(process.latest_package).not_to eq(original_package) end end context 'when the package is invalid' do before do allow(VCAP::CloudController::PackageCreate).to receive(:create_without_event). and_raise(VCAP::CloudController::PackageCreate::InvalidPackage.new('oops')) end it 'returns an UnprocessableEntity error' do set_current_user(admin_user, admin: true) process = ProcessModelFactory.make(app: AppModel.make(:docker), docker_image: 'repo/original-image') put "/v2/apps/#{process.app.guid}", MultiJson.dump({ docker_credentials: { username: 'username', password: 'foo' } }) expect(last_response.status).to eq(422) expect(last_response.body).to match /UnprocessableEntity/ expect(last_response.body).to match /oops/ end end end describe 'staging' do let(:app_stage) { instance_double(V2::AppStage, stage: nil) } let(:process) { ProcessModelFactory.make } before do allow(V2::AppStage).to receive(:new).and_return(app_stage) process.update(state: 'STARTED') end context 'when a state change is requested' do let(:req) { '{ "state": "STARTED" }' } context 'when the app needs staging' do before do process.app.update(droplet: nil) process.reload end it 'requests to be staged' do put "/v2/apps/#{process.app.guid}", req expect(last_response.status).to eq(201) expect(app_stage).to have_received(:stage) end end context 'when the app does not need staging' do it 'does not request to be staged' do put "/v2/apps/#{process.app.guid}", req expect(last_response.status).to eq(201) expect(app_stage).not_to have_received(:stage) end end end context 'when a state change is NOT requested' do let(:req) { '{ "name": "some-name" }' } context 'when the app needs staging' do before do process.app.update(droplet: nil) process.reload end it 'does not request to be staged' do put "/v2/apps/#{process.app.guid}", req expect(last_response.status).to eq(201) expect(app_stage).not_to have_received(:stage) end end context 'when the app does not need staging' do it 'does not request to be staged' do put "/v2/apps/#{process.app.guid}", req expect(last_response.status).to eq(201) expect(app_stage).not_to have_received(:stage) end end end end context 'when starting an app without a package' do let(:process) { ProcessModel.make(instances: 1) } it 'raises an error' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({ state: 'STARTED' }) expect(last_response.status).to eq(400) expect(last_response.body).to include('bits have not been uploaded') end end describe 'starting and stopping' do let(:parent_app) { process.app } let(:process) { ProcessModelFactory.make(instances: 1, state: state) } let(:sibling) { ProcessModel.make(instances: 1, state: state, app: parent_app, type: 'worker') } context 'starting' do let(:state) { 'STOPPED' } it 'is reflected in the parent app and all sibling processes' do expect(parent_app.desired_state).to eq('STOPPED') expect(process.state).to eq('STOPPED') expect(sibling.state).to eq('STOPPED') put "/v2/apps/#{process.app.guid}", '{ "state": "STARTED" }' expect(last_response.status).to eq(201) expect(parent_app.reload.desired_state).to eq('STARTED') expect(process.reload.state).to eq('STARTED') expect(sibling.reload.state).to eq('STARTED') end end context 'stopping' do let(:state) { 'STARTED' } it 'is reflected in the parent app and all sibling processes' do expect(parent_app.desired_state).to eq('STARTED') expect(process.state).to eq('STARTED') expect(sibling.state).to eq('STARTED') put "/v2/apps/#{process.app.guid}", '{ "state": "STOPPED" }' expect(last_response.status).to eq(201) expect(parent_app.reload.desired_state).to eq('STOPPED') expect(process.reload.state).to eq('STOPPED') expect(sibling.reload.state).to eq('STOPPED') end end context 'invalid state' do let(:state) { 'STOPPED' } it 'raises an error' do put "/v2/apps/#{process.app.guid}", '{ "state": "ohio" }' expect(last_response.status).to eq(400) expect(last_response.body).to include('Invalid app state') end end end end describe 'delete an app' do let(:process) { ProcessModelFactory.make } let(:developer) { make_developer_for_space(process.space) } let(:decoded_response) { MultiJson.load(last_response.body) } let(:parent_app) { process.app } before do set_current_user(developer) end def delete_app delete "/v2/apps/#{process.app.guid}" end it 'deletes the app' do expect(process.exists?).to be_truthy expect(parent_app.exists?).to be_truthy delete_app expect(last_response.status).to eq(204) expect(process.exists?).to be_falsey expect(parent_app.exists?).to be_falsey end context 'when the app disappears after the find_validate_access_check' do before do allow_any_instance_of(AppDelete).to receive(:delete_without_event).and_raise(Sequel::NoExistingObject) end it 'throws a not_found_exception' do delete_app expect(last_response.status).to eq(404) expect(parsed_response['description']).to eq("The app could not be found: #{parent_app.guid}") end end describe 'recursive deletion' do let!(:svc_instance) { ManagedServiceInstance.make(space: process.space) } let!(:service_binding) { ServiceBinding.make(app: process.app, service_instance: svc_instance) } let(:guid_pattern) { '[[:alnum:]-]+' } let(:broker_response_code) { 200 } before do service_broker = svc_instance.service.service_broker uri = URI(service_broker.broker_url) broker_url = uri.host + uri.path stub_request( :delete, %r{https://#{broker_url}/v2/service_instances/#{guid_pattern}/service_bindings/#{guid_pattern}}). with(basic_auth: basic_auth(service_broker: service_broker)). to_return(status: broker_response_code, body: '{}') end context 'when recursive=false is set' do before do delete_app end it 'should raise an error' do expect(last_response.status).to eq(400) expect(decoded_response['description']).to match(/service_bindings/i) end end context 'when recursive=true is set' do it 'should succeed on a recursive delete' do delete "/v2/apps/#{process.app.guid}?recursive=true" expect(last_response).to have_status_code(204) end context 'when the service binding unbind is asynchronous' do let(:broker_response_code) { 202 } it 'returns an error' do delete "/v2/apps/#{process.app.guid}?recursive=true" expect(last_response).to have_status_code(502) body = JSON.parse(last_response.body) expect(body['error_code']).to include 'CF-AppRecursiveDeleteFailed' err_msg = body['description'] expect(err_msg).to match "^Deletion of app #{process.app.name} failed because one or more associated resources could not be deleted\.\n\n" end end context 'when the error is a SubResource error' do before do errs = [StandardError.new('oops-1'), StandardError.new('oops-2')] allow_any_instance_of(AppDelete).to receive(:delete_without_event).and_raise(VCAP::CloudController::AppDelete::SubResourceError.new(errs)) end it 'returns all errors contained within it from the action' do delete "/v2/apps/#{process.guid}?recursive=true" expect(last_response).to have_status_code(502) body = JSON.parse(last_response.body) err_msg = body['description'] expect(err_msg).to match 'oops-1' expect(err_msg).to match 'oops-2' end end end end describe 'events' do it 'records an app delete-request' do delete_app event = Event.find(type: 'audit.app.delete-request', actee_type: 'app') expect(event.type).to eq('audit.app.delete-request') expect(event.metadata).to eq({ 'request' => { 'recursive' => false } }) expect(event.actor).to eq(developer.guid) expect(event.actor_type).to eq('user') expect(event.actee).to eq(process.app.guid) expect(event.actee_type).to eq('app') end it 'records the recursive query parameter when recursive' do delete "/v2/apps/#{process.app.guid}?recursive=true" event = Event.find(type: 'audit.app.delete-request', actee_type: 'app') expect(event.type).to eq('audit.app.delete-request') expect(event.metadata).to eq({ 'request' => { 'recursive' => true } }) expect(event.actor).to eq(developer.guid) expect(event.actor_type).to eq('user') expect(event.actee).to eq(process.app.guid) expect(event.actee_type).to eq('app') end it 'does not record when the destroy fails' do allow_any_instance_of(ProcessModel).to receive(:destroy).and_raise('Error saving') expect { delete_app }.to raise_error RuntimeError, /Error saving/ expect(Event.where(type: 'audit.app.delete-request').count).to eq(0) end end end describe 'route mapping' do let!(:process) { ProcessModelFactory.make(instances: 1, diego: true) } let!(:developer) { make_developer_for_space(process.space) } let!(:route) { Route.make(space: process.space) } let!(:route_mapping) { RouteMappingModel.make(app: process.app, route: route, process_type: process.type) } before do set_current_user(developer) end context 'GET' do it 'returns the route mapping' do get "/v2/apps/#{process.app.guid}/route_mappings" expect(last_response.status).to eql(200) parsed_body = parse(last_response.body) expect(parsed_body['resources'].first['entity']['route_guid']).to eq(route.guid) expect(parsed_body['resources'].first['entity']['app_guid']).to eq(process.app.guid) end end context 'POST' do it 'returns 404' do post "/v2/apps/#{process.app.guid}/route_mappings", '{}' expect(last_response.status).to eql(404) end end context 'PUT' do it 'returns 404' do put "/v2/apps/#{process.app.guid}/route_mappings/#{route_mapping.guid}", '{}' expect(last_response.status).to eql(404) end end context 'DELETE' do it 'returns 404' do delete "/v2/apps/#{process.app.guid}/route_mappings/#{route_mapping.guid}" expect(last_response.status).to eql(404) end end end describe "read an app's env" do let(:space) { process.space } let(:developer) { make_developer_for_space(space) } let(:auditor) { make_auditor_for_space(space) } let(:process) { ProcessModelFactory.make(detected_buildpack: 'buildpack-name') } let(:decoded_response) { MultiJson.load(last_response.body) } before do set_current_user(developer) end context 'when the user is a member of the space this app exists in' do context 'when the user is not a space developer' do before do set_current_user(User.make) end it 'returns a JSON payload indicating they do not have permission to read this endpoint' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(403) expect(JSON.parse(last_response.body)['description']).to eql('You are not authorized to perform the requested action') end end context 'when the user has only the cloud_controller.read scope' do before do set_current_user(developer, { scopes: ['cloud_controller.read'] }) end it 'returns successfully' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) parsed_body = parse(last_response.body) expect(parsed_body).to have_key('staging_env_json') expect(parsed_body).to have_key('running_env_json') expect(parsed_body).to have_key('environment_json') expect(parsed_body).to have_key('system_env_json') expect(parsed_body).to have_key('application_env_json') end end context 'environment variable' do it 'returns application environment with VCAP_APPLICATION' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) expect(decoded_response['application_env_json']).to have_key('VCAP_APPLICATION') expect(decoded_response['application_env_json']).to match({ 'VCAP_APPLICATION' => { 'cf_api' => "#{TestConfig.config[:external_protocol]}://#{TestConfig.config[:external_domain]}", 'limits' => { 'mem' => process.memory, 'disk' => process.disk_quota, 'fds' => 16384 }, 'application_id' => process.app.guid, 'application_name' => process.name, 'name' => process.name, 'application_uris' => [], 'uris' => [], 'application_version' => /^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/, 'version' => /^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/, 'space_name' => process.space.name, 'space_id' => process.space.guid, 'organization_id' => process.organization.guid, 'organization_name' => process.organization.name, 'process_id' => process.guid, 'process_type' => process.type, 'users' => nil } }) end end context 'when the user is space dev and has service instance bound to application' do let!(:service_instance) { ManagedServiceInstance.make(space: process.space) } let!(:service_binding) { ServiceBinding.make(app: process.app, service_instance: service_instance) } it 'returns system environment with VCAP_SERVICES' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) expect(decoded_response['system_env_json']['VCAP_SERVICES']).not_to eq({}) end context 'when the service binding is being asynchronously created' do let(:operation) { ServiceBindingOperation.make(state: 'in progress') } before do service_binding.service_binding_operation = operation end it 'does not include the binding in VCAP_SERVICES' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) expect(decoded_response['system_env_json']['VCAP_SERVICES']).to eq({}) end end end context 'when the staging env variable group is set' do before do staging_group = EnvironmentVariableGroup.staging staging_group.environment_json = { POTATO: 'delicious' } staging_group.save end it 'returns staging_env_json with those variables' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) expect(decoded_response['staging_env_json'].size).to eq(1) expect(decoded_response['staging_env_json']).to have_key('POTATO') expect(decoded_response['staging_env_json']['POTATO']).to eq('delicious') end end context 'when the running env variable group is set' do before do running_group = EnvironmentVariableGroup.running running_group.environment_json = { PIE: 'sweet' } running_group.save end it 'returns staging_env_json with those variables' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(200) expect(decoded_response['running_env_json'].size).to eq(1) expect(decoded_response['running_env_json']).to have_key('PIE') expect(decoded_response['running_env_json']['PIE']).to eq('sweet') end end context 'when the user does not have the necessary scope' do before do set_current_user(developer, { scopes: ['cloud_controller.write'] }) end it 'returns InsufficientScope' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(403) expect(JSON.parse(last_response.body)['description']).to eql('Your token lacks the necessary scopes to access this resource.') end end end context 'when the user is a global auditor' do before do set_current_user_as_global_auditor end it 'should not be able to read environment variables' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(403) expect(JSON.parse(last_response.body)['description']).to eql('You are not authorized to perform the requested action') end end context 'when the user reads environment variables from the app endpoint using inline-relations-depth=2' do let!(:test_environment_json) { { 'environ_key' => 'value' } } let(:parent_app) { AppModel.make(environment_variables: test_environment_json) } let!(:process) do ProcessModelFactory.make( detected_buildpack: 'buildpack-name', app: parent_app ) end let!(:service_instance) { ManagedServiceInstance.make(space: process.space) } let!(:service_binding) { ServiceBinding.make(app: process.app, service_instance: service_instance) } context 'when the user is a space developer' do it 'returns non-redacted environment values' do get '/v2/apps?inline-relations-depth=2' expect(last_response.status).to eql(200) expect(decoded_response['resources'].first['entity']['environment_json']).to eq(test_environment_json) expect(decoded_response).not_to have_key('system_env_json') end end context 'when the user is not a space developer' do before do set_current_user(auditor) end it 'returns redacted values' do get '/v2/apps?inline-relations-depth=2' expect(last_response.status).to eql(200) expect(decoded_response['resources'].first['entity']['environment_json']).to eq({ 'redacted_message' => '[PRIVATE DATA HIDDEN]' }) expect(decoded_response).not_to have_key('system_env_json') end end end context 'when the user is NOT a member of the space this instance exists in' do let(:process) { ProcessModelFactory.make(detected_buildpack: 'buildpack-name') } before do set_current_user(User.make) end it 'returns access denied' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(403) end end context 'when the user has not authenticated with Cloud Controller' do let(:developer) { nil } it 'returns an error saying that the user is not authenticated' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(401) end end context 'when the app does not exist' do it 'returns not found' do get '/v2/apps/nonexistentappguid/env' expect(last_response.status).to eql 404 end end context 'when the space_developer_env_var_visibility feature flag is disabled' do before do VCAP::CloudController::FeatureFlag.make(name: 'space_developer_env_var_visibility', enabled: false, error_message: nil) end it 'raises 403 for non-admins' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(403) expect(last_response.body).to include('FeatureDisabled') expect(last_response.body).to include('space_developer_env_var_visibility') end it 'succeeds for admins' do set_current_user_as_admin get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(200) end it 'succeeds for admin_read_onlys' do set_current_user_as_admin_read_only get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(200) end context 'when the user is not a space developer' do before do set_current_user(auditor) end it 'indicates they do not have permission rather than that the feature flag is disabled' do get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eql(403) expect(JSON.parse(last_response.body)['description']).to eql('You are not authorized to perform the requested action') end end end context 'when the env_var_visibility feature flag is disabled' do before do VCAP::CloudController::FeatureFlag.make(name: 'env_var_visibility', enabled: false, error_message: nil) end it 'raises 403 all user' do set_current_user_as_admin get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(403) expect(last_response.body).to include('Feature Disabled: env_var_visibility') end context 'when the space_developer_env_var_visibility feature flag is enabled' do before do VCAP::CloudController::FeatureFlag.make(name: 'space_developer_env_var_visibility', enabled: true, error_message: nil) end it 'raises 403 for non-admins' do set_current_user(developer) get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(403) expect(last_response.body).to include('Feature Disabled: env_var_visibility') end end end context 'when the env_var_visibility feature flag is enabled' do before do VCAP::CloudController::FeatureFlag.make(name: 'env_var_visibility', enabled: true, error_message: nil) end it 'continues to show 403 for roles that never had access to envs' do set_current_user(auditor) get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(403) expect(last_response.body).to include('NotAuthorized') end it 'show envs for admins' do set_current_user_as_admin get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(200) expect(decoded_response['application_env_json']).to match({ 'VCAP_APPLICATION' => { 'cf_api' => "#{TestConfig.config[:external_protocol]}://#{TestConfig.config[:external_domain]}", 'limits' => { 'mem' => process.memory, 'disk' => process.disk_quota, 'fds' => 16384 }, 'application_id' => process.app.guid, 'application_name' => process.name, 'name' => process.name, 'application_uris' => [], 'uris' => [], 'application_version' => /^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/, 'version' => /^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/, 'space_name' => process.space.name, 'space_id' => process.space.guid, 'organization_id' => process.organization.guid, 'organization_name' => process.organization.name, 'process_id' => process.guid, 'process_type' => process.type, 'users' => nil } }) end context 'when the space_developer_env_var_visibility feature flag is disabled' do before do VCAP::CloudController::FeatureFlag.make(name: 'space_developer_env_var_visibility', enabled: false, error_message: nil) end it 'raises 403 for space developers' do set_current_user(developer) get "/v2/apps/#{process.app.guid}/env" expect(last_response.status).to eq(403) expect(last_response.body).to include('Feature Disabled: space_developer_env_var_visibility') end end end end describe 'staging' do let(:developer) { make_developer_for_space(process.space) } before do set_current_user(developer) Buildpack.make end context 'when app will be staged', isolation: :truncation do let(:process) do ProcessModelFactory.make(diego: false, state: 'STOPPED', instances: 1).tap do |p| p.desired_droplet.destroy p.reload end end let(:stager_response) do double('StagingResponse', streaming_log_url: 'streaming-log-url') end let(:app_stager_task) do double(Diego::Stager, stage: stager_response) end before do allow(Diego::Stager).to receive(:new).and_return(app_stager_task) end it 'returns X-App-Staging-Log header with staging log url' do put "/v2/apps/#{process.app.guid}", MultiJson.dump(state: 'STARTED') expect(last_response.status).to eq(201), last_response.body expect(last_response.headers['X-App-Staging-Log']).to eq('streaming-log-url') end end context 'when app will not be staged' do let(:process) { ProcessModelFactory.make(state: 'STOPPED') } it 'does not add X-App-Staging-Log' do put "/v2/apps/#{process.app.guid}", MultiJson.dump({}) expect(last_response.status).to eq(201) expect(last_response.headers).not_to have_key('X-App-Staging-Log') end end end describe 'downloading the droplet' do let(:process) { ProcessModelFactory.make } let(:blob) { instance_double(CloudController::Blobstore::FogBlob) } let(:developer) { make_developer_for_space(process.space) } before do set_current_user(developer) allow(blob).to receive(:public_download_url).and_return('http://example.com/somewhere/else') allow_any_instance_of(CloudController::Blobstore::Client).to receive(:blob).and_return(blob) end it 'should let the user download the droplet' do get "/v2/apps/#{process.app.guid}/droplet/download", MultiJson.dump({}) expect(last_response).to be_redirect expect(last_response.header['Location']).to eq('http://example.com/somewhere/else') end it 'should return an error for non-existent apps' do get '/v2/apps/bad/droplet/download', MultiJson.dump({}) expect(last_response.status).to eq(404) end it 'should return an error for an app without a droplet' do process.desired_droplet.destroy get "/v2/apps/#{process.app.guid}/droplet/download", MultiJson.dump({}) expect(last_response.status).to eq(404) end end describe 'uploading the droplet' do before do TestConfig.override(directories: { tmpdir: File.dirname(valid_zip.path) }) end let(:process) { ProcessModel.make } let(:tmpdir) { Dir.mktmpdir } after { FileUtils.rm_rf(tmpdir) } let(:valid_zip) do zip_name = File.join(tmpdir, 'file.zip') TestZip.create(zip_name, 1, 1024) zip_file = File.new(zip_name) Rack::Test::UploadedFile.new(zip_file) end context 'as an admin' do let(:req_body) { { droplet: valid_zip } } it 'is allowed' do set_current_user(User.make, admin: true) put "/v2/apps/#{process.app.guid}/droplet/upload", req_body expect(last_response.status).to eq(201) end end context 'as a developer' do let(:user) { make_developer_for_space(process.space) } context 'with an empty request' do it 'fails to upload' do set_current_user(user) put "/v2/apps/#{process.app.guid}/droplet/upload", {} expect(last_response.status).to eq(400) expect(JSON.parse(last_response.body)['description']).to include('missing :droplet_path') end end context 'with valid request' do let(:req_body) { { droplet: valid_zip } } it 'creates a delayed job' do set_current_user(user) expect { put "/v2/apps/#{process.app.guid}/droplet/upload", req_body expect(last_response.status).to eq 201 }.to change { Delayed::Job.count }.by(1) job = Delayed::Job.last expect(job.handler).to include('V2::UploadDropletFromUser') end end end context 'as a non-developer' do let(:req_body) { { droplet: valid_zip } } it 'returns 403' do put "/v2/apps/#{process.app.guid}/droplet/upload", req_body expect(last_response.status).to eq(403) end end end describe 'on route change', isolation: :truncation do let(:space) { process.space } let(:domain) do PrivateDomain.make(name: 'jesse.cloud', owning_organization: space.organization) end let(:process) { ProcessModelFactory.make(diego: false, state: 'STARTED') } before do FeatureFlag.create(name: 'diego_docker', enabled: true) set_current_user(make_developer_for_space(space)) end it 'creates a route mapping when we add one url through PUT /v2/apps/:guid' do route = domain.add_route( host: 'app', space: space, ) fake_route_mapping_create = instance_double(V2::RouteMappingCreate) allow(V2::RouteMappingCreate).to receive(:new).with(anything, route, process, anything, instance_of(Steno::Logger)).and_return(fake_route_mapping_create) expect(fake_route_mapping_create).to receive(:add) put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response.status).to eq(201) end context 'with Docker app' do let(:space) { docker_process.space } let(:route) { domain.add_route(host: 'app', space: space) } let(:pre_mapped_route) { domain.add_route(host: 'pre_mapped_route', space: space) } let(:docker_process) do ProcessModelFactory.make( state: 'STARTED', diego: true, docker_image: 'some-image', ) end context 'when Docker is disabled' do before do allow_any_instance_of(Diego::Messenger).to receive(:send_desire_request) FeatureFlag.find(name: 'diego_docker').update(enabled: false) end context 'and a route is mapped' do it 'succeeds' do put "/v2/apps/#{docker_process.app.guid}/routes/#{route.guid}", nil expect(last_response.status).to eq(201) end end context 'and a previously mapped route is unmapped' do it 'succeeds' do delete "/v2/apps/#{docker_process.app.guid}/routes/#{pre_mapped_route.guid}", nil expect(last_response.status).to eq(204) end end end end end describe 'on instance number change' do before do FeatureFlag.create(name: 'diego_docker', enabled: true) end context 'when docker is disabled' do let!(:started_process) do ProcessModelFactory.make(state: 'STARTED', docker_image: 'docker-image') end before do FeatureFlag.find(name: 'diego_docker').update(enabled: false) set_current_user(make_developer_for_space(started_process.space)) end it 'does not return docker disabled message' do put "/v2/apps/#{started_process.app.guid}", MultiJson.dump(instances: 2) expect(last_response.status).to eq(201) end end end describe 'on state change' do before do FeatureFlag.create(name: 'diego_docker', enabled: true) end context 'when docker is disabled' do let!(:stopped_process) { ProcessModelFactory.make(:docker, state: 'STOPPED', docker_image: 'docker-image', type: 'web') } let!(:started_process) { ProcessModelFactory.make(:docker, state: 'STARTED', docker_image: 'docker-image', type: 'web') } before do FeatureFlag.find(name: 'diego_docker').update(enabled: false) end it 'returns docker disabled message on start' do set_current_user(make_developer_for_space(stopped_process.space)) put "/v2/apps/#{stopped_process.app.guid}", MultiJson.dump(state: 'STARTED') expect(last_response.status).to eq(400) expect(last_response.body).to match /Docker support has not been enabled/ expect(decoded_response['code']).to eq(320003) end it 'does not return docker disabled message on stop' do set_current_user(make_developer_for_space(started_process.space)) put "/v2/apps/#{started_process.app.guid}", MultiJson.dump(state: 'STOPPED') expect(last_response.status).to eq(201) end end end describe 'Permissions' do include_context 'permissions' before do @obj_a = ProcessModelFactory.make(app: AppModel.make(space: @space_a)) @obj_b = ProcessModelFactory.make(app: AppModel.make(space: @space_b)) end describe 'Org Level Permissions' do describe 'OrgManager' do let(:member_a) { @org_a_manager } let(:member_b) { @org_b_manager } include_examples 'permission enumeration', 'OrgManager', name: 'app', path: '/v2/apps', enumerate: 1 end describe 'OrgUser' do let(:member_a) { @org_a_member } let(:member_b) { @org_b_member } include_examples 'permission enumeration', 'OrgUser', name: 'app', path: '/v2/apps', enumerate: 0 end describe 'BillingManager' do let(:member_a) { @org_a_billing_manager } let(:member_b) { @org_b_billing_manager } include_examples 'permission enumeration', 'BillingManager', name: 'app', path: '/v2/apps', enumerate: 0 end describe 'Auditor' do let(:member_a) { @org_a_auditor } let(:member_b) { @org_b_auditor } include_examples 'permission enumeration', 'Auditor', name: 'app', path: '/v2/apps', enumerate: 0 end end describe 'App Space Level Permissions' do describe 'SpaceManager' do let(:member_a) { @space_a_manager } let(:member_b) { @space_b_manager } include_examples 'permission enumeration', 'SpaceManager', name: 'app', path: '/v2/apps', enumerate: 1 end describe 'Developer' do let(:member_a) { @space_a_developer } let(:member_b) { @space_b_developer } include_examples 'permission enumeration', 'Developer', name: 'app', path: '/v2/apps', enumerate: 1 end describe 'SpaceAuditor' do let(:member_a) { @space_a_auditor } let(:member_b) { @space_b_auditor } include_examples 'permission enumeration', 'SpaceAuditor', name: 'app', path: '/v2/apps', enumerate: 1 end end end describe 'Validation messages' do let(:space) { process.space } let!(:process) { ProcessModelFactory.make(state: 'STARTED') } before do set_current_user(make_developer_for_space(space)) end it 'returns duplicate app name message correctly' do existing_process = ProcessModel.make(app: AppModel.make(space: space)) put "/v2/apps/#{process.app.guid}", MultiJson.dump(name: existing_process.name) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(100002) end it 'returns organization quota memory exceeded message correctly' do space.organization.quota_definition = QuotaDefinition.make(memory_limit: 0) space.organization.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(100005) end it 'returns space quota memory exceeded message correctly' do space.space_quota_definition = SpaceQuotaDefinition.make(memory_limit: 0) space.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(310003) end it 'validates space quota memory limit before organization quotas' do space.organization.quota_definition = QuotaDefinition.make(memory_limit: 0) space.organization.save(validate: false) space.space_quota_definition = SpaceQuotaDefinition.make(memory_limit: 0) space.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(310003) end it 'returns memory invalid message correctly' do put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 0) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(100006) end it 'returns instance memory limit exceeded error correctly' do space.organization.quota_definition = QuotaDefinition.make(instance_memory_limit: 100) space.organization.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(100007) end it 'returns space instance memory limit exceeded error correctly' do space.space_quota_definition = SpaceQuotaDefinition.make(instance_memory_limit: 100) space.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(310004) end it 'returns app instance limit exceeded error correctly' do space.organization.quota_definition = QuotaDefinition.make(app_instance_limit: 4) space.organization.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(instances: 5) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(100008) end it 'validates space quota instance memory limit before organization quotas' do space.organization.quota_definition = QuotaDefinition.make(instance_memory_limit: 100) space.organization.save(validate: false) space.space_quota_definition = SpaceQuotaDefinition.make(instance_memory_limit: 100) space.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(memory: 128) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(310004) end it 'returns instances invalid message correctly' do put "/v2/apps/#{process.app.guid}", MultiJson.dump(instances: -1) expect(last_response.status).to eq(400) expect(last_response.body).to match /instances less than 0/ expect(decoded_response['code']).to eq(100001) end it 'returns state invalid message correctly' do put "/v2/apps/#{process.app.guid}", MultiJson.dump(state: 'mississippi') expect(last_response.status).to eq(400) expect(last_response.body).to match /Invalid app state provided/ expect(decoded_response['code']).to eq(100001) end it 'validates space quota app instance limit' do space.space_quota_definition = SpaceQuotaDefinition.make(app_instance_limit: 2) space.save(validate: false) put "/v2/apps/#{process.app.guid}", MultiJson.dump(instances: 3) expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(310008) end end describe 'enumerate' do let!(:web_process) { ProcessModel.make(type: 'web') } let!(:other_app) { ProcessModel.make(type: 'other') } before do set_current_user_as_admin end it 'displays processes with type web' do get '/v2/apps' expect(decoded_response['total_results']).to eq(1) expect(decoded_response['resources'][0]['metadata']['guid']).to eq(web_process.app.guid) end end describe 'PUT /v2/apps/:app_guid/routes/:route_guid' do let(:space) { Space.make } let(:process) { ProcessModelFactory.make(space: space) } let(:route) { Route.make(space: space) } let(:developer) { make_developer_for_space(space) } before do set_current_user(developer) end it 'adds the route to the app' do expect(process.reload.routes).to be_empty put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response).to have_status_code(201) expect(process.reload.routes).to match_array([route]) route_mapping = RouteMappingModel.last expect(route_mapping.app_port).to eq(8080) expect(route_mapping.process_type).to eq('web') end context 'when the app does not exist' do it 'returns 404' do put "/v2/apps/not-real/routes/#{route.guid}", nil expect(last_response).to have_status_code(404) expect(last_response.body).to include('AppNotFound') end end context 'when the route does not exist' do it 'returns 404' do put "/v2/apps/#{process.app.guid}/routes/not-real", nil expect(last_response).to have_status_code(404) expect(last_response.body).to include('RouteNotFound') end end context 'when the route is already mapped to the app' do before do RouteMappingModel.make(app: process.app, route: route, process_type: process.type) end it 'succeeds' do expect(process.reload.routes).to match_array([route]) put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response).to have_status_code(201) end end context 'when the user is not a developer in the apps space' do before do set_current_user(User.make) end it 'returns 403' do put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response).to have_status_code(403) end end context 'when the route is in a different space' do let(:route) { Route.make } it 'raises an error' do expect(process.reload.routes).to be_empty put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response.status).to eq(400) expect(last_response.body).to include('InvalidRelation') expect(decoded_response['description']).to include( 'The app cannot be mapped to this route because the route is not in this space. Apps must be mapped to routes in the same space') expect(process.reload.routes).to be_empty end end context 'when the app has multiple ports' do let(:process) { ProcessModelFactory.make(diego: true, space: route.space, ports: [9797, 7979]) } it 'uses the first port for the app as the app_port' do put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response.status).to eq(201) mapping = RouteMappingModel.last expect(mapping.app_port).to eq(9797) end end describe 'routes from tcp router groups' do let(:domain) { SharedDomain.make(name: 'tcp.com', router_group_guid: 'router-group-guid') } let(:route) { Route.make(space: process.space, domain: domain, port: 9090, host: '') } let(:routing_api_client) { double('routing_api_client', router_group: router_group) } let(:router_group) { double('router_group', type: 'tcp', guid: 'router-group-guid') } before do allow_any_instance_of(RouteValidator).to receive(:validate) allow(VCAP::CloudController::RoutingApi::Client).to receive(:new).and_return(routing_api_client) end it 'adds the route to the app' do expect(process.reload.routes).to be_empty put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response).to have_status_code(201) expect(process.reload.routes).to match_array([route]) route_mapping = RouteMappingModel.last expect(route_mapping.app_port).to eq(8080) expect(route_mapping.process_type).to eq('web') end context 'when routing api is disabled' do before do route TestConfig.override(routing_api: nil) end it 'existing routes with router groups return 403 when mapped to apps' do put "/v2/apps/#{process.app.guid}/routes/#{route.guid}", nil expect(last_response).to have_status_code(403) expect(decoded_response['description']).to include('Routing API is disabled') end end end end describe 'DELETE /v2/apps/:app_guid/routes/:route_guid' do let(:space) { Space.make } let(:process) { ProcessModelFactory.make(space: space) } let(:route) { Route.make(space: space) } let!(:route_mapping) { RouteMappingModel.make(app: process.app, route: route, process_type: process.type) } let(:developer) { make_developer_for_space(space) } before do set_current_user(developer) end it 'removes the association' do expect(process.reload.routes).to match_array([route]) delete "/v2/apps/#{process.app.guid}/routes/#{route.guid}" expect(last_response.status).to eq(204) expect(process.reload.routes).to be_empty end context 'when the app does not exist' do it 'returns 404' do delete "/v2/apps/not-found/routes/#{route.guid}" expect(last_response).to have_status_code(404) expect(last_response.body).to include('AppNotFound') end end context 'when the route does not exist' do it 'returns 404' do delete "/v2/apps/#{process.app.guid}/routes/not-found" expect(last_response).to have_status_code(404) expect(last_response.body).to include('RouteNotFound') end end context 'when the route is not mapped to the app' do before do route_mapping.destroy end it 'succeeds' do expect(process.reload.routes).to be_empty delete "/v2/apps/#{process.app.guid}/routes/#{route.guid}" expect(last_response).to have_status_code(204) end end context 'when the user is not a developer in the apps space' do before do set_current_user(User.make) end it 'returns 403' do delete "/v2/apps/#{process.app.guid}/routes/#{route.guid}" expect(last_response).to have_status_code(403) end end end describe 'GET /v2/apps/:app_guid/service_bindings' do let(:space) { Space.make } let(:managed_service_instance) { ManagedServiceInstance.make(space: space) } let(:developer) { make_developer_for_space(space) } let(:process1) { ProcessModelFactory.make(space: space, name: 'process1') } let(:process2) { ProcessModelFactory.make(space: space, name: 'process2') } let(:process3) { ProcessModelFactory.make(space: space, name: 'process3') } before do set_current_user(developer) ServiceBinding.make(service_instance: managed_service_instance, app: process1.app, name: 'guava') ServiceBinding.make(service_instance: managed_service_instance, app: process2.app, name: 'peach') ServiceBinding.make(service_instance: managed_service_instance, app: process3.app, name: 'cilantro') end it "queries apps' service_bindings by name" do # process1 has no peach bindings get "/v2/apps/#{process1.app.guid}/service_bindings?q=name:peach" expect(last_response.status).to eql(200), last_response.body service_bindings = decoded_response['resources'] expect(service_bindings.size).to eq(0) get "/v2/apps/#{process1.app.guid}/service_bindings?q=name:guava" expect(last_response.status).to eql(200), last_response.body service_bindings = decoded_response['resources'] expect(service_bindings.size).to eq(1) entity = service_bindings[0]['entity'] expect(entity['app_guid']).to eq(process1.app.guid) expect(entity['service_instance_guid']).to eq(managed_service_instance.guid) expect(entity['name']).to eq('guava') [[process1, 'guava'], [process2, 'peach'], [process3, 'cilantro']].each do |process, fruit| get "/v2/apps/#{process.app.guid}/service_bindings?q=name:#{fruit}" expect(last_response.status).to eql(200) service_bindings = decoded_response['resources'] expect(service_bindings.size).to eq(1) entity = service_bindings[0]['entity'] expect(entity['app_guid']).to eq(process.app.guid) expect(entity['service_instance_guid']).to eq(managed_service_instance.guid) expect(entity['name']).to eq(fruit) end end # This is why there isn't much point testing lookup by name with this endpoint -- # These tests show we can have at most one hit per name in the # apps/APPGUID/service_bindings endpoint. context 'when there are multiple services' do let(:si1) { ManagedServiceInstance.make(space: space) } let(:si2) { ManagedServiceInstance.make(space: space) } let(:developer) { make_developer_for_space(space) } let(:process1) { ProcessModelFactory.make(space: space, name: 'process1') } let(:process2) { ProcessModelFactory.make(space: space, name: 'process2') } before do set_current_user(developer) ServiceBinding.make(service_instance: si1, app: process1.app, name: 'out') ServiceBinding.make(service_instance: si2, app: process2.app, name: 'free') end it 'binding si2 to process1 with a name in use by process1 is not ok' do expect { ServiceBinding.make(service_instance: si2, app: process1.app, name: 'out') }.to raise_error(Sequel::ValidationFailed, /App binding names must be unique\./) end it 'binding si1 to process1 with a new name is not ok' do expect { ServiceBinding.make(service_instance: si1, app: process1.app, name: 'gravy') }.to raise_error(Sequel::ValidationFailed, 'The app is already bound to the service.') end it 'binding si2 to process1 with a name in use by process2 is ok' do ServiceBinding.make(service_instance: si2, app: process1.app, name: 'free') get "/v2/apps/#{process1.app.guid}/service_bindings?results-per-page=2&page=1&q=name:free" expect(last_response.status).to eq(200), last_response.body end end end describe 'DELETE /v2/apps/:app_guid/service_bindings/:service_binding_guid' do let(:space) { Space.make } let(:process) { ProcessModelFactory.make(space: space) } let(:instance) { ManagedServiceInstance.make(space: space) } let!(:service_binding) { ServiceBinding.make(app: process.app, service_instance: instance) } let(:developer) { make_developer_for_space(space) } before do set_current_user(developer) allow_any_instance_of(VCAP::Services::ServiceBrokers::V2::Client).to receive(:unbind).and_return({ async: false }) end it 'removes the association' do expect(process.reload.service_bindings).to match_array([service_binding]) delete "/v2/apps/#{process.app.guid}/service_bindings/#{service_binding.guid}" expect(last_response.status).to eq(204) expect(process.reload.service_bindings).to be_empty end it 'has the deprecated warning header' do delete "/v2/apps/not-found/service_bindings/#{service_binding.guid}" expect(last_response).to be_a_deprecated_response end context 'when the app does not exist' do it 'returns 404' do delete "/v2/apps/not-found/service_bindings/#{service_binding.guid}" expect(last_response).to have_status_code(404) expect(last_response.body).to include('AppNotFound') end end context 'when the service binding does not exist' do it 'returns 404' do delete "/v2/apps/#{process.app.guid}/service_bindings/not-found" expect(last_response).to have_status_code(404) expect(last_response.body).to include('ServiceBindingNotFound') end end context 'when the user is not a developer in the apps space' do before do set_current_user(User.make) end it 'returns 403' do delete "/v2/apps/#{process.app.guid}/service_bindings/#{service_binding.guid}" expect(last_response).to have_status_code(403) end end end describe 'GET /v2/apps/:guid/permissions' do let(:process) { ProcessModelFactory.make(space: space) } let(:space) { Space.make } let(:user) { User.make } before do space.organization.add_user(user) end context 'when the user is a SpaceDeveloper' do before do space.add_developer(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'succeeds and present data reading permissions' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(true) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when the user is a OrgManager' do before do process.organization.add_manager(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'succeeds and present data reading permissions' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(false) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when the user is a BillingManager' do before do space.organization.add_billing_manager(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'fails with a 403' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(403) expect(decoded_response['code']).to eq(10003) expect(decoded_response['error_code']).to eq('CF-NotAuthorized') expect(decoded_response['description']).to include('You are not authorized to perform the requested action') end end context 'when the user is a OrgAuditor' do before do space.organization.add_auditor(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'fails with a 403' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(403) expect(decoded_response['code']).to eq(10003) expect(decoded_response['error_code']).to eq('CF-NotAuthorized') expect(decoded_response['description']).to include('You are not authorized to perform the requested action') end end context 'when the user is a SpaceManager' do before do space.add_manager(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'succeeds and present data reading permissions' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(false) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when the user is a SpaceAuditor' do before do space.add_auditor(user) set_current_user(user, { scopes: ['cloud_controller.user'] }) end it 'succeeds and present data reading permissions' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(false) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when the user is a read-only admin' do before do set_current_user_as_admin_read_only end it 'returns 200' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(true) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when the user is a global auditor' do before do set_current_user_as_global_auditor end it 'returns 200 but false for sensitive data' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(200) expect(parsed_response['read_sensitive_data']).to eq(false) expect(parsed_response['read_basic_data']).to eq(true) end end context 'when missing cloud_controller.user scope' do let(:user) { make_developer_for_space(space) } before do set_current_user(user, { scopes: [] }) end it 'returns 403' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(403) end end context 'when the user is not part of the org or space' do before do new_user = User.make set_current_user(new_user) end it 'returns 403' do get "/v2/apps/#{process.app.guid}/permissions" expect(last_response.status).to eq(403) expect(decoded_response['code']).to eq(10003) expect(decoded_response['error_code']).to eq('CF-NotAuthorized') expect(decoded_response['description']).to include('You are not authorized to perform the requested action') end end context 'when the app does not exist' do it 'returns 404' do get '/v2/apps/made-up-guid/permissions' expect(last_response.status).to eq(404) end end end end end
37.782575
161
0.603247
7971b3090f5143b62056cf82339631d2ac6fa3f3
339
class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(contact_params) if @contact.valid? @contact.save else render action: 'new' end end private def contact_params params.require(:contact).permit(:email, :message) end end
16.142857
53
0.672566
1ad6f8a3cf2c3a52c2303e3a6ac6ec01748df7a8
35,106
describe :kernel_sprintf, shared: true do describe "integer formats" do it "converts argument into Integer with to_int" do obj = Object.new def obj.to_i; 10; end def obj.to_int; 10; end obj.should_receive(:to_int).and_return(10) @method.call("%b", obj).should == "1010" end it "converts argument into Integer with to_i if to_int isn't available" do obj = Object.new def obj.to_i; 10; end obj.should_receive(:to_i).and_return(10) @method.call("%b", obj).should == "1010" end it "converts String argument with Kernel#Integer" do @method.call("%d", "0b1010").should == "10" @method.call("%d", "112").should == "112" @method.call("%d", "0127").should == "87" @method.call("%d", "0xc4").should == "196" end it "raises TypeError exception if cannot convert to Integer" do -> { @method.call("%b", Object.new) }.should raise_error(TypeError) end ["b", "B"].each do |f| describe f do it "converts argument as a binary number" do @method.call("%#{f}", 10).should == "1010" end it "displays negative number as a two's complement prefixed with '..1'" do @method.call("%#{f}", -10).should == "..1" + "0110" end it "collapse negative number representation if it equals 1" do @method.call("%#{f}", -1).should_not == "..11" @method.call("%#{f}", -1).should == "..1" end end end ["d", "i", "u"].each do |f| describe f do it "converts argument as a decimal number" do @method.call("%#{f}", 112).should == "112" @method.call("%#{f}", -112).should == "-112" end it "works well with large numbers" do @method.call("%#{f}", 1234567890987654321).should == "1234567890987654321" end end end describe "o" do it "converts argument as an octal number" do @method.call("%o", 87).should == "127" end it "displays negative number as a two's complement prefixed with '..7'" do @method.call("%o", -87).should == "..7" + "651" end it "collapse negative number representation if it equals 7" do @method.call("%o", -1).should_not == "..77" @method.call("%o", -1).should == "..7" end end describe "x" do it "converts argument as a hexadecimal number" do @method.call("%x", 196).should == "c4" end it "displays negative number as a two's complement prefixed with '..f'" do @method.call("%x", -196).should == "..f" + "3c" end it "collapse negative number representation if it equals f" do @method.call("%x", -1).should_not == "..ff" @method.call("%x", -1).should == "..f" end end describe "X" do it "converts argument as a hexadecimal number with uppercase letters" do @method.call("%X", 196).should == "C4" end it "displays negative number as a two's complement prefixed with '..f'" do @method.call("%X", -196).should == "..F" + "3C" end it "collapse negative number representation if it equals F" do @method.call("%X", -1).should_not == "..FF" @method.call("%X", -1).should == "..F" end end end describe "float formats" do it "converts argument into Float" do obj = mock("float") obj.should_receive(:to_f).and_return(9.6) @method.call("%f", obj).should == "9.600000" end it "raises TypeError exception if cannot convert to Float" do -> { @method.call("%f", Object.new) }.should raise_error(TypeError) end {"e" => "e", "E" => "E"}.each_pair do |f, exp| describe f do it "converts argument into exponential notation [-]d.dddddde[+-]dd" do @method.call("%#{f}", 109.52).should == "1.095200#{exp}+02" @method.call("%#{f}", -109.52).should == "-1.095200#{exp}+02" @method.call("%#{f}", 0.10952).should == "1.095200#{exp}-01" @method.call("%#{f}", -0.10952).should == "-1.095200#{exp}-01" end it "cuts excessive digits and keeps only 6 ones" do @method.call("%#{f}", 1.123456789).should == "1.123457#{exp}+00" end it "rounds the last significant digit to the closest one" do @method.call("%#{f}", 1.555555555).should == "1.555556#{exp}+00" @method.call("%#{f}", -1.555555555).should == "-1.555556#{exp}+00" @method.call("%#{f}", 1.444444444).should == "1.444444#{exp}+00" end it "displays Float::INFINITY as Inf" do @method.call("%#{f}", Float::INFINITY).should == "Inf" @method.call("%#{f}", -Float::INFINITY).should == "-Inf" end it "displays Float::NAN as NaN" do @method.call("%#{f}", Float::NAN).should == "NaN" @method.call("%#{f}", -Float::NAN).should == "NaN" end end end describe "f" do it "converts floating point argument as [-]ddd.dddddd" do @method.call("%f", 10.952).should == "10.952000" @method.call("%f", -10.952).should == "-10.952000" end it "cuts excessive digits and keeps only 6 ones" do @method.call("%f", 1.123456789).should == "1.123457" end it "rounds the last significant digit to the closest one" do @method.call("%f", 1.555555555).should == "1.555556" @method.call("%f", -1.555555555).should == "-1.555556" @method.call("%f", 1.444444444).should == "1.444444" end it "displays Float::INFINITY as Inf" do @method.call("%f", Float::INFINITY).should == "Inf" @method.call("%f", -Float::INFINITY).should == "-Inf" end it "displays Float::NAN as NaN" do @method.call("%f", Float::NAN).should == "NaN" @method.call("%f", -Float::NAN).should == "NaN" end end {"g" => "e", "G" => "E"}.each_pair do |f, exp| describe f do context "the exponent is less than -4" do it "converts a floating point number using exponential form" do @method.call("%#{f}", 0.0000123456).should == "1.23456#{exp}-05" @method.call("%#{f}", -0.0000123456).should == "-1.23456#{exp}-05" @method.call("%#{f}", 0.000000000123456).should == "1.23456#{exp}-10" @method.call("%#{f}", -0.000000000123456).should == "-1.23456#{exp}-10" end end context "the exponent is greater than or equal to the precision (6 by default)" do it "converts a floating point number using exponential form" do @method.call("%#{f}", 1234567).should == "1.23457#{exp}+06" @method.call("%#{f}", 1234567890123).should == "1.23457#{exp}+12" @method.call("%#{f}", -1234567).should == "-1.23457#{exp}+06" end end context "otherwise" do it "converts a floating point number in dd.dddd form" do @method.call("%#{f}", 0.0001).should == "0.0001" @method.call("%#{f}", -0.0001).should == "-0.0001" @method.call("%#{f}", 123456).should == "123456" @method.call("%#{f}", -123456).should == "-123456" end it "cuts excessive digits in fractional part and keeps only 4 ones" do @method.call("%#{f}", 12.12341111).should == "12.1234" @method.call("%#{f}", -12.12341111).should == "-12.1234" end it "rounds the last significant digit to the closest one in fractional part" do @method.call("%#{f}", 1.555555555).should == "1.55556" @method.call("%#{f}", -1.555555555).should == "-1.55556" @method.call("%#{f}", 1.444444444).should == "1.44444" end it "cuts fraction part to have only 6 digits at all" do @method.call("%#{f}", 1.1234567).should == "1.12346" @method.call("%#{f}", 12.1234567).should == "12.1235" @method.call("%#{f}", 123.1234567).should == "123.123" @method.call("%#{f}", 1234.1234567).should == "1234.12" @method.call("%#{f}", 12345.1234567).should == "12345.1" @method.call("%#{f}", 123456.1234567).should == "123456" end end it "displays Float::INFINITY as Inf" do @method.call("%#{f}", Float::INFINITY).should == "Inf" @method.call("%#{f}", -Float::INFINITY).should == "-Inf" end it "displays Float::NAN as NaN" do @method.call("%#{f}", Float::NAN).should == "NaN" @method.call("%#{f}", -Float::NAN).should == "NaN" end end end describe "a" do it "converts floating point argument as [-]0xh.hhhhp[+-]dd" do @method.call("%a", 196).should == "0x1.88p+7" @method.call("%a", -196).should == "-0x1.88p+7" @method.call("%a", 196.1).should == "0x1.8833333333333p+7" @method.call("%a", 0.01).should == "0x1.47ae147ae147bp-7" @method.call("%a", -0.01).should == "-0x1.47ae147ae147bp-7" end it "displays Float::INFINITY as Inf" do @method.call("%a", Float::INFINITY).should == "Inf" @method.call("%a", -Float::INFINITY).should == "-Inf" end it "displays Float::NAN as NaN" do @method.call("%a", Float::NAN).should == "NaN" @method.call("%a", -Float::NAN).should == "NaN" end end describe "A" do it "converts floating point argument as [-]0xh.hhhhp[+-]dd and use uppercase X and P" do @method.call("%A", 196).should == "0X1.88P+7" @method.call("%A", -196).should == "-0X1.88P+7" @method.call("%A", 196.1).should == "0X1.8833333333333P+7" @method.call("%A", 0.01).should == "0X1.47AE147AE147BP-7" @method.call("%A", -0.01).should == "-0X1.47AE147AE147BP-7" end it "displays Float::INFINITY as Inf" do @method.call("%A", Float::INFINITY).should == "Inf" @method.call("%A", -Float::INFINITY).should == "-Inf" end it "displays Float::NAN as NaN" do @method.call("%A", Float::NAN).should == "NaN" @method.call("%A", -Float::NAN).should == "NaN" end end end describe "other formats" do describe "c" do it "displays character if argument is a numeric code of character" do @method.call("%c", 97).should == "a" end it "displays character if argument is a single character string" do @method.call("%c", "a").should == "a" end it "raises ArgumentError if argument is a string of several characters" do -> { @method.call("%c", "abc") }.should raise_error(ArgumentError) end it "raises ArgumentError if argument is an empty string" do -> { @method.call("%c", "") }.should raise_error(ArgumentError) end it "supports Unicode characters" do @method.call("%c", 1286).should == "Ԇ" @method.call("%c", "ش").should == "ش" end end describe "p" do it "displays argument.inspect value" do obj = mock("object") obj.should_receive(:inspect).and_return("<inspect-result>") @method.call("%p", obj).should == "<inspect-result>" end end describe "s" do it "substitute argument passes as a string" do @method.call("%s", "abc").should == "abc" end it "converts argument to string with to_s" do obj = mock("string") obj.should_receive(:to_s).and_return("abc") @method.call("%s", obj).should == "abc" end it "does not try to convert with to_str" do obj = BasicObject.new def obj.to_str "abc" end -> { @method.call("%s", obj) }.should raise_error(NoMethodError) end it "formats a partial substring without including omitted characters" do long_string = "aabbccddhelloddccbbaa" sub_string = long_string[8, 5] sprintf("%.#{1 * 3}s", sub_string).should == "hel" end end describe "%" do ruby_version_is ""..."2.5" do it "alone displays the percent sign" do @method.call("%").should == "%" end end ruby_version_is "2.5" do it "alone raises an ArgumentError" do -> { @method.call("%") }.should raise_error(ArgumentError) end end it "is escaped by %" do @method.call("%%").should == "%" @method.call("%%d", 10).should == "%d" end end end describe "flags" do describe "space" do context "applies to numeric formats bBdiouxXeEfgGaA" do it "leaves a space at the start of non-negative numbers" do @method.call("% b", 10).should == " 1010" @method.call("% B", 10).should == " 1010" @method.call("% d", 112).should == " 112" @method.call("% i", 112).should == " 112" @method.call("% o", 87).should == " 127" @method.call("% u", 112).should == " 112" @method.call("% x", 196).should == " c4" @method.call("% X", 196).should == " C4" @method.call("% e", 109.52).should == " 1.095200e+02" @method.call("% E", 109.52).should == " 1.095200E+02" @method.call("% f", 10.952).should == " 10.952000" @method.call("% g", 12.1234).should == " 12.1234" @method.call("% G", 12.1234).should == " 12.1234" @method.call("% a", 196).should == " 0x1.88p+7" @method.call("% A", 196).should == " 0X1.88P+7" end it "does not leave a space at the start of negative numbers" do @method.call("% b", -10).should == "-1010" @method.call("% B", -10).should == "-1010" @method.call("% d", -112).should == "-112" @method.call("% i", -112).should == "-112" @method.call("% o", -87).should == "-127" @method.call("% u", -112).should == "-112" @method.call("% x", -196).should == "-c4" @method.call("% X", -196).should == "-C4" @method.call("% e", -109.52).should == "-1.095200e+02" @method.call("% E", -109.52).should == "-1.095200E+02" @method.call("% f", -10.952).should == "-10.952000" @method.call("% g", -12.1234).should == "-12.1234" @method.call("% G", -12.1234).should == "-12.1234" @method.call("% a", -196).should == "-0x1.88p+7" @method.call("% A", -196).should == "-0X1.88P+7" end it "prevents converting negative argument to two's complement form" do @method.call("% b", -10).should == "-1010" @method.call("% B", -10).should == "-1010" @method.call("% o", -87).should == "-127" @method.call("% x", -196).should == "-c4" @method.call("% X", -196).should == "-C4" end it "treats several white spaces as one" do @method.call("% b", 10).should == " 1010" @method.call("% B", 10).should == " 1010" @method.call("% d", 112).should == " 112" @method.call("% i", 112).should == " 112" @method.call("% o", 87).should == " 127" @method.call("% u", 112).should == " 112" @method.call("% x", 196).should == " c4" @method.call("% X", 196).should == " C4" @method.call("% e", 109.52).should == " 1.095200e+02" @method.call("% E", 109.52).should == " 1.095200E+02" @method.call("% f", 10.952).should == " 10.952000" @method.call("% g", 12.1234).should == " 12.1234" @method.call("% G", 12.1234).should == " 12.1234" @method.call("% a", 196).should == " 0x1.88p+7" @method.call("% A", 196).should == " 0X1.88P+7" end end end describe "(digit)$" do it "specifies the absolute argument number for this field" do @method.call("%2$b", 0, 10).should == "1010" @method.call("%2$B", 0, 10).should == "1010" @method.call("%2$d", 0, 112).should == "112" @method.call("%2$i", 0, 112).should == "112" @method.call("%2$o", 0, 87).should == "127" @method.call("%2$u", 0, 112).should == "112" @method.call("%2$x", 0, 196).should == "c4" @method.call("%2$X", 0, 196).should == "C4" @method.call("%2$e", 0, 109.52).should == "1.095200e+02" @method.call("%2$E", 0, 109.52).should == "1.095200E+02" @method.call("%2$f", 0, 10.952).should == "10.952000" @method.call("%2$g", 0, 12.1234).should == "12.1234" @method.call("%2$G", 0, 12.1234).should == "12.1234" @method.call("%2$a", 0, 196).should == "0x1.88p+7" @method.call("%2$A", 0, 196).should == "0X1.88P+7" @method.call("%2$c", 1, 97).should == "a" @method.call("%2$p", "a", []).should == "[]" @method.call("%2$s", "-", "abc").should == "abc" end it "raises exception if argument number is bigger than actual arguments list" do -> { @method.call("%4$d", 1, 2, 3) }.should raise_error(ArgumentError) end it "ignores '-' sign" do @method.call("%2$d", 1, 2, 3).should == "2" @method.call("%-2$d", 1, 2, 3).should == "2" end it "raises ArgumentError exception when absolute and relative argument numbers are mixed" do -> { @method.call("%1$d %d", 1, 2) }.should raise_error(ArgumentError) end end describe "#" do context "applies to format o" do it "increases the precision until the first digit will be `0' if it is not formatted as complements" do @method.call("%#o", 87).should == "0127" end it "does nothing for negative argument" do @method.call("%#o", -87).should == "..7651" end end context "applies to formats bBxX" do it "prefixes the result with 0x, 0X, 0b and 0B respectively for non-zero argument" do @method.call("%#b", 10).should == "0b1010" @method.call("%#b", -10).should == "0b..10110" @method.call("%#B", 10).should == "0B1010" @method.call("%#B", -10).should == "0B..10110" @method.call("%#x", 196).should == "0xc4" @method.call("%#x", -196).should == "0x..f3c" @method.call("%#X", 196).should == "0XC4" @method.call("%#X", -196).should == "0X..F3C" end it "does nothing for zero argument" do @method.call("%#b", 0).should == "0" @method.call("%#B", 0).should == "0" @method.call("%#o", 0).should == "0" @method.call("%#x", 0).should == "0" @method.call("%#X", 0).should == "0" end end context "applies to formats aAeEfgG" do it "forces a decimal point to be added, even if no digits follow" do @method.call("%#.0a", 16.25).should == "0x1.p+4" @method.call("%#.0A", 16.25).should == "0X1.P+4" @method.call("%#.0e", 100).should == "1.e+02" @method.call("%#.0E", 100).should == "1.E+02" @method.call("%#.0f", 123.4).should == "123." @method.call("%#g", 123456).should == "123456." @method.call("%#G", 123456).should == "123456." end it "changes format from dd.dddd to exponential form for gG" do @method.call("%#.0g", 123.4).should_not == "123." @method.call("%#.0g", 123.4).should == "1.e+02" end end context "applies to gG" do it "does not remove trailing zeros" do @method.call("%#g", 123.4).should == "123.400" @method.call("%#g", 123.4).should == "123.400" end end end describe "+" do context "applies to numeric formats bBdiouxXaAeEfgG" do it "adds a leading plus sign to non-negative numbers" do @method.call("%+b", 10).should == "+1010" @method.call("%+B", 10).should == "+1010" @method.call("%+d", 112).should == "+112" @method.call("%+i", 112).should == "+112" @method.call("%+o", 87).should == "+127" @method.call("%+u", 112).should == "+112" @method.call("%+x", 196).should == "+c4" @method.call("%+X", 196).should == "+C4" @method.call("%+e", 109.52).should == "+1.095200e+02" @method.call("%+E", 109.52).should == "+1.095200E+02" @method.call("%+f", 10.952).should == "+10.952000" @method.call("%+g", 12.1234).should == "+12.1234" @method.call("%+G", 12.1234).should == "+12.1234" @method.call("%+a", 196).should == "+0x1.88p+7" @method.call("%+A", 196).should == "+0X1.88P+7" end it "does not use two's complement form for negative numbers for formats bBoxX" do @method.call("%+b", -10).should == "-1010" @method.call("%+B", -10).should == "-1010" @method.call("%+o", -87).should == "-127" @method.call("%+x", -196).should == "-c4" @method.call("%+X", -196).should == "-C4" end end end describe "-" do it "left-justifies the result of conversion if width is specified" do @method.call("%-10b", 10).should == "1010 " @method.call("%-10B", 10).should == "1010 " @method.call("%-10d", 112).should == "112 " @method.call("%-10i", 112).should == "112 " @method.call("%-10o", 87).should == "127 " @method.call("%-10u", 112).should == "112 " @method.call("%-10x", 196).should == "c4 " @method.call("%-10X", 196).should == "C4 " @method.call("%-20e", 109.52).should == "1.095200e+02 " @method.call("%-20E", 109.52).should == "1.095200E+02 " @method.call("%-20f", 10.952).should == "10.952000 " @method.call("%-20g", 12.1234).should == "12.1234 " @method.call("%-20G", 12.1234).should == "12.1234 " @method.call("%-20a", 196).should == "0x1.88p+7 " @method.call("%-20A", 196).should == "0X1.88P+7 " @method.call("%-10c", 97).should == "a " @method.call("%-10p", []).should == "[] " @method.call("%-10s", "abc").should == "abc " end end describe "0 (zero)" do context "applies to numeric formats bBdiouxXaAeEfgG and width is specified" do it "pads with zeros, not spaces" do @method.call("%010b", 10).should == "0000001010" @method.call("%010B", 10).should == "0000001010" @method.call("%010d", 112).should == "0000000112" @method.call("%010i", 112).should == "0000000112" @method.call("%010o", 87).should == "0000000127" @method.call("%010u", 112).should == "0000000112" @method.call("%010x", 196).should == "00000000c4" @method.call("%010X", 196).should == "00000000C4" @method.call("%020e", 109.52).should == "000000001.095200e+02" @method.call("%020E", 109.52).should == "000000001.095200E+02" @method.call("%020f", 10.952).should == "0000000000010.952000" @method.call("%020g", 12.1234).should == "000000000000012.1234" @method.call("%020G", 12.1234).should == "000000000000012.1234" @method.call("%020a", 196).should == "0x000000000001.88p+7" @method.call("%020A", 196).should == "0X000000000001.88P+7" end it "uses radix-1 when displays negative argument as a two's complement" do @method.call("%010b", -10).should == "..11110110" @method.call("%010B", -10).should == "..11110110" @method.call("%010o", -87).should == "..77777651" @method.call("%010x", -196).should == "..ffffff3c" @method.call("%010X", -196).should == "..FFFFFF3C" end end end describe "*" do it "uses the previous argument as the field width" do @method.call("%*b", 10, 10).should == " 1010" @method.call("%*B", 10, 10).should == " 1010" @method.call("%*d", 10, 112).should == " 112" @method.call("%*i", 10, 112).should == " 112" @method.call("%*o", 10, 87).should == " 127" @method.call("%*u", 10, 112).should == " 112" @method.call("%*x", 10, 196).should == " c4" @method.call("%*X", 10, 196).should == " C4" @method.call("%*e", 20, 109.52).should == " 1.095200e+02" @method.call("%*E", 20, 109.52).should == " 1.095200E+02" @method.call("%*f", 20, 10.952).should == " 10.952000" @method.call("%*g", 20, 12.1234).should == " 12.1234" @method.call("%*G", 20, 12.1234).should == " 12.1234" @method.call("%*a", 20, 196).should == " 0x1.88p+7" @method.call("%*A", 20, 196).should == " 0X1.88P+7" @method.call("%*c", 10, 97).should == " a" @method.call("%*p", 10, []).should == " []" @method.call("%*s", 10, "abc").should == " abc" end it "left-justifies the result if width is negative" do @method.call("%*b", -10, 10).should == "1010 " @method.call("%*B", -10, 10).should == "1010 " @method.call("%*d", -10, 112).should == "112 " @method.call("%*i", -10, 112).should == "112 " @method.call("%*o", -10, 87).should == "127 " @method.call("%*u", -10, 112).should == "112 " @method.call("%*x", -10, 196).should == "c4 " @method.call("%*X", -10, 196).should == "C4 " @method.call("%*e", -20, 109.52).should == "1.095200e+02 " @method.call("%*E", -20, 109.52).should == "1.095200E+02 " @method.call("%*f", -20, 10.952).should == "10.952000 " @method.call("%*g", -20, 12.1234).should == "12.1234 " @method.call("%*G", -20, 12.1234).should == "12.1234 " @method.call("%*a", -20, 196).should == "0x1.88p+7 " @method.call("%*A", -20, 196).should == "0X1.88P+7 " @method.call("%*c", -10, 97).should == "a " @method.call("%*p", -10, []).should == "[] " @method.call("%*s", -10, "abc").should == "abc " end it "uses the specified argument as the width if * is followed by a number and $" do @method.call("%1$*2$b", 10, 10).should == " 1010" @method.call("%1$*2$B", 10, 10).should == " 1010" @method.call("%1$*2$d", 112, 10).should == " 112" @method.call("%1$*2$i", 112, 10).should == " 112" @method.call("%1$*2$o", 87, 10).should == " 127" @method.call("%1$*2$u", 112, 10).should == " 112" @method.call("%1$*2$x", 196, 10).should == " c4" @method.call("%1$*2$X", 196, 10).should == " C4" @method.call("%1$*2$e", 109.52, 20).should == " 1.095200e+02" @method.call("%1$*2$E", 109.52, 20).should == " 1.095200E+02" @method.call("%1$*2$f", 10.952, 20).should == " 10.952000" @method.call("%1$*2$g", 12.1234, 20).should == " 12.1234" @method.call("%1$*2$G", 12.1234, 20).should == " 12.1234" @method.call("%1$*2$a", 196, 20).should == " 0x1.88p+7" @method.call("%1$*2$A", 196, 20).should == " 0X1.88P+7" @method.call("%1$*2$c", 97, 10).should == " a" @method.call("%1$*2$p", [], 10).should == " []" @method.call("%1$*2$s", "abc", 10).should == " abc" end it "left-justifies the result if specified with $ argument is negative" do @method.call("%1$*2$b", 10, -10).should == "1010 " @method.call("%1$*2$B", 10, -10).should == "1010 " @method.call("%1$*2$d", 112, -10).should == "112 " @method.call("%1$*2$i", 112, -10).should == "112 " @method.call("%1$*2$o", 87, -10).should == "127 " @method.call("%1$*2$u", 112, -10).should == "112 " @method.call("%1$*2$x", 196, -10).should == "c4 " @method.call("%1$*2$X", 196, -10).should == "C4 " @method.call("%1$*2$e", 109.52, -20).should == "1.095200e+02 " @method.call("%1$*2$E", 109.52, -20).should == "1.095200E+02 " @method.call("%1$*2$f", 10.952, -20).should == "10.952000 " @method.call("%1$*2$g", 12.1234, -20).should == "12.1234 " @method.call("%1$*2$G", 12.1234, -20).should == "12.1234 " @method.call("%1$*2$a", 196, -20).should == "0x1.88p+7 " @method.call("%1$*2$A", 196, -20).should == "0X1.88P+7 " @method.call("%1$*2$c", 97, -10).should == "a " @method.call("%1$*2$p", [], -10).should == "[] " @method.call("%1$*2$s", "abc", -10).should == "abc " end it "raises ArgumentError when is mixed with width" do -> { @method.call("%*10d", 10, 112) }.should raise_error(ArgumentError) end end end describe "width" do it "specifies the minimum number of characters that will be written to the result" do @method.call("%10b", 10).should == " 1010" @method.call("%10B", 10).should == " 1010" @method.call("%10d", 112).should == " 112" @method.call("%10i", 112).should == " 112" @method.call("%10o", 87).should == " 127" @method.call("%10u", 112).should == " 112" @method.call("%10x", 196).should == " c4" @method.call("%10X", 196).should == " C4" @method.call("%20e", 109.52).should == " 1.095200e+02" @method.call("%20E", 109.52).should == " 1.095200E+02" @method.call("%20f", 10.952).should == " 10.952000" @method.call("%20g", 12.1234).should == " 12.1234" @method.call("%20G", 12.1234).should == " 12.1234" @method.call("%20a", 196).should == " 0x1.88p+7" @method.call("%20A", 196).should == " 0X1.88P+7" @method.call("%10c", 97).should == " a" @method.call("%10p", []).should == " []" @method.call("%10s", "abc").should == " abc" end it "is ignored if argument's actual length is greater" do @method.call("%5d", 1234567890).should == "1234567890" end end describe "precision" do context "integer types" do it "controls the number of decimal places displayed" do @method.call("%.6b", 10).should == "001010" @method.call("%.6B", 10).should == "001010" @method.call("%.5d", 112).should == "00112" @method.call("%.5i", 112).should == "00112" @method.call("%.5o", 87).should == "00127" @method.call("%.5u", 112).should == "00112" @method.call("%.5x", 196).should == "000c4" @method.call("%.5X", 196).should == "000C4" end end context "float types" do it "controls the number of decimal places displayed in fraction part" do @method.call("%.10e", 109.52).should == "1.0952000000e+02" @method.call("%.10E", 109.52).should == "1.0952000000E+02" @method.call("%.10f", 10.952).should == "10.9520000000" @method.call("%.10a", 196).should == "0x1.8800000000p+7" @method.call("%.10A", 196).should == "0X1.8800000000P+7" end it "does not affect G format" do @method.call("%.10g", 12.1234).should == "12.1234" @method.call("%.10g", 123456789).should == "123456789" end end context "string formats" do it "determines the maximum number of characters to be copied from the string" do @method.call("%.1p", [1]).should == "[" @method.call("%.2p", [1]).should == "[1" @method.call("%.10p", [1]).should == "[1]" @method.call("%.0p", [1]).should == "" @method.call("%.1s", "abc").should == "a" @method.call("%.2s", "abc").should == "ab" @method.call("%.10s", "abc").should == "abc" @method.call("%.0s", "abc").should == "" end end end describe "reference by name" do describe "%<name>s style" do it "uses value passed in a hash argument" do @method.call("%<foo>d", foo: 123).should == "123" end it "supports flags, width, precision and type" do @method.call("%+20.10<foo>f", foo: 10.952).should == " +10.9520000000" end it "allows to place name in any position" do @method.call("%+15.5<foo>f", foo: 10.952).should == " +10.95200" @method.call("%+15<foo>.5f", foo: 10.952).should == " +10.95200" @method.call("%+<foo>15.5f", foo: 10.952).should == " +10.95200" @method.call("%<foo>+15.5f", foo: 10.952).should == " +10.95200" end it "cannot be mixed with unnamed style" do -> { @method.call("%d %<foo>d", 1, foo: "123") }.should raise_error(ArgumentError) end end describe "%{name} style" do it "uses value passed in a hash argument" do @method.call("%{foo}", foo: 123).should == "123" end it "does not support type style" do @method.call("%{foo}d", foo: 123).should == "123d" end it "supports flags, width and precision" do @method.call("%-20.5{foo}", foo: "123456789").should == "12345 " end it "cannot be mixed with unnamed style" do -> { @method.call("%d %{foo}", 1, foo: "123") }.should raise_error(ArgumentError) end it "raises KeyError when there is no matching key" do -> { @method.call("%{foo}", {}) }.should raise_error(KeyError) end it "converts value to String with to_s" do obj = Object.new def obj.to_s; end def obj.to_str; end obj.should_receive(:to_s).and_return("42") obj.should_not_receive(:to_str) @method.call("%{foo}", foo: obj).should == "42" end end end describe "faulty key" do before :each do @object = { foooo: 1 } end it "raises a KeyError" do -> { @method.call("%<foo>s", @object) }.should raise_error(KeyError) end ruby_version_is "2.5" do it "sets the Hash as the receiver of KeyError" do -> { @method.call("%<foo>s", @object) }.should raise_error(KeyError) { |err| err.receiver.should equal(@object) } end it "sets the unmatched key as the key of KeyError" do -> { @method.call("%<foo>s", @object) }.should raise_error(KeyError) { |err| err.key.to_s.should == 'foo' } end end end end
39.093541
111
0.507919
f784792878e718a142bb7948ee97c21aad538789
3,024
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Purpose # # Shows how to configure cross-origin resource sharing (CORS) rules for an # Amazon Simple Storage Service (Amazon S3) bucket. # snippet-start:[ruby.example_code.s3.helper.BucketCorsWrapper] require 'aws-sdk-s3' # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # snippet-end:[ruby.example_code.s3.helper.BucketCorsWrapper] # snippet-start:[ruby.example_code.s3.GetBucketCors] # Gets the CORS configuration of a bucket. # # @return [Aws::S3::Type::GetBucketCorsOutput, nil] The current CORS configuration for the bucket. def get_cors @bucket_cors.data rescue StandardError => e puts "Couldn't get CORS configuration for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" nil end # snippet-end:[ruby.example_code.s3.GetBucketCors] # snippet-start:[ruby.example_code.s3.PutBucketCors] # Sets CORS rules on a bucket. # # @param allowed_methods [Array<String>] The types of HTTP requests to allow. # @param allowed_origins [Array<String>] The origins to allow. # @returns [Boolean] True if the CORS rules were set; otherwise, false. def set_cors(allowed_methods, allowed_origins) @bucket_cors.put( cors_configuration: { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: allowed_origins, allowed_headers: %w[*], max_age_seconds: 3600 } ] } ) true rescue StandardError => e puts "Couldn't set CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end # snippet-end:[ruby.example_code.s3.PutBucketCors] # snippet-start:[ruby.example_code.s3.DeleteBucketCors] # Deletes the CORS configuration of a bucket. # # @return [Boolean] True if the CORS rules were deleted; otherwise, false. def delete_cors @bucket_cors.delete true rescue StandardError => e puts "Couldn't delete CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end # snippet-end:[ruby.example_code.s3.DeleteBucketCors] # snippet-start:[ruby.example_code.s3.helper.end.BucketCorsWrapper] end # snippet-end:[ruby.example_code.s3.helper.end.BucketCorsWrapper] def run_demo bucket_name = 'doc-example-bucket' allowed_methods = %w[GET PUT] allowed_origins = %w[http://www.example.com] wrapper = BucketCorsWrapper.new(Aws::S3::BucketCors.new(bucket_name)) return unless wrapper.set_cors(allowed_methods, allowed_origins) puts "Successfully set CORS rules on #{bucket_name}. The rules are:" puts wrapper.get_cors return unless wrapper.delete_cors puts "Successfully deleted CORS rules from #{bucket_name}." end run_demo if $PROGRAM_NAME == __FILE__
32.869565
101
0.72123
ac9e08c5f90736c40b644fab0b0031bbd613b46b
1,103
module SpreeAffiliateLinks module Generators class InstallGenerator < Rails::Generators::Base def add_javascripts append_file 'app/assets/javascripts/store/all.js', "//= require store/spree_affiliate_links\n" append_file 'app/assets/javascripts/admin/all.js', "//= require admin/spree_affiliate_links\n" end def add_stylesheets inject_into_file 'app/assets/stylesheets/store/all.css', " *= require store/spree_affiliate_links\n", :before => /\*\//, :verbose => true inject_into_file 'app/assets/stylesheets/admin/all.css', " *= require admin/spree_affiliate_links\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_affiliate_links' end def run_migrations res = ask 'Would you like to run the migrations now? [Y/n]' if res == '' || res.downcase == 'y' run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
36.766667
145
0.650952
39734f91226b9be7c93a8135bb18397c2c0d27f2
947
require "piston/commands/base" module Piston module Commands class Convert < Piston::Commands::Base attr_reader :options def run(targets) targets = Array.new unless targets wc = Piston::Svn::WorkingCopy.new(Dir.pwd) importer = Piston::Commands::Import.new(options) returning(Array.new) do |conversions| wc.externals.each_pair do |dir, args| next unless targets.empty? || targets.detect {|target| dir.to_s.include?(target.to_s) } conversions << dir logger.info "Importing #{dir.relative_path_from(wc.path)} from #{args[:url]}" importer.run(args[:url], args[:revision], dir) end wc.remove_external_references(*targets) end end def start(*args) targets = args.flatten.map {|d| Pathname.new(d).expand_path} run(targets) puts "#{targets.length} directories converted" end end end end
28.69697
99
0.630412
117270a3d1604794eeaaaee01bfd5f7f37771153
41,449
# frozen_string_literal: true require 'spec_helper' EXT_PREFIXES = %w[ext ex x xt # :].freeze describe PhonyRails do it 'should not pollute the global namespace with a Country class' do should_not be_const_defined 'Country' end describe 'phony_format String extension' do describe 'the phony_formatted method' do it 'does not modify the original options Hash' do options = { normalize: :NL, format: :international } '0101234123'.phony_formatted(options) expect(options).to eql(normalize: :NL, format: :international) end describe 'with the bang!' do it 'changes the String using the bang method' do # Mutable String s = +'0101234123' rescue '0101234123' expect(s.phony_formatted!(normalize: :NL, format: :international)).to eql('+31 10 123 4123') expect(s).to eql('+31 10 123 4123') end end describe 'with strict option' do it 'returns nil with non plausible number' do number = '+319090' # not valid expect(Phony.plausible?(number)).to be false expect(number.phony_formatted(strict: true)).to eql(nil) end it 'should not return nil with plausible number' do number = '+31101234123' # valid expect(Phony.plausible?(number)).to be true expect(number.phony_formatted(strict: true)).to_not eql(nil) end end describe 'with normalize option' do it 'should phony_format' do expect('101234123'.phony_formatted(normalize: :NL)).to eql('010 123 4123') expect('101234123'.phony_formatted(normalize: :NL, format: :international)).to eql('+31 10 123 4123') end it 'should not change original String' do s = '0101234123' expect(s.phony_formatted(normalize: :NL)).to eql('010 123 4123') expect(s).to eql('0101234123') end it 'should phony_format String with country code' do expect('31101234123'.phony_formatted(normalize: :NL)).to eql('010 123 4123') end it 'should phony_format String with country code' do expect('31101234123'.phony_formatted(normalize: :NL)).to eql('010 123 4123') end it 'should accept strings with non-digits in it' do expect('+31-10-1234123'.phony_formatted(normalize: :NL, format: :international, spaces: '-')).to eql('+31-10-123-4123') end it 'should phony_format String with country code different than normalized value' do expect('+4790909090'.phony_formatted(normalize: :SE, format: :international)).to eql('+47 909 09 090') end end describe 'with raise option' do # https://github.com/joost/phony_rails/issues/79 context 'when raise is true' do it 'should raise the error' do expect(lambda do '8887716095'.phony_formatted(format: :international, raise: true) end).to raise_error(Phony::FormattingError) end end context 'when raise is false (default)' do it 'returns original String on exception' do expect('8887716095'.phony_formatted(format: :international)).to eq('8887716095') end end end describe 'with extensions' do EXT_PREFIXES.each do |prefix| it "should format number with #{prefix} extension" do expect("+319090#{prefix}123".phony_formatted(strict: true)).to eql(nil) expect("101234123#{prefix}123".phony_formatted(normalize: :NL)).to eql('010 123 4123 x123') expect("101234123#{prefix}123".phony_formatted(normalize: :NL, format: :international)).to eql('+31 10 123 4123 x123') expect("31101234123#{prefix}123".phony_formatted(normalize: :NL)).to eql('010 123 4123 x123') expect("8887716095#{prefix}123".phony_formatted(format: :international, normalize: 'US', raise: true)).to eq('+1 (888) 771-6095 x123') expect("+12145551212#{prefix}123".phony_formatted).to eq('(214) 555-1212 x123') end end end describe 'specific tests from issues' do # https://github.com/joost/phony_rails/issues/79 it 'should pass Github issue #42' do expect('8887716095'.phony_formatted(format: :international, normalize: 'US', raise: true)).to eq('+1 (888) 771-6095') end # https://github.com/joost/phony_rails/issues/42 it 'should pass Github issue #42' do expect(PhonyRails.normalize_number('0606060606', default_country_code: 'FR')).to eq('+33606060606') end it 'should pass Github issue #85' do expect(PhonyRails.normalize_number('47386160', default_country_code: 'NO')).to eq('+4747386160') expect(PhonyRails.normalize_number('47386160', country_number: '47')).to eq('+4747386160') end it 'should pass Github issue #87' do expect(PhonyRails.normalize_number('2318725305', country_code: 'US')).to eq('+12318725305') expect(PhonyRails.normalize_number('2318725305', default_country_code: 'US')).to eq('+12318725305') expect(PhonyRails.normalize_number('+2318725305', default_country_code: 'US')).to eq('+2318725305') # expect(Phony.plausible?("#{PhonyRails.country_number_for('US')}02318725305")).to be_truthy expect(PhonyRails.normalize_number('02318725305', default_country_code: 'US')).to eq('+12318725305') end it 'should pass Github issue #89' do number = '+33 (0)6 87 36 18 75' expect(Phony.plausible?(number)).to be true expect(PhonyRails.normalize_number(number, country_code: 'FR')).to eq('+33687361875') end it 'should pass Github issue #90' do number = '(0)30 1234 123' expect(number.phony_normalized(country_code: 'NL')).to eq('+31301234123') end it 'should pass Github issue #107' do number = '04575700834' expect(number.phony_normalized(country_code: 'FI')).to eq('+3584575700834') # Seems this number can be interpreted as from multiple countries, following fails: # expect(number.phony_normalized(default_country_code: 'FI')).to eq('+3584575700834') # expect("04575700834".phony_formatted(normalize: 'FI', format: :international)).to eql('+358 45 757 00 834') end it 'should pass Github issue #113' do number = '(951) 703-593' expect(lambda do number.phony_formatted!(normalize: 'US', spaces: '-', strict: true) end).to raise_error(ArgumentError) end it 'should pass Github issue #95' do number = '02031234567' expect(number.phony_normalized(default_country_code: 'GB')).to eq('+442031234567') end it 'should pass Github issue #121' do number = '06-87-73-83-58' expect(number.phony_normalized(default_country_code: 'FR')).to eq('+33687738358') end it 'returns the original input if all goes wrong' do expect(Phony).to receive(:plausible?).and_raise('unexpected error') number = '(0)30 1234 123' expect(number.phony_normalized(country_code: 'NL')).to eq number end it 'should pass Github issue #126 (country_code)' do phone = '0143590213' # A plausible FR number phone = PhonyRails.normalize_number(phone, country_code: 'FR') expect(phone).to eq('+33143590213') expect(Phony.plausible?(phone)).to be_truthy phone = PhonyRails.normalize_number(phone, country_code: 'FR') expect(phone).to eq('+33143590213') end # Adding a country code is expected behavior when a # number is nog plausible. it 'should pass Github issue #126 (country_code) (intended)' do phone = '06123456789' # A non-plausible FR number phone = PhonyRails.normalize_number(phone, country_code: 'FR') expect(phone).to eq('+336123456789') expect(Phony.plausible?(phone)).to be_falsy phone = PhonyRails.normalize_number(phone, country_code: 'FR') expect(phone).to eq('+33336123456789') end it 'should pass Github issue #126 (default_country_code)' do phone = '06123456789' # French phone numbers have to be 10 chars long phone = PhonyRails.normalize_number(phone, default_country_code: 'FR') expect(phone).to eq('+336123456789') phone = PhonyRails.normalize_number(phone, default_country_code: 'FR') expect(phone).to eq('+336123456789') end it 'should pass Github issue #92 (invalid number with normalization)' do ActiveRecord::Schema.define do create_table :normal_homes do |table| table.column :phone_number, :string end end # rubocop:disable Lint/ConstantDefinitionInBlock class NormalHome < ActiveRecord::Base attr_accessor :phone_number phony_normalize :phone_number, default_country_code: 'US' validates :phone_number, phony_plausible: true end # rubocop:enable Lint/ConstantDefinitionInBlock normal = NormalHome.new normal.phone_number = 'HAHA' expect(normal).to_not be_valid expect(normal.phone_number).to eq('HAHA') expect(normal.errors.messages.to_hash).to include(phone_number: ['is an invalid number']) end it 'should pass Github issue #170' do phone = '(+49) 175 123 4567' phone = PhonyRails.normalize_number(phone) expect(phone).to eq('+491751234567') end it 'should pass Github issue #170 (part 2)' do phone = '(+49) 175 123 4567' phone = PhonyRails.normalize_number(phone, default_country_code: 'DE') expect(phone).to eq('+491751234567') end it 'should pass Github issue #175' do phone = '0041 23456789' phone = PhonyRails.normalize_number(phone, default_country_code: 'DE') expect(phone).to eq('+4123456789') end it 'should pass Github issue #175' do phone = '+1 260-437-9123' phone = PhonyRails.normalize_number(phone, default_country_code: 'DE') expect(phone).to eq('+12604379123') end it 'should pass Github issue #187' do phone1 = '0037253400030' phone1 = PhonyRails.normalize_number(phone1, default_country_code: 'EE') expect(phone1).to eq('+37253400030') phone2 = '0037275016183' phone2 = PhonyRails.normalize_number(phone2, default_country_code: 'EE') expect(phone2).to eq('+37275016183') end it 'should pass Github issue #180' do phone = '5555555555' phone = PhonyRails.normalize_number(phone, default_country_code: 'AU') expect(phone).to eq('+615555555555') phone = PhonyRails.normalize_number(phone, default_country_code: 'AU') expect(phone).to eq('+615555555555') end end it 'should not change original String' do s = '0101234123' expect(s.phony_formatted(normalize: :NL)).to eql('010 123 4123') expect(s).to eql('0101234123') end it 'should phony_format a digits string with spaces String' do expect('31 10 1234123'.phony_formatted(format: :international, spaces: '-')).to eql('+31-10-123-4123') end it 'should phony_format a digits String' do expect('31101234123'.phony_formatted(format: :international, spaces: '-')).to eql('+31-10-123-4123') end it 'returns nil if implausible phone' do expect('this is not a phone'.phony_formatted).to be_nil end it 'returns nil on blank string' do expect(''.phony_formatted).to be_nil end end describe 'the phony_normalized method' do it 'returns blank on blank string' do expect(''.phony_normalized).to be_nil end it 'should not modify the original options Hash' do options = { normalize: :NL, format: :international } '0101234123'.phony_normalized(options) expect(options).to eql(normalize: :NL, format: :international) end context 'when String misses a country_code' do it 'should normalize with :country_code option' do expect('010 1231234'.phony_normalized(country_code: :NL)).to eql('+31101231234') end it 'should normalize without :country_code option' do expect('010 1231234'.phony_normalized).to eql('101231234') end it 'should normalize with :add_plus option' do expect('010 1231234'.phony_normalized(country_code: :NL, add_plus: false)).to eql('31101231234') end end it 'should normalize with :add_plus option' do expect('+31 (0)10 1231234'.phony_normalized(add_plus: false)).to eql('31101231234') end it 'should normalize a String' do expect('+31 (0)10 1231234'.phony_normalized).to eql('+31101231234') end end end describe 'PhonyRails#normalize_number' do context 'number with a country code' do it 'should not add default_country_code' do expect(PhonyRails.normalize_number('+4790909090', default_country_code: 'SE')).to eql('+4790909090') # SE = +46 expect(PhonyRails.normalize_number('004790909090', default_country_code: 'SE')).to eql('+4790909090') expect(PhonyRails.normalize_number('4790909090', default_country_code: 'NO')).to eql('+4790909090') # NO = +47 end it 'should force add country_code' do expect(PhonyRails.normalize_number('+4790909090', country_code: 'SE')).to eql('+464790909090') expect(PhonyRails.normalize_number('004790909090', country_code: 'SE')).to eql('+4604790909090') # FIXME: differs due to Phony.normalize in v2.7.1?! expect(PhonyRails.normalize_number('4790909090', country_code: 'SE')).to eql('+464790909090') end it 'should recognize lowercase country codes' do expect(PhonyRails.normalize_number('4790909090', country_code: 'se')).to eql('+464790909090') end end context 'number without a country code' do it 'should normalize with a default_country_code' do expect(PhonyRails.normalize_number('010-1234123', default_country_code: 'NL')).to eql('+31101234123') end it 'should normalize with a country_code' do expect(PhonyRails.normalize_number('010-1234123', country_code: 'NL', default_country_code: 'DE')).to eql('+31101234123') expect(PhonyRails.normalize_number('010-1234123', country_code: 'NL')).to eql('+31101234123') end it 'should handle different countries' do expect(PhonyRails.normalize_number('(030) 8 61 29 06', country_code: 'DE')).to eql('+49308612906') expect(PhonyRails.normalize_number('0203 330 8897', country_code: 'GB')).to eql('+442033308897') end it 'should prefer country_code over default_country_code' do expect(PhonyRails.normalize_number('(030) 8 61 29 06', country_code: 'DE', default_country_code: 'NL')).to eql('+49308612906') end it 'should recognize lowercase country codes' do expect(PhonyRails.normalize_number('010-1234123', country_code: 'nl')).to eql('+31101234123') end end context 'number with an extension' do EXT_PREFIXES.each do |prefix| it "should handle some edge cases (with country_code) and #{prefix} extension" do expect(PhonyRails.normalize_number("some nasty stuff in this +31 number 10-1234123 string #{prefix}123", country_code: 'NL')).to eql('+31101234123 x123') expect(PhonyRails.normalize_number("070-4157134#{prefix}123", country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("0031-70-4157134#{prefix}123", country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("+31-70-4157134#{prefix}123", country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("0322-69497#{prefix}123", country_code: 'BE')).to eql('+3232269497 x123') expect(PhonyRails.normalize_number("+32 3 226 94 97#{prefix}123", country_code: 'BE')).to eql('+3232269497 x123') expect(PhonyRails.normalize_number("0450 764 000#{prefix}123", country_code: 'AU')).to eql('+61450764000 x123') end it "should handle some edge cases (with default_country_code) and #{prefix}" do expect(PhonyRails.normalize_number("some nasty stuff in this +31 number 10-1234123 string #{prefix}123", country_code: 'NL')).to eql('+31101234123 x123') expect(PhonyRails.normalize_number("070-4157134#{prefix}123", default_country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("0031-70-4157134#{prefix}123", default_country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("+31-70-4157134#{prefix}123", default_country_code: 'NL')).to eql('+31704157134 x123') expect(PhonyRails.normalize_number("0322-69497#{prefix}123", default_country_code: 'BE')).to eql('+3232269497 x123') expect(PhonyRails.normalize_number("+32 3 226 94 97#{prefix}123", default_country_code: 'BE')).to eql('+3232269497 x123') expect(PhonyRails.normalize_number("0450 764 000#{prefix}123", default_country_code: 'AU')).to eql('+61450764000 x123') end it "should remove #{prefix} extension (with extension: false)" do expect(PhonyRails.normalize_number("0031-70-4157134#{prefix}123", extension: false, country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number("+31-70-4157134#{prefix}123", extension: false, country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number("0322-69497#{prefix}123", extension: false, country_code: 'BE')).to eql('+3232269497') end end end it 'should handle some edge cases (with country_code)' do expect(PhonyRails.normalize_number('some nasty stuff in this +31 number 10-1234123 string', country_code: 'NL')).to eql('+31101234123') expect(PhonyRails.normalize_number('070-4157134', country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('0031-70-4157134', country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('+31-70-4157134', country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('0322-69497', country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('+32 3 226 94 97', country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('0450 764 000', country_code: 'AU')).to eql('+61450764000') end it 'should handle some edge cases (with default_country_code)' do expect(PhonyRails.normalize_number('some nasty stuff in this +31 number 10-1234123 string', country_code: 'NL')).to eql('+31101234123') expect(PhonyRails.normalize_number('070-4157134', default_country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('0031-70-4157134', default_country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('+31-70-4157134', default_country_code: 'NL')).to eql('+31704157134') expect(PhonyRails.normalize_number('0322-69497', default_country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('+32 3 226 94 97', default_country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('0450 764 000', default_country_code: 'AU')).to eql('+61450764000') end it 'should normalize even an implausible number' do expect(PhonyRails.normalize_number('01')).to eql('1') end context 'with default_country_code set' do before { PhonyRails.default_country_code = 'NL' } after { PhonyRails.default_country_code = nil } it 'normalize using the default' do expect(PhonyRails.normalize_number('010-1234123')).to eql('+31101234123') expect(PhonyRails.normalize_number('010-1234123')).to eql('+31101234123') expect(PhonyRails.normalize_number('070-4157134')).to eql('+31704157134') expect(PhonyRails.normalize_number('0031-70-4157134')).to eql('+31704157134') expect(PhonyRails.normalize_number('+31-70-4157134')).to eql('+31704157134') end it 'allows default_country_code to be overridden' do expect(PhonyRails.normalize_number('0322-69497', country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('+32 3 226 94 97', country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('0450 764 000', country_code: 'AU')).to eql('+61450764000') expect(PhonyRails.normalize_number('0322-69497', default_country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('+32 3 226 94 97', default_country_code: 'BE')).to eql('+3232269497') expect(PhonyRails.normalize_number('0450 764 000', default_country_code: 'AU')).to eql('+61450764000') end end end describe 'PhonyRails.plausible_number?' do subject { described_class } let(:valid_number) { '1 555 555 5555' } let(:invalid_number) { '123456789 123456789 123456789 123456789' } let(:another_invalid_number) { '441212' } let(:normalizable_number) { '555 555 5555' } let(:formatted_french_number_with_country_code) { '+33 627899541' } let(:empty_number) { '' } let(:nil_number) { nil } it 'returns true for a valid number' do is_expected.to be_plausible_number valid_number, country_code: 'US' end it 'returns false for an invalid numbers' do is_expected.not_to be_plausible_number invalid_number is_expected.not_to be_plausible_number invalid_number, country_code: 'US' is_expected.not_to be_plausible_number another_invalid_number is_expected.not_to be_plausible_number another_invalid_number, country_code: 'US' end it 'returns true for a normalizable number' do is_expected.to be_plausible_number normalizable_number, country_code: 'US' end it 'returns false for a valid number with the wrong country code' do is_expected.not_to be_plausible_number normalizable_number, country_code: 'FR' end it 'returns true for a well formatted valid number' do is_expected.to be_plausible_number formatted_french_number_with_country_code, country_code: 'FR' end it 'returns false for an empty number' do is_expected.not_to be_plausible_number empty_number, country_code: 'US' end it 'returns false for a nil number' do is_expected.not_to be_plausible_number nil_number, country_code: 'US' end it 'returns false when no country code is supplied' do is_expected.not_to be_plausible_number normalizable_number end it 'returns false if something goes wrong' do expect(Phony).to receive(:plausible?).twice.and_raise('unexpected error') is_expected.not_to be_plausible_number normalizable_number, country_code: 'US' end it 'should pass Github issue #95' do is_expected.to be_plausible_number '+358414955444', default_country_code: :de end context 'with default_country_code set' do before { PhonyRails.default_country_code = 'FR' } after { PhonyRails.default_country_code = nil } it 'uses the default' do is_expected.not_to be_plausible_number normalizable_number is_expected.to be_plausible_number formatted_french_number_with_country_code end it 'allows default_country_code to be overridden' do is_expected.not_to be_plausible_number empty_number, country_code: 'US' is_expected.not_to be_plausible_number nil_number, country_code: 'US' end end end describe 'PhonyRails.default_country' do before { PhonyRails.default_country_code = 'US' } after { PhonyRails.default_country_code = nil } it 'can set a global default country code' do expect(PhonyRails.default_country_code).to eq 'US' end it 'can set a global default country code' do PhonyRails.default_country_number = '1' expect(PhonyRails.default_country_number).to eq '1' end it 'default country code affects default country number' do expect(PhonyRails.default_country_number).to eq '1' end end describe 'PhonyRails#extract_extension' do it 'returns [nil, nil] on nil input' do expect(PhonyRails.extract_extension(nil)).to eq [nil, nil] end it 'returns [number, nil] when number does not have an extension' do expect(PhonyRails.extract_extension('123456789')).to eq ['123456789', nil] end EXT_PREFIXES.each do |prefix| it "returns [number, ext] when number has a #{prefix} extension" do expect(PhonyRails.extract_extension("123456789#{prefix}123")).to eq %w[123456789 123] end end end describe 'PhonyRails.country_code_from_number' do it 'returns the code of the plausible phone number' do expect(PhonyRails.country_code_from_number('+32475000000')).to eq '32' end end describe 'PhonyRails.country_from_number' do it 'returns the country of the plausible phone number' do expect(PhonyRails.country_from_number('+32475000000')).to eq 'BE' end end describe 'PhonyRails#format_extension' do it 'returns just number if no extension' do expect(PhonyRails.format_extension('+123456789', nil)).to eq '+123456789' end it 'returns number with extension if extension exists' do expect(PhonyRails.format_extension('+123456789', '123')).to eq '+123456789 x123' end end shared_examples_for 'model with PhonyRails' do describe 'defining model#phony_normalized_method' do it 'should add a normalized_phone_attribute method' do expect(model_klass.new).to respond_to(:normalized_phone_attribute) end it 'should add a normalized_phone_method method' do expect(model_klass.new).to respond_to(:normalized_phone_method) end it 'should raise error on existing methods' do expect(lambda do model_klass.phony_normalized_method(:phone_method) end).to raise_error(StandardError) end it 'should raise error on not existing attribute' do model_klass.phony_normalized_method(:phone_non_existing_method) expect(lambda do model_klass.new.normalized_phone_non_existing_method end).to raise_error(ArgumentError) end end describe 'defining model#phony_normalize' do it 'should not accept :as option with multiple attribute names' do expect(lambda do model_klass.phony_normalize(:phone_number, :phone1_method, as: 'non_existing_attribute') end).to raise_error(ArgumentError) end it 'should accept :as option with non existing attribute name' do expect(lambda do dummy_klass.phony_normalize(:non_existing_attribute, as: 'non_existing_attribute') end).to_not raise_error end it 'should accept :as option with single non existing attribute name' do expect(lambda do dummy_klass.phony_normalize(:phone_number, as: 'something_else') end).to_not raise_error end it 'should accept :as option with single existing attribute name' do expect(lambda do model_klass.phony_normalize(:phone_number, as: 'phone_number_as_normalized') end).to_not raise_error end it 'should accept a non existing attribute name' do expect(lambda do dummy_klass.phony_normalize(:non_existing_attribute) end).to_not raise_error end it 'should accept supported options' do options = %i[country_number default_country_number country_code default_country_code add_plus as enforce_record_country] options.each do |option_sym| expect(lambda do dummy_klass.phony_normalize(:phone_number, option_sym => false) end).to_not raise_error end end it 'should not accept unsupported options' do expect(lambda do dummy_klass.phony_normalize(:phone_number, unsupported_option: false) end).to raise_error(ArgumentError) end end describe 'using model#phony_normalized_method' do # Following examples have complete number (with country code!) it 'returns a normalized version of an attribute' do model = model_klass.new(phone_attribute: '+31-(0)10-1234123') expect(model.normalized_phone_attribute).to eql('+31101234123') end it 'returnsa normalized version of a method' do model = model_klass.new(phone_method: '+31-(0)10-1234123') expect(model.normalized_phone_method).to eql('+31101234123') end # Following examples have incomplete number it 'should normalize even a unplausible number (no country code)' do model = model_klass.new(phone_attribute: '(0)10-1234123') expect(model.normalized_phone_attribute).to eql('101234123') end it 'should use country_code option' do model = model_klass.new(phone_attribute: '(0)10-1234123') expect(model.normalized_phone_attribute(country_code: 'NL')).to eql('+31101234123') end it 'should use country_code object method' do model = model_klass.new(phone_attribute: '(0)10-1234123', country_code: 'NL') expect(model.normalized_phone_attribute).to eql('+31101234123') end it 'should fallback to default_country_code option' do model = model_klass.new(phone1_method: '(030) 8 61 29 06') expect(model.normalized_phone1_method).to eql('+49308612906') end it 'should overwrite default_country_code option with object method' do model = model_klass.new(phone1_method: '(030) 8 61 29 06', country_code: 'NL') expect(model.normalized_phone1_method).to eql('+31308612906') end it 'should overwrite default_country_code option with option' do model = model_klass.new(phone1_method: '(030) 8 61 29 06') expect(model.normalized_phone1_method(country_code: 'NL')).to eql('+31308612906') end it 'should use last passed options' do model = model_klass.new(phone1_method: '(030) 8 61 29 06') expect(model.normalized_phone1_method(country_code: 'NL')).to eql('+31308612906') expect(model.normalized_phone1_method(country_code: 'DE')).to eql('+49308612906') expect(model.normalized_phone1_method(country_code: nil)).to eql('+49308612906') end it 'should use last object method' do model = model_klass.new(phone1_method: '(030) 8 61 29 06') model.country_code = 'NL' expect(model.normalized_phone1_method).to eql('+31308612906') model.country_code = 'DE' expect(model.normalized_phone1_method).to eql('+49308612906') model.country_code = nil expect(model.normalized_phone1_method(country_code: nil)).to eql('+49308612906') end it 'should accept a symbol when setting country_code options' do model = model_klass.new(symboled_phone_method: '02031234567', country_code_attribute: 'GB') expect(model.normalized_symboled_phone_method).to eql('+442031234567') end end describe 'using model#phony_normalize' do it 'should not change normalized numbers (see #76)' do model = model_klass.new(phone_number: '+31-(0)10-1234123') expect(model).to be_valid expect(model.phone_number).to eql('+31101234123') end it 'should nilify attribute when it is set to nil' do model = model_klass.new(phone_number: '+31-(0)10-1234123') model.phone_number = nil expect(model).to be_valid expect(model.phone_number).to eql(nil) end it 'should nilify attribute when it is set to nil' do model = ActiveRecordModel.create!(phone_number: '+31-(0)10-1234123') model.phone_number = nil expect(model).to be_valid expect(model.save).to be(true) expect(model.reload.phone_number).to eql(nil) end it 'should empty attribute when it is set to ""' do # Github issue #149 model = ActiveRecordModel.create!(phone_number: '+31-(0)10-1234123') model.phone_number = '' expect(model).to be_valid expect(model.save).to be(true) expect(model.reload.phone_number).to eql('') end it 'should set a normalized version of an attribute using :as option' do model_klass.phony_normalize :phone_number, as: :phone_number_as_normalized model = model_klass.new(phone_number: '+31-(0)10-1234123') expect(model).to be_valid expect(model.phone_number_as_normalized).to eql('+31101234123') end it 'should nilify normalized version of an attribute when it is set to nil using :as option ' do model_klass.phony_normalize :phone_number, as: :phone_number_as_normalized model = model_klass.new(phone_number: '+31-(0)10-1234123', phone_number_as_normalized: '+31101234123') model.phone_number = nil expect(model).to be_valid expect(model.phone_number_as_normalized).to eq(nil) end it 'should not add a + using :add_plus option' do model_klass.phony_normalize :phone_number, add_plus: false model = model_klass.new(phone_number: '+31-(0)10-1234123') expect(model).to be_valid expect(model.phone_number).to eql('31101234123') end it 'should raise a RuntimeError at validation if the attribute doesn\'t exist' do dummy_klass.phony_normalize :non_existing_attribute dummy = dummy_klass.new expect(lambda do dummy.valid? end).to raise_error(RuntimeError) end it 'should raise a RuntimeError at validation if the :as option attribute doesn\'t exist' do dummy_klass.phony_normalize :phone_number, as: :non_existing_attribute dummy = dummy_klass.new expect(lambda do dummy.valid? end).to raise_error(RuntimeError) end it 'should accept a symbol when setting country_code options' do model = model_klass.new(symboled_phone: '0606060606', country_code_attribute: 'FR') expect(model).to be_valid expect(model.symboled_phone).to eql('+33606060606') end context 'relational normalization' do it 'should normalize based on custom attribute of the current model' do model_klass.phony_normalize :phone_number, default_country_code: ->(instance) { instance.custom_country_code } model = model_klass.new phone_number: '012 416 0001', custom_country_code: 'MY' expect(model).to be_valid expect(model.phone_number).to eq('+60124160001') end it 'should normalize based on specific attribute of the associative model' do model_klass.phony_normalize :phone_number, default_country_code: ->(instance) { instance.home_country.country_code } home_country = double('home_country', country_code: 'MY') model = model_klass.new phone_number: '012 416 0001', home_country: home_country expect(model).to be_valid expect(model.phone_number).to eq('+60124160001') end it 'should normalize based on default value if missing associative model' do model_klass.phony_normalize :phone_number, default_country_code: ->(instance) { instance.home_country&.country_code || 'MY' } model = model_klass.new phone_number: '012 416 0001', home_country: nil expect(model).to be_valid expect(model.phone_number).to eq('+60124160001') end end context 'conditional normalization' do context 'standalone methods' do it 'should only normalize if the :if conditional is true' do model_klass.phony_normalize :recipient, default_country_code: 'US', if: :use_phone? sms_alarm = model_klass.new recipient: '222 333 4444', delivery_method: 'sms' email_alarm = model_klass.new recipient: '[email protected]', delivery_method: 'email' expect(sms_alarm).to be_valid expect(email_alarm).to be_valid expect(sms_alarm.recipient).to eq('+12223334444') expect(email_alarm.recipient).to eq('[email protected]') end it 'should only normalize if the :unless conditional is false' do model_klass.phony_normalize :recipient, default_country_code: 'US', unless: :use_email? sms_alarm = model_klass.new recipient: '222 333 4444', delivery_method: 'sms' email_alarm = model_klass.new recipient: '[email protected]', delivery_method: 'email' expect(sms_alarm).to be_valid expect(email_alarm).to be_valid expect(sms_alarm.recipient).to eq('+12223334444') expect(email_alarm.recipient).to eq('[email protected]') end end context 'using lambdas' do it 'should only normalize if the :if conditional is true' do model_klass.phony_normalize :recipient, default_country_code: 'US', if: -> { delivery_method == 'sms' } sms_alarm = model_klass.new recipient: '222 333 4444', delivery_method: 'sms' email_alarm = model_klass.new recipient: '[email protected]', delivery_method: 'email' expect(sms_alarm).to be_valid expect(email_alarm).to be_valid expect(sms_alarm.recipient).to eq('+12223334444') expect(email_alarm.recipient).to eq('[email protected]') end it 'should only normalize if the :unless conditional is false' do model_klass.phony_normalize :recipient, default_country_code: 'US', unless: -> { delivery_method == 'email' } sms_alarm = model_klass.new recipient: '222 333 4444', delivery_method: 'sms' email_alarm = model_klass.new recipient: '[email protected]', delivery_method: 'email' expect(sms_alarm).to be_valid expect(email_alarm).to be_valid expect(sms_alarm.recipient).to eq('+12223334444') expect(email_alarm.recipient).to eq('[email protected]') end end end end end describe 'ActiveModel + ActiveModel::Validations::Callbacks' do let(:model_klass) { ActiveModelModel } let(:dummy_klass) { ActiveModelDummy } it_behaves_like 'model with PhonyRails' end describe 'ActiveRecord' do let(:model_klass) { ActiveRecordModel } let(:dummy_klass) { ActiveRecordDummy } it_behaves_like 'model with PhonyRails' it 'should correctly keep a hard set country_code' do model = model_klass.new(fax_number: '+1 978 555 0000') expect(model.valid?).to be true expect(model.fax_number).to eql('+19785550000') expect(model.save).to be true expect(model.save).to be true # revalidate model.reload expect(model.fax_number).to eql('+19785550000') model.fax_number = '(030) 8 61 29 06' expect(model.save).to be true # revalidate model.reload expect(model.fax_number).to eql('+61308612906') end context 'when enforce_record_country is turned off' do let(:model_klass) { RelaxedActiveRecordModel } let(:record) { model_klass.new } before do record.phone_number = phone_number record.country_code = 'DE' record.valid? # run the empty validation chain to execute the before hook (normalized the number) end context 'when the country_code attribute does not match the country number' do context 'when the number is prefixed with a country number and a plus' do let(:phone_number) { '+436601234567' } it 'should not add the records country number' do expect(record.phone_number).to eql('+436601234567') end end # In this case it's not clear if there is a country number, so it should be added context 'when the number is prefixed with a country number' do let(:phone_number) { '436601234567' } it 'should add the records country number' do expect(record.phone_number).to eql('+49436601234567') end end end # This should be the case anyways context 'when the country_code attribute matches the country number' do context 'when the number includes a country number and a plus' do let(:phone_number) { '+491721234567' } it 'should not add the records country number' do expect(record.phone_number).to eql('+491721234567') end end context 'when the number has neither country number nor plus' do let(:phone_number) { '01721234567' } it 'should not add the records country number' do expect(record.phone_number).to eql('+491721234567') end end end end end # describe 'Mongoid' do # let(:model_klass) { MongoidModel } # let(:dummy_klass) { MongoidDummy } # it_behaves_like 'model with PhonyRails' # end end
44.377944
163
0.670487
9194e293902cfce4fddd9307814a6afed21c2e4d
7,348
# This cannot take advantage of our relative requires, since this file is a # dependency of `rspec/mocks/argument_list_matcher.rb`. See comment there for # details. require 'rspec/support/matcher_definition' module RSpec module Mocks # ArgumentMatchers are placeholders that you can include in message # expectations to match arguments against a broader check than simple # equality. # # With the exception of `any_args` and `no_args`, they all match against # the arg in same position in the argument list. # # @see ArgumentListMatcher module ArgumentMatchers # Matches any args at all. Supports a more explicit variation of # `expect(object).to receive(:message)` # # @example # # expect(object).to receive(:message).with(any_args) def any_args AnyArgsMatcher.new end # Matches any argument at all. # # @example # # expect(object).to receive(:message).with(anything) def anything AnyArgMatcher.new end # Matches no arguments. # # @example # # expect(object).to receive(:message).with(no_args) def no_args NoArgsMatcher.new end # Matches if the actual argument responds to the specified messages. # # @example # # expect(object).to receive(:message).with(duck_type(:hello)) # expect(object).to receive(:message).with(duck_type(:hello, :goodbye)) def duck_type(*args) DuckTypeMatcher.new(*args) end # Matches a boolean value. # # @example # # expect(object).to receive(:message).with(boolean()) def boolean BooleanMatcher.new end # Matches a hash that includes the specified key(s) or key/value pairs. # Ignores any additional keys. # # @example # # expect(object).to receive(:message).with(hash_including(:key => val)) # expect(object).to receive(:message).with(hash_including(:key)) # expect(object).to receive(:message).with(hash_including(:key, :key2 => val2)) def hash_including(*args) HashIncludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) end # Matches an array that includes the specified items at least once. # Ignores duplicates and additional values # # @example # # expect(object).to receive(:message).with(array_including(1,2,3)) # expect(object).to receive(:message).with(array_including([1,2,3])) def array_including(*args) actually_an_array = Array === args.first && args.count == 1 ? args.first : args ArrayIncludingMatcher.new(actually_an_array) end # Matches a hash that doesn't include the specified key(s) or key/value. # # @example # # expect(object).to receive(:message).with(hash_excluding(:key => val)) # expect(object).to receive(:message).with(hash_excluding(:key)) # expect(object).to receive(:message).with(hash_excluding(:key, :key2 => :val2)) def hash_excluding(*args) HashExcludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) end alias_method :hash_not_including, :hash_excluding # Matches if `arg.instance_of?(klass)` # # @example # # expect(object).to receive(:message).with(instance_of(Thing)) def instance_of(klass) InstanceOf.new(klass) end alias_method :an_instance_of, :instance_of # Matches if `arg.kind_of?(klass)` # @example # # expect(object).to receive(:message).with(kind_of(Thing)) def kind_of(klass) KindOf.new(klass) end alias_method :a_kind_of, :kind_of # @private def self.anythingize_lonely_keys(*args) hash = args.last.class == Hash ? args.delete_at(-1) : {} args.each { | arg | hash[arg] = AnyArgMatcher.new } hash end # @private class AnyArgsMatcher def description "any args" end end # @private class AnyArgMatcher def ===(_other) true end def description "anything" end end # @private class NoArgsMatcher def description "no args" end end # @private class BooleanMatcher def ===(value) true == value || false == value end def description "boolean" end end # @private class BaseHashMatcher def initialize(expected) @expected = expected end def ===(predicate, actual) @expected.__send__(predicate) do |k, v| actual.key?(k) && Support::FuzzyMatcher.values_match?(v, actual[k]) end rescue NoMethodError false end def description(name) "#{name}(#{@expected.inspect.sub(/^\{/, "").sub(/\}$/, "")})" end end # @private class HashIncludingMatcher < BaseHashMatcher def ===(actual) super(:all?, actual) end def description super("hash_including") end end # @private class HashExcludingMatcher < BaseHashMatcher def ===(actual) super(:none?, actual) end def description super("hash_not_including") end end # @private class ArrayIncludingMatcher def initialize(expected) @expected = expected end def ===(actual) Set.new(actual).superset?(Set.new(@expected)) end def description "array_including(#{@expected.join(", ")})" end end # @private class DuckTypeMatcher def initialize(*methods_to_respond_to) @methods_to_respond_to = methods_to_respond_to end def ===(value) @methods_to_respond_to.all? { |message| value.respond_to?(message) } end def description "duck_type(#{@methods_to_respond_to.map(&:inspect).join(', ')})" end end # @private class InstanceOf def initialize(klass) @klass = klass end def ===(actual) actual.instance_of?(@klass) end def description "an_instance_of(#{@klass.name})" end end # @private class KindOf def initialize(klass) @klass = klass end def ===(actual) actual.kind_of?(@klass) end def description "kind of #{@klass.name}" end end matcher_namespace = name + '::' ::RSpec::Support.register_matcher_definition do |object| # This is the best we have for now. We should tag all of our matchers # with a module or something so we can test for it directly. # # (Note Module#parent in ActiveSupport is defined in a similar way.) begin object.class.name.include?(matcher_namespace) rescue NoMethodError # Some objects, like BasicObject, don't implemented standard # reflection methods. false end end end end end
25.964664
88
0.578797
79ec17ccd0ee4e4f1f0880e2e1475c856814590d
4,329
require 'spec_helper' require 'messages/builds_list_message' module VCAP::CloudController RSpec.describe BuildsListMessage do describe '.from_params' do let(:params) do { 'states' => 'state1,state2', 'app_guids' => 'appguid1,appguid2', 'package_guids' => 'packageguid1,packageguid2', 'page' => 1, 'per_page' => 5, 'order_by' => 'created_at', 'label_selector' => 'key=value', } end it 'returns the correct BuildsListMessage' do message = BuildsListMessage.from_params(params) expect(message).to be_a(BuildsListMessage) expect(message.states).to eq(['state1', 'state2']) expect(message.app_guids).to eq(['appguid1', 'appguid2']) expect(message.package_guids).to eq(['packageguid1', 'packageguid2']) expect(message.page).to eq(1) expect(message.per_page).to eq(5) expect(message.order_by).to eq('created_at') expect(message.label_selector).to eq('key=value') end it 'converts requested keys to symbols' do message = BuildsListMessage.from_params(params) expect(message.requested?(:states)).to be true expect(message.requested?(:app_guids)).to be true expect(message.requested?(:package_guids)).to be true expect(message.requested?(:page)).to be true expect(message.requested?(:per_page)).to be true expect(message.requested?(:order_by)).to be true end end describe 'fields' do it 'accepts a set of fields' do message = BuildsListMessage.from_params({ app_guids: [], package_guids: [], states: [], page: 1, per_page: 5, order_by: 'created_at', }) expect(message).to be_valid end it 'accepts an empty set' do message = BuildsListMessage.from_params({}) expect(message).to be_valid end it 'does not accept a field not in this set' do message = BuildsListMessage.from_params({ foobar: 'pants' }) expect(message).not_to be_valid expect(message.errors[:base]).to include("Unknown query parameter(s): 'foobar'") end it 'reject an invalid order_by field' do message = BuildsListMessage.from_params({ order_by: 'fail!', }) expect(message).not_to be_valid end describe 'validations' do context 'when the request contains space_guids' do it 'is invalid' do message = BuildsListMessage.from_params({ app_guids: ['blah'], space_guids: ['app1', 'app2'] }) expect(message).to_not be_valid expect(message.errors[:base]).to include("Unknown query parameter(s): 'space_guids'") end end context 'when the request contains organization_guids' do it 'is invalid' do message = BuildsListMessage.from_params({ app_guids: ['blah'], organization_guids: ['app1', 'app2'] }) expect(message).to_not be_valid expect(message.errors[:base]).to include("Unknown query parameter(s): 'organization_guids'") end end it 'validates app_guids is an array' do message = BuildsListMessage.from_params app_guids: 'tricked you, not an array' expect(message).to be_invalid expect(message.errors[:app_guids].length).to eq 1 end it 'validates package_guids is an array' do message = BuildsListMessage.from_params package_guids: 'also not an array' expect(message).to be_invalid expect(message.errors[:package_guids].length).to eq 1 end it 'validates states is an array' do message = BuildsListMessage.from_params states: 'not array at all' expect(message).to be_invalid expect(message.errors[:states].length).to eq 1 end it 'validates metadata requirements' do message = BuildsListMessage.from_params('label_selector' => '') expect_any_instance_of(Validators::LabelSelectorRequirementValidator). to receive(:validate). with(message). and_call_original message.valid? end end end end end
34.91129
114
0.613768
210817e886878ae712ed6e9b587cfbe8c40c6a97
105
module ToWa class DeniedOperator < StandardError end class DeniedColumn < StandardError end end
13.125
38
0.771429
ff49d318f46f43dbce2b290c5f2d93d345cbab90
1,458
# encoding: utf-8 # # 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. require File.expand_path('../../../spec_helper', __FILE__) module Selenium module WebDriver module Remote module Http describe Common do it 'sends non-empty body header for POST requests without command data' do common = Common.new common.server_url = URI.parse('http://server') expect(common).to receive(:request) .with(:post, URI.parse('http://server/clear'), hash_including('Content-Length' => '2'), '{}') common.call(:post, 'clear', nil) end end end # Http end # Remote end # WebDriver end # Selenium
34.714286
84
0.680384
7996a3f4d51790d84ca19f95859370d04f169152
10,396
class LlvmAT8 < Formula desc "Next-gen compiler infrastructure" homepage "https://llvm.org/" url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/llvm-8.0.1.src.tar.xz" sha256 "44787a6d02f7140f145e2250d56c9f849334e11f9ae379827510ed72f12b75e7" license "NCSA" revision 3 bottle do sha256 cellar: :any, catalina: "ab099d84e5f0a58ea37172fd85753336d855fc25e9459ceff12ddc2dbb56ef71" sha256 cellar: :any, mojave: "ee795cbebce64f79bbcf7c42526093df7bd2e5e986a721197bca5cf6c822e87a" sha256 cellar: :any, high_sierra: "3f80b7119307b128b1e3ae8a2fea97a9878afb5a7436a7d35615b1e743bc7622" end # Clang cannot find system headers if Xcode CLT is not installed pour_bottle? do reason "The bottle needs the Xcode CLT to be installed." satisfy { MacOS::CLT.installed? } end keg_only :versioned_formula # https://llvm.org/docs/GettingStarted.html#requirement depends_on "cmake" => :build depends_on xcode: :build depends_on arch: :x86_64 depends_on "libffi" depends_on "swig" resource "clang" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/cfe-8.0.1.src.tar.xz" sha256 "70effd69f7a8ab249f66b0a68aba8b08af52aa2ab710dfb8a0fba102685b1646" end resource "clang-extra-tools" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/clang-tools-extra-8.0.1.src.tar.xz" sha256 "187179b617e4f07bb605cc215da0527e64990b4a7dd5cbcc452a16b64e02c3e1" end resource "compiler-rt" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/compiler-rt-8.0.1.src.tar.xz" sha256 "11828fb4823387d820c6715b25f6b2405e60837d12a7469e7a8882911c721837" end resource "libcxx" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/libcxx-8.0.1.src.tar.xz" sha256 "7f0652c86a0307a250b5741ab6e82bb10766fb6f2b5a5602a63f30337e629b78" end resource "libunwind" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/libunwind-8.0.1.src.tar.xz" sha256 "1870161dda3172c63e632c1f60624564e1eb0f9233cfa8f040748ca5ff630f6e" end resource "lld" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/lld-8.0.1.src.tar.xz" sha256 "9fba1e94249bd7913e8a6c3aadcb308b76c8c3d83c5ce36c99c3f34d73873d88" end resource "lldb" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/lldb-8.0.1.src.tar.xz" sha256 "e8a79baa6d11dd0650ab4a1b479f699dfad82af627cbbcd49fa6f2dc14e131d7" end resource "openmp" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/openmp-8.0.1.src.tar.xz" sha256 "3e85dd3cad41117b7c89a41de72f2e6aa756ea7b4ef63bb10dcddf8561a7722c" end resource "polly" do url "https://github.com/llvm/llvm-project/releases/download/llvmorg-8.0.1/polly-8.0.1.src.tar.xz" sha256 "e8a1f7e8af238b32ce39ab5de1f3317a2e3f7d71a8b1b8bbacbd481ac76fd2d1" end def install # Apple's libstdc++ is too old to build LLVM ENV.libcxx if ENV.compiler == :clang (buildpath/"tools/clang").install resource("clang") (buildpath/"tools/clang/tools/extra").install resource("clang-extra-tools") (buildpath/"projects/openmp").install resource("openmp") (buildpath/"projects/libcxx").install resource("libcxx") (buildpath/"projects/libunwind").install resource("libunwind") (buildpath/"tools/lld").install resource("lld") (buildpath/"tools/lldb").install resource("lldb") (buildpath/"tools/polly").install resource("polly") (buildpath/"projects/compiler-rt").install resource("compiler-rt") # compiler-rt has some iOS simulator features that require i386 symbols # I'm assuming the rest of clang needs support too for 32-bit compilation # to work correctly, but if not, perhaps universal binaries could be # limited to compiler-rt. llvm makes this somewhat easier because compiler-rt # can almost be treated as an entirely different build from llvm. ENV.permit_arch_flags args = %W[ -DLIBOMP_ARCH=x86_64 -DLINK_POLLY_INTO_TOOLS=ON -DLLVM_BUILD_EXTERNAL_COMPILER_RT=ON -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_ENABLE_EH=ON -DLLVM_ENABLE_FFI=ON -DLLVM_ENABLE_LIBCXX=ON -DLLVM_ENABLE_RTTI=ON -DCLANG_ANALYZER_ENABLE_Z3_SOLVER=OFF -DLLVM_INCLUDE_DOCS=OFF -DLLVM_INSTALL_UTILS=ON -DLLVM_OPTIMIZED_TABLEGEN=ON -DLLVM_TARGETS_TO_BUILD=all -DWITH_POLLY=ON -DFFI_INCLUDE_DIR=#{Formula["libffi"].opt_lib}/libffi-#{Formula["libffi"].version}/include -DFFI_LIBRARY_DIR=#{Formula["libffi"].opt_lib} -DLLVM_CREATE_XCODE_TOOLCHAIN=ON -DLLDB_USE_SYSTEM_DEBUGSERVER=ON -DLLDB_DISABLE_PYTHON=1 -DLIBOMP_INSTALL_ALIASES=OFF ] if MacOS.version >= :mojave sdk_path = MacOS::CLT.installed? ? "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk" : MacOS.sdk_path args << "-DDEFAULT_SYSROOT=#{sdk_path}" end mkdir "build" do system "cmake", "-G", "Unix Makefiles", "..", *(std_cmake_args + args) system "make" system "make", "install" system "make", "install-xcode-toolchain" end (share/"clang/tools").install Dir["tools/clang/tools/scan-{build,view}"] (share/"cmake").install "cmake/modules" inreplace "#{share}/clang/tools/scan-build/bin/scan-build", "$RealBin/bin/clang", "#{bin}/clang" bin.install_symlink share/"clang/tools/scan-build/bin/scan-build", share/"clang/tools/scan-view/bin/scan-view" man1.install_symlink share/"clang/tools/scan-build/man/scan-build.1" # install llvm python bindings (lib/"python2.7/site-packages").install buildpath/"bindings/python/llvm" (lib/"python2.7/site-packages").install buildpath/"tools/clang/bindings/python/clang" end def caveats <<~EOS To use the bundled libc++ please add the following LDFLAGS: LDFLAGS="-L#{opt_lib} -Wl,-rpath,#{opt_lib}" EOS end test do assert_equal prefix.to_s, shell_output("#{bin}/llvm-config --prefix").chomp (testpath/"omptest.c").write <<~EOS #include <stdlib.h> #include <stdio.h> #include <omp.h> int main() { #pragma omp parallel num_threads(4) { printf("Hello from thread %d, nthreads %d\\n", omp_get_thread_num(), omp_get_num_threads()); } return EXIT_SUCCESS; } EOS clean_version = version.to_s[/(\d+\.?)+/] system "#{bin}/clang", "-L#{lib}", "-fopenmp", "-nobuiltininc", "-I#{lib}/clang/#{clean_version}/include", "omptest.c", "-o", "omptest" testresult = shell_output("./omptest") sorted_testresult = testresult.split("\n").sort.join("\n") expected_result = <<~EOS Hello from thread 0, nthreads 4 Hello from thread 1, nthreads 4 Hello from thread 2, nthreads 4 Hello from thread 3, nthreads 4 EOS assert_equal expected_result.strip, sorted_testresult.strip (testpath/"test.c").write <<~EOS #include <stdio.h> int main() { printf("Hello World!\\n"); return 0; } EOS (testpath/"test.cpp").write <<~EOS #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } EOS # Testing default toolchain and SDK location. system "#{bin}/clang++", "-v", "-std=c++11", "test.cpp", "-o", "test++" assert_includes MachO::Tools.dylibs("test++"), "/usr/lib/libc++.1.dylib" assert_equal "Hello World!", shell_output("./test++").chomp system "#{bin}/clang", "-v", "test.c", "-o", "test" assert_equal "Hello World!", shell_output("./test").chomp # Testing Command Line Tools if MacOS::CLT.installed? toolchain_path = "/Library/Developer/CommandLineTools" sdk_path = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk" system "#{bin}/clang++", "-v", "-isysroot", sdk_path, "-isystem", "#{toolchain_path}/usr/include/c++/v1", "-isystem", "#{toolchain_path}/usr/include", "-isystem", "#{sdk_path}/usr/include", "-std=c++11", "test.cpp", "-o", "testCLT++" assert_includes MachO::Tools.dylibs("testCLT++"), "/usr/lib/libc++.1.dylib" assert_equal "Hello World!", shell_output("./testCLT++").chomp system "#{bin}/clang", "-v", "test.c", "-o", "testCLT" assert_equal "Hello World!", shell_output("./testCLT").chomp end # Testing Xcode if MacOS::Xcode.installed? system "#{bin}/clang++", "-v", "-isysroot", MacOS.sdk_path, "-isystem", "#{MacOS::Xcode.toolchain_path}/usr/include/c++/v1", "-isystem", "#{MacOS::Xcode.toolchain_path}/usr/include", "-isystem", "#{MacOS.sdk_path}/usr/include", "-std=c++11", "test.cpp", "-o", "testXC++" assert_includes MachO::Tools.dylibs("testXC++"), "/usr/lib/libc++.1.dylib" assert_equal "Hello World!", shell_output("./testXC++").chomp system "#{bin}/clang", "-v", "-isysroot", MacOS.sdk_path, "test.c", "-o", "testXC" assert_equal "Hello World!", shell_output("./testXC").chomp end # link against installed libc++ # related to https://github.com/Homebrew/legacy-homebrew/issues/47149 system "#{bin}/clang++", "-v", "-isystem", "#{opt_include}/c++/v1", "-std=c++11", "-stdlib=libc++", "test.cpp", "-o", "testlibc++", "-L#{opt_lib}", "-Wl,-rpath,#{opt_lib}" assert_includes MachO::Tools.dylibs("testlibc++"), "#{opt_lib}/libc++.1.dylib" assert_equal "Hello World!", shell_output("./testlibc++").chomp (testpath/"scanbuildtest.cpp").write <<~EOS #include <iostream> int main() { int *i = new int; *i = 1; delete i; std::cout << *i << std::endl; return 0; } EOS assert_includes shell_output("#{bin}/scan-build --use-analyzer #{bin}/clang++ clang++ scanbuildtest.cpp 2>&1"), "warning: Use of memory after it is freed" (testpath/"clangformattest.c").write <<~EOS int main() { printf("Hello world!"); } EOS assert_equal "int main() { printf(\"Hello world!\"); }\n", shell_output("#{bin}/clang-format -style=google clangformattest.c") end end
38.64684
115
0.661216
18b9b8609b5566f798c9354049ccf0460c0cc223
6,627
require_relative 'functional_api' require 'test/unit/assertions' require 'mocha/setup' module OpenShift module Runtime end end class OpenShift::Runtime::DeploymentTester include Test::Unit::Assertions include OpenShift::Runtime::NodeLogger DEFAULT_TITLE = "Welcome to OpenShift" CHANGED_TITLE = "Test1" JENKINS_ADD_TITLE = "JenkinsClient" def setup @api = FunctionalApi.new @namespace = @api.create_domain end def teardown unless ENV['PRESERVE'] @api.delete_domain unless @api.nil? end end def up_gears @api.up_gears end def create_jenkins app_name = "jenkins#{@api.random_string}" @api.create_application(app_name, %w(jenkins-1), false) end def basic_build_test(cartridges, options = {}) scaling = !!options[:scaling] add_jenkins = !!options[:add_jenkins] keep_deployments = options[:keep_deployments] app_name = "app#{@api.random_string}" app_id = @api.create_application(app_name, cartridges, scaling) @api.add_ssh_key(app_id, app_name) framework = cartridges[0] app_container = OpenShift::Runtime::ApplicationContainer.from_uuid(app_id) if keep_deployments # keep up to #{keep} deployments logger.info "Setting OPENSHIFT_KEEP_DEPLOYMENTS to #{keep_deployments} for #{@namespace}" @api.configure_application(app_name, keep_deployments: keep_deployments) gear_env = OpenShift::Runtime::Utils::Environ.for_gear(app_container.container_dir) assert_equal keep_deployments.to_s, gear_env['OPENSHIFT_KEEP_DEPLOYMENTS'], "Keep deployments value was not actually updated" end assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) if scaling gear_registry = OpenShift::Runtime::GearRegistry.new(app_container) entries = gear_registry.entries logger.info("Gear registry contents: #{entries}") assert_equal 2, entries.keys.size web_entries = entries[:web] assert_equal 1, web_entries.keys.size assert_equal app_id, web_entries.keys[0] entry = web_entries[app_id] assert_equal app_id, entry.uuid assert_equal @namespace, entry.namespace domain = @api.cloud_domain assert_equal "#{app_name}-#{@namespace}.#{domain}", entry.dns local_hostname = `facter public_hostname`.chomp assert_equal local_hostname, entry.proxy_hostname @api.assert_http_title_for_entry entry, DEFAULT_TITLE, "Default title check for head gear failed" proxy_entries = entries[:proxy] assert_equal 1, proxy_entries.keys.size assert_equal app_id, proxy_entries.keys[0] entry = proxy_entries[app_id] assert_equal app_id, entry.uuid assert_equal @namespace, entry.namespace assert_equal "#{app_name}-#{@namespace}.#{domain}", entry.dns assert_equal local_hostname, entry.proxy_hostname assert_equal 0, entry.proxy_port.to_i # scale up to 2 @api.assert_scales_to app_name, framework, 2 assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) gear_registry.load entries = gear_registry.entries assert_equal 2, entries.keys.size web_entries = entries[:web] assert_equal 2, web_entries.keys.size # make sure the http content is good web_entries.values.each do |entry| logger.info("Checking title for #{entry.as_json}") @api.assert_http_title_for_entry entry, DEFAULT_TITLE, "Default title check for secondary gear failed" end else @api.assert_http_title_for_app app_name, @namespace, DEFAULT_TITLE, "Default title check failed" end deployment_metadata = app_container.deployment_metadata_for(app_container.current_deployment_datetime) deployment_id = deployment_metadata.id @api.clone_repo(app_id) @api.change_title(CHANGED_TITLE, app_name, app_id, framework) assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) if scaling web_entries.values.each { |entry| @api.assert_http_title_for_entry entry, CHANGED_TITLE, "Check for changed title before scale-up failed" } @api.assert_scales_to app_name, framework, 3 assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) gear_registry.load entries = gear_registry.entries assert_equal 3, entries[:web].size entries[:web].values.each { |entry| @api.assert_http_title_for_entry entry, CHANGED_TITLE, "Check for changed title after scale-up failed" } else @api.assert_http_title_for_app app_name, @namespace, CHANGED_TITLE, "Check for changed title failed" end if add_jenkins @api.add_cartridge('jenkins-client-1', app_name) @api.change_title(JENKINS_ADD_TITLE, app_name, app_id, framework) assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) if scaling entries = gear_registry.entries entries[:web].values.each { |entry| @api.assert_http_title_for_entry entry, JENKINS_ADD_TITLE } else @api.assert_http_title_for_app app_name, @namespace, JENKINS_ADD_TITLE end end if !keep_deployments.nil? && keep_deployments > 1 # rollback logger.info("Rolling back to #{deployment_id}") logger.info @api.ssh_command(app_id, "gear activate #{deployment_id} --all") assert_gear_deployment_consistency(@api.gears_for_app(app_name), keep_deployments) if scaling entries = gear_registry.entries entries[:web].values.each { |entry| @api.assert_http_title_for_entry entry, DEFAULT_TITLE, "Default title check after rollback failed" } else @api.assert_http_title_for_app app_name, @namespace, DEFAULT_TITLE, "Default title check after rollback failed" end end end def assert_gear_deployment_consistency(gears, keep_deployments) errors = [] deployments_to_keep ||= 1 gears.each do |gear| container = OpenShift::Runtime::ApplicationContainer.from_uuid(gear) logger.info "Validating deployments for #{gear}" all_deployments = container.all_deployments assert_operator all_deployments.length, :<=, keep_deployments if keep_deployments all_deployments.each do |deployment| %w(dependencies build-dependencies repo).each do |dir| path = File.join(deployment, dir) errors << "Broken or missing dir #{path}" unless File.exists?(path) end end end assert_equal 0, errors.length, "Corrupted deployment directories:\n#{errors.join("\n")}" end end
33.984615
146
0.722197
617f31f36e9090e2028afdbbce52c341f2ca18ba
347
require 'test_helper' class TemplateMailerTest < ActionMailer::TestCase tests TemplateMailer def test_message @expected.subject = 'TemplateMailer#message' @expected.body = read_fixture('message') @expected.date = Time.now assert_equal @expected.encoded, TemplateMailer.create_message(@expected.date).encoded end end
24.785714
89
0.752161
f7950c50205b3af8541d37461cafe482229dd05f
646
# frozen_string_literal: true require 'rails_helper' RSpec.describe ProvisionedSubjectsController, type: :routing do def action(name, opts) opts.merge(controller: 'provisioned_subjects', action: name, provider_id: '1') end context 'get /providers/:id/provisioned_subjects/:id/edit' do subject { { get: '/providers/1/provisioned_subjects/2/edit' } } it { is_expected.to route_to(action('edit', id: '2')) } end context 'patch /providers/:id/provisioned_subjects/:id' do subject { { patch: '/providers/1/provisioned_subjects/2' } } it { is_expected.to route_to(action('update', id: '2')) } end end
30.761905
67
0.69195
21ad6b1ce7dbb7959a469fd39d9d7b0e971d6154
20,137
#-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2017 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ require 'legacy_spec_helper' describe UserMailer, type: :mailer do include ::Rails::Dom::Testing::Assertions::SelectorAssertions before do Setting.mail_from = '[email protected]' Setting.host_name = 'mydomain.foo' Setting.protocol = 'http' Setting.plain_text_mail = '0' Setting.default_language = 'en' User.delete_all WorkPackage.delete_all Project.delete_all ::Type.delete_all end it 'should test mail sends a simple greeting' do user = FactoryGirl.create(:admin, mail: '[email protected]') FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) mail = UserMailer.test_mail(user) assert mail.deliver_now assert_equal 1, ActionMailer::Base.deliveries.size assert_equal 'OpenProject Test', mail.subject assert_equal ['[email protected]'], mail.to assert_equal ['[email protected]'], mail.from assert_match /OpenProject URL/, mail.body.encoded end it 'should generated links in emails' do Setting.default_language = 'en' Setting.host_name = 'mydomain.foo' Setting.protocol = 'https' project, user, related_issue, issue, changeset, attachment, journal = setup_complex_issue_update assert UserMailer.work_package_updated(user, journal).deliver_now assert last_email assert_select_email do # link to the main ticket assert_select 'a[href=?]', "https://mydomain.foo/work_packages/#{issue.id}", text: "My Type ##{issue.id}: My awesome Ticket" # link to a description diff assert_select 'li', text: /Description changed/ assert_select 'li>a[href=?]', "https://mydomain.foo/journals/#{journal.id}/diff/description", text: 'Details' # link to a referenced ticket assert_select 'a[href=?][title=?]', "https://mydomain.foo/work_packages/#{related_issue.id}", "My related Ticket (#{related_issue.status})", text: "##{related_issue.id}" # link to a changeset if changeset assert_select 'a[href=?][title=?]', url_for(controller: 'repositories', action: 'revision', project_id: project, rev: changeset.revision), 'This commit fixes #1, #2 and references #1 and #3', text: "r#{changeset.revision}" end # link to an attachment assert_select 'a[href=?]', "https://mydomain.foo/attachments/#{attachment.id}/#{attachment.filename}", text: "#{attachment.filename}" end end it 'should generated links with prefix' do Setting.default_language = 'en' Setting.host_name = 'mydomain.foo/rdm' Setting.protocol = 'http' project, user, related_issue, issue, changeset, attachment, journal = setup_complex_issue_update assert UserMailer.work_package_updated(user, journal).deliver_now assert last_email assert_select_email do # link to the main ticket assert_select 'a[href=?]', "http://mydomain.foo/rdm/work_packages/#{issue.id}", text: "My Type ##{issue.id}: My awesome Ticket" # link to a description diff assert_select 'li', text: /Description changed/ assert_select 'li>a[href=?]', "http://mydomain.foo/rdm/journals/#{journal.id}/diff/description", text: 'Details' # link to a referenced ticket assert_select 'a[href=?][title=?]', "http://mydomain.foo/rdm/work_packages/#{related_issue.id}", "My related Ticket (#{related_issue.status})", text: "##{related_issue.id}" # link to a changeset if changeset assert_select 'a[href=?][title=?]', url_for(controller: 'repositories', action: 'revision', project_id: project, rev: changeset.revision), 'This commit fixes #1, #2 and references #1 and #3', text: "r#{changeset.revision}" end # link to an attachment assert_select 'a[href=?]', "http://mydomain.foo/rdm/attachments/#{attachment.id}/#{attachment.filename}", text: "#{attachment.filename}" end end it 'should generated links with prefix and no relative url root' do begin Setting.default_language = 'en' relative_url_root = OpenProject::Configuration['rails_relative_url_root'] Setting.host_name = 'mydomain.foo/rdm' Setting.protocol = 'http' OpenProject::Configuration['rails_relative_url_root'] = nil project, user, related_issue, issue, changeset, attachment, journal = setup_complex_issue_update assert UserMailer.work_package_updated(user, journal).deliver_now assert last_email assert_select_email do # link to the main ticket assert_select 'a[href=?]', "http://mydomain.foo/rdm/work_packages/#{issue.id}", text: "My Type ##{issue.id}: My awesome Ticket" # link to a description diff assert_select 'li', text: /Description changed/ assert_select 'li>a[href=?]', "http://mydomain.foo/rdm/journals/#{journal.id}/diff/description", text: 'Details' # link to a referenced ticket assert_select 'a[href=?][title=?]', "http://mydomain.foo/rdm/work_packages/#{related_issue.id}", "My related Ticket (#{related_issue.status})", text: "##{related_issue.id}" # link to a changeset if changeset assert_select 'a[href=?][title=?]', url_for(controller: 'repositories', action: 'revision', project_id: project, rev: changeset.revision), 'This commit fixes #1, #2 and references #1 and #3', text: "r#{changeset.revision}" end # link to an attachment assert_select 'a[href=?]', "http://mydomain.foo/rdm/attachments/#{attachment.id}/#{attachment.filename}", text: "#{attachment.filename}" end ensure # restore it OpenProject::Configuration['rails_relative_url_root'] = relative_url_root end end it 'should email headers' do user = FactoryGirl.create(:user) issue = FactoryGirl.create(:work_package) mail = UserMailer.work_package_added(user, issue.journals.first, user) assert mail.deliver_now refute_nil mail assert_equal 'bulk', mail.header['Precedence'].to_s assert_equal 'auto-generated', mail.header['Auto-Submitted'].to_s end it 'sends plain text mail' do Setting.plain_text_mail = 1 user = FactoryGirl.create(:user) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) issue = FactoryGirl.create(:work_package) UserMailer.work_package_added(user, issue.journals.first, user).deliver_now mail = ActionMailer::Base.deliveries.last assert_match /text\/plain/, mail.content_type assert_equal 0, mail.parts.size assert !mail.encoded.include?('href') end it 'sends html mail' do Setting.plain_text_mail = 0 user = FactoryGirl.create(:user) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) issue = FactoryGirl.create(:work_package) UserMailer.work_package_added(user, issue.journals.first, user).deliver_now mail = ActionMailer::Base.deliveries.last assert_match /multipart\/alternative/, mail.content_type assert_equal 2, mail.parts.size assert mail.encoded.include?('href') end context 'with mail_from set', with_settings: { mail_from: 'Redmine app <[email protected]>' } do it 'should mail from with phrase' do user = FactoryGirl.create(:user) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) UserMailer.test_mail(user).deliver_now mail = ActionMailer::Base.deliveries.last refute_nil mail assert_equal 'Redmine app <[email protected]>', mail.header['From'].to_s end end it 'should not send email without recipient' do user = FactoryGirl.create(:user) news = FactoryGirl.create(:news) # notify him user.pref[:no_self_notified] = false user.pref.save ActionMailer::Base.deliveries.clear UserMailer.news_added(user, news, user).deliver_now assert_equal 1, last_email.to.size # nobody to notify user.pref[:no_self_notified] = true user.pref.save ActionMailer::Base.deliveries.clear UserMailer.news_added(user, news, user).deliver_now assert ActionMailer::Base.deliveries.empty? end it 'should issue add message id' do user = FactoryGirl.create(:user) issue = FactoryGirl.create(:work_package) mail = UserMailer.work_package_added(user, issue.journals.first, user) mail.deliver_now refute_nil mail assert_equal UserMailer.generate_message_id(issue, user), mail.message_id assert_nil mail.references end it 'should work package updated message id' do user = FactoryGirl.create(:user) issue = FactoryGirl.create(:work_package) journal = issue.journals.first UserMailer.work_package_updated(user, journal).deliver_now mail = ActionMailer::Base.deliveries.last refute_nil mail assert_equal UserMailer.generate_message_id(journal, user), mail.message_id assert_match mail.references, UserMailer.generate_message_id(journal.journable, user) end it 'should message posted message id' do user = FactoryGirl.create(:user) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) message = FactoryGirl.create(:message) UserMailer.message_posted(user, message, user).deliver_now mail = ActionMailer::Base.deliveries.last refute_nil mail assert_equal UserMailer.generate_message_id(message, user), mail.message_id assert_nil mail.references assert_select_email do # link to the message assert_select 'a[href*=?]', "#{Setting.protocol}://#{Setting.host_name}/topics/#{message.id}", text: message.subject end end it 'should reply posted message id' do user = FactoryGirl.create(:user) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) parent = FactoryGirl.create(:message) message = FactoryGirl.create(:message, parent: parent) UserMailer.message_posted(user, message, user).deliver_now mail = ActionMailer::Base.deliveries.last refute_nil mail assert_equal UserMailer.generate_message_id(message, user), mail.message_id assert_match mail.references, UserMailer.generate_message_id(parent, user) assert_select_email do # link to the reply assert_select 'a[href=?]', "#{Setting.protocol}://#{Setting.host_name}/topics/#{message.root.id}?r=#{message.id}#message-#{message.id}", text: message.subject end end context '#issue_add', with_settings: { available_languages: ['en', 'de'], default_language: 'de' } do it 'should change mail language depending on recipient language' do issue = FactoryGirl.create(:work_package) user = FactoryGirl.create(:user, mail: '[email protected]', language: 'de') FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) I18n.locale = 'en' assert UserMailer.work_package_added(user, issue.journals.first, user).deliver_now assert_equal 1, ActionMailer::Base.deliveries.size mail = last_email assert_equal ['[email protected]'], mail.to assert mail.body.encoded.include?('erstellt') assert !mail.body.encoded.include?('reported') assert_equal :en, I18n.locale end it 'should falls back to default language if user has no language' do # 1. user's language # 2. Setting.default_language # 3. I18n.default_locale issue = FactoryGirl.create(:work_package) user = FactoryGirl.create(:user, mail: '[email protected]', language: '') # (auto) FactoryGirl.create(:user_preference, user: user, others: { no_self_notified: false }) I18n.locale = 'de' assert UserMailer.work_package_added(user, issue.journals.first, user).deliver_now assert_equal 1, ActionMailer::Base.deliveries.size mail = last_email assert_equal ['[email protected]'], mail.to assert !mail.body.encoded.include?('reported') assert mail.body.encoded.include?('erstellt') assert_equal :de, I18n.locale end end it 'should news added' do user = FactoryGirl.create(:user) news = FactoryGirl.create(:news) assert UserMailer.news_added(user, news, user).deliver_now end it 'should news comment added' do user = FactoryGirl.create(:user) news = FactoryGirl.create(:news) comment = FactoryGirl.create(:comment, commented: news) assert UserMailer.news_comment_added(user, comment, user).deliver_now end it 'should message posted' do user = FactoryGirl.create(:user) message = FactoryGirl.create(:message) assert UserMailer.message_posted(user, message, user).deliver_now end it 'should account information' do user = FactoryGirl.create(:user) assert UserMailer.account_information(user, 'pAsswORd').deliver_now end it 'should lost password' do user = FactoryGirl.create(:user) token = FactoryGirl.create(:token, user: user) assert UserMailer.password_lost(token).deliver_now end it 'should register' do user = FactoryGirl.create(:user) token = FactoryGirl.create(:token, user: user) Setting.host_name = 'redmine.foo' Setting.protocol = 'https' mail = UserMailer.user_signed_up(token) assert mail.deliver_now assert mail.body.encoded.include?("https://redmine.foo/account/activate?token=#{token.value}") end it 'should reminders' do user = FactoryGirl.create(:user, mail: '[email protected]') issue = FactoryGirl.create(:work_package, due_date: Date.tomorrow, assigned_to: user, subject: 'some issue') DueIssuesReminder.new(42).remind_users assert_equal 1, ActionMailer::Base.deliveries.size mail = ActionMailer::Base.deliveries.last assert mail.to.include?('[email protected]') assert mail.body.encoded.include?("#{issue.project.name} - #{issue.type.name} ##{issue.id}: some issue") assert_equal '1 work package(s) due in the next 42 days', mail.subject end it 'should reminders for users' do user1 = FactoryGirl.create(:user, mail: '[email protected]') user2 = FactoryGirl.create(:user, mail: '[email protected]') issue = FactoryGirl.create(:work_package, due_date: Date.tomorrow, assigned_to: user1, subject: 'some issue') DueIssuesReminder.new(42, nil, nil, [user2.id]).remind_users assert_equal 0, ActionMailer::Base.deliveries.size DueIssuesReminder.new(42, nil, nil, [user1.id]).remind_users assert_equal 1, ActionMailer::Base.deliveries.size mail = ActionMailer::Base.deliveries.last assert mail.to.include?('[email protected]') assert mail.body.encoded.include?("#{issue.project.name} - #{issue.type.name} ##{issue.id}: some issue") assert_equal '1 work package(s) due in the next 42 days', mail.subject end context 'with locale settings', with_settings: { available_languages: ['en', 'de'], default_language: 'de' } do it 'should mailer should not change locale' do # Set current language to english I18n.locale = :en # Send an email to a german user user = FactoryGirl.create(:user, language: 'de') UserMailer.account_activated(user).deliver_now mail = ActionMailer::Base.deliveries.last assert mail.body.encoded.include?('aktiviert') assert_equal :en, I18n.locale end end it 'should with deliveries off' do user = FactoryGirl.create(:user) UserMailer.with_deliveries(false) do UserMailer.test_mail(user).deliver_now end assert ActionMailer::Base.deliveries.empty? # should restore perform_deliveries assert ActionMailer::Base.perform_deliveries end context 'layout', with_settings: { available_languages: [:en, :de], localized_emails_header: 'deutscher header' } do it 'should include the emails_header depeding on the locale' do user = FactoryGirl.create(:user, language: :de) assert UserMailer.test_mail(user).deliver_now mail = ActionMailer::Base.deliveries.last assert mail.body.encoded.include?('deutscher header') end end private def last_email mail = ActionMailer::Base.deliveries.last refute_nil mail mail end def setup_complex_issue_update project = FactoryGirl.create(:valid_project) user = FactoryGirl.create(:admin, member_in_project: project) type = FactoryGirl.create(:type, name: 'My Type') project.types << type project.save related_issue = FactoryGirl.create(:work_package, subject: 'My related Ticket', type: type, project: project) issue = FactoryGirl.create(:work_package, subject: 'My awesome Ticket', type: type, project: project, description: 'nothing here yet') # now change the issue, to get a nice journal issue.description = "This is related to issue ##{related_issue.id}\n" repository = FactoryGirl.create(:repository_subversion, project: project) changeset = FactoryGirl.create :changeset, repository: repository, comments: 'This commit fixes #1, #2 and references #1 and #3' issue.description += " A reference to a changeset r#{changeset.revision}\n" if changeset attachment = FactoryGirl.create(:attachment, container: issue, author: issue.author) issue.description += " A reference to an attachment attachment:#{attachment.filename}" assert issue.save issue.reload journal = issue.journals.last ActionMailer::Base.deliveries = [] # remove issue-created mails [project, user, related_issue, issue, changeset, attachment, journal] end def url_for(options) options.merge!(host: Setting.host_name, protocol: Setting.protocol) Rails.application.routes.url_helpers.url_for options end end
39.253411
164
0.657446
38c1f96bbb3e2c90fbd3ad621e6ca7afb44aca38
553
# frozen_string_literal: true RSpec.shared_context 'integration config' do let(:config) do config_file_name = File.expand_path('config.yml', __dir__) return {} unless File.exist?(config_file_name) YAML.safe_load(File.read(config_file_name)) end let(:ssh_host) { config['ssh']['host'] } let(:ssh_user) { config['ssh']['user'] } let(:ssh_key_file) { config['ssh']['key_file'] } let(:ssh_workdir) { config['ssh']['workdir'] } end RSpec.configure do |config| config.include_context 'integration config', type: :integration end
27.65
65
0.703436
e9971118a3344cce501b02cb97bb2e31b660fcaf
469
class CreateMeritActions < ActiveRecord::Migration def self.up create_table :merit_actions do |t| t.integer :user_id t.string :action_method t.integer :action_value t.boolean :had_errors, default: false t.string :target_model t.integer :target_id t.text :target_data t.boolean :processed, default: false t.timestamps null: false end end def self.down drop_table :merit_actions end end
19.541667
50
0.667377
1d2b724a5e5d51acf5ea7ed3bb2244af0169ed55
2,136
FactoryBot.define do factory :user, aliases: [:author, :assignee, :recipient, :owner, :resource_owner] do email { generate(:email) } name { generate(:name) } username { generate(:username) } password "12345678" confirmed_at { Time.now } confirmation_token { nil } can_create_group true after(:stub) do |user| user.notification_email = user.email end trait :admin do admin true end trait :blocked do after(:build) { |user, _| user.block! } end trait :external do external true end trait :two_factor do two_factor_via_otp end trait :ghost do ghost true after(:build) { |user, _| user.block! } end trait :with_avatar do avatar { fixture_file_upload('spec/fixtures/dk.png') } end trait :two_factor_via_otp do before(:create) do |user| user.otp_required_for_login = true user.otp_secret = User.generate_otp_secret(32) user.otp_grace_period_started_at = Time.now user.generate_otp_backup_codes! end end trait :two_factor_via_u2f do transient { registrations_count 5 } after(:create) do |user, evaluator| create_list(:u2f_registration, evaluator.registrations_count, user: user) end end trait :readme do project_view :readme end trait :commit_email do after(:create) do |user, evaluator| additional = create(:email, :confirmed, user: user, email: "commit-#{user.email}") user.update!(commit_email: additional.email) end end factory :omniauth_user do transient do extern_uid '123456' provider 'ldapmain' end after(:create) do |user, evaluator| identity_attrs = { provider: evaluator.provider, extern_uid: evaluator.extern_uid } if evaluator.respond_to?(:saml_provider) identity_attrs[:saml_provider] = evaluator.saml_provider end user.identities << create(:identity, identity_attrs) end end factory :admin, traits: [:admin] end end
23.217391
90
0.63015
5d4d5325f6012e36d40bd9d14086d8d7b2dbdc22
334
# frozen_string_literal: true control 'noop_imported_node' do describe import_node('nodeC', 'dry-source') do it { should exist } its('city') { should eq 'Brooklyn' } its('building') { should eq 'Big' } its('categories') { should eq %w(Servers Dev) } its('assets') { should eq('vendorPhone' => '311') } end end
30.363636
55
0.640719
9162776e60858d5acd4ed0e6232fbadc0b39a8cf
1,147
require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) Pod::Spec.new do |s| s.name = 'RNBackgroundGeolocation' s.version = package['version'] s.summary = package['description'] s.description = <<-DESC Cross-platform background geolocation module for React Native with battery-saving circular stationary-region monitoring and stop detection. DESC s.homepage = package['homepage'] s.license = package['license'] s.author = package['author'] s.source = { :git => 'https://github.com/transistorsoft/react-native-background-geolocation.git', :tag => s.version } s.platform = :ios, '8.0' s.dependency 'React' s.static_framework = true s.preserve_paths = 'docs', 'CHANGELOG.md', 'LICENSE', 'package.json', 'RNBackgroundGeolocation.ios.js' s.dependency 'CocoaLumberjack', '~> 3.6.1' s.source_files = 'ios/RNBackgroundGeolocation/*.{h,m}' s.libraries = 'sqlite3', 'z' s.vendored_frameworks = 'ios/RNBackgroundGeolocation/TSLocationManager.framework' end
42.481481
132
0.637315
1a1f8a415c667caa2c8c7911e0d31fe60c108ab0
2,912
# == Synopsis # # Simple BibApp citation model # # == Author # # Eric Larson (using Liam's CSL Citation example) # # == Copyright # # Copyright (c) 2008, Eric Larson. # Licensed under the same terms as Ruby - see http://www.ruby-lang.org/en/LICENSE.txt. # # module Bibapp # ---------- Classes ----------- # Defines the Citation class class SimpleCitation attr_accessor :type attr_accessor :title, :container_title, :collection_title attr_accessor :publisher, :publisher_place attr_accessor :event, :event_place attr_accessor :pages, :version, :volume, :number_of_volumes, :issue attr_accessor :medium, :status, :edition, :note, :annote, :abstract attr_accessor :keyword, :number attr_accessor :archive, :archive_location, :archive_place attr_accessor :url, :doi, :isbn attr_accessor :date_issued, :date_accessed attr_accessor :contributors def initialize @contributors = [] end def method_missing(name, *args) case name.to_s when "locator" return resolve_locator else "" end end def authors=(authors) add_contributors(authors, "author") end def authors contributors("author") end def editors=(editors) add_contributors(editors, "editor") end def editors contributors("editor") end def translators=(translators) add_contributors(translators, "translator") end def translators translators("translator") end def contributors(role = nil, sort_key = nil) results = @contributors.collect{|c| c if c.role and c.role == role }.compact end def add_contributor_name(name, role = "author") c = ContributingAgent.new c.name = name c.role = role add_contributor(c) end def add_contributor(contributor) @contributors << contributor if contributor.is_a?(ContributingAgent) end def add_contributors(contribs, role = "author") contribs.each do |contrib| c = ContributingAgent.new c.role = role contrib.each do |key, value| c.send("#{key}=", value) end @contributors << c end end def resolve_locator result = nil result ||= self.issue result ||= self.volume result ||= self.url result end end # Defines the Citation class class ContributingAgent attr_accessor :name, :role def initialize(role = "author", name = nil) @role = role @name = name end def given_name # brittle.... if !name.split(/,/)[1].nil? name.split(/,/)[1] else "" end end def family_name # brittle.... if !name.split(/,/)[0].nil? name.split(/,/)[0] else name end end end end
21.411765
87
0.596497
f72ac4011c88d2903ee505f8d305235427bf12e9
59
class CategoryRecommendationPolicy < ApplicationPolicy end
19.666667
54
0.898305
6accbd89a28b24980a3434a7474ed8e0647d740b
3,591
# frozen_string_literal: true require 'bundler/setup' require 'action_view' require 'action_controller' require 'active_model' require 'active_support/core_ext' # Thanks to Justin French for formtastic spec module FoundationRailsSpecHelper include ActionView::Helpers::FormHelper include ActionView::Helpers::FormOptionsHelper include ActionView::Helpers::DateHelper if defined?(ActionController::PolymorphicRoutes) include ActionController::PolymorphicRoutes end include ActionDispatch::Routing::PolymorphicRoutes include AbstractController::UrlFor if defined?(AbstractController::UrlFor) # to use dom_class in Rails 4 tests # in Rails 5, RecordIdentifier is already required by FormHelper module include ActionView::RecordIdentifier def active_model_validator(kind, attributes, options = {}) validator = mock( "ActiveModel::Validations::#{kind.to_s.titlecase}Validator", attributes: attributes, options: options ) allow(validator).to receive(:kind).and_return(kind) validator end def active_model_presence_validator(attributes, options = {}) active_model_validator(:presence, attributes, options) end def active_model_length_validator(attributes, options = {}) active_model_validator(:length, attributes, options) end def active_model_inclusion_validator(attributes, options = {}) active_model_validator(:inclusion, attributes, options) end def active_model_numericality_validator(attributes, options = {}) active_model_validator(:numericality, attributes, options) end def mock_everything mock_author mock_books mock_genres end # Resource-oriented styles like form_for(@post) will expect a path method # for the object, so we're defining some here. # the argument is required for Rails 4 tests def authors_path(*_args) '/authors' end def _routes double('_routes', polymorphic_mappings: {}) end def self.included(base) base.class_eval do attr_accessor :output_buffer def protect_against_forgery? false end end end private def mock_author @author = ::Author.new { login: 'fred_smith', email: '[email protected]', url: 'http://example.com', some_number: '42', phone: '317 456 2564', active: true, description: 'bla bla bla', birthdate: DateTime.parse('1969-06-18 20:30'), forty_two: DateTime.parse('1969-06-18 20:30') + 42.years, time_zone: 'Perth', publish_date: Date.new(2000, 1, 1), favorite_color: '#424242', favorite_book: nil }.each do |m, v| allow(@author).to receive(m).and_return(v) end end def mock_books mock_book_0 mock_book_1 allow(::Book).to receive(:all).and_return([@book_0, @book_1]) end def mock_book_0 @book_0 = ::Book.new allow(@book_0).to receive(:id).and_return('78') allow(@book_0).to receive(:title).and_return("Gulliver's Travels") end def mock_book_1 @book_1 = ::Book.new allow(@book_1).to receive(:id).and_return('133') allow(@book_1).to receive(:title).and_return('Treasure Island') end def mock_genres mock_genre_0 mock_genre_1 allow(::Genre).to receive(:all).and_return([@genre_0, @genre_1]) end def mock_genre_0 @genre_0 = ::Genre.new allow(@genre_0).to receive(:name).and_return('Exploration') allow(@genre_0).to receive(:books).and_return([@book_0]) end def mock_genre_1 @genre_1 = ::Genre.new allow(@genre_1).to receive(:name).and_return('Pirate Exploits') allow(@genre_1).to receive(:books).and_return([@book_1]) end end
28.728
80
0.715121
28fa11b7a7999ba218e321d82007a93bff3dce1a
2,495
class Freediameter < Formula desc "Open source Diameter (Authentication) protocol implementation" homepage "http://www.freediameter.net" url "http://www.freediameter.net/hg/freeDiameter/archive/1.2.1.tar.gz" sha256 "bd7f105542e9903e776aa006c6931c1f5d3d477cb59af33a9162422efa477097" head "http://www.freediameter.net/hg/freeDiameter", :using => :hg bottle do sha256 "8a16e612b93ae8a1c55fe090f0301a7d778c858730a144c152aa6eb8080d8c68" => :high_sierra sha256 "615bfb731e99779234533bed9f6def01487783e1b1b22f3f6d41efceef1899bb" => :sierra sha256 "6d562bd62780a6b942b6ca3b4b1807a6ac3eef80209748b6748bcbc8b6b389b5" => :el_capitan end option "with-all-extensions", "Enable all extensions" depends_on "cmake" => :build depends_on "gnutls" depends_on "libgcrypt" depends_on "libidn" if build.with? "all-extensions" depends_on "swig" => :build depends_on :postgresql depends_on :mysql end def install args = std_cmake_args + %W[ -DDEFAULT_CONF_PATH=#{etc} -DDISABLE_SCTP=ON ] args << "-DALL_EXTENSIONS=ON" if build.with? "all-extensions" mkdir "build" do system "cmake", "..", *args system "make" system "make", "install" end doc.install Dir["doc/*"] pkgshare.install "contrib" end def post_install return if File.exist?(etc/"freeDiameter.conf") cp doc/"freediameter.conf.sample", etc/"freeDiameter.conf" end def caveats; <<~EOS To configure freeDiameter, edit #{etc}/freeDiameter.conf to taste. Sample configuration files can be found in #{doc}. For more information about freeDiameter configuration options, read: http://www.freediameter.net/trac/wiki/Configuration Other potentially useful files can be found in #{opt_pkgshare}/contrib. EOS end plist_options :startup => true def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/freeDiameterd</string> </array> <key>KeepAlive</key> <dict> <key>NetworkState</key> <true/> </dict> </dict> </plist> EOS end test do assert_match version.to_s, shell_output("#{bin}/freeDiameterd --version") end end
28.033708
115
0.676152
f70585796ea801f248a74dc14d69dbce8c60f028
638
require "figaro/cli/task" module Figaro class CLI < Thor class AptibleSet < Task def run system(configuration, command) end private def command "aptible config:set #{vars} #{for_app} #{for_remote}" end def for_app options[:app] ? "--app=#{options[:app]}" : nil end def for_remote options[:remote] ? "--remote=#{options[:remote]}" : nil end def vars configuration.keys.map { |k| var(k) }.join(" ") end def var(key) Gem.win_platform? ? %(#{key}="%#{key}%") : %(#{key}="$#{key}") end end end end
18.764706
70
0.520376
877d273531ca233c9937c35366acee7548ff7efd
136
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_pres_session'
34
74
0.801471
b92d67a6e6a7c983717ac8e1700510f41acb432d
340
require 'settings' module AIProject # Now it will be with PRECISION class Location attr_reader :x, :y def initialize(x, y) @x = x @y = y end def x=(value) @x = value.round(Settings::PRECISION) end def y=(value) @y = value.round(Settings::PRECISION) end end end
17
44
0.552941
393b0d6698e87abe63ce87653483d05a691659be
3,158
require "open-uri" NEW_RELEASE_TEMPLATE = " NEW RELEASE: ============= Image URL: %{image_url} Version: %{version} Platform: %{platform} Channel: %{channel} " OLD_RELEASE_TEMPLATE = " NOT SAVING %{platform} %{version} (%{channel}) " namespace :releases do module ReleaseTask def self.download_metadata(tag_name) real_url = "https://api.github.com/repos/farmbot/farmbot_os/releases/tags/#{tag_name}" JSON.parse(URI.open(real_url).read, symbolize_names: true) end def self.select_version(choices) puts "=== AVAILABLE RELEASES ===" choices.each_with_index do |version, index| puts "#{index}) #{version}" end puts "Select a release to publish:" choices.fetch(STDIN.gets.chomp.to_i) end def self.get_release_list uri = "https://api.github.com/repos/farmbot/farmbot_os/releases" file = URI.open(uri) raw_json = file.read json = JSON.parse(raw_json, symbolize_names: true).pluck(:tag_name) json.first(9).sort.reverse end def self.get_channel puts "=== AVAILABLE CHANNELS ===" puts "Select a channel to publish to:" Release::CHANNEL.each_with_index do |chan, inx| puts "#{inx}) #{chan}" end Release::CHANNEL.fetch(STDIN.gets.chomp.to_i) end def self.print_release(release) is_new = release.saved_change_to_attribute?(:id) tpl = is_new ? NEW_RELEASE_TEMPLATE : OLD_RELEASE_TEMPLATE params = release.as_json.symbolize_keys puts tpl % params release end def self.create_releases(metadata, channel) output = Releases::Parse.run!(metadata) .map { |params| Releases::Create.run!(params.merge(channel: channel)) } .map { |release| print_release(release) } if channel == "stable" # QA cycles are expected to be short. # Do not allow devices to stay on unstable channels # when a QA cycle ends. puts "=== Moving all devices to `stable`" FbosConfig .where .not(update_channel: "stable") .update_all(update_channel: "stable") end output end def self.prevent_disaster(version:, chan:) if version.include?("rc") && chan == Release::STABLE puts "Refusing to publish unstable release candidate to stable channel." exit 1 end end end desc "Send upgrade notification to devices that are online" task notify: :environment do Devices::UnattendedUpgrade.delay.run!() end desc "Publish the latest release found on farmbot/farmbot_os github org" task publish: :environment do choices = ReleaseTask.get_release_list version = ReleaseTask.select_version(choices) chan = ReleaseTask.get_channel ReleaseTask.prevent_disaster(version: version, chan: chan) json = ReleaseTask.download_metadata(version) releases = ReleaseTask.create_releases(json, chan) # Clean out old releases for $CHANNEL Release .where(channel: chan) .where.not(id: releases.pluck(:id)) .map do |release| puts "Destroying old release ##{release.id}" release.destroy! end end end
30.07619
92
0.659278
08a8b4ac248b8e597d374f31a0da55676ee3f0d7
141
require 'rails_helper' RSpec.describe Train::Type::Note::Info, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
23.5
56
0.730496
6221d6fb45fb7973a11cdfb06d4c07a741b8cf43
3,681
# frozen_string_literal: true require 'spec_helper' describe Gitlab::RepositorySetCache, :clean_gitlab_redis_cache do let_it_be(:project) { create(:project) } let(:repository) { project.repository } let(:namespace) { "#{repository.full_path}:#{project.id}" } let(:cache) { described_class.new(repository) } describe '#cache_key' do subject { cache.cache_key(:foo) } shared_examples 'cache_key examples' do it 'includes the namespace' do is_expected.to eq("foo:#{namespace}:set") end context 'with a given namespace' do let(:extra_namespace) { 'my:data' } let(:cache) { described_class.new(repository, extra_namespace: extra_namespace) } it 'includes the full namespace' do is_expected.to eq("foo:#{namespace}:#{extra_namespace}:set") end end end describe 'project repository' do it_behaves_like 'cache_key examples' do let(:repository) { project.repository } end end describe 'personal snippet repository' do let_it_be(:personal_snippet) { create(:personal_snippet) } let(:namespace) { repository.full_path } it_behaves_like 'cache_key examples' do let(:repository) { personal_snippet.repository } end end describe 'project snippet repository' do let_it_be(:project_snippet) { create(:project_snippet, project: project) } it_behaves_like 'cache_key examples' do let(:repository) { project_snippet.repository } end end end describe '#expire' do subject { cache.expire(*keys) } before do cache.write(:foo, ['value']) cache.write(:bar, ['value2']) end it 'actually wrote the values' do expect(cache.read(:foo)).to contain_exactly('value') expect(cache.read(:bar)).to contain_exactly('value2') end context 'single key' do let(:keys) { %w(foo) } it { is_expected.to eq(1) } it 'deletes the given key from the cache' do subject expect(cache.read(:foo)).to be_empty end end context 'multiple keys' do let(:keys) { %w(foo bar) } it { is_expected.to eq(2) } it 'deletes the given keys from the cache' do subject expect(cache.read(:foo)).to be_empty expect(cache.read(:bar)).to be_empty end end context 'no keys' do let(:keys) { [] } it { is_expected.to eq(0) } end context "unlink isn't supported" do before do allow_any_instance_of(Redis).to receive(:unlink) { raise ::Redis::CommandError } end it 'still deletes the given key' do expect(cache.expire(:foo)).to eq(1) expect(cache.read(:foo)).to be_empty end end end describe '#exist?' do it 'checks whether the key exists' do expect(cache.exist?(:foo)).to be(false) cache.write(:foo, ['value']) expect(cache.exist?(:foo)).to be(true) end end describe '#fetch' do let(:blk) { -> { ['block value'] } } subject { cache.fetch(:foo, &blk) } it 'fetches the key from the cache when filled' do cache.write(:foo, ['value']) is_expected.to contain_exactly('value') end it 'writes the value of the provided block when empty' do cache.expire(:foo) is_expected.to contain_exactly('block value') expect(cache.read(:foo)).to contain_exactly('block value') end end describe '#include?' do it 'checks inclusion in the Redis set' do cache.write(:foo, ['value']) expect(cache.include?(:foo, 'value')).to be(true) expect(cache.include?(:foo, 'bar')).to be(false) end end end
25.040816
89
0.625645
2691326e861ff7774adc0c64c6f25c740a8b82fc
1,897
# frozen_string_literal: true module Capybara module RSpecMatcherProxies def all(*args, &block) if defined?(::RSpec::Matchers::BuiltIn::All) && args.first.respond_to?(:matches?) ::RSpec::Matchers::BuiltIn::All.new(*args) else find_all(*args, &block) end end def within(*args) if block_given? within_element(*args, &Proc.new) else be_within(*args) end end end end if RUBY_ENGINE == 'jruby' module Capybara::DSL class <<self remove_method :included def included(base) warn 'including Capybara::DSL in the global scope is not recommended!' if base == Object base.send(:include, ::Capybara::RSpecMatcherProxies) if defined?(::RSpec::Matchers) && base.include?(::RSpec::Matchers) super end end end if defined?(::RSpec::Matchers) module ::RSpec::Matchers def self.included(base) base.send(:include, ::Capybara::RSpecMatcherProxies) if base.include?(::Capybara::DSL) super end end end else module Capybara::DSLRSpecProxyInstaller module ClassMethods def included(base) base.include(::Capybara::RSpecMatcherProxies) if defined?(::RSpec::Matchers) && base.include?(::RSpec::Matchers) super end end def self.prepended(base) class <<base prepend ClassMethods end end end module Capybara::RSpecMatcherProxyInstaller module ClassMethods def included(base) base.include(::Capybara::RSpecMatcherProxies) if base.include?(::Capybara::DSL) super end end def self.prepended(base) class <<base prepend ClassMethods end end end Capybara::DSL.prepend ::Capybara::DSLRSpecProxyInstaller ::RSpec::Matchers.prepend ::Capybara::RSpecMatcherProxyInstaller if defined?(::RSpec::Matchers) end
24.012658
127
0.642594
f77546e9ee5833586c2dbbacf44e64ad9d1c00cb
813
Pod::Spec.new do |s| s.name = "SLAppPay" s.version = "1.0.0" s.swift_version = "5.0" s.summary = "支付" s.description = "微信支付,支付宝支付" s.homepage = "https://github.com/2NU71AN9/SLAppPay" #项目主页,不是git地址 s.license = { :type => "MIT", :file => "LICENSE" } #开源协议 s.author = { "孙梁" => "[email protected]" } s.platform = :ios, "11.0" s.source = { :git => "https://github.com/2NU71AN9/SLAppPay.git", :tag => "v#{s.version}" } #存储库的git地址,以及tag值 s.source_files = "SLAppPay/AppPay/**/*.{h,m,swift}" #需要托管的源代码路径 #s.resources = "SLAppPay/AppPay/**/*.a" s.vendored_libraries = "SLAppPay/AppPay/**/*.a" s.requires_arc = true #是否支持ARC s.dependency "HandyJSON" s.dependency "PKHUD" s.dependency "WechatOpenSDK" s.dependency "AlipaySDK-iOS" end
35.347826
116
0.597786
3306cab9424f79042b43b71dcfe5924e2bede649
1,435
# typed: false require 'ddtrace/contrib/analytics' require 'ddtrace/contrib/action_cable/event' module Datadog module Contrib module ActionCable module Events # Defines instrumentation for 'broadcast.action_cable' event. # # A single 'broadcast' event will trigger as many 'transmit' events # as there are clients subscribed to a channel. module Broadcast include ActionCable::Event EVENT_NAME = 'broadcast.action_cable'.freeze module_function def event_name self::EVENT_NAME end def span_name Ext::SPAN_BROADCAST end def span_type # Starts a broadcast of messages over WebSockets Datadog::Ext::AppTypes::WEB end def process(span, _event, _id, payload) channel = payload[:broadcasting] # Channel has high cardinality span.service = configuration[:service_name] span.span_type = span_type # Set analytics sample rate if Contrib::Analytics.enabled?(configuration[:analytics_enabled]) Contrib::Analytics.set_sample_rate(span, configuration[:analytics_sample_rate]) end span.set_tag(Ext::TAG_CHANNEL, channel) span.set_tag(Ext::TAG_BROADCAST_CODER, payload[:coder]) end end end end end end
28.137255
93
0.616028
1c54dcec82e45865f001a7be54b7a25f79bcb007
5,442
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: MIT # DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN. # vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments require 'date' module VSphereAutomation module VCenter class VcenterVmHardwareDiskCreateResult attr_accessor :value # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'value' => :'value' } end # Attribute type mapping. def self.openapi_types { :'value' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'value') self.value = attributes[:'value'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @value.nil? invalid_properties.push('invalid value for "value", value cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @value.nil? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && value == o.value end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [value].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN, :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = VSphereAutomation::VCenter.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end end
28.946809
111
0.619993
79509bb0239645670b43719700985b068b496f2b
1,511
# encoding: utf-8 #--- # @author [email protected] #--- class SessionsController < ApplicationController def new if Rails.configuration.shibboleth redirect_to shibboleth_path else redirect_to developer_path end end def developer find_or_create_user('developer') end def shibboleth find_or_create_user('shibboleth') end def find_or_create_user(auth_type) find_or_create_method = "find_or_create_for_#{auth_type.downcase}".to_sym auth = request.env['omniauth.auth'] user = User.send(find_or_create_method, auth) if auth_type == 'shibboleth' && !User.in_supergroup?(auth.uid) render file: Rails.root.join('public', '403'), formats: [:html], status: 403, layout: false else create_user_session(user) if user redirect_to root_url, notice: "You have successfully authenticated from #{auth_type} account!" end end def destroy destroy_user_session flash[:alert] = ('You have been logged out of this application. To logout of all Single Sign-On applications, close your browser or <a href="/Shibboleth.sso/Logout?return=https://a4.ucsd.edu/tritON/logout?target=' + root_url + '">terminate your Shibboleth session</a>.').html_safe if Rails.configuration.shibboleth redirect_to root_url end private def create_user_session(user) session[:user_name] = user.full_name session[:user_id] = user.uid end def destroy_user_session session[:user_id] = nil session[:user_name] = nil end end
26.982143
318
0.718068
6a1d6b18b48364ed02ad6b707fc1f376deb2a66e
461
Gem::Specification.new do |gem| gem.name = "vpmframe" gem.version = "0.10.0" gem.authors = ["Chris Van Patten"] gem.email = ["[email protected]"] gem.description = "vpmframe Ruby tools" gem.summary = "General vpmframe Ruby utilities and requirements" gem.homepage = "http://github.com/vanpattenmedia/vpmframe-gem" gem.files = `git ls-files`.split("\n") gem.require_paths = ["lib"] end
32.928571
72
0.618221
4a22bd6f342a8200e136a9ad2657e5e95c9fc210
2,011
require 'spec_helper' require Rails.root.join('db', 'migrate', '20180201110056_add_foreign_keys_to_todos.rb') describe AddForeignKeysToTodos, :migration do let(:todos) { table(:todos) } let(:project) { create(:project) } let(:user) { create(:user) } context 'add foreign key on user_id' do let!(:todo_with_user) { create_todo(user_id: user.id) } let!(:todo_without_user) { create_todo(user_id: 4711) } it 'removes orphaned todos without corresponding user' do expect { migrate! }.to change { Todo.count }.from(2).to(1) end it 'does not remove entries with valid user_id' do expect { migrate! }.not_to change { todo_with_user.reload } end end context 'add foreign key on author_id' do let!(:todo_with_author) { create_todo(author_id: user.id) } let!(:todo_with_invalid_author) { create_todo(author_id: 4711) } it 'removes orphaned todos by author_id' do expect { migrate! }.to change { Todo.count }.from(2).to(1) end it 'does not touch author_id for valid entries' do expect { migrate! }.not_to change { todo_with_author.reload } end end context 'add foreign key on note_id' do let(:note) { create(:note) } let!(:todo_with_note) { create_todo(note_id: note.id) } let!(:todo_with_invalid_note) { create_todo(note_id: 4711) } let!(:todo_without_note) { create_todo(note_id: nil) } it 'deletes todo if note_id is set but does not exist in notes table' do expect { migrate! }.to change { Todo.count }.from(3).to(2) end it 'does not touch entry if note_id is nil' do expect { migrate! }.not_to change { todo_without_note.reload } end it 'does not touch note_id for valid entries' do expect { migrate! }.not_to change { todo_with_note.reload } end end def create_todo(**opts) todos.create!( project_id: project.id, user_id: user.id, author_id: user.id, target_type: '', action: 0, state: '', **opts ) end end
30.469697
87
0.664843
26b1fa325015368a4516acc9128d4dcb984a6fe8
1,298
Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send # config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict if ::Draftsman.active_record_protected_attributes? # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true end
39.333333
109
0.781972
335135696ef899c28c4a5541770b6d378ec30b7f
5,538
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Gfm::ReferenceRewriter do let_it_be(:group) { create(:group) } let_it_be(:user) { create(:user) } let(:new_project) { create(:project, name: 'new-project', group: group) } let(:old_project) { create(:project, name: 'old-project', group: group) } let(:old_project_ref) { old_project.to_reference_base(new_project) } let(:text) { 'some text' } before do old_project.add_reporter(user) end describe '#rewrite' do subject do described_class.new(text, old_project, user).rewrite(new_project) end context 'multiple issues and merge requests referenced' do let!(:issue_first) { create(:issue, project: old_project) } let!(:issue_second) { create(:issue, project: old_project) } let!(:merge_request) { create(:merge_request, source_project: old_project) } context 'plain text description' do let(:text) { 'Description that references #1, #2 and !1' } it { is_expected.to include issue_first.to_reference(new_project) } it { is_expected.to include issue_second.to_reference(new_project) } it { is_expected.to include merge_request.to_reference(new_project) } end context 'description with ignored elements' do let(:text) do "Hi. This references #1, but not `#2`\n" \ '<pre>and not !1</pre>' end it { is_expected.to include issue_first.to_reference(new_project) } it { is_expected.not_to include issue_second.to_reference(new_project) } it { is_expected.not_to include merge_request.to_reference(new_project) } end context 'rewrite ambigous references' do context 'url' do let(:url) { 'http://gitlab.com/#1' } let(:text) { "This references #1, but not #{url}" } it { is_expected.to include url } end context 'code' do let(:text) { "#1, but not `[#1]`" } it { is_expected.to eq "#{issue_first.to_reference(new_project)}, but not `[#1]`" } end context 'code reverse' do let(:text) { "not `#1`, but #1" } it { is_expected.to eq "not `#1`, but #{issue_first.to_reference(new_project)}" } end context 'code in random order' do let(:text) { "#1, `#1`, #1, `#1`" } let(:ref) { issue_first.to_reference(new_project) } it { is_expected.to eq "#{ref}, `#1`, #{ref}, `#1`" } end context 'description with project labels' do let!(:label) { create(:label, id: 123, name: 'test', project: old_project) } context 'label referenced by id' do let(:text) { '#1 and ~123' } it { is_expected.to eq %Q{#{old_project_ref}#1 and #{old_project_ref}~123} } end context 'label referenced by text' do let(:text) { '#1 and ~"test"' } it { is_expected.to eq %Q{#{old_project_ref}#1 and #{old_project_ref}~123} } end end context 'description with group labels' do let(:old_group) { create(:group) } let!(:group_label) { create(:group_label, id: 321, name: 'group label', group: old_group) } before do old_project.update(namespace: old_group) end context 'label referenced by id' do let(:text) { '#1 and ~321' } it { is_expected.to eq %Q{#{old_project_ref}#1 and #{old_project_ref}~321} } end context 'label referenced by text' do let(:text) { '#1 and ~"group label"' } it { is_expected.to eq %Q{#{old_project_ref}#1 and #{old_project_ref}~321} } end end end end context 'with a commit' do let(:old_project) { create(:project, :repository, name: 'old-project', group: group) } let(:commit) { old_project.commit } context 'reference to an absolute URL to a commit' do let(:text) { Gitlab::UrlBuilder.build(commit) } it { is_expected.to eq(text) } end context 'reference to a commit' do let(:text) { commit.id } it { is_expected.to eq("#{old_project_ref}@#{text}") } end end context 'reference contains project milestone' do let!(:milestone) do create(:milestone, title: '9.0', project: old_project) end let(:text) { 'milestone: %"9.0"' } it { is_expected.to eq %Q[milestone: #{old_project_ref}%"9.0"] } end context 'when referring to group milestone' do let!(:milestone) do create(:milestone, title: '10.0', group: group) end let(:text) { 'milestone %"10.0"' } it { is_expected.to eq text } end context 'when referring to a group' do let(:text) { "group @#{group.full_path}" } it { is_expected.to eq text } end context 'when referring to a user' do let(:text) { "user @#{user.full_path}" } it { is_expected.to eq text } end context 'when referable has a nil reference' do before do create(:milestone, title: '9.0', project: old_project) allow_any_instance_of(Milestone) .to receive(:to_reference) .and_return(nil) end let(:text) { 'milestone: %"9.0"' } it 'raises an error that should be fixed' do expect { subject }.to raise_error( described_class::RewriteError, 'Unspecified reference detected for Milestone' ) end end end end
30.428571
101
0.59191
1a8a0ea5b44915d8c87ec70e4278e6b4d53efc3b
499
require 'formula' class Coccinelle < Formula homepage 'http://coccinelle.lip6.fr/' url 'http://coccinelle.lip6.fr/distrib/coccinelle-1.0.0-rc17.tgz' sha1 '5c13e521578e20d3805f571dc86931cbd8d63ccd' depends_on "objective-caml" def install system "./configure", "--disable-dependency-tracking", "--enable-ocaml", "--enable-opt", "--prefix=#{prefix}" system "make" system "make", "install" end end
26.263158
67
0.593186
4a65c978e5c36da4fc8a2cd05d5ab4355b240732
755
class Profiles::EmailsController < ApplicationController layout "profile" def index @primary = current_user.email @emails = current_user.emails end def create @email = current_user.emails.new(email_params) flash[:alert] = @email.errors.full_messages.first unless @email.save redirect_to profile_emails_url end def destroy @email = current_user.emails.find(params[:id]) @email.destroy current_user.set_notification_email current_user.save if current_user.notification_email_changed? respond_to do |format| format.html { redirect_to profile_emails_url } format.js { render nothing: true } end end private def email_params params.require(:email).permit(:email) end end
20.972222
72
0.724503
62e8ef6f11aad2b39b6f3ae856e465762edd6851
643
module Arel module Nodes class And < Arel::Nodes::Node attr_reader :children def initialize children, right = nil super() unless Array === children warn "(#{caller.first}) AND nodes should be created with a list" children = [children, right] end @children = children end def left children.first end def right children[1] end def hash children.hash end def eql? other self.class == other.class && self.children == other.children end alias :== :eql? end end end
18.371429
74
0.534992
3362b194772991f37c7bb37d3449cabc096edf3d
359
class CreateParties < ActiveRecord::Migration[5.2] def change create_table :parties do |t| t.string :title t.text :description t.references :comuna, foreign_key: true t.string :address t.integer :cost t.boolean :search, :default => true t.boolean :ended, :default => false t.timestamps end end end
22.4375
50
0.635097
79df4dba539ff97be2e6f44d57614073ae1f665c
83
require 'test_helper' class InstrumentsDatasetsTest < ActiveSupport::TestCase end
16.6
55
0.843373
ab6a6992725304c543e153645fb348f4005dd723
294
module TD::Types # A chat was blocked or unblocked. # # @attr chat_id [Integer] Chat identifier. # @attr is_blocked [Boolean] New value of is_blocked. class Update::ChatIsBlocked < Update attribute :chat_id, TD::Types::Integer attribute :is_blocked, TD::Types::Bool end end
26.727273
55
0.707483
330a01b66f6d0cdccf434d4d78d0a9d71a0587ba
1,503
class Proxytunnel < Formula desc "Create TCP tunnels through HTTPS proxies" homepage "https://github.com/proxytunnel/proxytunnel" url "https://github.com/proxytunnel/proxytunnel/archive/v1.10.20210604.tar.gz" sha256 "47b7ef7acd36881744db233837e7e6be3ad38e45dc49d2488934882fa2c591c3" license "GPL-2.0-or-later" bottle do sha256 cellar: :any, arm64_monterey: "65570cf9f771e78f7c3a08c88630fc5af7100df0025ff1c35286306735e37a40" sha256 cellar: :any, arm64_big_sur: "97ccd9b616094e055755979daed8216f418d2aeb4639cf978b5df289d1c7e4ea" sha256 cellar: :any, monterey: "c3058d31c2f16a210b122115dfdfa5e29a36905185a505abeb4e9f02d04b9d09" sha256 cellar: :any, big_sur: "88027c4126895fb5c1f25b1045df6bd3e79dd9d4c3e0e7c9623c0538f72d0df7" sha256 cellar: :any, catalina: "b69ed34113341b0c25778b0b10af2079d17e32e2f7288fa2feed80677124ec15" sha256 cellar: :any, mojave: "9f941a568397ae9ec164cde36aaafe90237f36b516e1403985e10687601cf15a" sha256 cellar: :any_skip_relocation, x86_64_linux: "f65fb0bf533922b366e1c60989fd0db345afdf7769eb88ae6bdb9aaa5833d482" end depends_on "asciidoc" => :build depends_on "xmlto" => :build depends_on "[email protected]" def install ENV["XML_CATALOG_FILES"] = etc/"xml/catalog" system "make" system "make", "install", "prefix=#{prefix}" end test do system "#{bin}/proxytunnel", "--version" end end
46.96875
123
0.726547
3927d435a5482a3e6df1c7897228b8a466c5830c
137
require "test_helper" class BooksControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
17.125
59
0.737226
6adfb2ca2f1d2abf57b93be5853815c30e0da267
27,707
# frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "gapic/common" require "gapic/operation" require "google/cloud/security_center/v1p1beta1/version" require "google/cloud/security_center/v1p1beta1/security_center/client" require "google/longrunning/operations_pb" module Google module Cloud module SecurityCenter module V1p1beta1 module SecurityCenter # Service that implements Longrunning Operations API. class Operations # @private attr_reader :operations_stub ## # Configuration for the SecurityCenter Operations API. # # @yield [config] Configure the Operations client. # @yieldparam config [Operations::Configuration] # # @return [Operations::Configuration] # def self.configure @configure ||= Operations::Configuration.new yield @configure if block_given? @configure end ## # Configure the SecurityCenter Operations instance. # # The configuration is set to the derived mode, meaning that values can be changed, # but structural changes (adding new fields, etc.) are not allowed. Structural changes # should be made on {Operations.configure}. # # @yield [config] Configure the Operations client. # @yieldparam config [Operations::Configuration] # # @return [Operations::Configuration] # def configure yield @config if block_given? @config end ## # Create a new Operations client object. # # @yield [config] Configure the Client client. # @yieldparam config [Operations::Configuration] # def initialize # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "gapic/grpc" require "google/longrunning/operations_services_pb" # Create the configuration object @config = Configuration.new Operations.configure # Yield the configuration if needed yield @config if block_given? # Create credentials credentials = @config.credentials credentials ||= Credentials.default scope: @config.scope if credentials.is_a?(String) || credentials.is_a?(Hash) credentials = Credentials.new credentials, scope: @config.scope end @operations_stub = Gapic::ServiceStub.new( Google::Longrunning::Operations::Stub, credentials: credentials, endpoint: @config.endpoint, channel_args: @config.channel_args, interceptors: @config.interceptors ) end # Service calls ## # Lists operations that match the specified filter in the request. If the # server doesn't support this method, it returns `UNIMPLEMENTED`. # # NOTE: the `name` binding below allows API services to override the binding # to use different resource name schemes, such as `users/*/operations`. # # @overload list_operations(request, options = nil) # @param request [Google::Longrunning::ListOperationsRequest | Hash] # Lists operations that match the specified filter in the request. If the # server doesn't support this method, it returns `UNIMPLEMENTED`. # # NOTE: the `name` binding below allows API services to override the binding # to use different resource name schemes, such as `users/*/operations`. # @param options [Gapic::CallOptions, Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload list_operations(name: nil, filter: nil, page_size: nil, page_token: nil) # @param name [String] # The name of the operation collection. # @param filter [String] # The standard list filter. # @param page_size [Integer] # The standard list page size. # @param page_token [String] # The standard list page token. # # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [Gapic::PagedEnumerable<Gapic::Operation>] # @yieldparam operation [GRPC::ActiveCall::Operation] # # @return [Gapic::PagedEnumerable<Gapic::Operation>] # # @raise [Google::Cloud::Error] if the RPC is aborted. # def list_operations request, options = nil raise ArgumentError, "request must be provided" if request.nil? request = Gapic::Protobuf.coerce request, to: Google::Longrunning::ListOperationsRequest # Converts hash and nil to an options object options = Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.list_operations.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::SecurityCenter::V1p1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.list_operations.timeout, metadata: metadata, retry_policy: @config.rpcs.list_operations.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :list_operations, request, options: options do |response, operation| wrap_lro_operation = ->(op_response) { Gapic::Operation.new op_response, @operations_client } response = Gapic::PagedEnumerable.new @operations_stub, :list_operations, request, response, operation, options, format_resource: wrap_lro_operation yield response, operation if block_given? return response end rescue GRPC::BadStatus => e raise Google::Cloud::Error.from_error(e) end ## # Gets the latest state of a long-running operation. Clients can use this # method to poll the operation result at intervals as recommended by the API # service. # # @overload get_operation(request, options = nil) # @param request [Google::Longrunning::GetOperationRequest | Hash] # Gets the latest state of a long-running operation. Clients can use this # method to poll the operation result at intervals as recommended by the API # service. # @param options [Gapic::CallOptions, Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload get_operation(name: nil) # @param name [String] # The name of the operation resource. # # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [Gapic::Operation] # @yieldparam operation [GRPC::ActiveCall::Operation] # # @return [Gapic::Operation] # # @raise [Google::Cloud::Error] if the RPC is aborted. # def get_operation request, options = nil raise ArgumentError, "request must be provided" if request.nil? request = Gapic::Protobuf.coerce request, to: Google::Longrunning::GetOperationRequest # Converts hash and nil to an options object options = Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.get_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::SecurityCenter::V1p1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.get_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.get_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :get_operation, request, options: options do |response, operation| response = Gapic::Operation.new response, @operations_client, options: options yield response, operation if block_given? return response end rescue GRPC::BadStatus => e raise Google::Cloud::Error.from_error(e) end ## # Deletes a long-running operation. This method indicates that the client is # no longer interested in the operation result. It does not cancel the # operation. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. # # @overload delete_operation(request, options = nil) # @param request [Google::Longrunning::DeleteOperationRequest | Hash] # Deletes a long-running operation. This method indicates that the client is # no longer interested in the operation result. It does not cancel the # operation. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. # @param options [Gapic::CallOptions, Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload delete_operation(name: nil) # @param name [String] # The name of the operation resource to be deleted. # # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [Google::Protobuf::Empty] # @yieldparam operation [GRPC::ActiveCall::Operation] # # @return [Google::Protobuf::Empty] # # @raise [Google::Cloud::Error] if the RPC is aborted. # def delete_operation request, options = nil raise ArgumentError, "request must be provided" if request.nil? request = Gapic::Protobuf.coerce request, to: Google::Longrunning::DeleteOperationRequest # Converts hash and nil to an options object options = Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.delete_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::SecurityCenter::V1p1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.delete_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.delete_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :delete_operation, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue GRPC::BadStatus => e raise Google::Cloud::Error.from_error(e) end ## # Starts asynchronous cancellation on a long-running operation. The server # makes a best effort to cancel the operation, but success is not # guaranteed. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. Clients can use # Operations.GetOperation or # other methods to check whether the cancellation succeeded or whether the # operation completed despite cancellation. On successful cancellation, # the operation is not deleted; instead, it becomes an operation with # an {Google::Longrunning::Operation#error Operation.error} value with a {Google::Rpc::Status#code google.rpc.Status.code} of 1, # corresponding to `Code.CANCELLED`. # # @overload cancel_operation(request, options = nil) # @param request [Google::Longrunning::CancelOperationRequest | Hash] # Starts asynchronous cancellation on a long-running operation. The server # makes a best effort to cancel the operation, but success is not # guaranteed. If the server doesn't support this method, it returns # `google.rpc.Code.UNIMPLEMENTED`. Clients can use # Operations.GetOperation or # other methods to check whether the cancellation succeeded or whether the # operation completed despite cancellation. On successful cancellation, # the operation is not deleted; instead, it becomes an operation with # an {Google::Longrunning::Operation#error Operation.error} value with a {Google::Rpc::Status#code google.rpc.Status.code} of 1, # corresponding to `Code.CANCELLED`. # @param options [Gapic::CallOptions, Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload cancel_operation(name: nil) # @param name [String] # The name of the operation resource to be cancelled. # # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [Google::Protobuf::Empty] # @yieldparam operation [GRPC::ActiveCall::Operation] # # @return [Google::Protobuf::Empty] # # @raise [Google::Cloud::Error] if the RPC is aborted. # def cancel_operation request, options = nil raise ArgumentError, "request must be provided" if request.nil? request = Gapic::Protobuf.coerce request, to: Google::Longrunning::CancelOperationRequest # Converts hash and nil to an options object options = Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.cancel_operation.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::SecurityCenter::V1p1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "name" => request.name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.cancel_operation.timeout, metadata: metadata, retry_policy: @config.rpcs.cancel_operation.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @operations_stub.call_rpc :cancel_operation, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue GRPC::BadStatus => e raise Google::Cloud::Error.from_error(e) end ## # Configuration class for the Operations API. # # This class represents the configuration for Operations, # providing control over timeouts, retry behavior, logging, transport # parameters, and other low-level controls. Certain parameters can also be # applied individually to specific RPCs. See # {Google::Longrunning::Operations::Client::Configuration::Rpcs} # for a list of RPCs that can be configured independently. # # Configuration can be applied globally to all clients, or to a single client # on construction. # # # Examples # # To modify the global config, setting the timeout for list_operations # to 20 seconds, and all remaining timeouts to 10 seconds: # # Google::Longrunning::Operations::Client.configure do |config| # config.timeout = 10_000 # config.rpcs.list_operations.timeout = 20_000 # end # # To apply the above configuration only to a new client: # # client = Google::Longrunning::Operations::Client.new do |config| # config.timeout = 10_000 # config.rpcs.list_operations.timeout = 20_000 # end # # @!attribute [rw] endpoint # The hostname or hostname:port of the service endpoint. # Defaults to `"securitycenter.googleapis.com"`. # @return [String] # @!attribute [rw] credentials # Credentials to send with calls. You may provide any of the following types: # * (`String`) The path to a service account key file in JSON format # * (`Hash`) A service account key as a Hash # * (`Google::Auth::Credentials`) A googleauth credentials object # (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html)) # * (`Signet::OAuth2::Client`) A signet oauth2 client object # (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html)) # * (`GRPC::Core::Channel`) a gRPC channel with included credentials # * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object # * (`nil`) indicating no credentials # @return [Object] # @!attribute [rw] scope # The OAuth scopes # @return [Array<String>] # @!attribute [rw] lib_name # The library name as recorded in instrumentation and logging # @return [String] # @!attribute [rw] lib_version # The library version as recorded in instrumentation and logging # @return [String] # @!attribute [rw] channel_args # Extra parameters passed to the gRPC channel. Note: this is ignored if a # `GRPC::Core::Channel` object is provided as the credential. # @return [Hash] # @!attribute [rw] interceptors # An array of interceptors that are run before calls are executed. # @return [Array<GRPC::ClientInterceptor>] # @!attribute [rw] timeout # The call timeout in milliseconds. # @return [Numeric] # @!attribute [rw] metadata # Additional gRPC headers to be sent with the call. # @return [Hash{Symbol=>String}] # @!attribute [rw] retry_policy # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # @return [Hash] # class Configuration extend Gapic::Config config_attr :endpoint, "securitycenter.googleapis.com", String config_attr :credentials, nil do |value| allowed = [::String, ::Hash, ::Proc, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil] allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC allowed.any? { |klass| klass === value } end config_attr :scope, nil, String, Array, nil config_attr :lib_name, nil, String, nil config_attr :lib_version, nil, String, nil config_attr(:channel_args, { "grpc.service_config_disable_resolution"=>1 }, Hash, nil) config_attr :interceptors, nil, Array, nil config_attr :timeout, nil, Numeric, nil config_attr :metadata, nil, Hash, nil config_attr :retry_policy, nil, Hash, Proc, nil # @private def initialize parent_config = nil @parent_config = parent_config unless parent_config.nil? yield self if block_given? end ## # Configurations for individual RPCs # @return [Rpcs] # def rpcs @rpcs ||= begin parent_rpcs = nil parent_rpcs = @parent_config.rpcs if @parent_config&.respond_to? :rpcs Rpcs.new parent_rpcs end end ## # Configuration RPC class for the Operations API. # # Includes fields providing the configuration for each RPC in this service. # Each configuration object is of type `Gapic::Config::Method` and includes # the following configuration fields: # # * `timeout` (*type:* `Numeric`) - The call timeout in milliseconds # * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers # * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields # include the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # class Rpcs ## # RPC-specific configuration for `list_operations` # @return [Gapic::Config::Method] # attr_reader :list_operations ## # RPC-specific configuration for `get_operation` # @return [Gapic::Config::Method] # attr_reader :get_operation ## # RPC-specific configuration for `delete_operation` # @return [Gapic::Config::Method] # attr_reader :delete_operation ## # RPC-specific configuration for `cancel_operation` # @return [Gapic::Config::Method] # attr_reader :cancel_operation # @private def initialize parent_rpcs = nil list_operations_config = parent_rpcs&.list_operations if parent_rpcs&.respond_to? :list_operations @list_operations = Gapic::Config::Method.new list_operations_config get_operation_config = parent_rpcs&.get_operation if parent_rpcs&.respond_to? :get_operation @get_operation = Gapic::Config::Method.new get_operation_config delete_operation_config = parent_rpcs&.delete_operation if parent_rpcs&.respond_to? :delete_operation @delete_operation = Gapic::Config::Method.new delete_operation_config cancel_operation_config = parent_rpcs&.cancel_operation if parent_rpcs&.respond_to? :cancel_operation @cancel_operation = Gapic::Config::Method.new cancel_operation_config yield self if block_given? end end end end end end end end end
49.565295
164
0.572671
7a6ea5c32311e7d347bef0ff5bb992373c61eedf
2,543
module IOStreams module Zip class Reader < IOStreams::Reader # Read from a zip file or stream, decompressing the contents as it is read # The input stream from the first file found in the zip file is passed # to the supplied block. # # Parameters: # entry_file_name: [String] # Name of the file within the Zip file to read. # Default: Read the first file found in the zip file. # # Example: # IOStreams::Zip::Reader.open('abc.zip') do |io_stream| # # Read 256 bytes at a time # while data = io_stream.read(256) # puts data # end # end if defined?(JRuby) # Java has built-in support for Zip files def self.file(file_name, entry_file_name: nil, &block) if entry_file_name&.include?(".CSV") get_file_io(file_name, entry_file_name, &block) else fin = Java::JavaIo::FileInputStream.new(file_name) zin = Java::JavaUtilZip::ZipInputStream.new(fin) get_entry(zin, entry_file_name) || raise(Java::JavaUtilZip::ZipException, "File #{entry_file_name} not found within zip file.") yield(zin.to_io) end ensure zin&.close fin&.close end def self.get_entry(zin, entry_file_name) if entry_file_name.nil? zin.get_next_entry return true end while (entry = zin.get_next_entry) return true if entry.name == entry_file_name end false end else # Read from a zip file or stream, decompressing the contents as it is read # The input stream from the first file found in the zip file is passed # to the supplied block def self.file(file_name, entry_file_name: nil, &block) get_file_io(file_name, entry_file_name, &block) end end def self.get_file_io(file_name, entry_file_name, &block) Utils.load_soft_dependency("rubyzip v1.x", "Read Zip", "zip") unless defined?(::Zip) ::Zip::File.open(file_name) do |zip_file| if entry_file_name zip_file.get_input_stream(entry_file_name, &block) else result = nil # Return the first file zip_file.each do |entry| result = entry.get_input_stream(&block) break end result end end end end end end
32.189873
106
0.575698
6235b8dfe825d9a0209c7088682e44322a421d14
241
# encoding: UTF-8 require 'spec_helper' describe Outcome, type: :model do context "validations" do it { should validate_presence_of :title } end context "associations" do it { should have_many :review_decisions } end end
18.538462
45
0.713693
33a323748ac9c16b5b76603cfdd18071aad81eac
251
class AddTypeToContentProviders < ActiveRecord::Migration[4.2] def change add_column :content_providers, :content_provider_type, :string, :default => 'Organisation' ContentProvider.update_all(content_provider_type: 'Organisation') end end
35.857143
94
0.792829
38625b05a64909240a60468ae5be2d7f68b09b03
2,475
# Actions for QingGroups # All requests in this controller are AJAX based. class QingGroupsController < ApplicationController include Parameters # authorization via cancan load_and_authorize_resource before_action :prepare_qing_group, only: [:create] before_action :validate_destroy, only: [:destroy] after_action :check_rank_fail def new @form = Form.find(params[:form_id]) # Adding group requires same permissions as removing questions. authorize!(:add_questions, @form) @qing_group = QingGroup.new( form: @form, ancestry: @form.root_id, one_screen: true, mission: current_mission ) render(partial: 'modal') end def edit @qing_group = QingGroup.find(params[:id]) # The QingGroupDecorator might declare this group can't do one-screen even if the property is # set to true. If so, we should disable the checkbox. @one_screen_disabled = true unless odk_decorator.one_screen_allowed? render(partial: 'modal') end def create # Adding group requires same permissions as removing questions. authorize!(:add_questions, @qing_group.form) @qing_group.parent = @qing_group.form.root_group @qing_group.save! render partial: 'group', locals: {qing_group: @qing_group} end def update @qing_group.update_attributes!(qing_group_params) render partial: 'group_inner', locals: {qing_group: @qing_group} end def destroy # Removing group requires same permissions as removing questions. authorize!(:remove_questions, @qing_group.form) @qing_group.destroy render body: nil, status: 204 end private def validate_destroy if @qing_group.children.size > 0 return render json: [], status: 404 end end # prepares qing_group def prepare_qing_group attrs = qing_group_params attrs[:ancestry] = Form.find(attrs[:form_id]).root_id @qing_group = QingGroup.accessible_by(current_ability).new(attrs) @qing_group.mission = current_mission end def qing_group_params condition_params = [:id, :ref_qing_id, :op, :value, :_destroy, option_node_ids: []] translation_keys = permit_translations(params[:qing_group], :group_name, :group_hint, :group_item_name) params.require(:qing_group).permit( %i[form_id repeatable one_screen] + translation_keys, display_conditions_attributes: condition_params ) end def odk_decorator Odk::DecoratorFactory.decorate(@qing_group) end end
28.77907
107
0.726465
7aa115f790f6752028d820c3a3b914357af0fa20
260
class AlterTableAddresses < ActiveRecord::Migration def change remove_column :addresses, :state remove_column :addresses, :user_id change_column :addresses, :city, 'integer USING CAST(city AS integer)' rename_column :addresses, :city, :city_id end end
28.888889
71
0.784615
18ead8e97d12a97a583dda5a7237ceea9e76444f
912
class FixCanarsieLorimerMyrtle < ActiveRecord::Migration[5.2] def change canarsieln = LineDirection.joins(:line).find_by(lines: {name: "Canarsie (Lorimer Street—Myrtle Avenue)"}, direction: 1) canarsieln.first_stop = "L16N" # DeKalb Av canarsieln.first_branch_stop = "L17N" canarsieln.first_alternate_branch_stop = "L17N" canarsieln.last_stop = "L11N" # Graham Av canarsieln.last_branch_stop = "L10N" canarsieln.last_alternate_branch_stop = "L10N" canarsieln.save! canarsiels = LineDirection.joins(:line).find_by(lines: {name: "Canarsie (Lorimer Street—Myrtle Avenue)"}, direction: 3) canarsiels.first_stop = "L11S" canarsiels.first_branch_stop = "L10S" canarsiels.first_alternate_branch_stop = "L10S" canarsiels.last_stop = "L16S" canarsiels.last_branch_stop = "L17S" canarsiels.last_alternate_branch_stop = "L17S" canarsiels.save! end end
41.454545
123
0.735746
33d076ee7eedac0825593efe717a5f8b56ae5c81
1,945
class OptionButton < Button def initialize(source = nil) init_source source init_inner_control_vars end def current_godot_object "OptionButton" end def selected @source.selected end def selected=(v) @source.selected = v end def align @source.align end def align=(v) @source.align = v end def toggle_mode @source.toggle_mode end def toggle_mode=(v) @source.toggle_mode = v end def action_mode @source.action_mode end def action_mode=(v) @source.action_mode = v end def add_icon_texture(texture, label, id) @source.add_icon_texture texture, label, id end def add_item(label, id) @source.add_item label, id end def add_separator @source.add_separator end def clear @source.clear end def get_item_count @source.get_item_count end def get_item_icon(idx) @source.get_item_icon idx end def get_item_id(idx) @source.get_item_id idx end def get_item_index(id) @source.get_item_index id end def get_item_metadata(idx) @source.get_item_metadata idx end def get_item_text(idx) @source.get_item_text idx end def get_popup # TODO: Popup.new @source.get_popup end def get_selected_id @source.get_selected_id end def get_selected_metadata @source.get_selected_metadata end def is_item_disabled?(idx) @source.is_item_disabled idx end def remove_item(idx) @source.remove_item idx end def select(idx) @source.select idx end def set_item_disabled(idx, disabled) @source.set_item_disabled idx, disabled end def set_item_icon(idx, texture) @source.set_item_icon idx, texture end def set_item_id(idx, id) @source.set_item_id idx, id end def set_item_metadata(idx, metadata) @source.set_item_metadata idx, metadata end def set_item_text(idx, text) @source.set_item_text idx, text end end
15.436508
47
0.698715
6160524eb38ba998863ec40e0521aec06c2b016f
23,686
require "abstract_unit" Category = Struct.new(:id, :name) class FormCollectionsHelperTest < ActionView::TestCase def assert_no_select(selector, value = nil) assert_select(selector, text: value, count: 0) end def with_collection_radio_buttons(*args, &block) @output_buffer = collection_radio_buttons(*args, &block) end def with_collection_check_boxes(*args, &block) @output_buffer = collection_check_boxes(*args, &block) end # COLLECTION RADIO BUTTONS test "collection radio accepts a collection and generates inputs from value method" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s assert_select "input[type=radio][value=true]#user_active_true" assert_select "input[type=radio][value=false]#user_active_false" end test "collection radio accepts a collection and generates inputs from label method" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s assert_select "label[for=user_active_true]", "true" assert_select "label[for=user_active_false]", "false" end test "collection radio handles camelized collection values for labels correctly" do with_collection_radio_buttons :user, :active, ["Yes", "No"], :to_s, :to_s assert_select "label[for=user_active_yes]", "Yes" assert_select "label[for=user_active_no]", "No" end test "collection radio should sanitize collection values for labels correctly" do with_collection_radio_buttons :user, :name, ["$0.99", "$1.99"], :to_s, :to_s assert_select "label[for=user_name_099]", "$0.99" assert_select "label[for=user_name_199]", "$1.99" end test "collection radio accepts checked item" do with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, checked: true assert_select "input[type=radio][value=true][checked=checked]" assert_no_select "input[type=radio][value=false][checked=checked]" end test "collection radio accepts multiple disabled items" do collection = [[1, true], [0, false], [2, "other"]] with_collection_radio_buttons :user, :active, collection, :last, :first, disabled: [true, false] assert_select "input[type=radio][value=true][disabled=disabled]" assert_select "input[type=radio][value=false][disabled=disabled]" assert_no_select "input[type=radio][value=other][disabled=disabled]" end test "collection radio accepts single disabled item" do collection = [[1, true], [0, false]] with_collection_radio_buttons :user, :active, collection, :last, :first, disabled: true assert_select "input[type=radio][value=true][disabled=disabled]" assert_no_select "input[type=radio][value=false][disabled=disabled]" end test "collection radio accepts multiple readonly items" do collection = [[1, true], [0, false], [2, "other"]] with_collection_radio_buttons :user, :active, collection, :last, :first, readonly: [true, false] assert_select "input[type=radio][value=true][readonly=readonly]" assert_select "input[type=radio][value=false][readonly=readonly]" assert_no_select "input[type=radio][value=other][readonly=readonly]" end test "collection radio accepts single readonly item" do collection = [[1, true], [0, false]] with_collection_radio_buttons :user, :active, collection, :last, :first, readonly: true assert_select "input[type=radio][value=true][readonly=readonly]" assert_no_select "input[type=radio][value=false][readonly=readonly]" end test "collection radio accepts html options as input" do collection = [[1, true], [0, false]] with_collection_radio_buttons :user, :active, collection, :last, :first, {}, class: "special-radio" assert_select "input[type=radio][value=true].special-radio#user_active_true" assert_select "input[type=radio][value=false].special-radio#user_active_false" end test "collection radio accepts html options as the last element of array" do collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first assert_select "input[type=radio][value=true].foo#user_active_true" assert_select "input[type=radio][value=false].bar#user_active_false" end test "collection radio sets the label class defined inside the block" do collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first do |b| b.label(class: "collection_radio_buttons") end assert_select "label.collection_radio_buttons[for=user_active_true]" assert_select "label.collection_radio_buttons[for=user_active_false]" end test "collection radio does not include the input class in the respective label" do collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first assert_no_select "label.foo[for=user_active_true]" assert_no_select "label.bar[for=user_active_false]" end test "collection radio does not wrap input inside the label" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s assert_select "input[type=radio] + label" assert_no_select "label input" end test "collection radio accepts a block to render the label as radio button wrapper" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label { b.radio_button } end assert_select "label[for=user_active_true] > input#user_active_true[type=radio]" assert_select "label[for=user_active_false] > input#user_active_false[type=radio]" end test "collection radio accepts a block to change the order of label and radio button" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label + b.radio_button end assert_select "label[for=user_active_true] + input#user_active_true[type=radio]" assert_select "label[for=user_active_false] + input#user_active_false[type=radio]" end test "collection radio with block helpers accept extra html options" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label(class: "radio_button") + b.radio_button(class: "radio_button") end assert_select "label.radio_button[for=user_active_true] + input#user_active_true.radio_button[type=radio]" assert_select "label.radio_button[for=user_active_false] + input#user_active_false.radio_button[type=radio]" end test "collection radio with block helpers allows access to current text and value" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label("data-value": b.value) { b.radio_button + b.text } end assert_select "label[for=user_active_true][data-value=true]", "true" do assert_select "input#user_active_true[type=radio]" end assert_select "label[for=user_active_false][data-value=false]", "false" do assert_select "input#user_active_false[type=radio]" end end test "collection radio with block helpers allows access to the current object item in the collection to access extra properties" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label(class: b.object) { b.radio_button + b.text } end assert_select "label.true[for=user_active_true]", "true" do assert_select "input#user_active_true[type=radio]" end assert_select "label.false[for=user_active_false]", "false" do assert_select "input#user_active_false[type=radio]" end end test "collection radio buttons with fields for" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] @output_buffer = fields_for(:post) do |p| p.collection_radio_buttons :category_id, collection, :id, :name end assert_select 'input#post_category_id_1[type=radio][value="1"]' assert_select 'input#post_category_id_2[type=radio][value="2"]' assert_select "label[for=post_category_id_1]", "Category 1" assert_select "label[for=post_category_id_2]", "Category 2" end test "collection radio accepts checked item which has a value of false" do with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, checked: false assert_no_select "input[type=radio][value=true][checked=checked]" assert_select "input[type=radio][value=false][checked=checked]" end test "collection radio buttons generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 1 end test "collection radio buttons generates a hidden field using the given :name in :html_options" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, {}, name: "user[other_category_ids]" assert_select "input[type=hidden][name='user[other_category_ids]'][value='']", count: 1 end test "collection radio buttons generates a hidden field with index if it was provided" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, index: 322 assert_select "input[type=hidden][name='user[322][category_ids]'][value='']", count: 1 end test "collection radio buttons does not generate a hidden field if include_hidden option is false" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, include_hidden: false assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 0 end test "collection radio buttons does not generate a hidden field if include_hidden option is false with key as string" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, "include_hidden" => false assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 0 end # COLLECTION CHECK BOXES test "collection check boxes accepts a collection and generate a series of checkboxes for value method" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name assert_select 'input#user_category_ids_1[type=checkbox][value="1"]' assert_select 'input#user_category_ids_2[type=checkbox][value="2"]' end test "collection check boxes generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 1 end test "collection check boxes generates a hidden field using the given :name in :html_options" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, name: "user[other_category_ids][]" assert_select "input[type=hidden][name='user[other_category_ids][]'][value='']", count: 1 end test "collection check boxes generates a hidden field with index if it was provided" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name, index: 322 assert_select "input[type=hidden][name='user[322][category_ids][]'][value='']", count: 1 end test "collection check boxes does not generate a hidden field if include_hidden option is false" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name, include_hidden: false assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0 end test "collection check boxes does not generate a hidden field if include_hidden option is false with key as string" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name, "include_hidden" => false assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0 end test "collection check boxes accepts a collection and generate a series of checkboxes with labels for label method" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name assert_select "label[for=user_category_ids_1]", "Category 1" assert_select "label[for=user_category_ids_2]", "Category 2" end test "collection check boxes handles camelized collection values for labels correctly" do with_collection_check_boxes :user, :active, ["Yes", "No"], :to_s, :to_s assert_select "label[for=user_active_yes]", "Yes" assert_select "label[for=user_active_no]", "No" end test "collection check box should sanitize collection values for labels correctly" do with_collection_check_boxes :user, :name, ["$0.99", "$1.99"], :to_s, :to_s assert_select "label[for=user_name_099]", "$0.99" assert_select "label[for=user_name_199]", "$1.99" end test "collection check boxes accepts html options as the last element of array" do collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :first, :second assert_select 'input[type=checkbox][value="1"].foo' assert_select 'input[type=checkbox][value="2"].bar' end test "collection check boxes propagates input id to the label for attribute" do collection = [[1, "Category 1", { id: "foo" }], [2, "Category 2", { id: "bar" }]] with_collection_check_boxes :user, :active, collection, :first, :second assert_select 'input[type=checkbox][value="1"]#foo' assert_select 'input[type=checkbox][value="2"]#bar' assert_select "label[for=foo]" assert_select "label[for=bar]" end test "collection check boxes sets the label class defined inside the block" do collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :second, :first do |b| b.label(class: "collection_check_boxes") end assert_select "label.collection_check_boxes[for=user_active_category_1]" assert_select "label.collection_check_boxes[for=user_active_category_2]" end test "collection check boxes does not include the input class in the respective label" do collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :second, :first assert_no_select "label.foo[for=user_active_category_1]" assert_no_select "label.bar[for=user_active_category_2]" end test "collection check boxes accepts selected values as :checked option" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: [1, 3] assert_select 'input[type=checkbox][value="1"][checked=checked]' assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end test "collection check boxes accepts selected string values as :checked option" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: ["1", "3"] assert_select 'input[type=checkbox][value="1"][checked=checked]' assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end test "collection check boxes accepts a single checked value" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: 3 assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="1"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end test "collection check boxes accepts selected values as :checked option and override the model values" do user = Struct.new(:category_ids).new(2) collection = (1..3).map { |i| [i, "Category #{i}"] } @output_buffer = fields_for(:user, user) do |p| p.collection_check_boxes :category_ids, collection, :first, :last, checked: [1, 3] end assert_select 'input[type=checkbox][value="1"][checked=checked]' assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end test "collection check boxes accepts multiple disabled items" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: [1, 3] assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end test "collection check boxes accepts single disabled item" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: 1 assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end test "collection check boxes accepts a proc to disabled items" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: proc { |i| i.first == 1 } assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end test "collection check boxes accepts multiple readonly items" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: [1, 3] assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end test "collection check boxes accepts single readonly item" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: 1 assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end test "collection check boxes accepts a proc to readonly items" do collection = (1..3).map { |i| [i, "Category #{i}"] } with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: proc { |i| i.first == 1 } assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end test "collection check boxes accepts html options" do collection = [[1, "Category 1"], [2, "Category 2"]] with_collection_check_boxes :user, :category_ids, collection, :first, :last, {}, class: "check" assert_select 'input.check[type=checkbox][value="1"]' assert_select 'input.check[type=checkbox][value="2"]' end test "collection check boxes with fields for" do collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] @output_buffer = fields_for(:post) do |p| p.collection_check_boxes :category_ids, collection, :id, :name end assert_select 'input#post_category_ids_1[type=checkbox][value="1"]' assert_select 'input#post_category_ids_2[type=checkbox][value="2"]' assert_select "label[for=post_category_ids_1]", "Category 1" assert_select "label[for=post_category_ids_2]", "Category 2" end test "collection check boxes does not wrap input inside the label" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s assert_select "input[type=checkbox] + label" assert_no_select "label input" end test "collection check boxes accepts a block to render the label as check box wrapper" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label { b.check_box } end assert_select "label[for=user_active_true] > input#user_active_true[type=checkbox]" assert_select "label[for=user_active_false] > input#user_active_false[type=checkbox]" end test "collection check boxes accepts a block to change the order of label and check box" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label + b.check_box end assert_select "label[for=user_active_true] + input#user_active_true[type=checkbox]" assert_select "label[for=user_active_false] + input#user_active_false[type=checkbox]" end test "collection check boxes with block helpers accept extra html options" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label(class: "check_box") + b.check_box(class: "check_box") end assert_select "label.check_box[for=user_active_true] + input#user_active_true.check_box[type=checkbox]" assert_select "label.check_box[for=user_active_false] + input#user_active_false.check_box[type=checkbox]" end test "collection check boxes with block helpers allows access to current text and value" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label("data-value": b.value) { b.check_box + b.text } end assert_select "label[for=user_active_true][data-value=true]", "true" do assert_select "input#user_active_true[type=checkbox]" end assert_select "label[for=user_active_false][data-value=false]", "false" do assert_select "input#user_active_false[type=checkbox]" end end test "collection check boxes with block helpers allows access to the current object item in the collection to access extra properties" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label(class: b.object) { b.check_box + b.text } end assert_select "label.true[for=user_active_true]", "true" do assert_select "input#user_active_true[type=checkbox]" end assert_select "label.false[for=user_active_false]", "false" do assert_select "input#user_active_false[type=checkbox]" end end end
46.261719
180
0.718906
e972cb44df5fefc9441a14a256a18a577d5447bf
42
module Api::LocationsControllerHelper end
14
37
0.880952
39124707bdc48aa5935445763d9257a1093b0b85
210
class CreateBuildings < ActiveRecord::Migration[6.0] def change create_table :buildings do |t| t.string :name t.string :address t.integer :owner_id t.timestamps end end end
17.5
52
0.652381
39008f982c46a1bb8284c70f366ba3a3510e4245
644
require 'did_you_mean/spell_checkers/name_error_checkers/class_name_checker' require 'did_you_mean/spell_checkers/name_error_checkers/variable_name_checker' module DidYouMean module NameErrorCheckers def self.included(*) raise "Do not include this module since it overrides Class.new method." end def self.new(exception) case exception.original_message when /uninitialized constant/ ClassNameChecker when /undefined local variable or method/, /undefined method/, /uninitialized class variable/ VariableNameChecker else NullChecker end.new(exception) end end end
29.272727
99
0.743789
f79b022f31b77a8e31dc7cec0657fe257dd3aa97
7,651
## # Copyright 2012 Twitter, 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. ## class RSReputation < ActiveRecord::Base belongs_to :target, :polymorphic => true has_many :received_messages, :class_name => 'RSReputationMessage', :foreign_key => :receiver_id, :dependent => :destroy do def from(sender) self.find_by_sender_id_and_sender_type(sender.id, sender.class.to_s) end end has_many :sent_messages, :as => :sender, :class_name => 'RSReputationMessage', :dependent => :destroy attr_accessible :reputation_name, :value, :aggregated_by, :active, :target, :target_id, :target_type, :received_messages before_save :change_zero_value_in_case_of_product_process VALID_PROCESSES = ['sum', 'average', 'product'] validates_inclusion_of :aggregated_by, :in => VALID_PROCESSES, :message => "Value chosen for aggregated_by is not valid process" validates_uniqueness_of :reputation_name, :scope => [:target_id, :target_type] def self.find_by_reputation_name_and_target(reputation_name, target) RSReputation.find_by_reputation_name_and_target_id_and_target_type(reputation_name.to_s, target.id, target.class.name) end # All external access to reputation should use this since they are created lazily. def self.find_or_create_reputation(reputation_name, target, process) rep = find_by_reputation_name_and_target(reputation_name, target) rep ? rep : create_reputation(reputation_name, target, process) end def self.create_reputation(reputation_name, target, process) create_options = {:reputation_name => reputation_name.to_s, :target_id => target.id, :target_type => target.class.name, :aggregated_by => process.to_s} default_value = ReputationSystem::Network.get_reputation_def(target.class.name, reputation_name)[:init_value] create_options.merge!(:value => default_value) if default_value rep = create(create_options) initialize_reputation_value(rep, target, process) end def self.update_reputation_value_with_new_source(rep, source, weight, process) weight ||= 1 # weight is 1 by default. size = rep.received_messages.size valueBeforeUpdate = size > 0 ? rep.value : nil newValue = source.value case process.to_sym when :sum rep.value += (newValue * weight) when :average rep.value = (rep.value * size + newValue * weight) / (size + 1) when :product rep.value *= (newValue * weight) else raise ArgumentError, "#{process} process is not supported yet" end rep.save! RSReputationMessage.add_reputation_message_if_not_exist(source, rep) propagate_updated_reputation_value(rep, valueBeforeUpdate) if rep.target end def self.update_reputation_value_with_updated_source(rep, source, oldValue, weight, process) weight ||= 1 # weight is 1 by default. size = rep.received_messages.size valueBeforeUpdate = size > 0 ? rep.value : nil newValue = source.value case process.to_sym when :sum rep.value += (newValue - oldValue) * weight when :average rep.value += ((newValue - oldValue) * weight) / size when :product rep.value = (rep.value * newValue) / oldValue else raise ArgumentError, "#{process} process is not supported yet" end rep.save! propagate_updated_reputation_value(rep, valueBeforeUpdate) if rep.target end def normalized_value if self.active == 1 || self.active == true max = RSReputation.max(self.reputation_name, self.target_type) min = RSReputation.min(self.reputation_name, self.target_type) if max && min range = max - min range == 0 ? 0 : (self.value - min) / range else 0 end else 0 end end protected # Updates reputation value for new reputation if its source already exist. def self.initialize_reputation_value(receiver, target, process) name = receiver.reputation_name unless ReputationSystem::Network.is_primary_reputation?(target.class.name, name) sender_defs = ReputationSystem::Network.get_reputation_def(target.class.name, name)[:source] sender_defs.each do |sd| sender_targets = target.get_attributes_of(sd) sender_targets.each do |st| update_reputation_if_source_exist(sd, st, receiver, process) if receiver.target end end end receiver end # Propagates updated reputation value to the reputations whose source is the updated reputation. def self.propagate_updated_reputation_value(sender, oldValue) sender_name = sender.reputation_name.to_sym receiver_defs = ReputationSystem::Network.get_reputation_def(sender.target.class.name, sender_name)[:source_of] if receiver_defs receiver_defs.each do |rd| receiver_targets = sender.target.get_attributes_of(rd) receiver_targets.each do |rt| scope = sender.target.evaluate_reputation_scope(rd[:scope]) srn = ReputationSystem::Network.get_scoped_reputation_name(rt.class.name, rd[:reputation], scope) process = ReputationSystem::Network.get_reputation_def(rt.class.name, srn)[:aggregated_by] rep = find_by_reputation_name_and_target(srn, rt) if rep weight = ReputationSystem::Network.get_weight_of_source_from_reputation_name_of_target(rt, sender_name, srn) unless oldValue update_reputation_value_with_new_source(rep, sender, weight, process) else update_reputation_value_with_updated_source(rep, sender, oldValue, weight, process) end # If r is new then value update will be done when it is initialized. else create_reputation(srn, rt, process) end end end end end def self.update_reputation_if_source_exist(sd, st, receiver, process) scope = receiver.target.evaluate_reputation_scope(sd[:scope]) srn = ReputationSystem::Network.get_scoped_reputation_name(st.class.name, sd[:reputation], scope) source = find_by_reputation_name_and_target(srn, st) if source update_reputation_value_with_new_source(receiver, source, sd[:weight], process) RSReputationMessage.add_reputation_message_if_not_exist(source, receiver) end end def self.max(reputation_name, target_type) RSReputation.maximum(:value, :conditions => {:reputation_name => reputation_name.to_s, :target_type => target_type, :active => true}) end def self.min(reputation_name, target_type) RSReputation.minimum(:value, :conditions => {:reputation_name => reputation_name.to_s, :target_type => target_type, :active => true}) end def change_zero_value_in_case_of_product_process self.value = 1 if self.value == 0 && self.aggregated_by == "product" end def remove_associated_messages RSReputationMessage.delete_all(:sender_type => self.class.name, :sender_id => self.id) RSReputationMessage.delete_all(:receiver_id => self.id) end end
42.270718
131
0.707228
91667c8eef7b84729600d06fc04e7f2d2b5ccdf2
522
module Cronis::Lecture13 class Task11 def sort(array) (1..array.size - 2).each do |i| prev_val, next_val = array[i - 1], array[i + 1] is_top = array[i] >= prev_val && array[i] >= next_val is_down = array[i] <= prev_val && array[i] <= next_val if !is_top && !is_down swap(array, i + 1, i) end end array end def swap(array, from, to) temp = array[to] array[to] = array[from] array[from] = temp end end end
20.88
62
0.515326
4ac9f5d7783d786991e01553ad39a1e3552488d2
375
require "bundler/setup" require "can_render_markdown" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
25
66
0.76
ed56ebd63afe5864d92e3d08c6dd34106d824e63
911
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint background_sms.podspec' to validate before publishing. # Pod::Spec.new do |s| s.name = 'background_sms' s.version = '0.0.1' s.summary = 'A new flutter plugin project.' s.description = <<-DESC A new flutter plugin project. DESC s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' s.platform = :ios, '8.0' # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } s.swift_version = '5.0' end
37.958333
104
0.599341
286c2e217eef9b906fbdd75be5a6aee382171873
2,533
ActiveAdmin.register Bio do # See permitted parameters documentation: # https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :bio, :user, :title, :name, :info, :admin_user_id, :admin_user, :image, :twitter, :email, :website, :linkedin, :github, :chapter_id, :chapter show do |ad| attributes_table do row :id row :name row :chapter row :title row :info row :created_at row :updated_at row :admin_user_id row :twitter row :email row :website row :linkedin row :github row :image do image_tag(ad.image.url) end end active_admin_comments end filter :roles filter :chapter, member_label: :chapter filter :name filter :title filter :info filter :email filter :website filter :created_at filter :updated_at form(:html => { :multipart => true }) do |f| f.inputs "Edit Bio" do #if user only has one role and it is leader... if current_admin_user.roles.count == 1 and current_admin_user.roles.first.name == "leader" #...then set the chapter_id to the leader's chapter_id f.input :chapter_id, :input_html => { :value => current_admin_user.chapter_id }, as: :hidden else #otherwise, admin can pick the chapter for the new bio using dropdown list :chapter f.input :chapter, member_label: :chapter end #f.input :admin_user f.input :title, as: :select, collection: ['LEADERS', 'INSTRUCTORS', 'VOLUNTEERS'] f.input :name, placeholder: "Jane Doe" f.input :email, placeholder: current_admin_user.email f.input :info, placeholder: "Please fell free to type out your bio in normal text. If you have links you can type them out as normal url text like: www.girldevelopit.com. If you want to have a second paragraph, just return twice. If you would rather write you bio info in html fell free it will be converted into html on the website." f.input :website, placeholder: "http://www.your_website.com" f.input :twitter, placeholder: "YourTwitterName" f.input :linkedin, placeholder: "YourLinkedinName" f.input :github, placeholder: "YourGitHubName" f.input :image do image_tag(ad.image.url) end end f.actions end # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end end
31.6625
176
0.663245
5dedae03c74870340b4c341f6af5600a5c1c41f9
45
module HashValidator VERSION = '1.0.0' end
11.25
20
0.711111
01a25533eb16598442a14d91de6b4345c1e35956
1,023
module Fog module Compute class DigitalOcean class Real def list_images(options = {}) request( :expects => [200], :method => 'GET', :path => 'images' ) end end class Mock def list_images response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "images" => [ # Sample image { "id" => 1601, "name" => "CentOS 5.8 x64", "distribution" => "CentOS" }, { "id" => 1602, "name" => "CentOS 5.8 x32", "distribution" => "CentOS" }, { "id" => 2676, "name" => "Ubuntu 12.04 x64", "distribution" => "Ubuntu" }, ] } response end end end end end
22.23913
45
0.346041
ac325fed4047a1a03a9a7c0059d4b6c8a5c4f8d5
2,813
class Mpich < Formula desc "Implementation of the MPI Message Passing Interface standard" homepage "https://www.mpich.org/" url "https://www.mpich.org/static/downloads/3.2.1/mpich-3.2.1.tar.gz" mirror "https://fossies.org/linux/misc/mpich-3.2.1.tar.gz" sha256 "5db53bf2edfaa2238eb6a0a5bc3d2c2ccbfbb1badd79b664a1a919d2ce2330f1" revision 1 bottle do sha256 "bab0862c4f607c8f411d16b754fb6474f536c5340c2d1c9be4a339ca4a6d9bf9" => :high_sierra sha256 "bfb708826242dd9e27ce8c46bba866cbec2c95ee6db419c56e7942c32a88b3b3" => :sierra sha256 "214e469d1b5bdbdc685cc31a53e8673880640a2551274c8f06c08b347db7ee54" => :el_capitan end devel do url "https://www.mpich.org/static/downloads/3.3a2/mpich-3.3a2.tar.gz" sha256 "5d408e31917c5249bf5e35d1341afc34928e15483473dbb4e066b76c951125cf" end head do url "http://git.mpich.org/mpich.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "gcc" # for gfortran conflicts_with "open-mpi", :because => "both install MPI compiler wrappers" def install if build.head? # ensure that the consistent set of autotools built by homebrew is used to # build MPICH, otherwise very bizarre build errors can occur ENV["MPICH_AUTOTOOLS_DIR"] = HOMEBREW_PREFIX + "bin" system "./autogen.sh" end system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--mandir=#{man}" system "make" system "make", "check" system "make", "install" end test do (testpath/"hello.c").write <<~EOS #include <mpi.h> #include <stdio.h> int main() { int size, rank, nameLen; char name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(name, &nameLen); printf("[%d/%d] Hello, world! My name is %s.\\n", rank, size, name); MPI_Finalize(); return 0; } EOS system "#{bin}/mpicc", "hello.c", "-o", "hello" system "./hello" system "#{bin}/mpirun", "-np", "4", "./hello" (testpath/"hellof.f90").write <<~EOS program hello include 'mpif.h' integer rank, size, ierror, tag, status(MPI_STATUS_SIZE) call MPI_INIT(ierror) call MPI_COMM_SIZE(MPI_COMM_WORLD, size, ierror) call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierror) print*, 'node', rank, ': Hello Fortran world' call MPI_FINALIZE(ierror) end EOS system "#{bin}/mpif90", "hellof.f90", "-o", "hellof" system "./hellof" system "#{bin}/mpirun", "-np", "4", "./hellof" end end
31.965909
93
0.644152
1a917e58ec4190226fe269ca68cfbfb05c8f44cb
3,898
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/archive/OTP-21.0.tar.gz" sha256 "5a2d8e33c39a78a2dcc0c39bf9d2dfdf2974f0fad28385b4ede020a2321d643f" head "https://github.com/erlang/otp.git" bottle do cellar :any sha256 "ce3a7ebbbecb30a8e00becbe5ee9bd1d0eac42bbbe76eb48d28af6ef393b97f9" => :high_sierra sha256 "02b1e1ab3246636bde3fe7e4f4c1b1ac2057240161318b27fad18097748aaf19" => :sierra sha256 "4cc3d15970a4c4cc056f881456a214f7dd36ac147bd84d4f5204e343a8f21144" => :el_capitan end option "without-hipe", "Disable building hipe; fails on various macOS systems" option "with-native-libs", "Enable native library compilation" option "with-dirty-schedulers", "Enable experimental dirty schedulers" option "with-java", "Build jinterface application" option "without-docs", "Do not install documentation" deprecated_option "disable-hipe" => "without-hipe" deprecated_option "no-docs" => "without-docs" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "openssl" depends_on "fop" => :optional # enables building PDF docs depends_on :java => :optional depends_on "wxmac" => :recommended # for GUI apps like observer resource "man" do url "https://www.erlang.org/download/otp_doc_man_21.0.tar.gz" mirror "https://fossies.org/linux/misc/otp_doc_man_21.0.tar.gz" sha256 "10bf0e44b97ee8320c4868d5a4259c49d4d2a74e9c48583735ae0401f010fb31" end resource "html" do url "https://www.erlang.org/download/otp_doc_html_21.0.tar.gz" mirror "https://fossies.org/linux/misc/otp_doc_html_21.0.tar.gz" sha256 "fcc10885e8bf2eef14f7d6e150c34eeccf3fcf29c19e457b4fb8c203e57e153c" end def install # Unset these so that building wx, kernel, compiler and # other modules doesn't fail with an unintelligable error. %w[LIBS FLAGS AFLAGS ZFLAGS].each { |k| ENV.delete("ERL_#{k}") } ENV["FOP"] = "#{HOMEBREW_PREFIX}/bin/fop" if build.with? "fop" # Do this if building from a checkout to generate configure system "./otp_build", "autoconf" if File.exist? "otp_build" args = %W[ --disable-debug --disable-silent-rules --prefix=#{prefix} --enable-threads --enable-sctp --enable-dynamic-ssl-lib --with-ssl=#{Formula["openssl"].opt_prefix} --enable-shared-zlib --enable-smp-support ] args << "--enable-darwin-64bit" if MacOS.prefer_64_bit? args << "--enable-native-libs" if build.with? "native-libs" args << "--enable-dirty-schedulers" if build.with? "dirty-schedulers" args << "--enable-wx" if build.with? "wxmac" args << "--with-dynamic-trace=dtrace" if MacOS::CLT.installed? args << "--enable-kernel-poll" if MacOS.version > :el_capitan if build.without? "hipe" # HIPE doesn't strike me as that reliable on macOS # https://syntatic.wordpress.com/2008/06/12/macports-erlang-bus-error-due-to-mac-os-x-1053-update/ # https://www.erlang.org/pipermail/erlang-patches/2008-September/000293.html args << "--disable-hipe" else args << "--enable-hipe" end if build.with? "java" args << "--with-javac" else args << "--without-javac" end system "./configure", *args system "make" system "make", "install" if build.with? "docs" (lib/"erlang").install resource("man").files("man") doc.install resource("html") end 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" end end
35.117117
104
0.691124
3913648083e59f3ac02007e817d2d8b034796f15
4,198
require "spec_helper" describe DailyViolationEmailWorker do let(:user1) { create(:user) } let(:user2) { create(:user) } let(:user3) { create(:user) } let(:advocate1) { create(:user, :advocate) } let(:advocate2) { create(:user, :admin) } let(:advocate3) { create(:user, :advocate) } let(:sensor1) { create(:sensor, user: user1) } let(:sensor2) { create(:sensor, user: user2) } let(:sensor3) { create(:sensor, user: user3) } before do advocate1.collaborators << [user1, user2, user3] advocate2.collaborators << [user1, user3] advocate3.collaborators << [user3] reading(user1, sensor1, "2016-12-01 02:00:00", violation: true) reading(user1, sensor1, "2016-12-01 03:00:00", violation: false) reading(user1, sensor1, "2016-12-01 04:00:00", violation: true) reading(user1, sensor1, "2016-12-01 05:00:00", violation: true) reading(user1, sensor1, "2016-12-01 06:00:00", violation: true) reading(user1, sensor1, "2016-12-01 07:00:00", violation: true) reading(user1, sensor1, "2016-12-01 08:00:00", violation: true) reading(user1, sensor1, "2016-12-01 09:00:00", violation: false) reading(user1, sensor1, "2016-12-01 10:00:00", violation: true) reading(user2, sensor2, "2016-12-01 02:00:00", violation: true) reading(user2, sensor2, "2016-12-01 03:00:00", violation: true) reading(user2, sensor2, "2016-12-01 04:00:00", violation: true) reading(user2, sensor2, "2016-12-01 05:00:00", violation: true) reading(user2, sensor2, "2016-12-01 06:00:00", violation: false) reading(user2, sensor2, "2016-12-01 07:00:00", violation: true) reading(user2, sensor2, "2016-12-01 08:00:00", violation: true) reading(user2, sensor2, "2016-12-01 09:00:00", violation: true) reading(user2, sensor2, "2016-12-01 10:00:00", violation: true) reading(user2, sensor2, "2016-12-01 11:00:00", violation: false) reading(user3, sensor3, "2016-12-01 03:00:00", violation: false) reading(user3, sensor3, "2016-12-01 04:00:00", violation: false) reading(user3, sensor3, "2016-12-01 05:00:00", violation: false) reading(user3, sensor3, "2016-12-01 06:00:00", violation: false) reading(user3, sensor3, "2016-12-01 07:00:00", violation: false) reading(user3, sensor3, "2016-12-01 08:00:00", violation: false) reading(user3, sensor3, "2016-12-01 09:00:00", violation: false) reading(user3, sensor3, "2016-12-01 10:00:00", violation: false) end it "groups readings into violations of greater than 3 hours" do worker = DailyViolationEmailWorker.new( start_at: DateTime.parse("2016-12-01 00:00:00"), end_at: DateTime.parse("2016-12-02 00:00:00"), ) results = worker.violations_periods_query.to_a expect(results.size).to eq 3 results = results.sort_by { |r| [r['user_id'], r['start_at']] } expect(results[0]).to include("user_id" => user1.id.to_s, "duration" => (4*60*60).to_s) expect(results[1]).to include("user_id" => user2.id.to_s, "duration" => (3*60*60).to_s) expect(results[2]).to include("user_id" => user2.id.to_s, "duration" => (3*60*60).to_s) expect(UserMailer).to receive(:violations_report).with(hash_including(recipient: advocate1)) do |args| violations = args[:violations] expect(violations.size).to eq 3 expect(violations[0].user).to eq user1 expect(violations[0].data["duration"]).to eq (4*60*60).to_s expect(violations[1].user).to eq user2 expect(violations[1].data["duration"]).to eq (3*60*60).to_s expect(violations[2].user).to eq user2 expect(violations[2].data["duration"]).to eq (3*60*60).to_s double(deliver: true) end expect(UserMailer).to receive(:violations_report).with(hash_including(recipient: advocate2)) do |args| violations = args[:violations] expect(violations.size).to eq 1 expect(violations[0].user).to eq user1 expect(violations[0].data["duration"]).to eq (4*60*60).to_s double(deliver: true) end worker.perform end def reading(user, sensor, time, violation:) s = create(:reading, user: user, sensor: sensor, created_at: DateTime.parse(time)) s.update(violation: violation) end end
42.836735
106
0.669843
62a44899a05296a8898702ec60904c2c2591aaf0
1,537
module Cryptoexchange::Exchanges module Indoex module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? false end end def fetch output = super(ticker_url) adapt_all(output) end def ticker_url "#{Cryptoexchange::Exchanges::Indoex::Market::API_URL}/getMarketDetails" end def adapt_all(output) output['marketdetails'].map do |pair| base, target = pair["pair"].split('_') market_pair = Cryptoexchange::Models::MarketPair.new( base: base, target: target, market: Indoex::Market::NAME ) adapt(pair, market_pair) end end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Indoex::Market::NAME ticker.last = NumericHelper.to_d(output['last']) ticker.high = NumericHelper.to_d(output['highsale']) ticker.low = NumericHelper.to_d(output['lowsale']) ticker.volume = NumericHelper.to_d(output['baseVolume']) / ticker.last ticker.timestamp = nil ticker.payload = output ticker end end end end end
31.367347
83
0.536109
2129c40c733a8a8be22b4403f75c716b7e5cc09f
181
class Hotel attr_accessor :name, :info @@all = [] def initialize(name, info) @name = name @info = info @@all << self end def self.all @@all end end
10.055556
28
0.552486
4a7df9db5ca9d45ad45293308fa6214b5f422f4d
2,770
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. module Elasticsearch module API module Indices module Actions # Allow to shrink an existing index into a new index with fewer primary shards. # # @option arguments [String] :index The name of the source index to shrink # @option arguments [String] :target The name of the target index to shrink into # @option arguments [Time] :timeout Explicit operation timeout # @option arguments [Time] :master_timeout Specify timeout for connection to master # @option arguments [String] :wait_for_active_shards Set the number of active shards to wait for on the shrunken index before the operation returns. # @option arguments [Hash] :headers Custom HTTP headers # @option arguments [Hash] :body The configuration for the target index (`settings` and `aliases`) # # @see https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html # def shrink(arguments = {}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'target' missing" unless arguments[:target] headers = arguments.delete(:headers) || {} arguments = arguments.clone _index = arguments.delete(:index) _target = arguments.delete(:target) method = Elasticsearch::API::HTTP_PUT path = "#{Utils.__listify(_index)}/_shrink/#{Utils.__listify(_target)}" params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__) body = arguments[:body] perform_request(method, path, params, body, headers).body end # Register this action with its valid params when the module is loaded. # # @since 6.2.0 ParamsRegistry.register(:shrink, [ :timeout, :master_timeout, :wait_for_active_shards ].freeze) end end end end
41.969697
156
0.688087