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
7982ae1b68a8c4d7e2c58aff515d0475b90edb9e
39
module Satisfy VERSION = '0.0.1' end
9.75
19
0.666667
7af8025d3ea1f8b6856af285ab3a43381abe65a1
2,473
require 'test_helper' class PasswordResetsTest < ActionDispatch::IntegrationTest def setup ActionMailer::Base.deliveries.clear @user = users(:michael) end test "password resets" do get new_password_reset_path assert_template "password_resets/new" # メールアドレスが無効 post password_resets_path, params:{password_reset:{email:""}} assert_not flash.empty? assert_template "password_resets/new" # メールアドレスが有効 post password_resets_path, params:{password_reset:{email:@user.email}} assert_not_equal @user.reset_digest, @user.reload.reset_digest assert_equal 1, ActionMailer::Base.deliveries.size assert_not flash.empty? assert_redirected_to root_url # パスワード再設定フォームテスト user = assigns(:user) # メールアドレスが無効 get edit_password_reset_path(user.reset_token, email:"") assert_redirected_to root_url # 無効なユーザー user.toggle!(:activated) get edit_password_reset_path(user.reset_token, email: user.email) assert_redirected_to root_url user.toggle!(:activated) # メールアドレスが有効で、トークンが無効 get edit_password_reset_path("wrong token", email: user.email) assert_redirected_to root_url # メールアドレスもトークンも有効 get edit_password_reset_path(user.reset_token, email: user.email) assert_template "password_resets/edit" assert_select "input[name=email][type=hidden][value=?]", user.email # 無効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params:{email: user.email, user:{password:"foobaz", password_confirmation: "barquux"}} assert_select "div#error_explanation" # パスワードか空 patch password_reset_path(user.reset_token),params: { email: user.email,user: { password:"",password_confirmation:""}} assert_select 'div#error_explanation' # 有効なパスワードとパスワード確認 patch password_reset_path(user.reset_token),params: { email: user.email,user: { password:"foobaz",password_confirmation: "foobaz" } } assert is_logged_in? assert_not flash.empty? assert_redirected_to user end test "expired token" do get new_password_reset_path post password_resets_path, params: { password_reset: { email: @user.email } } @user = assigns(:user) @user.update_attribute(:reset_sent_at, 3.hours.ago) patch password_reset_path(@user.reset_token),params: { email: @user.email,user: { password:"foobar",password_confirmation: "foobar" } } assert_response :redirect # follow_redirect! # assert_match /FILL_IN/i, response.body end end
38.640625
139
0.743631
1adb44900e115c45269e27da3e72dd021290c626
363
module Glysellin module Cart class Address include ModelWrapper wraps :embed_address, class_name: "Glysellin::Address" def as_json attributes.reject do |attr, _| key = attr.to_s %w(id created_at updated_at activated).include?(key) || key.match(/addressable/) end end end end end
22.6875
65
0.606061
ab6d6aef1c3dec8c310570ff227722359a364bda
2,217
# frozen_string_literal: true require 'test_helper' class UsersEditTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test 'unsuccessful edit' do log_in_as(@user) get edit_user_path(@user) assert_template 'users/edit' patch user_path(@user), params: { user: { name: '', email: 'foo@invalid', password: 'foo', password_confirmation: 'bar' } } assert_template 'users/edit' end test 'successful edit' do log_in_as(@user) get edit_user_path(@user) assert_template 'users/edit' name = 'Foo Bar' email = '[email protected]' patch user_path(@user), params: { user: { name: name, email: email, password: '', password_confirmation: '' } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end test 'Should redirect edit when not logged in' do get edit_user_path(@user) assert_not flash.empty? assert_redirected_to login_url end test 'should redirect update when not logged in' do patch user_path(@user), params: { user: { name: @user.name, email: @user.email } } assert_not flash.empty? assert_redirected_to login_url end test 'successful edit with friendly forwarding' do get edit_user_path(@user) assert_equal session[:forwarding_url], edit_user_url log_in_as(@user) assert_redirected_to edit_user_url(@user) name = 'Foo Bar' email = '[email protected]' patch user_path(@user), params: { user: { name: name, email: email, password: '', password_confirmation: '' } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end end
31.671429
78
0.54894
28024fd010b5e2785e0095f3a024828791ef2fb0
686
# frozen_string_literal: true module Types module Tree # rubocop: disable Graphql/AuthorizeTypes # This is presented through `Repository` that has its own authorization class TreeEntryType < BaseObject graphql_name 'TreeEntry' description 'Represents a directory' implements Types::Tree::EntryType present_using TreeEntryPresenter field :web_path, GraphQL::Types::String, null: true, description: 'Web path for the tree entry (directory).' field :web_url, GraphQL::Types::String, null: true, description: 'Web URL for the tree entry (directory).' end # rubocop: enable Graphql/AuthorizeTypes end end
32.666667
75
0.701166
6ad8890048946a4bcdd37db941f5f070607e4d7a
52
Fabricator(:tag) do name { "tag_#{sequence}" } end
17.333333
28
0.653846
610a83510f8c6e743ec1b3cd44a3fc9153f8b868
18
module Census end
6
13
0.833333
79de60d20fd245b75980e4a37c9d21a107519197
184
class AddFullnameAndGoogleApiidToUsers < ActiveRecord::Migration[5.1] def change add_column :users, :full_name, :string add_column :users, :google_api_key, :string end end
26.285714
69
0.76087
4a9f96fa7fd34bd52f5e7f93240f8e62a816a95b
1,771
class Libmagic < Formula desc "Implementation of the file(1) command" homepage "https://www.darwinsys.com/file/" url "ftp://ftp.astron.com/pub/file/file-5.36.tar.gz" sha256 "fb608290c0fd2405a8f63e5717abf6d03e22e183fb21884413d1edd918184379" bottle do root_url "https://linuxbrew.bintray.com/bottles" sha256 "2f9cd29505ced7c842c5c673db528c68237acc69f552fb1ebe7b903f0e2597be" => :mojave sha256 "b63065cb2c3501a8b352d1587804a0c7af97e2fac27fd114987e7571dfc1c3ab" => :high_sierra sha256 "8187a0d50ab22d037e598c08d2e2793a84c9ce994748fa79ad8f505b889528c6" => :sierra sha256 "ab9c8ca3942de494be2c29c51a4dd6841c6594c01af31e6cc9e5a26af4debb05" => :x86_64_linux end def install system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--enable-fsect-man5", "--enable-static" system "make", "install" (share/"misc/magic").install Dir["magic/Magdir/*"] # Don't dupe this system utility rm bin/"file" rm man1/"file.1" end test do (testpath/"test.c").write <<~EOS #include <assert.h> #include <stdio.h> #include <magic.h> int main(int argc, char **argv) { magic_t cookie = magic_open(MAGIC_MIME_TYPE); assert(cookie != NULL); assert(magic_load(cookie, NULL) == 0); // Prints the MIME type of the file referenced by the first argument. puts(magic_file(cookie, argv[1])); } EOS system ENV.cc, "-I#{include}", "-L#{lib}", "-lmagic", "test.c", "-o", "test" cp test_fixtures("test.png"), "test.png" assert_equal "image/png", shell_output("./test test.png").chomp end end
36.142857
94
0.643704
212bb09abc1ed2dc917fb6f16e4db5533eaa82a0
1,313
Pod::Spec.new do |s| s.name = "BQMM_RC" s.version = "1.7.2" s.summary = "BQMM RongCloud SDK" s.description = <<-DESC The developer can use this SDK to integrate more and more emoji, such as some static image emoji, or animated emoji DESC s.homepage = "http://biaoqingmm.com/" s.license = 'MIT' s.author = { "Teng" => "[email protected]" } s.source = { :git => "https://github.com/siyanhui/bqmm-sdk-ios-rc.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.requires_arc = true s.source_files = '*/BQMM.framework/Headers/*.h', '*/RongIMKit.framework/Headers/*.h' s.resources = [ '*/BQMM.bundle', '*/RongCloud.bundle', '*/en.lproj', '*/zh-Hans.lproj' ] s.xcconfig = { 'OTHER_LDFLAGS' => '-ObjC' } s.vendored_frameworks = ['*/BQMM.framework', '*/RongIMKit.framework', '*/RongIMLib.framework'] s.vendored_libraries = ['*/*.a'] s.libraries = ['z', 'xml2', 'stdc++', 'sqlite3', 'c++', 'c++abi'] s.frameworks = ['AssetsLibrary', 'MapKit', 'ImageIO', 'CoreLocation', 'SystemConfiguration', 'QuartzCore', 'OpenGLES', 'CoreVideo', 'CoreTelephony', 'CoreMedia', 'CoreAudio', 'CFNetwork', 'AudioToolbox', 'AVFoundation', 'UIKit', 'CoreGraphics'] end
42.354839
246
0.584158
bfe6a5aac1c4170b078cdb24a634559f3e18525d
993
require 'spec_helper' describe Storage::VersionStorage do describe "#name" do let(:version) { double(name: "123", options: {foo: "var"}) } let(:model) { double } it "works" do version_storage = described_class.new(version, model) expect(version_storage.name).to eq version.name expect(version_storage.options).to eq version.options end end describe "#url" do context "with local file" do let(:model) { mod = double(:model, filename: "1.jpg") allow(mod).to receive(:key) { |version_name, filename| "uploads/public/#{version_name}/#{filename}" } mod } let(:version) { double(name: "my_version", options: {foo: "var"}) } it "works" do version_storage = described_class.new(version, model) allow(version_storage).to receive(:local_copy_exists?).and_return(true) expect(version_storage.url).to eq '/uploads/public/my_version/1.jpg' end end end end
29.205882
79
0.632427
bb4ffbd8168882edfadcebed60f8cd46fb70d606
156
class <%= @scope_prefix %>SessionsController < DeviseJwt::SessionsController # def create # super # end # # def destroy # super # end end
15.6
76
0.641026
4aeb94450f2c72838ccf53f6c811f7c0cac63081
454
require 'pty' # Wrapper for PTY pseudo-terminal module Ansible::SafePty # Spawns process for command # @param command [String] command # @return [Integer] exit status def self.spawn(command) PTY.spawn(command) do |r,w,p| begin yield r,w,p if block_given? rescue Errno::EIO nil # ignore Errno::EIO: Input/output error @ io_fillbuf ensure Process.wait p end end $?.exitstatus end end
20.636364
64
0.638767
218c4b174aa7df4eea15a6f7695b6909268a4838
137
class RemoveColumnTramiteToCircuito < ActiveRecord::Migration def change remove_column :circuitos, :tramite_id, :integer end end
22.833333
61
0.79562
4a117700721cff1922ffcbca87231ec1721eef19
213
FactoryBot.define do factory :forums_post_edit, class: 'Forums::PostEdit' do association :post, factory: :forums_post association :created_by, factory: :user content { 'Stuff happened!!' } end end
26.625
57
0.71831
ffa67f2e25b1df1b4a7e7c2f55ce5303f7d9bd4f
1,811
# 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 XPack module API module Security module Actions # Retrieves role mappings. # # @option arguments [String] :name Role-Mapping name # @option arguments [Hash] :headers Custom HTTP headers # # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role-mapping.html # def get_role_mapping(arguments = {}) headers = arguments.delete(:headers) || {} arguments = arguments.clone _name = arguments.delete(:name) method = Elasticsearch::API::HTTP_GET path = if _name "_security/role_mapping/#{Elasticsearch::API::Utils.__listify(_name)}" else "_security/role_mapping" end params = {} body = nil perform_request(method, path, params, body, headers).body end end end end end end
34.169811
115
0.641634
7a4da95b5aaf95646efa951a265c64eb386538f2
130
class RenameTextColumnInPredictions < ActiveRecord::Migration def change rename_column :predictions, :text, :body end end
21.666667
61
0.784615
7a24cb613d2156c6c60997622b4a1c93d5e5cb8d
628
module TaskHelper module API class Cache def initialize(limit: 0, **call_defaults) @limit = limit @call_defaults = call_defaults @calls = [] end def get(**args) new_call = Call.new(@call_defaults.merge(args)) cached_call = @calls.find { |call| call == new_call } if cached_call cached_call.run else @calls << new_call sort_calls.pop if @calls.size > @limit new_call.run end end private def sort_calls @calls.sort! { |x, y| y.time <=> x.time } end end end end
20.933333
61
0.536624
1caf1f9bc474d90064ffb704138e7df311204d1d
27,559
# -*- encoding: utf-8; frozen_string_literal: true -*- # #-- # This file is part of HexaPDF. # # HexaPDF - A Versatile PDF Creation and Manipulation Library For Ruby # Copyright (C) 2014-2020 Thomas Leitner # # HexaPDF is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License version 3 as # published by the Free Software Foundation with the addition of the # following permission added to Section 15 as permitted in Section 7(a): # FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY # THOMAS LEITNER, THOMAS LEITNER DISCLAIMS THE WARRANTY OF NON # INFRINGEMENT OF THIRD PARTY RIGHTS. # # HexaPDF 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 Affero General Public # License for more details. # # You should have received a copy of the GNU Affero General Public License # along with HexaPDF. If not, see <http://www.gnu.org/licenses/>. # # The interactive user interfaces in modified source and object code # versions of HexaPDF must display Appropriate Legal Notices, as required # under Section 5 of the GNU Affero General Public License version 3. # # In accordance with Section 7(b) of the GNU Affero General Public # License, a covered work must retain the producer line in every PDF that # is created or manipulated using HexaPDF. # # If the GNU Affero General Public License doesn't fit your need, # commercial licenses are available at <https://gettalong.at/hexapdf/>. #++ require 'hexapdf/font/invalid_glyph' require 'hexapdf/error' module HexaPDF # Manages both the global and document specific configuration options for HexaPDF. # # == Overview # # HexaPDF allows detailed control over many aspects of PDF manipulation. If there is a need to # use a certain default value somewhere, it is defined as configuration options so that it can # easily be changed. # # Some options are defined as global options because they are needed on the class level - see # HexaPDF::GlobalConfiguration[index.html#GlobalConfiguration]. Other options can be configured for # individual documents as they allow to fine-tune some behavior - see # HexaPDF::DefaultDocumentConfiguration[index.html#DefaultDocumentConfiguration]. # # A configuration option name is dot-separted to provide a hierarchy of option names. For # example, io.chunk_size. class Configuration # Creates a new document specific Configuration object by merging the values into the default # configuration object. def self.with_defaults(values = {}) DefaultDocumentConfiguration.merge(values) end # Creates a new Configuration object using the provided hash argument. def initialize(options = {}) @options = options end # Returns +true+ if the given option exists. def key?(name) options.key?(name) end alias option? key? # Returns the value for the configuration option +name+. def [](name) options[name] end # Uses +value+ as the value for the configuration option +name+. def []=(name, value) options[name] = value end # Returns a new Configuration object containing the options from the given configuration # object (or hash) and this configuration object. # # If a key already has a value in this object, its value is overwritten by the one from # +config+. However, hash values are merged instead of being overwritten. Array values are # duplicated. def merge(config) config = (config.kind_of?(self.class) ? config.options : config) merged_config = options.each_with_object({}) do |(key, old), conf| new = config[key] conf[key] = if old.kind_of?(Hash) && new.kind_of?(Hash) old.merge(new) elsif new.kind_of?(Array) || old.kind_of?(Array) (new || old).dup elsif config.key?(key) new else old end end self.class.new(merged_config) end # :call-seq: # config.constantize(name, *keys) -> constant # config.constantize(name, *keys) {|name| block} -> obj # # Returns the constant the option +name+ is referring to. If +keys+ are provided and the value # of the option +name+ responds to \#dig, the constant to which the keys refer is returned. # # If no constant can be found and no block is provided, an error is raised. If a block is # provided it is called with the option name and its result will be returned. # # config.constantize('encryption.aes') #=> HexaPDF::Encryption::FastAES # config.constantize('filter.map', :Fl) #=> HexaPDF::Filter::FlateDecode def constantize(name, *keys) data = self[name] data = data.dig(*keys) if data.respond_to?(:dig) (data = ::Object.const_get(data) rescue nil) if data.kind_of?(String) if data.nil? && block_given? data = yield(name) elsif data.nil? raise HexaPDF::Error, "Error getting constant for configuration option '#{name}'" + (keys.empty? ? "" : " and keys '#{keys.join(', ')}'") end data end protected # Returns the hash with the configuration options. attr_reader :options end # The default document specific configuration object. # # Modify this object if you want to globally change document specific options or if you want to # introduce new document specific options. # # The following options are provided: # # acro_form.appearance_generator:: # The class that should be used for generating appearances for AcroForm fields. If the value is # a String, it should contain the name of a constant to such a class. # # See HexaPDF::Type::AcroForm::AppearanceGenerator # # acro_form.create_appearances:: # A boolean specifying whether an AcroForm field's appearances should automatically be # generated if they are missing. # # acro_form.text_field.default_width:: # A number specifying the default width of AcroForm text fields which should be auto-sized. # # acro_form.default_font_size:: # A number specifying the default font size of AcroForm text fields which should be auto-sized. # # acro_form.fallback_font:: # The font that should be used when a variable text field references a font that cannot be used. # # Can either be the name of a font, like 'Helvetica', or an array consisting of the font name # and a hash of font options, like ['Helvetica', variant: :italic]. If set to +nil+, the use of # the fallback font is disabled. # # Default is 'Helvetica'. # # acro_form.on_invalid_value:: # Callback hook when an invalid value is set for certain types of AcroForm fields. # # The value needs to be an object that responds to \#call(field, value) where +field+ is the # AcroForm field on which the value is set and +value+ is the invalid value. The returned value # is used instead of the invalid value. # # The default implementation raises an error. # # acro_form.text_field.default_width:: # A number specifying the default width of AcroForm text fields which should be auto-sized. # # document.auto_decrypt:: # A boolean determining whether the document should be decrypted automatically when parsed. # # If this is set to +false+ and the PDF document should later be decrypted, the method # Encryption::SecurityHandler.set_up_decryption(document, decryption_opts) has to be called to # set and retrieve the needed security handler. Note, however, that already loaded indirect # objects have to be decrypted manually! # # In nearly all cases this option should not be changed from its default setting! # # encryption.aes:: # The class that should be used for AES encryption. If the value is a String, it should # contain the name of a constant to such a class. # # See HexaPDF::Encryption::AES for the general interface such a class must conform to and # HexaPDF::Encryption::RubyAES as well as HexaPDF::Encryption::FastAES for implementations. # # encryption.arc4:: # The class that should be used for ARC4 encryption. If the value is a String, it should # contain the name of a constant to such a class. # # See HexaPDF::Encryption::ARC4 for the general interface such a class must conform to and # HexaPDF::Encryption::RubyARC4 as well as HexaPDF::Encryption::FastARC4 for implementations. # # encryption.filter_map:: # A mapping from a PDF name (a Symbol) to a security handler class (see # Encryption::SecurityHandler). If the value is a String, it should contain the name of a # constant to such a class. # # PDF defines a standard security handler that is implemented # (HexaPDF::Encryption::StandardSecurityHandler) and assigned the :Standard name. # # encryption.sub_filter_map:: # A mapping from a PDF name (a Symbol) to a security handler class (see # HexaPDF::Encryption::SecurityHandler). If the value is a String, it should contain the name # of a constant to such a class. # # The sub filter map is used when the security handler defined by the encryption dictionary # is not available, but a compatible implementation is. # # filter.map:: # A mapping from a PDF name (a Symbol) to a filter object (see Filter). If the value is a # String, it should contain the name of a constant that contains a filter object. # # The most often used filters are implemented and readily available. # # See PDF1.7 s7.4.1, ADB sH.3 3.3 # # font.map:: # Defines a mapping from font names and variants to font files. # # The value needs to be a hash of the form: # {"font_name": {variant: file_name, variant2: file_name2, ...}, ...} # # Once a font is registered in this way, the font name together with a variant name can be used # with the HexaPDF::Document::Fonts#add method to load the font. # # For best compatibility, the following variant names should be used: # # [none] For the normal variant of the font # [bold] For the bold variant of the font # [italic] For the italic or oblique variant of the font # [bold_italic] For the bold and italic/oblique variant of the font # # font.on_missing_glyph:: # Callback hook when an UTF-8 character cannot be mapped to a glyph of a font. # # The value needs to be an object that responds to \#call(character, font_type, font) where # +character+ is the Unicode character for the missing glyph and returns a substitute glyph to # be used instead. # # The default implementation returns an object of class HexaPDF::Font::InvalidGlyph which, when # not removed before encoding, will raise an error. # # font.on_missing_unicode_mapping:: # Callback hook when a character code point cannot be converted to a Unicode character. # # The value needs to be an object that responds to \#call(code, font_dict) where +code+ is the # decoded code point and +font_dict+ is the font dictionary which was used for the conversion. # The returned value is used as the Unicode character and should be a string. # # The default implementation raises an error. # # font_loader:: # An array with font loader implementations. When a font should be loaded, the array is # iterated in sequence and the first valid font returned by a font loader is used. # # If a value is a String, it should contain the name of a constant that is a font loader # object. # # See the HexaPDF::FontLoader module for information on how to implement a font loader object. # # graphic_object.map:: # A mapping from graphic object names to graphic object factories. # # See HexaPDF::Content::GraphicObject for more information. # # graphic_object.arc.max_curves:: # The maximum number of curves used for approximating a complete ellipse using Bezier curves. # # The default value is 6, higher values result in better approximations but also take longer # to compute. It should not be set to values lower than 4, otherwise the approximation of a # complete ellipse is visibly false. # # image_loader:: # An array with image loader implementations. When an image should be loaded, the array is # iterated in sequence to find a suitable image loader. # # If a value is a String, it should contain the name of a constant that is an image loader # object. # # See the HexaPDF::ImageLoader module for information on how to implement an image loader # object. # # image_loader.pdf.use_stringio:: # A boolean determining whether images specified via file names should be read into memory # all at once using a StringIO object. # # Since loading a PDF as image entails having the IO object from the image PDF around until # the PDF document where it is used is written, there is the choice whether memory should be # used to load the image PDF all at once or whether a File object is used that needs to be # manually closed. # # To avoid leaking file descriptors, using the StringIO is the default setting. If you set # this option to +false+, it is strongly advised to use ObjectSpace.each_object(File) (or # +IO+ instead of +File) to traverse the list of open file descriptors and close the ones # that have been used for PDF images. # # io.chunk_size:: # The size of the chunks that are used when reading IO data. # # This can be used to limit the memory needed for reading or writing PDF files with huge # stream objects. # # page.default_media_box:: # The media box that is used for new pages that don't define a media box. Default value is # A4. See HexaPDF::Type::Page::PAPER_SIZE for a list of predefined paper sizes. # # The value can either be a rectangle defining the paper size or a Symbol referencing one of # the predefined paper sizes. # # page.default_media_orientation:: # The page orientation that is used for new pages that don't define a media box. It is only # used if 'page.default_media_box' references a predefined paper size. Default value is # :portrait. The other possible value is :landscape. # # parser.on_correctable_error:: # Callback hook when the parser encounters an error that can be corrected. # # The value needs to be an object that responds to \#call(document, message, position) and # returns +true+ if an error should be raised. # # parser.try_xref_reconstruction:: # A boolean specifying whether non-recoverable parsing errors should lead to reconstructing the # main cross-reference table. # # The reconstructed cross-reference table might make damaged files usable but there is no way # to ensure that the reconstructed file is equal to the undamaged original file (though # generally it works out). # # There is also the possibility that reconstructing doesn't work because the algorithm has to # assume that the PDF was written in a certain way (which is recommended by the PDF # specification). # # Defaults to +true+. # # sorted_tree.max_leaf_node_size:: # The maximum number of nodes that should be in a leaf node of a node tree. # # style.layers_map:: # A mapping from style layer names to layer objects. # # See HexaPDF::Layout::Style::Layers for more information. # # task.map:: # A mapping from task names to callable task objects. See HexaPDF::Task for more information. DefaultDocumentConfiguration = Configuration.new('acro_form.appearance_generator' => 'HexaPDF::Type::AcroForm::AppearanceGenerator', 'acro_form.create_appearances' => true, 'acro_form.default_font_size' => 10, 'acro_form.fallback_font' => 'Helvetica', 'acro_form.on_invalid_value' => proc do |field, value| raise HexaPDF::Error, "Invalid value #{value.inspect} for " \ "#{field.concrete_field_type} field #{field.full_field_name}" end, 'acro_form.text_field.default_width' => 100, 'document.auto_decrypt' => true, 'encryption.aes' => 'HexaPDF::Encryption::FastAES', 'encryption.arc4' => 'HexaPDF::Encryption::FastARC4', 'encryption.filter_map' => { Standard: 'HexaPDF::Encryption::StandardSecurityHandler', }, 'encryption.sub_filter_map' => { }, 'filter.map' => { ASCIIHexDecode: 'HexaPDF::Filter::ASCIIHexDecode', AHx: 'HexaPDF::Filter::ASCIIHexDecode', ASCII85Decode: 'HexaPDF::Filter::ASCII85Decode', A85: 'HexaPDF::Filter::ASCII85Decode', LZWDecode: 'HexaPDF::Filter::LZWDecode', LZW: 'HexaPDF::Filter::LZWDecode', FlateDecode: 'HexaPDF::Filter::FlateDecode', Fl: 'HexaPDF::Filter::FlateDecode', RunLengthDecode: 'HexaPDF::Filter::RunLengthDecode', RL: 'HexaPDF::Filter::RunLengthDecode', CCITTFaxDecode: 'HexaPDF::Filter::PassThrough', CCF: 'HexaPDF::Filter::PassThrough', JBIG2Decode: 'HexaPDF::Filter::PassThrough', DCTDecode: 'HexaPDF::Filter::PassThrough', DCT: 'HexaPDF::Filter::PassThrough', JPXDecode: 'HexaPDF::Filter::PassThrough', Crypt: nil, Encryption: 'HexaPDF::Filter::Encryption', }, 'font.map' => {}, 'font.on_missing_glyph' => proc do |char, _type, font| HexaPDF::Font::InvalidGlyph.new(font, char) end, 'font.on_missing_unicode_mapping' => proc do |code_point, font| raise HexaPDF::Error, "No Unicode mapping for code point #{code_point} " \ "in font #{font[:BaseFont]}" end, 'font_loader' => [ 'HexaPDF::FontLoader::Standard14', 'HexaPDF::FontLoader::FromConfiguration', 'HexaPDF::FontLoader::FromFile', ], 'graphic_object.map' => { arc: 'HexaPDF::Content::GraphicObject::Arc', endpoint_arc: 'HexaPDF::Content::GraphicObject::EndpointArc', solid_arc: 'HexaPDF::Content::GraphicObject::SolidArc', geom2d: 'HexaPDF::Content::GraphicObject::Geom2D', }, 'graphic_object.arc.max_curves' => 6, 'image_loader' => [ 'HexaPDF::ImageLoader::JPEG', 'HexaPDF::ImageLoader::PNG', 'HexaPDF::ImageLoader::PDF', ], 'image_loader.pdf.use_stringio' => true, 'io.chunk_size' => 2**16, 'page.default_media_box' => :A4, 'page.default_media_orientation' => :portrait, 'parser.on_correctable_error' => proc { false }, 'parser.try_xref_reconstruction' => true, 'sorted_tree.max_leaf_node_size' => 64, 'style.layers_map' => { link: 'HexaPDF::Layout::Style::LinkLayer', }, 'task.map' => { optimize: 'HexaPDF::Task::Optimize', dereference: 'HexaPDF::Task::Dereference', }) # The global configuration object, providing the following options: # # color_space.map:: # A mapping from a PDF name (a Symbol) to a color space class (see # HexaPDF::Content::ColorSpace). If the value is a String, it should contain the name of a # constant that contains a color space class. # # Classes for the most often used color space families are implemented and readily available. # # See PDF1.7 s8.6 # # filter.flate_compression:: # Specifies the compression level that should be used with the FlateDecode filter. The level # can range from 0 (no compression), 1 (best speed) to 9 (best compression, default). # # filter.flate_memory:: # Specifies the memory level that should be used with the FlateDecode filter. The level can # range from 1 (minimum memory usage; slow, reduces compression) to 9 (maximum memory usage). # # The HexaPDF default value of 6 has been found in tests to be nearly equivalent to the Zlib # default of 8 in terms of speed and compression level but uses less memory. # # filter.predictor.strict:: # Specifies whether the predictor algorithm used by LZWDecode and FlateDecode should operate in # strict mode, i.e. adhering to the PDF specification without correcting for common deficiences # of PDF writer libraries. # # object.type_map:: # A mapping from a PDF name (a Symbol) to PDF object classes which is based on the /Type # field. If the value is a String, it should contain the name of a constant that contains a # PDF object class. # # This mapping is used to provide automatic wrapping of objects in the HexaPDF::Document#wrap # method. # # object.subtype_map:: # A mapping from a PDF name (a Symbol) to PDF object classes which is based on the /Subtype # field. If the value is a String, it should contain the name of a constant that contains a # PDF object class. # # This mapping is used to provide automatic wrapping of objects in the HexaPDF::Document#wrap # method. GlobalConfiguration = Configuration.new('filter.flate_compression' => 9, 'filter.flate_memory' => 6, 'filter.predictor.strict' => false, 'color_space.map' => { DeviceRGB: 'HexaPDF::Content::ColorSpace::DeviceRGB', DeviceCMYK: 'HexaPDF::Content::ColorSpace::DeviceCMYK', DeviceGray: 'HexaPDF::Content::ColorSpace::DeviceGray', }, 'object.type_map' => { XRef: 'HexaPDF::Type::XRefStream', ObjStm: 'HexaPDF::Type::ObjectStream', Catalog: 'HexaPDF::Type::Catalog', Pages: 'HexaPDF::Type::PageTreeNode', Page: 'HexaPDF::Type::Page', Filespec: 'HexaPDF::Type::FileSpecification', EmbeddedFile: 'HexaPDF::Type::EmbeddedFile', ExtGState: 'HexaPDF::Type::GraphicsStateParameter', Font: 'HexaPDF::Type::Font', FontDescriptor: 'HexaPDF::Type::FontDescriptor', XXEmbeddedFileParameters: 'HexaPDF::Type::EmbeddedFile::Parameters', XXEmbeddedFileParametersMacInfo: 'HexaPDF::Type::EmbeddedFile::MacInfo', XXFilespecEFDictionary: 'HexaPDF::Type::FileSpecification::EFDictionary', XXInfo: 'HexaPDF::Type::Info', XXNames: 'HexaPDF::Type::Names', XXResources: 'HexaPDF::Type::Resources', XXTrailer: 'HexaPDF::Type::Trailer', XXViewerPreferences: 'HexaPDF::Type::ViewerPreferences', Action: 'HexaPDF::Type::Action', XXLaunchActionWinParameters: 'HexaPDF::Type::Actions::Launch::WinParameters', Annot: 'HexaPDF::Type::Annotation', XXAppearanceCharacteristics: \ 'HexaPDF::Type::Annotations::Widget::AppearanceCharacteristics', XXIconFit: 'HexaPDF::Type::IconFit', XXAcroForm: 'HexaPDF::Type::AcroForm::Form', XXAcroFormField: 'HexaPDF::Type::AcroForm::Field', XXAppearanceDictionary: 'HexaPDF::Type::Annotation::AppearanceDictionary', Border: 'HexaPDF::Type::Annotation::Border', }, 'object.subtype_map' => { nil => { Image: 'HexaPDF::Type::Image', Form: 'HexaPDF::Type::Form', Type0: 'HexaPDF::Type::FontType0', Type1: 'HexaPDF::Type::FontType1', TrueType: 'HexaPDF::Type::FontTrueType', CIDFontType0: 'HexaPDF::Type::CIDFont', CIDFontType2: 'HexaPDF::Type::CIDFont', GoTo: 'HexaPDF::Type::Actions::GoTo', GoToR: 'HexaPDF::Type::Actions::GoToR', Launch: 'HexaPDF::Type::Actions::Launch', URI: 'HexaPDF::Type::Actions::URI', Text: 'HexaPDF::Type::Annotations::Text', Link: 'HexaPDF::Type::Annotations::Link', Widget: 'HexaPDF::Type::Annotations::Widget', }, XObject: { Image: 'HexaPDF::Type::Image', Form: 'HexaPDF::Type::Form', }, Font: { Type0: 'HexaPDF::Type::FontType0', Type1: 'HexaPDF::Type::FontType1', Type3: 'HexaPDF::Type::FontType3', TrueType: 'HexaPDF::Type::FontTrueType', CIDFontType0: 'HexaPDF::Type::CIDFont', CIDFontType2: 'HexaPDF::Type::CIDFont', }, Action: { GoTo: 'HexaPDF::Type::Actions::GoTo', GoToR: 'HexaPDF::Type::Actions::GoToR', Launch: 'HexaPDF::Type::Actions::Launch', URI: 'HexaPDF::Type::Actions::URI', }, Annot: { Text: 'HexaPDF::Type::Annotations::Text', Link: 'HexaPDF::Type::Annotations::Link', Widget: 'HexaPDF::Type::Annotations::Widget', }, XXAcroFormField: { Tx: 'HexaPDF::Type::AcroForm::TextField', Btn: 'HexaPDF::Type::AcroForm::ButtonField', Ch: 'HexaPDF::Type::AcroForm::ChoiceField', }, }) end
48.519366
105
0.611488
d5f151a01e78b015c3a73b95ac8907ff7cda016b
2,986
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::MariaDB::Mgmt::V2018_06_01_preview module Models # # A virtual network rule. # class VirtualNetworkRule < ProxyResource include MsRestAzure # @return [String] The ARM resource id of the virtual network subnet. attr_accessor :virtual_network_subnet_id # @return [Boolean] Create firewall rule before the virtual network has # vnet service endpoint enabled. attr_accessor :ignore_missing_vnet_service_endpoint # @return [VirtualNetworkRuleState] Virtual Network Rule State. Possible # values include: 'Initializing', 'InProgress', 'Ready', 'Deleting', # 'Unknown' attr_accessor :state # # Mapper for VirtualNetworkRule class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VirtualNetworkRule', type: { name: 'Composite', class_name: 'VirtualNetworkRule', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, virtual_network_subnet_id: { client_side_validation: true, required: true, serialized_name: 'properties.virtualNetworkSubnetId', type: { name: 'String' } }, ignore_missing_vnet_service_endpoint: { client_side_validation: true, required: false, serialized_name: 'properties.ignoreMissingVnetServiceEndpoint', type: { name: 'Boolean' } }, state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.state', type: { name: 'String' } } } } } end end end end
29.86
79
0.497991
6286e7c6a057d9cdeddac1fe1551f8a16c928483
532
# frozen_string_literal: true module Stupidedi module Versions module FunctionalGroups module ThirtyTen module SegmentDefs s = Schema e = ElementDefs r = ElementReqs N3 = s::SegmentDef.build(:N3 , "Address Information", "To specify the location of the named party", e::E166 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)), e::E166 .simple_use(r::Optional, s::RepeatCount.bounded(1))) end end end end end
24.181818
74
0.593985
1aeae70b36e4d0c76479380c3c6f10caa8848bc2
316
class AddTagsToSavedSearches < ActiveRecord::Migration[4.2] def change execute "set statement_timeout = 0" add_column :saved_searches, :labels, "text", array: true, null: false, default: [] add_index :saved_searches, :labels, using: :gin rename_column :saved_searches, :tag_query, :query end end
35.111111
86
0.727848
e284bb669b3cfe16bce947c862ebb2e61a1218e4
8,397
=begin #Xero Payroll AU API #This is the Xero Payroll API for orgs in Australia region. Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.3.1 =end require 'time' require 'date' module XeroRuby::PayrollAu require 'bigdecimal' class BankAccount # The text that will appear on your employee's bank statement when they receive payment attr_accessor :statement_text # The name of the account attr_accessor :account_name # The BSB number of the account attr_accessor :bsb # The account number attr_accessor :account_number # If this account is the Remaining bank account attr_accessor :remainder # Fixed amounts (for example, if an employee wants to have $100 of their salary transferred to one account, and the remaining amount to another) attr_accessor :amount # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'statement_text' => :'StatementText', :'account_name' => :'AccountName', :'bsb' => :'BSB', :'account_number' => :'AccountNumber', :'remainder' => :'Remainder', :'amount' => :'Amount' } end # Attribute type mapping. def self.openapi_types { :'statement_text' => :'String', :'account_name' => :'String', :'bsb' => :'String', :'account_number' => :'String', :'remainder' => :'Boolean', :'amount' => :'BigDecimal' } 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 `XeroRuby::PayrollAu::BankAccount` 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 `XeroRuby::PayrollAu::BankAccount`. 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?(:'statement_text') self.statement_text = attributes[:'statement_text'] end if attributes.key?(:'account_name') self.account_name = attributes[:'account_name'] end if attributes.key?(:'bsb') self.bsb = attributes[:'bsb'] end if attributes.key?(:'account_number') self.account_number = attributes[:'account_number'] end if attributes.key?(:'remainder') self.remainder = attributes[:'remainder'] end if attributes.key?(:'amount') self.amount = attributes[:'amount'] 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 && statement_text == o.statement_text && account_name == o.account_name && bsb == o.bsb && account_number == o.account_number && remainder == o.remainder && amount == o.amount 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 [statement_text, account_name, bsb, account_number, remainder, amount].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 XeroRuby::PayrollAu.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
30.98524
210
0.620579
1a1b9ab04435522b3968fd543f37fadf2b4d6192
232
class SearchController < ApplicationController def index keywords = params[:q] || '' keywords.gsub!('#', '%23') redirect_to "https://www.google.com.hk/#hl=zh-CN&q=site:ruby-china.org+#{CGI.escape(keywords)}" end end
29
99
0.668103
ff7ff1bffeecd36bf9e78cf53e7ac3fdb74ab72d
1,720
# encoding: utf-8 # # Redmine - project management software # Copyright (C) 2006-2017 Jean-Philippe Lang # # 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. module MembersHelper def render_principals_for_new_members(project, limit=100) scope = Principal.active.visible.sorted.not_member_of(project).like(params[:q]) principal_count = scope.count principal_pages = Redmine::Pagination::Paginator.new principal_count, limit, params['page'] principals = scope.offset(principal_pages.offset).limit(principal_pages.per_page).to_a s = content_tag('div', content_tag('div', principals_check_box_tags('membership[user_ids][]', principals), :id => 'principals'), :class => 'objects-selection' ) links = pagination_links_full(principal_pages, principal_count, :per_page_links => false) {|text, parameters, options| link_to text, autocomplete_project_memberships_path(project, parameters.merge(:q => params[:q], :format => 'js')), :remote => true } s + content_tag('span', links, :class => 'pagination') end end
44.102564
136
0.742442
62f9bdcc99597084fc04d9f0cbba4bf2b6ef353f
544
require "bar_back/version" require "bar_back/engine" module Webpacker; end require "webpacker/ENV" require "webpacker/configuration" require "webpacker/instance" module BarBack mattr_accessor :http_basic_enabled mattr_accessor :http_basic_username mattr_accessor :http_basic_password ROOT_PATH = Pathname.new(File.join(__dir__, "..")) class << self def webpacker @webpacker ||= ::Webpacker::Instance.new( root_path: ROOT_PATH, config_path: ROOT_PATH.join("config/webpacker.yml") ) end end end
22.666667
59
0.731618
ac34ebd0a7756a4e56755e1225d25840d6bad38d
2,074
require "sidekiq/logging/json/version" require "sidekiq/logging/json" require "json" module Sidekiq module Logging module Json class Logger < Sidekiq::Logging::Pretty # Provide a call() method that returns the formatted message. def call(severity, time, program_name, message) { '@timestamp' => time.utc.iso8601, '@fields' => { :pid => ::Process.pid, :tid => "TID-#{Thread.current.object_id.to_s(36)}", :context => "#{context}", :program_name => program_name, :worker => "#{context}".split(" ")[0] }, '@type' => 'sidekiq', '@status' => nil, '@severity' => severity, '@run_time' => nil, '@message' => "#{time.utc.iso8601} #{::Process.pid} TID-#{Thread.current.object_id.to_s(36)}#{context} #{severity}: #{message}", }.merge(process_message(severity, time, program_name, message)).to_json + "\n" end def process_message(severity, time, program_name, message) return { '@status' => 'exception' } if message.is_a?(Exception) if message.is_a? Hash if message["retry"] status = "retry" msg = "#{message['class']} failed, retrying with args #{message['args']}." else status = "dead" msg = "#{message['class']} failed with args #{message['args']}, not retrying." end return { '@status' => status, '@message' => "#{time.utc.iso8601} #{::Process.pid} TID-#{Thread.current.object_id.to_s(36)}#{context} #{severity}: #{msg}" } end result = message.split(" ") status = result[0].match(/^(start|done|fail):?$/) || [] { '@status' => status[1], # start or done '@run_time' => status[1] && result[1] && result[1].to_f # run time in seconds } end end end end end
36.385965
140
0.499036
f7c4ec6134f6dbf4f5d15b89a41e59a029e706c1
261
require 'rubygems' require 'test/unit' require 'shoulda' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'ActionMailer-Base-to-use-an-absolute-path-template' class Test::Unit::TestCase end
23.727273
66
0.762452
08fac1d4cd939f90af563d4dc3df28d2aced42c0
106
exclude :test_enclosed_thgroup, "needs investigation" exclude :test_frozen_thgroup, "needs investigation"
35.333333
53
0.849057
288ce8c71745f232520bee67466c551da5ffeece
45
require "zelotes/engine" module Zelotes end
9
24
0.8
e20f1d35b2821564b031e4f27713767246872c25
2,549
require 'test/unit' $: << File.expand_path(File.join(File.dirname(__FILE__), "..", "lib")) require 'orientdb4r' ### # This class tests Utils methods. class TestUtils < Test::Unit::TestCase include Orientdb4r::Utils def test_verify_options opt_pattern = {:a => :mandatory, :b => :optional, :c => 'predefined', :d => [1, false]} assert_nothing_thrown do verify_options({:a => 'A', :b => 'B', :c => 'C', :d => 1}, opt_pattern); end # missing mandatory assert_raise ArgumentError do verify_options({}, opt_pattern); end # unknown key assert_raise ArgumentError do verify_options({:a => 1, :z => 2}, opt_pattern); end # value not in predefined set assert_raise ArgumentError do verify_options({:a => 1, :d => 3}, opt_pattern); end end def test_verify_and_sanitize_options opt_pattern = {:a => 'A', :b => 'B'} options = {:a => 'X'} verify_and_sanitize_options(options, opt_pattern) assert_equal 2, options.size assert_equal 'X', options[:a] assert_equal 'B', options[:b] # :optional cannot be set as default value opt_pattern = {:a => :optional, :b => 'B'} options = {} verify_and_sanitize_options(options, opt_pattern) assert_equal 1, options.size assert !options.include?(:a) assert_equal 'B', options[:b] end def test_compare_versions assert_raise ArgumentError do compare_versions 'foo', 'bar'; end assert_raise ArgumentError do compare_versions nil, 'bar'; end assert_raise ArgumentError do compare_versions 'foo', nil; end assert_raise ArgumentError do compare_versions '1.0.0', 'bar'; end assert_raise ArgumentError do compare_versions 'foo', '1.0.0'; end assert_nothing_thrown do compare_versions '1.0.0', '1.1.0'; end assert_equal 0, compare_versions('1.0.0', '1.0.0') assert_equal 0, compare_versions('1.2.0', '1.2.0') assert_equal 0, compare_versions('1.2.3', '1.2.3') assert_equal 1, compare_versions('1.0.1', '1.0.0') assert_equal 1, compare_versions('1.1.0', '1.0.0') assert_equal 1, compare_versions('2.0.0', '1.0.0') assert_equal -1, compare_versions('1.0.0', '1.0.1') assert_equal -1, compare_versions('1.0.0', '1.1.0') assert_equal -1, compare_versions('1.0.0', '2.0.0') # test block tmp = -100; compare_versions('1.0.0', '1.0.0') { |comp| tmp = comp } assert_equal 0, tmp compare_versions('1.0.0', '2.0.0') { |comp| tmp = comp } assert_equal -1, tmp compare_versions('3.0.0', '2.0.0') { |comp| tmp = comp } assert_equal 1, tmp end end
36.414286
105
0.655159
d5d9683ad995915fac66761e839b23a0bced90a6
9,033
# frozen_string_literal: true # Copyright 2022 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! module Google module Cloud module AIPlatform module V1 module PipelineService # Path helper methods for the PipelineService API. module Paths ## # Create a fully-qualified Artifact resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}` # # @param project [String] # @param location [String] # @param metadata_store [String] # @param artifact [String] # # @return [::String] def artifact_path project:, location:, metadata_store:, artifact: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" raise ::ArgumentError, "metadata_store cannot contain /" if metadata_store.to_s.include? "/" "projects/#{project}/locations/#{location}/metadataStores/#{metadata_store}/artifacts/#{artifact}" end ## # Create a fully-qualified Context resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}` # # @param project [String] # @param location [String] # @param metadata_store [String] # @param context [String] # # @return [::String] def context_path project:, location:, metadata_store:, context: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" raise ::ArgumentError, "metadata_store cannot contain /" if metadata_store.to_s.include? "/" "projects/#{project}/locations/#{location}/metadataStores/#{metadata_store}/contexts/#{context}" end ## # Create a fully-qualified CustomJob resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/customJobs/{custom_job}` # # @param project [String] # @param location [String] # @param custom_job [String] # # @return [::String] def custom_job_path project:, location:, custom_job: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" "projects/#{project}/locations/#{location}/customJobs/#{custom_job}" end ## # Create a fully-qualified Endpoint resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/endpoints/{endpoint}` # # @param project [String] # @param location [String] # @param endpoint [String] # # @return [::String] def endpoint_path project:, location:, endpoint: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" "projects/#{project}/locations/#{location}/endpoints/#{endpoint}" end ## # Create a fully-qualified Execution resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/metadataStores/{metadata_store}/executions/{execution}` # # @param project [String] # @param location [String] # @param metadata_store [String] # @param execution [String] # # @return [::String] def execution_path project:, location:, metadata_store:, execution: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" raise ::ArgumentError, "metadata_store cannot contain /" if metadata_store.to_s.include? "/" "projects/#{project}/locations/#{location}/metadataStores/#{metadata_store}/executions/#{execution}" end ## # Create a fully-qualified Location resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}` # # @param project [String] # @param location [String] # # @return [::String] def location_path project:, location: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" "projects/#{project}/locations/#{location}" end ## # Create a fully-qualified Model resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/models/{model}` # # @param project [String] # @param location [String] # @param model [String] # # @return [::String] def model_path project:, location:, model: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" "projects/#{project}/locations/#{location}/models/#{model}" end ## # Create a fully-qualified Network resource string. # # The resource will be in the following format: # # `projects/{project}/global/networks/{network}` # # @param project [String] # @param network [String] # # @return [::String] def network_path project:, network: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" "projects/#{project}/global/networks/#{network}" end ## # Create a fully-qualified PipelineJob resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}` # # @param project [String] # @param location [String] # @param pipeline_job [String] # # @return [::String] def pipeline_job_path project:, location:, pipeline_job: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" "projects/#{project}/locations/#{location}/pipelineJobs/#{pipeline_job}" end ## # Create a fully-qualified TrainingPipeline resource string. # # The resource will be in the following format: # # `projects/{project}/locations/{location}/trainingPipelines/{training_pipeline}` # # @param project [String] # @param location [String] # @param training_pipeline [String] # # @return [::String] def training_pipeline_path project:, location:, training_pipeline: raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/" raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/" "projects/#{project}/locations/#{location}/trainingPipelines/#{training_pipeline}" end extend self end end end end end end
39.969027
114
0.560611
e9f536a566201509034f6014f5e3ad0289dc847e
5,631
#!/usr/bin/ruby -w begin; require 'rubygems'; rescue LoadError; end require 'test/unit' require 'aem' require 'kae' require 'ae' def num(s) if [1].pack('s') == "\001\000" # host system is i386 s.reverse else s end end def ut16(s) if [1].pack('s') == "\001\000" # host system is i386 i = 0 s2 = '' (s.length / 2).times do s2 += s[i, 2].reverse i+=2 end s2 else s end end class TC_Codecs < Test::Unit::TestCase def setup @c = AEM::Codecs.new end def test_nil d = @c.pack(nil) assert_equal(KAE::TypeNull, d.type) assert_equal('', d.data) assert_nil(@c.unpack(d)) end def test_bool [ [true, KAE::TypeTrue], [false, KAE::TypeFalse] ].each do |val, type| d = @c.pack(val) assert_equal(type, d.type) assert_equal('', d.data) assert_equal(val, @c.unpack(d)) end assert_equal(true, @c.unpack(AE::AEDesc.new(KAE::TypeBoolean, "\xfe"))) assert_equal(true, @c.unpack(AE::AEDesc.new(KAE::TypeTrue, ''))) assert_equal(false, @c.unpack(AE::AEDesc.new(KAE::TypeFalse, ''))) end def test_num [ # (mostly testing at threshold points where Codecs switches types when packing integers) [0, "\x00\x00\x00\x00", KAE::TypeInteger], [2, "\x00\x00\x00\x02", KAE::TypeInteger], [-9, "\xff\xff\xff\xf7", KAE::TypeInteger], [2**31-1, "\x7f\xff\xff\xff", KAE::TypeInteger], [-2**31, "\x80\x00\x00\x00", KAE::TypeInteger], [2**31, "\x00\x00\x00\x00\x80\x00\x00\x00", KAE::TypeSInt64], [2**32-1, "\x00\x00\x00\x00\xff\xff\xff\xff", KAE::TypeSInt64], [2**32, "\x00\x00\x00\x01\x00\x00\x00\x00", KAE::TypeSInt64], [-2**32, "\xff\xff\xff\xff\x00\x00\x00\x00", KAE::TypeSInt64], [2**63-1, "\x7f\xff\xff\xff\xff\xff\xff\xff", KAE::TypeSInt64], [-2**63, "\x80\x00\x00\x00\x00\x00\x00\x00", KAE::TypeSInt64], [-2**63+1, "\x80\x00\x00\x00\x00\x00\x00\x01", KAE::TypeSInt64], [2**63, "C\xe0\x00\x00\x00\x00\x00\x00", KAE::TypeFloat], [-2**63-1, "\xc3\xe0\x00\x00\x00\x00\x00\x00", KAE::TypeFloat], [0.1, "?\xb9\x99\x99\x99\x99\x99\x9a", KAE::TypeFloat], [-0.9e-9, "\xbe\x0e\xec{\xd5\x12\xb5r", KAE::TypeFloat], [2**300, "R\xb0\x00\x00\x00\x00\x00\x00", KAE::TypeFloat], ].each do |val, data, type| data = num(data) d = @c.pack(val) assert_equal(type, d.type) assert_equal(data, d.data) assert_equal(val, @c.unpack(d)) end end def test_str s = "\xc6\x92\xe2\x88\x82\xc2\xae\xd4\xb7\xd5\x96\xd4\xb9\xe0\xa8\x89\xe3\x82\xa2\xe3\x84\xbb" # test Ruby 1.9+ String Encoding support version, sub_version = RUBY_VERSION.split('.').collect {|n| n.to_i} [0, 2] if version >= 1 and sub_version >= 9 s.force_encoding('utf-8') end [ # note: aem has to pack UTF8 data as typeUnicodeText (UTF16) as stupid apps expect that type and will error on typeUTF8Text instead of just asking AEM to coerce it to the desired type in advance. # note: UTF16 BOM must be omitted when packing UTF16 data into typeUnicodeText AEDescs, as a BOM will upset stupid apps like iTunes 7 that don't recognise it as a BOM and treat it as character data instead ['', ''], ['hello', "\000h\000e\000l\000l\000o"], [s, "\x01\x92\"\x02\x00\xae\x057\x05V\x059\n\t0\xa21;"], ].each do |val, data| data = ut16(data) d = @c.pack(val) assert_equal(KAE::TypeUnicodeText, d.type) assert_equal(data, d.data) assert_equal(val, @c.unpack(d)) end assert_raises(TypeError) { @c.pack("\x88") } # non-valid UTF8 strings should raise error when coercing from typeUTF8Text to typeUnicodeText end def test_date # note: not testing on ST-DST boundaries; this is known to have out-by-an-hour problems due to LongDateTime type being crap [ [Time.local(2005, 12, 11, 15, 40, 43), "\x00\x00\x00\x00\xbf\xc1\xf8\xfb"], [Time.local(2005, 5, 1, 6, 51, 7), "\x00\x00\x00\x00\xbe\x9a\x2c\xdb"], ].each do |t, data| data = num(data) d = @c.pack(t) assert_equal(KAE::TypeLongDateTime, d.type) assert_equal(data, d.data) assert_equal(t, @c.unpack(AE::AEDesc.new(KAE::TypeLongDateTime, data))) end end def test_file path = '/Applications/TextEdit.app' d = @c.pack(MacTypes::Alias.path(path)) assert_equal(path, @c.unpack(d).to_s) path = '/Applications/TextEdit.app' d = @c.pack(MacTypes::FileURL.path(path)) assert_equal(path, @c.unpack(d).to_s) end def test_typewrappers [ AEM::AEType.new("docu"), AEM::AEEnum.new('yes '), AEM::AEProp.new('pnam'), AEM::AEKey.new('ABCD'), ].each do |val| d = @c.pack(val) val2 = @c.unpack(d) assert_equal(val, val2) assert_block { val.eql?(val2) } val2 = @c.unpack(d) assert_equal(val2, val) assert_block { val2.eql?(val) } end assert_raises(ArgumentError) { AEM::AEType.new(3) } assert_raises(ArgumentError) { AEM::AEType.new("docum") } end def test_list end def test_hash val = {'foo' => 1, AEM::AEType.new('foob') => 2, AEM::AEProp.new('barr') => 3} expected_val = {'foo' => 1, AEM::AEType.new('foob') => 2, AEM::AEType.new('barr') => 3} # note that four-char-code keys are always unpacked as AEType d = @c.pack(val) assert_equal(expected_val, @c.unpack(d)) end def test_units val = MacTypes::Units.new(3.3, :inches) assert_equal(:inches, val.type) assert_equal(3.3, val.value) d = @c.pack(val) assert_equal('inch', d.type) assert_equal(3.3, @c.unpack(d.coerce(KAE::TypeFloat))) val2 = @c.unpack(d) assert_equal(val, val2) assert_equal(:inches, val2.type) assert_equal(3.3, val2.value) end def test_app val = AEM::Application.by_path(FindApp.by_name('TextEdit')) d = @c.pack(val) assert_equal(KAE::TypeProcessSerialNumber, d.type) end end
30.112299
208
0.648553
08f99cffd48877e03613aafac9573d17dfbf80c2
268
cask :v1 => 'cpumeter' do version :latest sha256 :no_check url 'https://github.com/yusukeshibata/cpumeter/blob/master/dist/cpumeter.zip?raw=true' name 'cpumeter' homepage 'https://github.com/yusukeshibata/cpumeter/' license :mit app 'cpumeter.app' end
22.333333
88
0.727612
4a6a5367f7acaa4cd5198bd5b368774e4aa32d97
1,137
class SoundTouch < Formula desc "Audio processing library" homepage "https://www.surina.net/soundtouch/" url "https://gitlab.com/soundtouch/soundtouch/-/archive/2.1.2/soundtouch-2.1.2.tar.gz" sha256 "2826049e2f34efbc4c8a47d00c93649822b0c14e1f29f5569835704814590732" license "LGPL-2.1" bottle do cellar :any sha256 "89d1037259a1c68865339b7dbdc837f22f397a33772d45c1296d9137ebc28a58" => :catalina sha256 "39081044f19ddcb8982560fb86e8c9b621c94e8bfc2de6eb4e398ba0fb2a2b9e" => :mojave sha256 "6d6651a6a7cc88c83279a49d2d676f8baf7731316f41dff3b0c77ac2d2fe7fb6" => :high_sierra sha256 "4b55c5ffffbba6f1c16f9a82860d3a0316b1d2bc478a6f7ac59e4cb36d70342a" => :sierra end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build def install system "/bin/sh", "bootstrap" args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} ] system "./configure", *args system "make", "install" end test do assert_match /SoundStretch v#{version} -/, shell_output("#{bin}/soundstretch 2>&1", 255) end end
31.583333
93
0.734389
610eab78937b458a1fdf40d8605c68037fcf7f9e
752
class IRWebmachine::TracedRequest def initialize(app) @app = app @req = nil @res = nil @stack = IRWebmachine::Stack.new end def stack @stack end def dispatch(*args) dispatch!(*args) while frame = @stack.tracer.continue @stack << frame end @res end def dispatch!(type, path, params = {}, headers = {}, body = "") uri = URI::HTTP.build(host: "localhost", path: path) uri.query_params.merge!(params) @req = Webmachine::Request.new type.upcase, uri, headers, body @res = Webmachine::Response.new @stack.tracer.trace do @app.dispatcher.dispatch(@req, @res) end @res end def to_a [@req.method, @req.uri.path, @req.query, @req.headers, @req.body] end end
20.888889
69
0.615691
e277633664faa6ca44d2f125db02a9b449a0bd2b
3,160
# frozen_string_literal: true module Integrations class EmailsOnPush < Integration include NotificationBranchSelection RECIPIENTS_LIMIT = 750 boolean_accessor :send_from_committer_email boolean_accessor :disable_diffs prop_accessor :recipients, :branches_to_be_notified validates :recipients, presence: true, if: :validate_recipients? validate :number_of_recipients_within_limit, if: :validate_recipients? def self.valid_recipients(recipients) recipients.split.select do |recipient| recipient.include?('@') end.uniq(&:downcase) end def title s_('EmailsOnPushService|Emails on push') end def description s_('EmailsOnPushService|Email the commits and diff of each push to a list of recipients.') end def self.to_param 'emails_on_push' end def self.supported_events %w(push tag_push) end def initialize_properties super self.branches_to_be_notified = 'all' if branches_to_be_notified.nil? end def execute(push_data) return unless supported_events.include?(push_data[:object_kind]) return if project.emails_disabled? return unless notify_for_ref?(push_data) EmailsOnPushWorker.perform_async( project_id, recipients, push_data, send_from_committer_email: send_from_committer_email?, disable_diffs: disable_diffs? ) end def notify_for_ref?(push_data) return true if push_data[:object_kind] == 'tag_push' return true if push_data.dig(:object_attributes, :tag) notify_for_branch?(push_data) end def send_from_committer_email? Gitlab::Utils.to_boolean(self.send_from_committer_email) end def disable_diffs? Gitlab::Utils.to_boolean(self.disable_diffs) end def fields domains = Notify.allowed_email_domains.map { |domain| "user@#{domain}" }.join(", ") [ { type: 'checkbox', name: 'send_from_committer_email', title: s_("EmailsOnPushService|Send from committer"), help: s_("EmailsOnPushService|Send notifications from the committer's email address if the domain matches the domain used by your GitLab instance (such as %{domains}).") % { domains: domains } }, { type: 'checkbox', name: 'disable_diffs', title: s_("EmailsOnPushService|Disable code diffs"), help: s_("EmailsOnPushService|Don't include possibly sensitive code diffs in notification body.") }, { type: 'select', name: 'branches_to_be_notified', choices: branch_choices }, { type: 'textarea', name: 'recipients', placeholder: s_('EmailsOnPushService|[email protected] [email protected]'), help: s_('EmailsOnPushService|Emails separated by whitespace.') } ] end private def number_of_recipients_within_limit return if recipients.blank? if self.class.valid_recipients(recipients).size > RECIPIENTS_LIMIT errors.add(:recipients, s_("EmailsOnPushService|can't exceed %{recipients_limit}") % { recipients_limit: RECIPIENTS_LIMIT }) end end end end
31.6
205
0.692405
081ebb6a81da9fbe802f7ee535685352bb096836
833
require 'bundler/setup' require 'webmock/rspec' require 'httparty' require 'active_support' require 'pensio_api' require './spec/support/helpers' RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.include Helpers config.before :each do PensioAPI::Credentials.base_uri = 'https://testgateway.pensio.com' PensioAPI::Credentials.username = 'test_user' PensioAPI::Credentials.password = 'password' PensioAPI::Credentials.allow_defaults = true # because some spec examples set up additional creds end # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' end
30.851852
101
0.752701
088c584392f3a7e0ee1e38d7e667d2b3db422385
154
class EnablePgcryptoExtension < ActiveRecord::Migration[5.2] def change enable_extension "pgcrypto" unless extension_enabled?("pgcrypto") end end
25.666667
69
0.785714
ab1e7ad269ce835c3ba528ba70962740c1929b62
99,611
# frozen_string_literal: true require "active_support/core_ext/enumerable" require "active_support/core_ext/string/conversions" require "active_support/core_ext/module/remove_method" require "active_record/errors" module ActiveRecord class AssociationNotFoundError < ConfigurationError #:nodoc: def initialize(record = nil, association_name = nil) if record && association_name super("Association named '#{association_name}' was not found on #{record.class.name}; perhaps you misspelled it?") else super("Association was not found.") end end end class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc: def initialize(reflection = nil, associated_class = nil) if reflection super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})") else super("Could not find the inverse association.") end end end class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil) if owner_class_name && reflection super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}") else super("Could not find the association.") end end end class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) if owner_class_name && reflection && source_reflection super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.") else super("Cannot have a has_many :through association.") end end end class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil) if owner_class_name && reflection super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") else super("Cannot have a has_many :through association.") end end end class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) if owner_class_name && reflection && source_reflection super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.") else super("Cannot have a has_many :through association.") end end end class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) if owner_class_name && reflection && through_reflection super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.") else super("Cannot have a has_one :through association.") end end end class HasOneAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil) if owner_class_name && reflection super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") else super("Cannot have a has_one :through association.") end end end class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc: def initialize(reflection = nil) if reflection through_reflection = reflection.through_reflection source_reflection_names = reflection.source_reflection_names source_associations = reflection.through_reflection.klass._reflections.keys super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?") else super("Could not find the source association(s).") end end end class HasManyThroughOrderError < ActiveRecordError #:nodoc: def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) if owner_class_name && reflection && through_reflection super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through '#{owner_class_name}##{through_reflection.name}' before the through association is defined.") else super("Cannot have a has_many :through association before the through association is defined.") end end end class ThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc: def initialize(owner = nil, reflection = nil) if owner && reflection super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.") else super("Cannot modify association.") end end end class AmbiguousSourceReflectionForThroughAssociation < ActiveRecordError # :nodoc: def initialize(klass, macro, association_name, options, possible_sources) example_options = options.dup example_options[:source] = possible_sources.first super("Ambiguous source reflection for through association. Please " \ "specify a :source directive on your declaration like:\n" \ "\n" \ " class #{klass} < ActiveRecord::Base\n" \ " #{macro} :#{association_name}, #{example_options}\n" \ " end" ) end end class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: end class HasOneThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: end class ThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc: def initialize(owner = nil, reflection = nil) if owner && reflection super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.") else super("Through nested associations are read-only.") end end end class HasManyThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: end class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: end # This error is raised when trying to eager load a polymorphic association using a JOIN. # Eager loading polymorphic associations is only possible with # {ActiveRecord::Relation#preload}[rdoc-ref:QueryMethods#preload]. class EagerLoadPolymorphicError < ActiveRecordError def initialize(reflection = nil) if reflection super("Cannot eagerly load the polymorphic association #{reflection.name.inspect}") else super("Eager load polymorphic error.") end end end # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations # (has_many, has_one) when there is at least 1 child associated instance. # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project class DeleteRestrictionError < ActiveRecordError #:nodoc: def initialize(name = nil) if name super("Cannot delete record because of dependent #{name}") else super("Delete restriction error.") end end end # See ActiveRecord::Associations::ClassMethods for documentation. module Associations # :nodoc: extend ActiveSupport::Autoload extend ActiveSupport::Concern # These classes will be loaded when associations are created. # So there is no need to eager load them. autoload :Association autoload :SingularAssociation autoload :CollectionAssociation autoload :ForeignAssociation autoload :CollectionProxy autoload :ThroughAssociation module Builder #:nodoc: autoload :Association, "active_record/associations/builder/association" autoload :SingularAssociation, "active_record/associations/builder/singular_association" autoload :CollectionAssociation, "active_record/associations/builder/collection_association" autoload :BelongsTo, "active_record/associations/builder/belongs_to" autoload :HasOne, "active_record/associations/builder/has_one" autoload :HasMany, "active_record/associations/builder/has_many" autoload :HasAndBelongsToMany, "active_record/associations/builder/has_and_belongs_to_many" end eager_autoload do autoload :BelongsToAssociation autoload :BelongsToPolymorphicAssociation autoload :HasManyAssociation autoload :HasManyThroughAssociation autoload :HasOneAssociation autoload :HasOneThroughAssociation autoload :Preloader autoload :JoinDependency autoload :AssociationScope autoload :AliasTracker end def self.eager_load! super Preloader.eager_load! end # Returns the association instance for the given name, instantiating it if it doesn't already exist def association(name) #:nodoc: association = association_instance_get(name) if association.nil? unless reflection = self.class._reflect_on_association(name) raise AssociationNotFoundError.new(self, name) end association = reflection.association_class.new(self, reflection) association_instance_set(name, association) end association end def association_cached?(name) # :nodoc: @association_cache.key?(name) end def initialize_dup(*) # :nodoc: @association_cache = {} super end def reload(*) # :nodoc: clear_association_cache super end private # Clears out the association cache. def clear_association_cache @association_cache.clear if persisted? end def init_internals @association_cache = {} super end # Returns the specified association instance if it exists, +nil+ otherwise. def association_instance_get(name) @association_cache[name] end # Set the specified association instance. def association_instance_set(name, association) @association_cache[name] = association end # \Associations are a set of macro-like class methods for tying objects together through # foreign keys. They express relationships like "Project has one Project Manager" # or "Project belongs to a Portfolio". Each macro adds a number of methods to the # class which are specialized according to the collection or association symbol and the # options hash. It works much the same way as Ruby's own <tt>attr*</tt> # methods. # # class Project < ActiveRecord::Base # belongs_to :portfolio # has_one :project_manager # has_many :milestones # has_and_belongs_to_many :categories # end # # The project class now has the following methods (and more) to ease the traversal and # manipulation of its relationships: # * <tt>Project#portfolio</tt>, <tt>Project#portfolio=(portfolio)</tt>, <tt>Project#reload_portfolio</tt> # * <tt>Project#project_manager</tt>, <tt>Project#project_manager=(project_manager)</tt>, <tt>Project#reload_project_manager</tt> # * <tt>Project#milestones.empty?</tt>, <tt>Project#milestones.size</tt>, <tt>Project#milestones</tt>, <tt>Project#milestones<<(milestone)</tt>, # <tt>Project#milestones.delete(milestone)</tt>, <tt>Project#milestones.destroy(milestone)</tt>, <tt>Project#milestones.find(milestone_id)</tt>, # <tt>Project#milestones.build</tt>, <tt>Project#milestones.create</tt> # * <tt>Project#categories.empty?</tt>, <tt>Project#categories.size</tt>, <tt>Project#categories</tt>, <tt>Project#categories<<(category1)</tt>, # <tt>Project#categories.delete(category1)</tt>, <tt>Project#categories.destroy(category1)</tt> # # === A word of warning # # Don't create associations that have the same name as {instance methods}[rdoc-ref:ActiveRecord::Core] of # <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to # its model, using an association with the same name as one provided by <tt>ActiveRecord::Base</tt> will override the method inherited through <tt>ActiveRecord::Base</tt> and will break things. # For instance, +attributes+ and +connection+ would be bad choices for association names, because those names already exist in the list of <tt>ActiveRecord::Base</tt> instance methods. # # == Auto-generated methods # See also Instance Public methods below for more details. # # === Singular associations (one-to-one) # | | belongs_to | # generated methods | belongs_to | :polymorphic | has_one # ----------------------------------+------------+--------------+--------- # other | X | X | X # other=(other) | X | X | X # build_other(attributes={}) | X | | X # create_other(attributes={}) | X | | X # create_other!(attributes={}) | X | | X # reload_other | X | X | X # # === Collection associations (one-to-many / many-to-many) # | | | has_many # generated methods | habtm | has_many | :through # ----------------------------------+-------+----------+---------- # others | X | X | X # others=(other,other,...) | X | X | X # other_ids | X | X | X # other_ids=(id,id,...) | X | X | X # others<< | X | X | X # others.push | X | X | X # others.concat | X | X | X # others.build(attributes={}) | X | X | X # others.create(attributes={}) | X | X | X # others.create!(attributes={}) | X | X | X # others.size | X | X | X # others.length | X | X | X # others.count | X | X | X # others.sum(*args) | X | X | X # others.empty? | X | X | X # others.clear | X | X | X # others.delete(other,other,...) | X | X | X # others.delete_all | X | X | X # others.destroy(other,other,...) | X | X | X # others.destroy_all | X | X | X # others.find(*args) | X | X | X # others.exists? | X | X | X # others.distinct | X | X | X # others.reset | X | X | X # others.reload | X | X | X # # === Overriding generated methods # # Association methods are generated in a module included into the model # class, making overrides easy. The original generated method can thus be # called with +super+: # # class Car < ActiveRecord::Base # belongs_to :owner # belongs_to :old_owner # # def owner=(new_owner) # self.old_owner = self.owner # super # end # end # # The association methods module is included immediately after the # generated attributes methods module, meaning an association will # override the methods for an attribute with the same name. # # == Cardinality and associations # # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many # relationships between models. Each model uses an association to describe its role in # the relation. The #belongs_to association is always used in the model that has # the foreign key. # # === One-to-one # # Use #has_one in the base, and #belongs_to in the associated model. # # class Employee < ActiveRecord::Base # has_one :office # end # class Office < ActiveRecord::Base # belongs_to :employee # foreign key - employee_id # end # # === One-to-many # # Use #has_many in the base, and #belongs_to in the associated model. # # class Manager < ActiveRecord::Base # has_many :employees # end # class Employee < ActiveRecord::Base # belongs_to :manager # foreign key - manager_id # end # # === Many-to-many # # There are two ways to build a many-to-many relationship. # # The first way uses a #has_many association with the <tt>:through</tt> option and a join model, so # there are two stages of associations. # # class Assignment < ActiveRecord::Base # belongs_to :programmer # foreign key - programmer_id # belongs_to :project # foreign key - project_id # end # class Programmer < ActiveRecord::Base # has_many :assignments # has_many :projects, through: :assignments # end # class Project < ActiveRecord::Base # has_many :assignments # has_many :programmers, through: :assignments # end # # For the second way, use #has_and_belongs_to_many in both models. This requires a join table # that has no corresponding model or primary key. # # class Programmer < ActiveRecord::Base # has_and_belongs_to_many :projects # foreign keys in the join table # end # class Project < ActiveRecord::Base # has_and_belongs_to_many :programmers # foreign keys in the join table # end # # Choosing which way to build a many-to-many relationship is not always simple. # If you need to work with the relationship model as its own entity, # use #has_many <tt>:through</tt>. Use #has_and_belongs_to_many when working with legacy schemas or when # you never work directly with the relationship itself. # # == Is it a #belongs_to or #has_one association? # # Both express a 1-1 relationship. The difference is mostly where to place the foreign # key, which goes on the table for the class declaring the #belongs_to relationship. # # class User < ActiveRecord::Base # # I reference an account. # belongs_to :account # end # # class Account < ActiveRecord::Base # # One user references me. # has_one :user # end # # The tables for these classes could look something like: # # CREATE TABLE users ( # id bigint NOT NULL auto_increment, # account_id bigint default NULL, # name varchar default NULL, # PRIMARY KEY (id) # ) # # CREATE TABLE accounts ( # id bigint NOT NULL auto_increment, # name varchar default NULL, # PRIMARY KEY (id) # ) # # == Unsaved objects and associations # # You can manipulate objects and associations before they are saved to the database, but # there is some special behavior you should be aware of, mostly involving the saving of # associated objects. # # You can set the <tt>:autosave</tt> option on a #has_one, #belongs_to, # #has_many, or #has_and_belongs_to_many association. Setting it # to +true+ will _always_ save the members, whereas setting it to +false+ will # _never_ save the members. More details about <tt>:autosave</tt> option is available at # AutosaveAssociation. # # === One-to-one associations # # * Assigning an object to a #has_one association automatically saves that object and # the object being replaced (if there is one), in order to update their foreign # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>). # * If either of these saves fail (due to one of the objects being invalid), an # ActiveRecord::RecordNotSaved exception is raised and the assignment is # cancelled. # * If you wish to assign an object to a #has_one association without saving it, # use the <tt>#build_association</tt> method (documented below). The object being # replaced will still be saved to update its foreign key. # * Assigning an object to a #belongs_to association does not save the object, since # the foreign key field belongs on the parent. It does not save the parent either. # # === Collections # # * Adding an object to a collection (#has_many or #has_and_belongs_to_many) automatically # saves that object, except if the parent object (the owner of the collection) is not yet # stored in the database. # * If saving any of the objects being added to a collection (via <tt>push</tt> or similar) # fails, then <tt>push</tt> returns +false+. # * If saving fails while replacing the collection (via <tt>association=</tt>), an # ActiveRecord::RecordNotSaved exception is raised and the assignment is # cancelled. # * You can add an object to a collection without automatically saving it by using the # <tt>collection.build</tt> method (documented below). # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically # saved when the parent is saved. # # == Customizing the query # # \Associations are built from <tt>Relation</tt> objects, and you can use the Relation syntax # to customize them. For example, to add a condition: # # class Blog < ActiveRecord::Base # has_many :published_posts, -> { where(published: true) }, class_name: 'Post' # end # # Inside the <tt>-> { ... }</tt> block you can use all of the usual Relation methods. # # === Accessing the owner object # # Sometimes it is useful to have access to the owner object when building the query. The owner # is passed as a parameter to the block. For example, the following association would find all # events that occur on the user's birthday: # # class User < ActiveRecord::Base # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event' # end # # Note: Joining, eager loading and preloading of these associations is not possible. # These operations happen before instance creation and the scope will be called with a +nil+ argument. # # == Association callbacks # # Similar to the normal callbacks that hook into the life cycle of an Active Record object, # you can also define callbacks that get triggered when you add an object to or remove an # object from an association collection. # # class Project # has_and_belongs_to_many :developers, after_add: :evaluate_velocity # # def evaluate_velocity(developer) # ... # end # end # # It's possible to stack callbacks by passing them as an array. Example: # # class Project # has_and_belongs_to_many :developers, # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}] # end # # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+. # # If any of the +before_add+ callbacks throw an exception, the object will not be # added to the collection. # # Similarly, if any of the +before_remove+ callbacks throw an exception, the object # will not be removed from the collection. # # == Association extensions # # The proxy objects that control the access to associations can be extended through anonymous # modules. This is especially beneficial for adding new finders, creators, and other # factory-type methods that are only used as part of this association. # # class Account < ActiveRecord::Base # has_many :people do # def find_or_create_by_name(name) # first_name, last_name = name.split(" ", 2) # find_or_create_by(first_name: first_name, last_name: last_name) # end # end # end # # person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson") # person.first_name # => "David" # person.last_name # => "Heinemeier Hansson" # # If you need to share the same extensions between many associations, you can use a named # extension module. # # module FindOrCreateByNameExtension # def find_or_create_by_name(name) # first_name, last_name = name.split(" ", 2) # find_or_create_by(first_name: first_name, last_name: last_name) # end # end # # class Account < ActiveRecord::Base # has_many :people, -> { extending FindOrCreateByNameExtension } # end # # class Company < ActiveRecord::Base # has_many :people, -> { extending FindOrCreateByNameExtension } # end # # Some extensions can only be made to work with knowledge of the association's internals. # Extensions can access relevant state using the following methods (where +items+ is the # name of the association): # # * <tt>record.association(:items).owner</tt> - Returns the object the association is part of. # * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association. # * <tt>record.association(:items).target</tt> - Returns the associated object for #belongs_to and #has_one, or # the collection of associated objects for #has_many and #has_and_belongs_to_many. # # However, inside the actual extension code, you will not have access to the <tt>record</tt> as # above. In this case, you can access <tt>proxy_association</tt>. For example, # <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return # the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside # association extensions. # # == Association Join Models # # Has Many associations can be configured with the <tt>:through</tt> option to use an # explicit join model to retrieve the data. This operates similarly to a # #has_and_belongs_to_many association. The advantage is that you're able to add validations, # callbacks, and extra attributes on the join model. Consider the following schema: # # class Author < ActiveRecord::Base # has_many :authorships # has_many :books, through: :authorships # end # # class Authorship < ActiveRecord::Base # belongs_to :author # belongs_to :book # end # # @author = Author.first # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to # @author.books # selects all books by using the Authorship join model # # You can also go through a #has_many association on the join model: # # class Firm < ActiveRecord::Base # has_many :clients # has_many :invoices, through: :clients # end # # class Client < ActiveRecord::Base # belongs_to :firm # has_many :invoices # end # # class Invoice < ActiveRecord::Base # belongs_to :client # end # # @firm = Firm.first # @firm.clients.flat_map { |c| c.invoices } # select all invoices for all clients of the firm # @firm.invoices # selects all invoices by going through the Client join model # # Similarly you can go through a #has_one association on the join model: # # class Group < ActiveRecord::Base # has_many :users # has_many :avatars, through: :users # end # # class User < ActiveRecord::Base # belongs_to :group # has_one :avatar # end # # class Avatar < ActiveRecord::Base # belongs_to :user # end # # @group = Group.first # @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group # @group.avatars # selects all avatars by going through the User join model. # # An important caveat with going through #has_one or #has_many associations on the # join model is that these associations are *read-only*. For example, the following # would not work following the previous example: # # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around # @group.avatars.delete(@group.avatars.last) # so would this # # == Setting Inverses # # If you are using a #belongs_to on the join model, it is a good idea to set the # <tt>:inverse_of</tt> option on the #belongs_to, which will mean that the following example # works correctly (where <tt>tags</tt> is a #has_many <tt>:through</tt> association): # # @post = Post.first # @tag = @post.tags.build name: "ruby" # @tag.save # # The last line ought to save the through record (a <tt>Tagging</tt>). This will only work if the # <tt>:inverse_of</tt> is set: # # class Tagging < ActiveRecord::Base # belongs_to :post # belongs_to :tag, inverse_of: :taggings # end # # If you do not set the <tt>:inverse_of</tt> record, the association will # do its best to match itself up with the correct inverse. Automatic # inverse detection only works on #has_many, #has_one, and # #belongs_to associations. # # Extra options on the associations, as defined in the # <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will # also prevent the association's inverse from being found automatically. # # The automatic guessing of the inverse association uses a heuristic based # on the name of the class, so it may not work for all associations, # especially the ones with non-standard names. # # You can turn off the automatic detection of inverse associations by setting # the <tt>:inverse_of</tt> option to <tt>false</tt> like so: # # class Tagging < ActiveRecord::Base # belongs_to :tag, inverse_of: false # end # # == Nested \Associations # # You can actually specify *any* association with the <tt>:through</tt> option, including an # association which has a <tt>:through</tt> option itself. For example: # # class Author < ActiveRecord::Base # has_many :posts # has_many :comments, through: :posts # has_many :commenters, through: :comments # end # # class Post < ActiveRecord::Base # has_many :comments # end # # class Comment < ActiveRecord::Base # belongs_to :commenter # end # # @author = Author.first # @author.commenters # => People who commented on posts written by the author # # An equivalent way of setting up this association this would be: # # class Author < ActiveRecord::Base # has_many :posts # has_many :commenters, through: :posts # end # # class Post < ActiveRecord::Base # has_many :comments # has_many :commenters, through: :comments # end # # class Comment < ActiveRecord::Base # belongs_to :commenter # end # # When using a nested association, you will not be able to modify the association because there # is not enough information to know what modification to make. For example, if you tried to # add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the # intermediate <tt>Post</tt> and <tt>Comment</tt> objects. # # == Polymorphic \Associations # # Polymorphic associations on models are not restricted on what types of models they # can be associated with. Rather, they specify an interface that a #has_many association # must adhere to. # # class Asset < ActiveRecord::Base # belongs_to :attachable, polymorphic: true # end # # class Post < ActiveRecord::Base # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use. # end # # @asset.attachable = @post # # This works by using a type column in addition to a foreign key to specify the associated # record. In the Asset example, you'd need an +attachable_id+ integer column and an # +attachable_type+ string column. # # Using polymorphic associations in combination with single table inheritance (STI) is # a little tricky. In order for the associations to work as expected, ensure that you # store the base model for the STI models in the type column of the polymorphic # association. To continue with the asset example above, suppose there are guest posts # and member posts that use the posts table for STI. In this case, there must be a +type+ # column in the posts table. # # Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+. # The +class_name+ of the +attachable+ is passed as a String. # # class Asset < ActiveRecord::Base # belongs_to :attachable, polymorphic: true # # def attachable_type=(class_name) # super(class_name.constantize.base_class.to_s) # end # end # # class Post < ActiveRecord::Base # # because we store "Post" in attachable_type now dependent: :destroy will work # has_many :assets, as: :attachable, dependent: :destroy # end # # class GuestPost < Post # end # # class MemberPost < Post # end # # == Caching # # All of the methods are built on a simple caching principle that will keep the result # of the last query around unless specifically instructed not to. The cache is even # shared across methods to make it even cheaper to use the macro-added methods without # worrying too much about performance at the first go. # # project.milestones # fetches milestones from the database # project.milestones.size # uses the milestone cache # project.milestones.empty? # uses the milestone cache # project.milestones.reload.size # fetches milestones from the database # project.milestones # uses the milestone cache # # == Eager loading of associations # # Eager loading is a way to find objects of a certain class and a number of named associations. # It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100 # posts that each need to display their author triggers 101 database queries. Through the # use of eager loading, the number of queries will be reduced from 101 to 2. # # class Post < ActiveRecord::Base # belongs_to :author # has_many :comments # end # # Consider the following loop using the class above: # # Post.all.each do |post| # puts "Post: " + post.title # puts "Written by: " + post.author.name # puts "Last comment on: " + post.comments.first.created_on # end # # To iterate over these one hundred posts, we'll generate 201 database queries. Let's # first just optimize it for retrieving the author: # # Post.includes(:author).each do |post| # # This references the name of the #belongs_to association that also used the <tt>:author</tt> # symbol. After loading the posts, +find+ will collect the +author_id+ from each one and load # all of the referenced authors with one query. Doing so will cut down the number of queries # from 201 to 102. # # We can improve upon the situation further by referencing both associations in the finder with: # # Post.includes(:author, :comments).each do |post| # # This will load all comments with a single query. This reduces the total number of queries # to 3. In general, the number of queries will be 1 plus the number of associations # named (except if some of the associations are polymorphic #belongs_to - see below). # # To include a deep hierarchy of associations, use a hash: # # Post.includes(:author, { comments: { author: :gravatar } }).each do |post| # # The above code will load all the comments and all of their associated # authors and gravatars. You can mix and match any combination of symbols, # arrays, and hashes to retrieve the associations you want to load. # # All of this power shouldn't fool you into thinking that you can pull out huge amounts # of data with no performance penalty just because you've reduced the number of queries. # The database still needs to send all the data to Active Record and it still needs to # be processed. So it's no catch-all for performance problems, but it's a great way to # cut down on the number of queries in a situation as the one described above. # # Since only one table is loaded at a time, conditions or orders cannot reference tables # other than the main one. If this is the case, Active Record falls back to the previously # used <tt>LEFT OUTER JOIN</tt> based strategy. For example: # # Post.includes([:author, :comments]).where(['comments.approved = ?', true]) # # This will result in a single SQL query with joins along the lines of: # <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions # like this can have unintended consequences. # In the above example, posts with no approved comments are not returned at all because # the conditions apply to the SQL statement as a whole and not just to the association. # # You must disambiguate column references for this fallback to happen, for example # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not. # # If you want to load all posts (including posts with no approved comments), then write # your own <tt>LEFT OUTER JOIN</tt> query using <tt>ON</tt>: # # Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'") # # In this case, it is usually more natural to include an association which has conditions defined on it: # # class Post < ActiveRecord::Base # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment' # end # # Post.includes(:approved_comments) # # This will load posts and eager load the +approved_comments+ association, which contains # only those comments that have been approved. # # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored, # returning all the associated objects: # # class Picture < ActiveRecord::Base # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment' # end # # Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments. # # Eager loading is supported with polymorphic associations. # # class Address < ActiveRecord::Base # belongs_to :addressable, polymorphic: true # end # # A call that tries to eager load the addressable model # # Address.includes(:addressable) # # This will execute one query to load the addresses and load the addressables with one # query per addressable type. # For example, if all the addressables are either of class Person or Company, then a total # of 3 queries will be executed. The list of addressable types to load is determined on # the back of the addresses loaded. This is not supported if Active Record has to fallback # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. # The reason is that the parent model's type is a column value so its corresponding table # name cannot be put in the +FROM+/+JOIN+ clauses of that query. # # == Table Aliasing # # Active Record uses table aliasing in the case that a table is referenced multiple times # in a join. If a table is referenced only once, the standard table name is used. The # second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>. # Indexes are appended for any more successive uses of the table name. # # Post.joins(:comments) # # => SELECT ... FROM posts INNER JOIN comments ON ... # Post.joins(:special_comments) # STI # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment' # Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts # # Acts as tree example: # # TreeMixin.joins(:children) # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... # TreeMixin.joins(children: :parent) # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... # INNER JOIN parents_mixins ... # TreeMixin.joins(children: {parent: :children}) # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... # INNER JOIN parents_mixins ... # INNER JOIN mixins childrens_mixins_2 # # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix: # # Post.joins(:categories) # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... # Post.joins(categories: :posts) # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories # Post.joins(categories: {posts: :categories}) # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2 # # If you wish to specify your own custom joins using ActiveRecord::QueryMethods#joins method, those table # names will take precedence over the eager associations: # # Post.joins(:comments).joins("inner join comments ...") # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ... # Post.joins(:comments, :special_comments).joins("inner join comments ...") # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ... # INNER JOIN comments special_comments_posts ... # INNER JOIN comments ... # # Table aliases are automatically truncated according to the maximum length of table identifiers # according to the specific database. # # == Modules # # By default, associations will look for objects within the current module scope. Consider: # # module MyApplication # module Business # class Firm < ActiveRecord::Base # has_many :clients # end # # class Client < ActiveRecord::Base; end # end # end # # When <tt>Firm#clients</tt> is called, it will in turn call # <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>. # If you want to associate with a class in another module scope, this can be done by # specifying the complete class name. # # module MyApplication # module Business # class Firm < ActiveRecord::Base; end # end # # module Billing # class Account < ActiveRecord::Base # belongs_to :firm, class_name: "MyApplication::Business::Firm" # end # end # end # # == Bi-directional associations # # When you specify an association, there is usually an association on the associated model # that specifies the same relationship in reverse. For example, with the following models: # # class Dungeon < ActiveRecord::Base # has_many :traps # has_one :evil_wizard # end # # class Trap < ActiveRecord::Base # belongs_to :dungeon # end # # class EvilWizard < ActiveRecord::Base # belongs_to :dungeon # end # # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are # the inverse of each other, and the inverse of the +dungeon+ association on +EvilWizard+ # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default, # Active Record can guess the inverse of the association based on the name # of the class. The result is the following: # # d = Dungeon.first # t = d.traps.first # d.object_id == t.dungeon.object_id # => true # # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to # the same in-memory instance since the association matches the name of the class. # The result would be the same if we added +:inverse_of+ to our model definitions: # # class Dungeon < ActiveRecord::Base # has_many :traps, inverse_of: :dungeon # has_one :evil_wizard, inverse_of: :dungeon # end # # class Trap < ActiveRecord::Base # belongs_to :dungeon, inverse_of: :traps # end # # class EvilWizard < ActiveRecord::Base # belongs_to :dungeon, inverse_of: :evil_wizard # end # # For more information, see the documentation for the +:inverse_of+ option. # # == Deleting from associations # # === Dependent associations # # #has_many, #has_one, and #belongs_to associations support the <tt>:dependent</tt> option. # This allows you to specify that associated records should be deleted when the owner is # deleted. # # For example: # # class Author # has_many :posts, dependent: :destroy # end # Author.find(1).destroy # => Will destroy all of the author's posts, too # # The <tt>:dependent</tt> option can have different values which specify how the deletion # is done. For more information, see the documentation for this option on the different # specific association types. When no option is given, the behavior is to do nothing # with the associated records when destroying a record. # # Note that <tt>:dependent</tt> is implemented using Rails' callback # system, which works by processing callbacks in order. Therefore, other # callbacks declared either before or after the <tt>:dependent</tt> option # can affect what it does. # # Note that <tt>:dependent</tt> option is ignored for #has_one <tt>:through</tt> associations. # # === Delete or destroy? # # #has_many and #has_and_belongs_to_many associations have the methods <tt>destroy</tt>, # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>. # # For #has_and_belongs_to_many, <tt>delete</tt> and <tt>destroy</tt> are the same: they # cause the records in the join table to be removed. # # For #has_many, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the # record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or # if no <tt>:dependent</tt> option is given, then it will follow the default strategy. # The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for # #has_many <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete # the join records, without running their callbacks). # # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that # it returns the association rather than the records which have been deleted. # # === What gets deleted? # # There is a potential pitfall here: #has_and_belongs_to_many and #has_many <tt>:through</tt> # associations have records in join tables, as well as the associated records. So when we # call one of these deletion methods, what exactly should be deleted? # # The answer is that it is assumed that deletion on an association is about removing the # <i>link</i> between the owner and the associated object(s), rather than necessarily the # associated objects themselves. So with #has_and_belongs_to_many and #has_many # <tt>:through</tt>, the join records will be deleted, but the associated records won't. # # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt> # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself # to be removed from the database. # # However, there are examples where this strategy doesn't make sense. For example, suppose # a person has many projects, and each project has many tasks. If we deleted one of a person's # tasks, we would probably not want the project to be deleted. In this scenario, the delete method # won't actually work: it can only be used if the association on the join model is a # #belongs_to. In other situations you are expected to perform operations directly on # either the associated records or the <tt>:through</tt> association. # # With a regular #has_many there is no distinction between the "associated records" # and the "link", so there is only one choice for what gets deleted. # # With #has_and_belongs_to_many and #has_many <tt>:through</tt>, if you want to delete the # associated records themselves, you can always do something along the lines of # <tt>person.tasks.each(&:destroy)</tt>. # # == Type safety with ActiveRecord::AssociationTypeMismatch # # If you attempt to assign an object to an association that doesn't match the inferred # or specified <tt>:class_name</tt>, you'll get an ActiveRecord::AssociationTypeMismatch. # # == Options # # All of the association macros can be specialized through options. This makes cases # more complex than the simple and guessable ones possible. module ClassMethods # Specifies a one-to-many association. The following methods for retrieval and query of # collections of associated objects will be added: # # +collection+ is a placeholder for the symbol passed as the +name+ argument, so # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>. # # [collection] # Returns a Relation of all the associated objects. # An empty Relation is returned if none are found. # [collection<<(object, ...)] # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. # Note that this operation instantly fires update SQL without waiting for the save or update call on the # parent object, unless the parent object is a new record. # This will also run validations and callbacks of associated object(s). # [collection.delete(object, ...)] # Removes one or more objects from the collection by setting their foreign keys to +NULL+. # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>, # and deleted if they're associated with <tt>dependent: :delete_all</tt>. # # If the <tt>:through</tt> option is used, then the join records are deleted (rather than # nullified) by default, but you can specify <tt>dependent: :destroy</tt> or # <tt>dependent: :nullify</tt> to override this. # [collection.destroy(object, ...)] # Removes one or more objects from the collection by running <tt>destroy</tt> on # each record, regardless of any dependent option, ensuring callbacks are run. # # If the <tt>:through</tt> option is used, then the join records are destroyed # instead, not the objects themselves. # [collection=objects] # Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt> # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is # direct by default. You can specify <tt>dependent: :destroy</tt> or # <tt>dependent: :nullify</tt> to override this. # [collection_singular_ids] # Returns an array of the associated objects' ids # [collection_singular_ids=ids] # Replace the collection with the objects identified by the primary keys in +ids+. This # method loads the models and calls <tt>collection=</tt>. See above. # [collection.clear] # Removes every object from the collection. This destroys the associated objects if they # are associated with <tt>dependent: :destroy</tt>, deletes them directly from the # database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+. # If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models. # Join models are directly deleted. # [collection.empty?] # Returns +true+ if there are no associated objects. # [collection.size] # Returns the number of associated objects. # [collection.find(...)] # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find. # [collection.exists?(...)] # Checks whether an associated object with the given conditions exists. # Uses the same rules as ActiveRecord::FinderMethods#exists?. # [collection.build(attributes = {}, ...)] # Returns one or more new objects of the collection type that have been instantiated # with +attributes+ and linked to this object through a foreign key, but have not yet # been saved. # [collection.create(attributes = {})] # Returns a new object of the collection type that has been instantiated # with +attributes+, linked to this object through a foreign key, and that has already # been saved (if it passed the validation). *Note*: This only works if the base model # already exists in the DB, not if it is a new (unsaved) record! # [collection.create!(attributes = {})] # Does the same as <tt>collection.create</tt>, but raises ActiveRecord::RecordInvalid # if the record is invalid. # [collection.reload] # Returns a Relation of all of the associated objects, forcing a database read. # An empty Relation is returned if none are found. # # === Example # # A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add: # * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>) # * <tt>Firm#clients<<</tt> # * <tt>Firm#clients.delete</tt> # * <tt>Firm#clients.destroy</tt> # * <tt>Firm#clients=</tt> # * <tt>Firm#client_ids</tt> # * <tt>Firm#client_ids=</tt> # * <tt>Firm#clients.clear</tt> # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>) # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>) # * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>) # * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>) # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new(firm_id: id)</tt>) # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new(firm_id: id); c.save; c</tt>) # * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new(firm_id: id); c.save!</tt>) # * <tt>Firm#clients.reload</tt> # The declaration can also include an +options+ hash to specialize the behavior of the association. # # === Scopes # # You can pass a second argument +scope+ as a callable (i.e. proc or # lambda) to retrieve a specific set of records or customize the generated # query when you access the associated collection. # # Scope examples: # has_many :comments, -> { where(author_id: 1) } # has_many :employees, -> { joins(:address) } # has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) } # # === Extensions # # The +extension+ argument allows you to pass a block into a has_many # association. This is useful for adding new finders, creators and other # factory-type methods to be used as part of the association. # # Extension examples: # has_many :employees do # def find_or_create_by_name(name) # first_name, last_name = name.split(" ", 2) # find_or_create_by(first_name: first_name, last_name: last_name) # end # end # # === Options # [:class_name] # Specify the class name of the association. Use it only if that name can't be inferred # from the association name. So <tt>has_many :products</tt> will by default be linked # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to # specify it with this option. # [:foreign_key] # Specify the foreign key used for the association. By default this is guessed to be the name # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many # association will use "person_id" as the default <tt>:foreign_key</tt>. # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option. # [:foreign_type] # Specify the column used to store the associated object's type, if this is a polymorphic # association. By default this is guessed to be the name of the polymorphic association # specified on "as" option with a "_type" suffix. So a class that defines a # <tt>has_many :tags, as: :taggable</tt> association will use "taggable_type" as the # default <tt>:foreign_type</tt>. # [:primary_key] # Specify the name of the column to use as the primary key for the association. By default this is +id+. # [:dependent] # Controls what happens to the associated objects when # their owner is destroyed. Note that these are implemented as # callbacks, and Rails executes callbacks in order. Therefore, other # similar callbacks may affect the <tt>:dependent</tt> behavior, and the # <tt>:dependent</tt> behavior may affect other callbacks. # # * <tt>:destroy</tt> causes all the associated objects to also be destroyed. # * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed). # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed. # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records. # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects. # # If using with the <tt>:through</tt> option, the association on the join model must be # a #belongs_to, and the records which get deleted are the join records, rather than # the associated records. # # If using <tt>dependent: :destroy</tt> on a scoped association, only the scoped objects are destroyed. # For example, if a Post model defines # <tt>has_many :comments, -> { where published: true }, dependent: :destroy</tt> and <tt>destroy</tt> is # called on a post, only published comments are destroyed. This means that any unpublished comments in the # database would still contain a foreign key pointing to the now deleted post. # [:counter_cache] # This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option, # when you customized the name of your <tt>:counter_cache</tt> on the #belongs_to association. # [:as] # Specifies a polymorphic interface (See #belongs_to). # [:through] # Specifies an association through which to perform the query. This can be any other type # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>, # <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the # source reflection. # # If the association on the join model is a #belongs_to, the collection can be modified # and the records on the <tt>:through</tt> model will be automatically created and removed # as appropriate. Otherwise, the collection is read-only, so you should manipulate the # <tt>:through</tt> association directly. # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option on the source association on the # join model. This allows associated records to be built which will automatically create # the appropriate join model records when they are saved. (See the 'Association Join Models' # section above.) # [:source] # Specifies the source association name used by #has_many <tt>:through</tt> queries. # Only use it if the name cannot be inferred from the association. # <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or # <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given. # [:source_type] # Specifies type of the source association used by #has_many <tt>:through</tt> queries where the source # association is a polymorphic #belongs_to. # [:validate] # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. # [:autosave] # If true, always save the associated objects or destroy them if marked for destruction, # when saving the parent object. If false, never save or destroy the associated objects. # By default, only save associated objects that are new records. This option is implemented as a # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects # may need to be explicitly saved in any user-defined +before_save+ callbacks. # # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets # <tt>:autosave</tt> to <tt>true</tt>. # [:inverse_of] # Specifies the name of the #belongs_to association on the associated object # that is the inverse of this #has_many association. # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. # [:extend] # Specifies a module or array of modules that will be extended into the association object returned. # Useful for defining methods on associations, especially when they should be shared between multiple # association objects. # # Option examples: # has_many :comments, -> { order("posted_on") } # has_many :comments, -> { includes(:author) } # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person" # has_many :tracks, -> { order("position") }, dependent: :destroy # has_many :comments, dependent: :nullify # has_many :tags, as: :taggable # has_many :reports, -> { readonly } # has_many :subscribers, through: :subscriptions, source: :user def has_many(name, scope = nil, **options, &extension) reflection = Builder::HasMany.build(self, name, scope, options, &extension) Reflection.add_reflection self, name, reflection end # Specifies a one-to-one association with another class. This method should only be used # if the other class contains the foreign key. If the current class contains the foreign key, # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview # on when to use #has_one and when to use #belongs_to. # # The following methods for retrieval and query of a single associated object will be added: # # +association+ is a placeholder for the symbol passed as the +name+ argument, so # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>. # # [association] # Returns the associated object. +nil+ is returned if none is found. # [association=(associate)] # Assigns the associate object, extracts the primary key, sets it as the foreign key, # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing # associated object when assigning a new one, even if the new one isn't saved to database. # [build_association(attributes = {})] # Returns a new object of the associated type that has been instantiated # with +attributes+ and linked to this object through a foreign key, but has not # yet been saved. # [create_association(attributes = {})] # Returns a new object of the associated type that has been instantiated # with +attributes+, linked to this object through a foreign key, and that # has already been saved (if it passed the validation). # [create_association!(attributes = {})] # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid # if the record is invalid. # [reload_association] # Returns the associated object, forcing a database read. # # === Example # # An Account class declares <tt>has_one :beneficiary</tt>, which will add: # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>) # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>) # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new(account_id: id)</tt>) # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new(account_id: id); b.save; b</tt>) # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new(account_id: id); b.save!; b</tt>) # * <tt>Account#reload_beneficiary</tt> # # === Scopes # # You can pass a second argument +scope+ as a callable (i.e. proc or # lambda) to retrieve a specific record or customize the generated query # when you access the associated object. # # Scope examples: # has_one :author, -> { where(comment_id: 1) } # has_one :employer, -> { joins(:company) } # has_one :latest_post, ->(blog) { where("created_at > ?", blog.enabled_at) } # # === Options # # The declaration can also include an +options+ hash to specialize the behavior of the association. # # Options are: # [:class_name] # Specify the class name of the association. Use it only if that name can't be inferred # from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but # if the real class name is Person, you'll have to specify it with this option. # [:dependent] # Controls what happens to the associated object when # its owner is destroyed: # # * <tt>:destroy</tt> causes the associated object to also be destroyed # * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute) # * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed. # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object # # Note that <tt>:dependent</tt> option is ignored when using <tt>:through</tt> option. # [:foreign_key] # Specify the foreign key used for the association. By default this is guessed to be the name # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association # will use "person_id" as the default <tt>:foreign_key</tt>. # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option. # [:foreign_type] # Specify the column used to store the associated object's type, if this is a polymorphic # association. By default this is guessed to be the name of the polymorphic association # specified on "as" option with a "_type" suffix. So a class that defines a # <tt>has_one :tag, as: :taggable</tt> association will use "taggable_type" as the # default <tt>:foreign_type</tt>. # [:primary_key] # Specify the method that returns the primary key used for the association. By default this is +id+. # [:as] # Specifies a polymorphic interface (See #belongs_to). # [:through] # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>, # <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the # source reflection. You can only use a <tt>:through</tt> query through a #has_one # or #belongs_to association on the join model. # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option. # [:source] # Specifies the source association name used by #has_one <tt>:through</tt> queries. # Only use it if the name cannot be inferred from the association. # <tt>has_one :favorite, through: :favorites</tt> will look for a # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given. # [:source_type] # Specifies type of the source association used by #has_one <tt>:through</tt> queries where the source # association is a polymorphic #belongs_to. # [:validate] # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. # [:autosave] # If true, always save the associated object or destroy it if marked for destruction, # when saving the parent object. If false, never save or destroy the associated object. # By default, only save the associated object if it's a new record. # # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets # <tt>:autosave</tt> to <tt>true</tt>. # [:inverse_of] # Specifies the name of the #belongs_to association on the associated object # that is the inverse of this #has_one association. # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. # [:required] # When set to +true+, the association will also have its presence validated. # This will validate the association itself, not the id. You can use # +:inverse_of+ to avoid an extra query during validation. # # Option examples: # has_one :credit_card, dependent: :destroy # destroys the associated credit card # has_one :credit_card, dependent: :nullify # updates the associated records foreign # # key value to NULL rather than destroying it # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment" # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person" # has_one :attachment, as: :attachable # has_one :boss, -> { readonly } # has_one :club, through: :membership # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable # has_one :credit_card, required: true def has_one(name, scope = nil, **options) reflection = Builder::HasOne.build(self, name, scope, options) Reflection.add_reflection self, name, reflection end # Specifies a one-to-one association with another class. This method should only be used # if this class contains the foreign key. If the other class contains the foreign key, # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview # on when to use #has_one and when to use #belongs_to. # # Methods will be added for retrieval and query for a single associated object, for which # this object holds an id: # # +association+ is a placeholder for the symbol passed as the +name+ argument, so # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>. # # [association] # Returns the associated object. +nil+ is returned if none is found. # [association=(associate)] # Assigns the associate object, extracts the primary key, and sets it as the foreign key. # No modification or deletion of existing records takes place. # [build_association(attributes = {})] # Returns a new object of the associated type that has been instantiated # with +attributes+ and linked to this object through a foreign key, but has not yet been saved. # [create_association(attributes = {})] # Returns a new object of the associated type that has been instantiated # with +attributes+, linked to this object through a foreign key, and that # has already been saved (if it passed the validation). # [create_association!(attributes = {})] # Does the same as <tt>create_association</tt>, but raises ActiveRecord::RecordInvalid # if the record is invalid. # [reload_association] # Returns the associated object, forcing a database read. # # === Example # # A Post class declares <tt>belongs_to :author</tt>, which will add: # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>) # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>) # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>) # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>) # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>) # * <tt>Post#reload_author</tt> # The declaration can also include an +options+ hash to specialize the behavior of the association. # # === Scopes # # You can pass a second argument +scope+ as a callable (i.e. proc or # lambda) to retrieve a specific record or customize the generated query # when you access the associated object. # # Scope examples: # belongs_to :firm, -> { where(id: 2) } # belongs_to :user, -> { joins(:friends) } # belongs_to :level, ->(game) { where("game_level > ?", game.current_level) } # # === Options # # [:class_name] # Specify the class name of the association. Use it only if that name can't be inferred # from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but # if the real class name is Person, you'll have to specify it with this option. # [:foreign_key] # Specify the foreign key used for the association. By default this is guessed to be the name # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> # association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly, # <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key # of "favorite_person_id". # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option. # [:foreign_type] # Specify the column used to store the associated object's type, if this is a polymorphic # association. By default this is guessed to be the name of the association with a "_type" # suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt> # association will use "taggable_type" as the default <tt>:foreign_type</tt>. # [:primary_key] # Specify the method that returns the primary key of associated object used for the association. # By default this is +id+. # [:dependent] # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. # This option should not be specified when #belongs_to is used in conjunction with # a #has_many relationship on another class because of the potential to leave # orphaned records behind. # [:counter_cache] # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this # class is created and decremented when it's destroyed. This requires that a column # named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class) # is used on the associate class (such as a Post class) - that is the migration for # <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will # return the count cached, see note below). You can also specify a custom counter # cache column by providing a column name instead of a +true+/+false+ value to this # option (e.g., <tt>counter_cache: :my_custom_counter</tt>.) # Note: Specifying a counter cache will add it to that model's list of readonly attributes # using +attr_readonly+. # [:polymorphic] # Specify this association is a polymorphic association by passing +true+. # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>). # [:validate] # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. # [:autosave] # If true, always save the associated object or destroy it if marked for destruction, when # saving the parent object. # If false, never save or destroy the associated object. # By default, only save the associated object if it's a new record. # # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for # sets <tt>:autosave</tt> to <tt>true</tt>. # [:touch] # If true, the associated object will be touched (the updated_at/on attributes set to current time) # when this record is either saved or destroyed. If you specify a symbol, that attribute # will be updated with the current time in addition to the updated_at/on attribute. # Please note that with touching no validation is performed and only the +after_touch+, # +after_commit+ and +after_rollback+ callbacks are executed. # [:inverse_of] # Specifies the name of the #has_one or #has_many association on the associated # object that is the inverse of this #belongs_to association. # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. # [:optional] # When set to +true+, the association will not have its presence validated. # [:required] # When set to +true+, the association will also have its presence validated. # This will validate the association itself, not the id. You can use # +:inverse_of+ to avoid an extra query during validation. # NOTE: <tt>required</tt> is set to <tt>true</tt> by default and is deprecated. If # you don't want to have association presence validated, use <tt>optional: true</tt>. # [:default] # Provide a callable (i.e. proc or lambda) to specify that the association should # be initialized with a particular record before validation. # # Option examples: # belongs_to :firm, foreign_key: "client_of" # belongs_to :person, primary_key: "name", foreign_key: "person_name" # belongs_to :author, class_name: "Person", foreign_key: "author_id" # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count }, # class_name: "Coupon", foreign_key: "coupon_id" # belongs_to :attachable, polymorphic: true # belongs_to :project, -> { readonly } # belongs_to :post, counter_cache: true # belongs_to :comment, touch: true # belongs_to :company, touch: :employees_last_updated_at # belongs_to :user, optional: true # belongs_to :account, default: -> { company.account } def belongs_to(name, scope = nil, **options) reflection = Builder::BelongsTo.build(self, name, scope, options) Reflection.add_reflection self, name, reflection end # Specifies a many-to-many relationship with another class. This associates two classes via an # intermediate join table. Unless the join table is explicitly specified as an option, it is # guessed using the lexical order of the class names. So a join between Developer and Project # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically. # Note that this precedence is calculated using the <tt><</tt> operator for String. This # means that if the strings are of different lengths, and the strings are equal when compared # up to the shortest length, then the longer string is considered of higher # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the # custom <tt>:join_table</tt> option if you need to. # If your tables share a common prefix, it will only appear once at the beginning. For example, # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products". # # The join table should not have a primary key or a model associated with it. You must manually generate the # join table with a migration such as this: # # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0] # def change # create_join_table :developers, :projects # end # end # # It's also a good idea to add indexes to each of those columns to speed up the joins process. # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only # uses one index per table during the lookup. # # Adds the following methods for retrieval and query: # # +collection+ is a placeholder for the symbol passed as the +name+ argument, so # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>. # # [collection] # Returns a Relation of all the associated objects. # An empty Relation is returned if none are found. # [collection<<(object, ...)] # Adds one or more objects to the collection by creating associations in the join table # (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method). # Note that this operation instantly fires update SQL without waiting for the save or update call on the # parent object, unless the parent object is a new record. # [collection.delete(object, ...)] # Removes one or more objects from the collection by removing their associations from the join table. # This does not destroy the objects. # [collection.destroy(object, ...)] # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option. # This does not destroy the objects. # [collection=objects] # Replaces the collection's content by deleting and adding objects as appropriate. # [collection_singular_ids] # Returns an array of the associated objects' ids. # [collection_singular_ids=ids] # Replace the collection by the objects identified by the primary keys in +ids+. # [collection.clear] # Removes every object from the collection. This does not destroy the objects. # [collection.empty?] # Returns +true+ if there are no associated objects. # [collection.size] # Returns the number of associated objects. # [collection.find(id)] # Finds an associated object responding to the +id+ and that # meets the condition that it has to be associated with this object. # Uses the same rules as ActiveRecord::FinderMethods#find. # [collection.exists?(...)] # Checks whether an associated object with the given conditions exists. # Uses the same rules as ActiveRecord::FinderMethods#exists?. # [collection.build(attributes = {})] # Returns a new object of the collection type that has been instantiated # with +attributes+ and linked to this object through the join table, but has not yet been saved. # [collection.create(attributes = {})] # Returns a new object of the collection type that has been instantiated # with +attributes+, linked to this object through the join table, and that has already been # saved (if it passed the validation). # [collection.reload] # Returns a Relation of all of the associated objects, forcing a database read. # An empty Relation is returned if none are found. # # === Example # # A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add: # * <tt>Developer#projects</tt> # * <tt>Developer#projects<<</tt> # * <tt>Developer#projects.delete</tt> # * <tt>Developer#projects.destroy</tt> # * <tt>Developer#projects=</tt> # * <tt>Developer#project_ids</tt> # * <tt>Developer#project_ids=</tt> # * <tt>Developer#projects.clear</tt> # * <tt>Developer#projects.empty?</tt> # * <tt>Developer#projects.size</tt> # * <tt>Developer#projects.find(id)</tt> # * <tt>Developer#projects.exists?(...)</tt> # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new(developer_id: id)</tt>) # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new(developer_id: id); c.save; c</tt>) # * <tt>Developer#projects.reload</tt> # The declaration may include an +options+ hash to specialize the behavior of the association. # # === Scopes # # You can pass a second argument +scope+ as a callable (i.e. proc or # lambda) to retrieve a specific set of records or customize the generated # query when you access the associated collection. # # Scope examples: # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } # has_and_belongs_to_many :categories, ->(post) { # where("default_category = ?", post.default_category) # } # # === Extensions # # The +extension+ argument allows you to pass a block into a # has_and_belongs_to_many association. This is useful for adding new # finders, creators and other factory-type methods to be used as part of # the association. # # Extension examples: # has_and_belongs_to_many :contractors do # def find_or_create_by_name(name) # first_name, last_name = name.split(" ", 2) # find_or_create_by(first_name: first_name, last_name: last_name) # end # end # # === Options # # [:class_name] # Specify the class name of the association. Use it only if that name can't be inferred # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the # Project class, but if the real class name is SuperProject, you'll have to specify it with this option. # [:join_table] # Specify the name of the join table if the default based on lexical order isn't what you want. # <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work. # [:foreign_key] # Specify the foreign key used for the association. By default this is guessed to be the name # of this class in lower-case and "_id" suffixed. So a Person class that makes # a #has_and_belongs_to_many association to Project will use "person_id" as the # default <tt>:foreign_key</tt>. # # If you are going to modify the association (rather than just read from it), then it is # a good idea to set the <tt>:inverse_of</tt> option. # [:association_foreign_key] # Specify the foreign key used for the association on the receiving side of the association. # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed. # So if a Person class makes a #has_and_belongs_to_many association to Project, # the association will use "project_id" as the default <tt>:association_foreign_key</tt>. # [:validate] # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. # [:autosave] # If true, always save the associated objects or destroy them if marked for destruction, when # saving the parent object. # If false, never save or destroy the associated objects. # By default, only save associated objects that are new records. # # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets # <tt>:autosave</tt> to <tt>true</tt>. # # Option examples: # has_and_belongs_to_many :projects # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } # has_and_belongs_to_many :nations, class_name: "Country" # has_and_belongs_to_many :categories, join_table: "prods_cats" # has_and_belongs_to_many :categories, -> { readonly } def has_and_belongs_to_many(name, scope = nil, **options, &extension) habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) builder = Builder::HasAndBelongsToMany.new name, self, options join_model = builder.through_model const_set join_model.name, join_model private_constant join_model.name middle_reflection = builder.middle_reflection join_model Builder::HasMany.define_callbacks self, middle_reflection Reflection.add_reflection self, middle_reflection.name, middle_reflection middle_reflection.parent_reflection = habtm_reflection include Module.new { class_eval <<-RUBY, __FILE__, __LINE__ + 1 def destroy_associations association(:#{middle_reflection.name}).delete_all(:delete_all) association(:#{name}).reset super end RUBY } hm_options = {} hm_options[:through] = middle_reflection.name hm_options[:source] = join_model.right_reflection.name [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k| hm_options[k] = options[k] if options.key? k end has_many name, scope, hm_options, &extension _reflections[name.to_s].parent_reflection = habtm_reflection end end end end
53.468062
456
0.635251
62caf02a95e66a04e8748572521801db613efe3e
4,870
Then(/(.*) should see active and renewing enrollments/) do |named_person| visit "/families/home" person = people[named_person] ce = CensusEmployee.where(:first_name => /#{person[:first_name]}/i, :last_name => /#{person[:last_name]}/i).first renewal_effective_date = ce.benefit_sponsorship.renewal_benefit_application.start_on effective_date = ce.benefit_sponsorship.active_benefit_application.start_on wait_for_condition_until(5) do find_all('.hbx-enrollment-panel').count { |n| n.find_all("h3", :text => /Coverage/i).any? } > 1 end expect(page.find_all('.hbx-enrollment-panel').any?{|e| (e.find('.label-success').text() == 'Auto Renewing') && (e.find('.enrollment-effective').text() == "Plan Start: " + renewal_effective_date.strftime('%m/%d/%Y')) }).to be_truthy expect(page.find_all('.hbx-enrollment-panel').any?{|e| (e.find('.label-success').text() == 'Coverage Selected') && (e.find('.enrollment-effective').text() == "Plan Start: " + effective_date.strftime('%m/%d/%Y')) }).to be_truthy end # For new updates When(/.+ clicks continue on group selection page/) do if find_all(EmployeeChooseCoverage.continue_btn).any? find(EmployeeChooseCoverage.continue_btn, wait: 10).click else find(EmployeeChooseCoverage.shop_for_new_plan_btn, :wait => 10).click end end When(/(.*) proceed with continue on the group selection page/) do |named_person| employer_profile = EmployerProfile.all.first plan_year = EmployerProfile.all.first.plan_years.first.start_on.year carrier_profile = EmployerProfile.all.first.plan_years.first.benefit_groups.first.reference_plan.carrier_profile sic_factors = SicCodeRatingFactorSet.new(active_year: plan_year, default_factor_value: 1.0, carrier_profile: carrier_profile).tap do |factor_set| factor_set.rating_factor_entries.new(factor_key: employer_profile.sic_code, factor_value: 1.0) end sic_factors.save! group_size_factors = EmployerGroupSizeRatingFactorSet.new(active_year: plan_year, default_factor_value: 1.0, max_integer_factor_key: 5, carrier_profile: carrier_profile).tap do |factor_set| [0..5].each do |size| factor_set.rating_factor_entries.new(factor_key: size, factor_value: 1.0) end end group_size_factors.save! sleep(1) if find_all('.interaction-click-control-continue').any? find('.interaction-click-control-continue').click else find('.interaction-click-control-shop-for-new-plan', :wait => 10).click end end Then(/(.*) should see \"my account\" page with new enrollment and passive renewal should be canceled/) do |named_person| visit "/families/home" person = people[named_person] ce = CensusEmployee.where(:first_name => /#{person[:first_name]}/i, :last_name => /#{person[:last_name]}/i).first effective_date = ce.employer_profile.renewing_plan_year.start_on expect(page.find_all('.hbx-enrollment-panel').any?{|e| (e.find('.label-success').text() == 'Coverage Selected') && (e.find('.enrollment-effective').text() == "Plan Start: " + effective_date.strftime('%m/%d/%Y')) }).to be_truthy expect(page.find_all('.family-plan-selection').any?{|e| e.find('.status').find('h4').text() == 'Auto Renewing'}).to be_falsey end When(/^.+ selects waiver on the plan shopping page$/) do click_link 'Waive Coverage' end When(/^.+ submits waiver reason$/) do waiver_modal = find('#waive_confirm', wait: 10) waiver_modal.find('span', text: 'Please select waive reason').click waiver_modal.find('#waiver_reason_selection_dropdown').select('I have coverage through Medicaid') waiver_modal.find('#waiver_reason_submit', wait: 5).click end Then(/^.+ should see waiver summary page$/) do expect(page).to have_content 'Waiver confirmation' end When(/^.+ clicks continue on waiver summary page/) do page.find('.interaction-click-control-continue').click end Then("Employee should see Waiver tile") do find('.interaction-click-control-shop-for-plans', wait: 5) expect(page).to have_content 'Waived' expect(page).to have_content 'Waived Date' expect(page).to have_content 'Reason Waived' end Then(/(.+) should see \"my account\" page with waiver and passive renewal should be canceled/) do |named_person| sleep 1 person = people[named_person] ce = CensusEmployee.where(:first_name => /#{person[:first_name]}/i, :last_name => /#{person[:last_name]}/i).first effective_date = ce.employer_profile.renewing_plan_year.start_on enrollments = page.all('.hbx-enrollment-panel') statuses = enrollments.collect{|e| e.find('.panel-heading').find('.label-success').text()} expect(statuses).to include('Waived') expect(statuses).to include('Coverage Termination Pending') expect(statuses).not_to include('Auto Renewing') end When(/^.+ clicks continue on family members page/) do page.find('#dependent_buttons').find('.interaction-click-control-continue').click end
41.623932
191
0.732444
e94285536a7785a505c5e522a0dfe2374a68d0f1
217
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) map Web::Application.config.relative_url_root || "/" do run Rails.application end
27.125
67
0.75576
b98ff49916ea38a416a0d37c443335f2957b0470
3,946
require "cmd/update-report" require "formula_versions" require "yaml" describe Reporter do def perform_update(fixture_name = "") allow(Formulary).to receive(:factory).and_return(double(pkg_version: "1.0")) allow(FormulaVersions).to receive(:new).and_return(double(formula_at_revision: "2.0")) diff = YAML.load_file("#{TEST_FIXTURE_DIR}/updater_fixture.yaml")[fixture_name] allow(subject).to receive(:diff).and_return(diff || "") hub.add(subject) if subject.updated? end subject { reporter_class.new(tap) } let(:reporter_class) do Class.new(described_class) do def initialize(tap) @tap = tap ENV["HOMEBREW_UPDATE_BEFORE#{repo_var}"] = "12345678" ENV["HOMEBREW_UPDATE_AFTER#{repo_var}"] = "abcdef00" super(tap) end end end let(:tap) { CoreTap.new } let(:hub) { ReporterHub.new } specify "without revision variable" do ENV.delete_if { |k, _v| k.start_with? "HOMEBREW_UPDATE" } expect { described_class.new(tap) }.to raise_error(Reporter::ReporterRevisionUnsetError) end specify "without any changes" do perform_update expect(hub).to be_empty end specify "without Formula changes" do perform_update("update_git_diff_output_without_formulae_changes") expect(hub.select_formula(:M)).to be_empty expect(hub.select_formula(:A)).to be_empty expect(hub.select_formula(:D)).to be_empty end specify "with Formula changes" do perform_update("update_git_diff_output_with_formulae_changes") expect(hub.select_formula(:M)).to eq(%w[xar yajl]) expect(hub.select_formula(:A)).to eq(%w[antiword bash-completion ddrescue dict lua]) end specify "with removed Formulae" do perform_update("update_git_diff_output_with_removed_formulae") expect(hub.select_formula(:D)).to eq(%w[libgsasl]) end specify "with changed file type" do perform_update("update_git_diff_output_with_changed_filetype") expect(hub.select_formula(:M)).to eq(%w[elixir]) expect(hub.select_formula(:A)).to eq(%w[libbson]) expect(hub.select_formula(:D)).to eq(%w[libgsasl]) end specify "with renamed Formula" do allow(tap).to receive(:formula_renames).and_return("cv" => "progress") perform_update("update_git_diff_output_with_formula_rename") expect(hub.select_formula(:A)).to be_empty expect(hub.select_formula(:D)).to be_empty expect(hub.select_formula(:R)).to eq([["cv", "progress"]]) end context "when updating a Tap other than the core Tap" do let(:tap) { Tap.new("foo", "bar") } before do (tap.path/"Formula").mkpath end after do tap.path.parent.rmtree end specify "with restructured Tap" do perform_update("update_git_diff_output_with_restructured_tap") expect(hub.select_formula(:A)).to be_empty expect(hub.select_formula(:D)).to be_empty expect(hub.select_formula(:R)).to be_empty end specify "with renamed Formula and restructured Tap" do allow(tap).to receive(:formula_renames).and_return("xchat" => "xchat2") perform_update("update_git_diff_output_with_formula_rename_and_restructuring") expect(hub.select_formula(:A)).to be_empty expect(hub.select_formula(:D)).to be_empty expect(hub.select_formula(:R)).to eq([%w[foo/bar/xchat foo/bar/xchat2]]) end specify "with simulated 'homebrew/php' restructuring" do perform_update("update_git_diff_simulate_homebrew_php_restructuring") expect(hub.select_formula(:A)).to be_empty expect(hub.select_formula(:D)).to be_empty expect(hub.select_formula(:R)).to be_empty end specify "with Formula changes" do perform_update("update_git_diff_output_with_tap_formulae_changes") expect(hub.select_formula(:A)).to eq(%w[foo/bar/lua]) expect(hub.select_formula(:M)).to eq(%w[foo/bar/git]) expect(hub.select_formula(:D)).to be_empty end end end
30.353846
90
0.707045
7a42509fd688ced56282d27512f66d28d3b937ef
3,284
require 'test_helper' class QbmsTest < Test::Unit::TestCase def setup Base.mode = :test @gateway_options = fixtures(:qbms) @gateway = QbmsGateway.new(@gateway_options) @amount = 100 @card = credit_card('4111111111111111') @options = { billing_address: address, } end def test_successful_authorization assert response = @gateway.authorize(@amount, @card, @options) assert_instance_of Response, response assert_success response assert response.authorization end def test_successful_capture assert response = @gateway.authorize(@amount, @card, @options) assert_instance_of Response, response assert_success response assert response.authorization assert response = @gateway.capture(@amount, response.authorization, @options) assert_instance_of Response, response assert_success response assert response.authorization end def test_successful_void assert response = @gateway.authorize(@amount, @card, @options) assert_instance_of Response, response assert_success response assert response.authorization assert response = @gateway.void(response.authorization, @options) assert_instance_of Response, response assert_success response assert response.authorization end def test_successful_purchase assert response = @gateway.purchase(@amount, @card, @options) assert_instance_of Response, response assert_success response assert response.authorization end def test_successful_credit assert response = @gateway.purchase(@amount, @card, @options) assert_instance_of Response, response assert_success response assert response.authorization assert response = @gateway.credit(@amount, response.authorization, @options) assert_instance_of Response, response assert_success response assert response.authorization end def test_invalid_ticket gateway = QbmsGateway.new(@gateway_options.merge(ticket: 'test123')) assert response = gateway.authorize(@amount, @card, @options) assert_instance_of Response, response assert_failure response assert_equal 'Application agent not found test123', response.message end def test_invalid_card_number assert response = @gateway.authorize(@amount, error_card('10301_ccinvalid'), @options) assert_instance_of Response, response assert_failure response assert_equal 'This credit card number is invalid.', response.message end def test_decline assert response = @gateway.authorize(@amount, error_card('10401_decline'), @options) assert_instance_of Response, response assert_failure response assert_equal 'The request to process this transaction has been declined.', response.message end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end transcript = @gateway.scrub(transcript) assert_scrubbed(@credit_card.number, transcript) assert_scrubbed(@credit_card.verification_value, transcript) assert_scrubbed(@gateway.options[:ticket], transcript) end private def error_card(config_id) credit_card('4111111111111111', first_name: "configid=#{config_id}", last_name: '') end end
30.407407
95
0.752132
7af9f44a603db6cfcaff512dd87de413cc97653b
1,783
module Spree module TestingSupport module AuthorizationHelpers module CustomAbility def build_ability(&block) block ||= proc { |_u| can :manage, :all } Class.new do include CanCan::Ability define_method(:initialize, block) end end end module Controller include CustomAbility def stub_authorization!(&block) ability_class = build_ability(&block) before do allow(controller).to receive(:current_ability).and_return(ability_class.new(nil)) end end end module Request include CustomAbility def stub_authorization! ability = build_ability ability_class = Spree::Dependencies.ability_class.constantize after(:all) do ability_class.remove_ability(ability) end before(:all) do ability_class.register_ability(ability) end before do allow(Spree.user_class).to receive(:find_by). with(hash_including(:spree_api_key)). and_return(Spree.user_class.new) end end def custom_authorization!(&block) ability = build_ability(&block) ability_class = Spree::Dependencies.ability_class.constantize after(:all) do ability_class.remove_ability(ability) end before(:all) do ability_class.register_ability(ability) end end end end end end RSpec.configure do |config| config.extend Spree::TestingSupport::AuthorizationHelpers::Controller, type: :controller config.extend Spree::TestingSupport::AuthorizationHelpers::Request, type: :feature end
26.61194
93
0.609647
213fe8206fa42cf468eafefbe8d4f8f871ddf035
130
#!/usr/bin/env ruby # frozen_string_literal: true (1..10).each { |n| puts format("%<n>2i\t%<square>6.2f", n: n, square: n**2) }
21.666667
77
0.607692
62f8ea4c411e686d36e77ff83eb0d48c6cce0452
12,993
# frozen_string_literal: true require 'rspec' describe 'config/haproxy.config HTTPS frontend' do let(:template) { haproxy_job.template('config/haproxy.config') } let(:haproxy_conf) do parse_haproxy_config(template.render({ 'ha_proxy' => properties })) end let(:frontend_https) { haproxy_conf['frontend https-in'] } let(:default_properties) do { 'ssl_pem' => 'ssl pem contents' } end let(:properties) { default_properties } context 'when ha_proxy.drain_enable is true' do let(:properties) do default_properties.merge({ 'drain_enable' => true }) end it 'has a default grace period of 0 milliseconds' do expect(frontend_https).to include('grace 0') end context('when ha_proxy.drain_frontend_grace_time is provided') do let(:properties) do default_properties.merge({ 'drain_enable' => true, 'drain_frontend_grace_time' => 12 }) end # FIXME: if drain_frontend_grace_time is provided but drain_enable is false then it should error it 'overrides the grace period' do expect(frontend_https).to include('grace 12000') end end end it 'binds to all interfaces by default' do expect(frontend_https).to include('bind :443 ssl crt /var/vcap/jobs/haproxy/config/ssl') end context 'when ha_proxy.binding_ip is provided' do let(:properties) do default_properties.merge({ 'binding_ip' => '1.2.3.4' }) end it 'binds to the provided ip' do expect(frontend_https).to include('bind 1.2.3.4:443 ssl crt /var/vcap/jobs/haproxy/config/ssl') end context 'when ha_proxy.v4v6 is true and binding_ip is ::' do let(:properties) do default_properties.merge({ 'v4v6' => true, 'binding_ip' => '::' }) end it 'enables ipv6' do expect(frontend_https).to include('bind :::443 ssl crt /var/vcap/jobs/haproxy/config/ssl v4v6') end end context 'when ha_proxy.accept_proxy is true' do let(:properties) do default_properties.merge({ 'accept_proxy' => true }) end it 'sets accept-proxy' do expect(frontend_https).to include('bind :443 accept-proxy ssl crt /var/vcap/jobs/haproxy/config/ssl') end end end context 'when mutual tls is enabled' do let(:properties) do default_properties.merge({ 'client_cert' => 'client_cert contents' }) end it 'configures ssl to use the client ca' do expect(frontend_https).to include('bind :443 ssl crt /var/vcap/jobs/haproxy/config/ssl ca-file /etc/ssl/certs/ca-certificates.crt verify optional') end context 'when ha_proxy.client_cert_ignore_err is true' do let(:properties) do default_properties.merge({ 'client_cert' => 'client_cert contents', 'client_cert_ignore_err' => true }) end # FIXME: if client_cert_ignore_err is true but client_cert is not provided, then it should error it 'adds the crt-ignore-err flag' do expect(frontend_https).to include('bind :443 ssl crt /var/vcap/jobs/haproxy/config/ssl ca-file /etc/ssl/certs/ca-certificates.crt verify optional crt-ignore-err true') end end context 'when ha_proxy.client_revocation_list is provided' do let(:properties) do default_properties.merge({ 'client_cert' => 'client_cert contents', 'client_revocation_list' => 'client_revocation_list contents' }) end # FIXME: if client_revocation_list is provided but client_cert is not provided, then it should error it 'references the crl list' do expect(frontend_https).to include('bind :443 ssl crt /var/vcap/jobs/haproxy/config/ssl ca-file /etc/ssl/certs/ca-certificates.crt verify optional crl-file /var/vcap/jobs/haproxy/config/client-revocation-list.pem') end end end context 'when ha_proxy.forwarded_client_cert is always_forward_only (the default)' do it 'deletes the X-Forwarded-Client-Cert header by default' do expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert') end end context 'when ha_proxy.forwarded_client_cert is forward_only' do let(:properties) do default_properties.merge({ 'forwarded_client_cert' => 'forward_only' }) end it 'deletes the X-Forwarded-Client-Cert header' do expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert') end context 'when mutual TLS is enabled' do let(:properties) do default_properties.merge({ 'client_cert' => 'client_cert contents', 'forwarded_client_cert' => 'forward_only' }) end it 'only deletes the X-Forwarded-Client-Cert header when mTLS is not used' do expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert if ! { ssl_c_used }') end end end context 'when ha_proxy.forwarded_client_cert is sanitize_set' do let(:properties) do default_properties.merge({ 'forwarded_client_cert' => 'sanitize_set' }) end it 'deletes the X-Forwarded-Client-Cert header' do expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert') end context 'when mutual TLS is enabled' do let(:properties) do default_properties.merge({ 'client_cert' => 'client_cert contents', 'forwarded_client_cert' => 'sanitize_set' }) end it 'sets X-Forwarded-Client-Cert to the client cert for mTLS connections ' do expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert') expect(frontend_https).to include('http-request set-header X-Forwarded-Client-Cert %[ssl_c_der,base64] if { ssl_c_used }') end end end context 'when ha_proxy.forwarded_client_cert is forward_only_if_route_service' do let(:properties) do default_properties.merge({ 'forwarded_client_cert' => 'forward_only_if_route_service' }) end it 'deletes the X-Forwarded-Client-Cert header for non-route service requests' do expect(frontend_https).to include('acl route_service_request hdr(X-Cf-Proxy-Signature) -m found') expect(frontend_https).to include('http-request del-header X-Forwarded-Client-Cert if !route_service_request') expect(frontend_https).to include('http-request set-header X-Forwarded-Client-Cert %[ssl_c_der,base64] if { ssl_c_used }') end end context 'when ha_proxy.hsts_enable is true' do let(:properties) do default_properties.merge({ 'hsts_enable' => true }) end it 'sets the Strict-Transport-Security header' do expect(frontend_https).to include('http-response set-header Strict-Transport-Security max-age=31536000;') end context 'when ha_proxy.hsts_max_age is provided' do let(:properties) do default_properties.merge({ 'hsts_enable' => true, 'hsts_max_age' => 9999 }) end it 'sets the Strict-Transport-Security header with the correct max-age' do expect(frontend_https).to include('http-response set-header Strict-Transport-Security max-age=9999;') end end context 'when ha_proxy.hsts_include_subdomains is true' do let(:properties) do default_properties.merge({ 'hsts_enable' => true, 'hsts_include_subdomains' => true }) end # FIXME: hsts_include_subdomains is true but hsts_enable is false, then it should error it 'sets the includeSubDomains flag' do expect(frontend_https).to include('http-response set-header Strict-Transport-Security max-age=31536000;\ includeSubDomains;') end end context 'when ha_proxy.hsts_preload is true' do let(:properties) do default_properties.merge({ 'hsts_enable' => true, 'hsts_preload' => true }) end # FIXME: hsts_preload is true but hsts_enable is false, then it should error it 'sets the preload flag' do expect(frontend_https).to include('http-response set-header Strict-Transport-Security max-age=31536000;\ preload;') end end end it 'correct request capturing configuration' do expect(frontend_https).to include('capture request header Host len 256') end it 'has the correct default backend' do expect(frontend_https).to include('default_backend http-routers') end context 'when ha_proxy.http_request_deny_conditions are provided' do let(:properties) do default_properties.merge({ 'http_request_deny_conditions' => [{ 'condition' => [{ 'acl_name' => 'block_host', 'acl_rule' => 'hdr_beg(host) -i login' }, { 'acl_name' => 'whitelist_ips', 'acl_rule' => 'src 5.22.5.11 5.22.5.12', 'negate' => true }] }] }) end it 'adds the correct acls and http-request deny rules' do expect(frontend_https).to include('acl block_host hdr_beg(host) -i login') expect(frontend_https).to include('acl whitelist_ips src 5.22.5.11 5.22.5.12') expect(frontend_https).to include('http-request deny if block_host !whitelist_ips') end end context 'when a custom ha_proxy.frontend_config is provided' do let(:properties) do default_properties.merge({ 'frontend_config' => 'custom config content' }) end it 'includes the custom config' do expect(frontend_https).to include('custom config content') end end context 'when a ha_proxy.cidr_whitelist is provided' do let(:properties) do default_properties.merge({ 'cidr_whitelist' => ['172.168.4.1/32', '10.2.0.0/16'] }) end it 'sets the correct acl and content accept rules' do expect(frontend_https).to include('acl whitelist src -f /var/vcap/jobs/haproxy/config/whitelist_cidrs.txt') expect(frontend_https).to include('tcp-request content accept if whitelist') end end context 'when a ha_proxy.cidr_blacklist is provided' do let(:properties) do default_properties.merge({ 'cidr_blacklist' => ['172.168.4.1/32', '10.2.0.0/16'] }) end it 'sets the correct acl and content reject rules' do expect(frontend_https).to include('acl blacklist src -f /var/vcap/jobs/haproxy/config/blacklist_cidrs.txt') expect(frontend_https).to include('tcp-request content reject if blacklist') end end context 'when ha_proxy.block_all is provided' do let(:properties) do default_properties.merge({ 'block_all' => true }) end it 'sets the correct content reject rules' do expect(frontend_https).to include('tcp-request content reject') end end context 'when ha_proxy.headers are provided' do let(:properties) do default_properties.merge({ 'headers' => ['X-Application-ID: my-custom-header', 'MyCustomHeader: 3'] }) end it 'adds the request headers' do expect(frontend_https).to include('http-request add-header X-Application-ID:\ my-custom-header ""') expect(frontend_https).to include('http-request add-header MyCustomHeader:\ 3 ""') end end context 'when ha_proxy.rsp_headers are provided' do let(:properties) do default_properties.merge({ 'rsp_headers' => ['X-Application-ID: my-custom-header', 'MyCustomHeader: 3'] }) end it 'adds the response headers' do expect(frontend_https).to include('http-response add-header X-Application-ID:\ my-custom-header ""') expect(frontend_https).to include('http-response add-header MyCustomHeader:\ 3 ""') end end context 'when ha_proxy.internal_only_domains are provided' do let(:properties) do default_properties.merge({ 'internal_only_domains' => ['bosh.internal'] }) end it 'adds the correct acl and http-request deny rules' do expect(frontend_https).to include('acl private src -f /var/vcap/jobs/haproxy/config/trusted_domain_cidrs.txt') expect(frontend_https).to include('acl internal hdr(Host) -m sub bosh.internal') expect(frontend_https).to include('http-request deny if internal !private') end end context 'when ha_proxy.routed_backend_servers are provided' do let(:properties) do default_properties.merge({ 'routed_backend_servers' => { '/images' => { 'port' => 12_000, 'servers' => ['10.0.0.1'] } } }) end it 'grants access to the backend servers' do expect(frontend_https).to include('acl routed_backend_9c1bb7 path_beg /images') expect(frontend_https).to include('use_backend http-routed-backend-9c1bb7 if routed_backend_9c1bb7') end end it 'adds the X-Forwarded-Proto header' do expect(frontend_https).to include('acl xfp_exists hdr_cnt(X-Forwarded-Proto) gt 0') expect(frontend_https).to include('http-request add-header X-Forwarded-Proto "https" if ! xfp_exists') end context 'when no ssl options are provided' do let(:properties) { {} } it 'removes the https frontend' do expect(haproxy_conf).not_to have_key('frontend https-in') end end end
36.192201
223
0.687447
7979fba958026c98a9d9b4bae7da319814eab128
5,653
Shindo.tests('OpenStack | authenticate', ['openstack']) do begin @old_mock_value = Excon.defaults[:mock] Excon.defaults[:mock] = true Excon.stubs.clear expires = Time.now.utc + 600 token = Fog::Mock.random_numbers(8).to_s tenant_token = Fog::Mock.random_numbers(8).to_s body = { "access" => { "token" => { "expires" => expires.iso8601, "id" => token, "tenant" => { "enabled" => true, "description" => nil, "name" => "admin", "id" => tenant_token, } }, "serviceCatalog" => [{ "endpoints" => [{ "adminURL" => "http://example:8774/v2/#{tenant_token}", "region" => "RegionOne", "internalURL" => "http://example:8774/v2/#{tenant_token}", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example:8774/v2/#{tenant_token}" }], "endpoints_links" => [], "type" => "compute", "name" => "nova" }, { "endpoints" => [{ "adminURL" => "http://example:9292", "region" => "RegionOne", "internalURL" => "http://example:9292", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example:9292" }], "endpoints_links" => [], "type" => "image", "name" => "glance" }], "user" => { "username" => "admin", "roles_links" => [], "id" => Fog::Mock.random_numbers(8).to_s, "roles" => [ { "name" => "admin" }, { "name" => "KeystoneAdmin" }, { "name" => "KeystoneServiceAdmin" } ], "name" => "admin" }, "metadata" => { "is_admin" => 0, "roles" => [ Fog::Mock.random_numbers(8).to_s, Fog::Mock.random_numbers(8).to_s, Fog::Mock.random_numbers(8).to_s,]}}} tests("v2") do Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body) }) expected = { :user => body['access']['user'], :tenant => body['access']['token']['tenant'], :identity_public_endpoint => nil, :server_management_url => body['access']['serviceCatalog']. first['endpoints'].first['publicURL'], :token => token, :expires => expires.iso8601, :current_user_id => body['access']['user']['id'], :unscoped_token => token, } returns(expected) do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[compute]) end end tests("v2 missing service") do Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body) }) raises(Fog::Errors::NotFound, 'Could not find service network. Have compute, image') do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[network]) end end tests("v2 auth with two compute services") do body_clone = body.clone body_clone["access"]["serviceCatalog"] << { "endpoints" => [{ "adminURL" => "http://example2:8774/v2/#{tenant_token}", "region" => "RegionOne", "internalURL" => "http://example2:8774/v2/#{tenant_token}", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example2:8774/v2/#{tenant_token}" }], "endpoints_links" => [], "type" => "compute", "name" => "nova2" } Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body_clone) }) returns("http://example2:8774/v2/#{tenant_token}") do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[compute], :openstack_service_name => 'nova2')[:server_management_url] end end tests("legacy v1 auth") do headers = { "X-Storage-Url" => "https://swift.myhost.com/v1/AUTH_tenant", "X-Auth-Token" => "AUTH_yui193bdc00c1c46c5858788yuio0e1e2p", "X-Trans-Id" => "iu99nm9999f9b999c9b999dad9cd999e99", "Content-Length" => "0", "Date" => "Wed, 07 Aug 2013 11:11:11 GMT" } Excon.stub({:method => 'GET', :path => "/auth/v1.0"}, {:status => 200, :body => "", :headers => headers}) returns("https://swift.myhost.com/v1/AUTH_tenant") do Fog::OpenStack.authenticate_v1( :openstack_auth_uri => URI('https://swift.myhost.com/auth/v1.0'), :openstack_username => 'tenant:dev', :openstack_api_key => 'secret_key', :openstack_service_type => %w[storage])[:server_management_url] end end ensure Excon.stubs.clear Excon.defaults[:mock] = @old_mock_value end end
34.260606
79
0.482399
01287deacf5eb8f2ec15188a4a68522d15509705
948
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require_relative '../../api1800/c7000/server_hardware_type' module OneviewSDK module API2000 module C7000 # Server hardware type resource implementation for API2000 C7000 class ServerHardwareType < OneviewSDK::API1800::C7000::ServerHardwareType def self.api_version 2000 end end end end end
36.461538
85
0.748945
6a7cf3fc075b5eb802b7db65fb22b90755a76e51
369
=begin Copyright (c) 2015, Koichiro Tamura/Toshinari Naminatsu/Yuki Ishikawa/Tatsuya Onishi/Mamoru Endo/Kenji Suzuki This software is released under the BSD 2-Clause License. http://opensource.org/licenses/BSD-2-Clause =end # system development and maintenance information for administration class MaintenanceInfo < Run set_table_name "maintenance_infos" end
23.0625
109
0.807588
0312b2c86e1e45bf32f52f0ac3f8ed2db96bdd80
23
module TemasHelper end
7.666667
18
0.869565
6a482989e69a184686aa21168b9a186d0f37981f
3,506
# frozen_string_literal: true class Idt::V1::AppealDetailsSerializer include FastJsonapi::ObjectSerializer set_id do |object| object.is_a?(LegacyAppeal) ? object.vacols_id : object.uuid end attribute :case_details_url do |object, params| "#{params[:base_url]}/queue/appeals/#{object.external_id}" end attribute :veteran_first_name attribute :veteran_middle_name, &:veteran_middle_initial attribute :veteran_last_name attribute :veteran_name_suffix attribute :veteran_gender attribute :veteran_ssn attribute :veteran_is_deceased attribute :veteran_death_date attribute :appellant_is_not_veteran do |object| object.is_a?(LegacyAppeal) ? object.appellant_is_not_veteran : !!object.veteran_is_not_claimant end attribute :appellants do |object, params| if object.is_a?(LegacyAppeal) [object.claimant] else object.claimants.map do |claimant| address = if params[:include_addresses] { address_line_1: claimant.address_line_1, address_line_2: claimant.address_line_2, city: claimant.city, state: claimant.state, zip: claimant.zip, country: claimant.country } end representative = { name: claimant.representative_name, type: claimant.representative_type, participant_id: claimant.representative_participant_id, address: params[:include_addresses] ? claimant.representative_address : nil } { first_name: claimant.first_name, middle_name: claimant.middle_name, last_name: claimant.last_name, name_suffix: "", address: address, representative: claimant.representative_name ? representative : nil } end end end attribute :contested_claimants do |object| object.is_a?(LegacyAppeal) ? object.contested_claimants : nil end attribute :contested_claimant_agents do |object| object.is_a?(LegacyAppeal) ? object.contested_claimant_agents : nil end attribute :congressional_interest_addresses do |object| object.is_a?(LegacyAppeal) ? object.congressional_interest_addresses : "Not implemented for AMA" end attribute :file_number do |object| object.is_a?(LegacyAppeal) ? object.sanitized_vbms_id : object.veteran_file_number end attribute :docket_number attribute :docket_name attribute :number_of_issues attribute :issues do |object| if object.is_a?(LegacyAppeal) object.issues.map do |issue| ::WorkQueue::LegacyIssueSerializer.new(issue).serializable_hash[:data][:attributes] end else object.request_issues.active_or_decided_or_withdrawn.map do |issue| { id: issue.id, program: Constants::BENEFIT_TYPES[issue.benefit_type], description: issue.description } end end end attribute :aod, &:advanced_on_docket? attribute :cavc attribute :status attribute :previously_selected_for_quality_review attribute :assigned_by, &:reviewing_judge_name attribute :documents do |object| object.attorney_case_reviews.map do |document| { written_by: document.written_by_name, document_id: document.document_id } end end attribute :outstanding_mail do |object| object.is_a?(LegacyAppeal) ? object.outstanding_vacols_mail : "not implemented for AMA" end end
31.585586
100
0.68939
f83c225e8911f0b77f39b3ec396e5b7f176ac886
422
module MsGraphRest class Error < StandardError end class ResourceNotFound < Error end class AuthenticationError < Error end class BadRequestErrorCreator def self.error(ms_error) ms_error_code = JSON.parse(ms_error.response[:body] || '{}').dig("error", "code") return AuthenticationError.new(ms_error) if ms_error_code == 'AuthenticationError' Error.new(ms_error) end end end
20.095238
88
0.7109
bf58a806b17f75b79fc282706bc40dc27fed2460
1,972
require 'sentry-raven-without-integrations' require 'pry' require 'simplecov' SimpleCov.start if ENV["CI"] require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end Raven.configure do |config| config.dsn = "dummy://12345:[email protected]/sentry/42" config.encoding = "json" config.silence_ready = true config.logger = Logger.new(nil) end if ENV["RAILS_VERSION"] && (ENV["RAILS_VERSION"].to_i == 0) RSpec.configure do |config| config.filter_run_excluding :rails => true end else require File.dirname(__FILE__) + "/support/test_rails_app/app.rb" require "rspec/rails" end RSpec.configure do |config| config.mock_with(:rspec) { |mocks| mocks.verify_partial_doubles = true } config.raise_errors_for_deprecations! config.disable_monkey_patching! Kernel.srand config.seed end RSpec.shared_examples "Raven default capture behavior" do it "captures exceptions" do expect { block }.to raise_error(captured_class) expect(Raven.client.transport.events.size).to eq(1) event = JSON.parse!(Raven.client.transport.events.first[1]) expect(event["exception"]["values"][0]["type"]).to eq(captured_class.name) expect(event["exception"]["values"][0]["value"]).to eq(captured_message) end end def build_exception 1 / 0 rescue ZeroDivisionError => e e end def build_exception_with_cause(cause = "exception a") begin raise cause rescue raise "exception b" end rescue RuntimeError => e e end def build_exception_with_two_causes begin begin raise "exception a" rescue raise "exception b" end rescue raise "exception c" end rescue RuntimeError => e e end def build_exception_with_recursive_cause backtrace = [] exception = double("Exception") allow(exception).to receive(:cause).and_return(exception) allow(exception).to receive(:message).and_return("example") allow(exception).to receive(:backtrace).and_return(backtrace) exception end
22.930233
78
0.732252
bf558ba961a3f429531d84869b5e67854917876e
128
# # Cookbook Name:: workstation # Recipe:: git include_recipe "git_wrapper" execute "git config --global push.default simple"
16
49
0.75
28f71068f1a16e5546db6663356827d152e13f5b
563
require_relative 'node_literal.rb' class DabNodeLiteralFloat < DabNodeLiteral attr_reader :number def initialize(number) super() @number = number end def extra_dump number.to_s end def compile_as_ssa(output, output_register) output.comment(self.extra_value) output.print('LOAD_FLOAT', "R#{output_register}", extra_dump) end def extra_value extra_dump end def my_type DabConcreteType.new(DabTypeFloat.new) end def formatted_source(_options) extra_dump end def constant_value @number end end
16.085714
65
0.724689
38e2833f216eda6d47f3244b114980f37912e8ca
2,534
cask 'thunderbird' do version '45.7.1' language 'de' do sha256 '2a9f128bed773eafb28e1a17687e42319e2a6db22db1269b775e2821dd1f225c' 'de' end language 'en-GB' do sha256 'f0ea3365a434681e8da6df6d27651d3499297812c2e80263a9c94f3882598989' 'en-GB' end language 'en', default: true do sha256 '297aa21c91cf4b83d1bf88103a8c53a034452039f13c3a4da146a2668f7479cd' 'en-US' end language 'fr' do sha256 '40446db3034bca40d2ee2f50bc80f2a34bd516df98aec2d15f02cc6e4ea81fbc' 'fr' end language 'gl' do sha256 '2a6ff57bf80b9459ca4973eedc3edcdf1e45bb5d1d2075e19879f8522d244800' 'gl' end language 'it' do sha256 'c96a7fe7e0662e067057ef185fd6083e8270432380640463abb39dc3f542d2d8' 'it' end language 'ja' do sha256 '925df210182d732e46e2f276e62f26a7e335f391e2206bd383d49f553b17418c' 'ja-JP-mac' end language 'nl' do sha256 '64d36ebb079971beeecbf76d439a051896b72389d1ab6f4b9a01e656db54711a' 'nl' end language 'pl' do sha256 '34996c44da6786592dfcc24f405860131b3812891615f7e113b0db2a168a07f4' 'pl' end language 'pt' do sha256 'a3ccf168aa3fa2f8716a753b018793cc3dcaeef792ee71e162417aa10c93e31b' 'pt-BR' end language 'ru' do sha256 '66dd4eb0884ec6422130879e83b3b042243bef2886c1236932534ef625201a80' 'ru' end language 'uk' do sha256 '4ff1622fe6c4cd9ded23c21be4840e58b11f1a6b24a16860987ede041a683120' 'uk' end language 'zh-TW' do sha256 '08c112f9db690d27f2559b8290061a9433b13df6fa3553e56f600d953a040a47' 'zh-TW' end language 'zh' do sha256 'd11ab21c2dcb01c1e8b9e16fc56bf01d73af69da8f87835db9f67fc68a469ee2' 'zh-CN' end url "https://ftp.mozilla.org/pub/thunderbird/releases/#{version}/mac/#{language}/Thunderbird%20#{version}.dmg" appcast "https://aus5.mozilla.org/update/3/Thunderbird/#{version}/0/Darwin_x86_64-gcc3-u-i386-x86_64/en-US/release/Darwin%2015.3.0/default/default/update.xml?force=1", checkpoint: 'ee412add136f2d6d0932b250eb49bfbc1b9f4e07dcd1d9a4bcad58ac90322198' name 'Mozilla Thunderbird' homepage 'https://www.mozilla.org/thunderbird/' auto_updates true app 'Thunderbird.app' zap delete: [ '~/Library/Thunderbird', '~/Library/Caches/Thunderbird', '~/Library/Saved Application State/org.mozilla.thunderbird.savedState', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.thunderbird.sfl', ] end
27.846154
169
0.746646
113896626bdeb291154329a3229346812d19ee3e
1,557
class Tssh < Formula desc "SSH Lightweight management tools" homepage "https://github.com/luanruisong/tssh" url "https://github.com/luanruisong/tssh/archive/refs/tags/2.1.2.tar.gz" sha256 "1c6b00750260d2c567d99f8bfd0c7fc87a96ac0faa3cfc8d54cb32400e95bb56" license "Apache-2.0" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "5f45fc530482f76d31be04fc447ad9ddf1db45542f845346d035738fe12bca04" sha256 cellar: :any_skip_relocation, arm64_big_sur: "222ab84f9c686b2606c5424d5ba3183517ab606851d7d6f9131f8122b3f4047b" sha256 cellar: :any_skip_relocation, monterey: "48d5b1f6af2a47e38deb9aae9d969607b250a574458b1825ca664b4ce689e2e3" sha256 cellar: :any_skip_relocation, big_sur: "d19409fa804d5d474ac267f4bacc1a808a48c04a0d6f441a7e26b2e1c3c48f3b" sha256 cellar: :any_skip_relocation, catalina: "ebf00c55633da328741f17335406fd7572ea8b1509182131b7d46878e9451ea8" sha256 cellar: :any_skip_relocation, mojave: "518731cf99cf6194aa510453b50fbd1da16bd15c4eccfd0d8e8d6f35537ac669" sha256 cellar: :any_skip_relocation, x86_64_linux: "148c99f128411e59d6e67e73f70f1a5cf74ae7553afe9587dfdcc631bf38a2bc" end # Bump to 1.18 on the next release, if possible. depends_on "[email protected]" => :build def install system "go", "build", *std_go_args(ldflags: "-X main.version=#{version}") end test do output_v = shell_output("#{bin}/tssh -v") assert_match "version #{version}", output_v output_e = shell_output("#{bin}/tssh -e") assert_match "TSSH_HOME", output_e end end
48.65625
123
0.782916
ac2ec3097deaa741355e82424c2e33865cd56f5a
1,494
class Libcouchbase < Formula desc "C library for Couchbase" homepage "https://docs.couchbase.com/c-sdk/current/hello-world/start-using-sdk.html" url "https://packages.couchbase.com/clients/c/libcouchbase-3.2.1.tar.gz" sha256 "c5ee6a5591c644b97f83ecff339abfa8e01e06fa4af126df4b226a425df5f056" license "Apache-2.0" head "https://github.com/couchbase/libcouchbase.git" bottle do sha256 arm64_big_sur: "8a2632dded34cf0fb3276450aa1c50da27b72e9f29b0ab1e669f68665e5948dc" sha256 big_sur: "78e1ae2880a9faf26cb1547f4f97c7c2e5b2793c17bd8857c2f7457d05006ac4" sha256 catalina: "91b6eb7779b6053e086246f41076d38b141f2f6c0b1dfa133ed18486039a92be" sha256 mojave: "878a0815e2be09e485decf50128ee6ed4adc84996ff1ab36102e1faa4f581d8a" sha256 x86_64_linux: "2e72fe50a2149609f07e06cd1697a42580e0aa504d72f2d7eb69d5634030d508" # linuxbrew-core end depends_on "cmake" => :build depends_on "libev" depends_on "libevent" depends_on "libuv" depends_on "[email protected]" def install mkdir "build" do system "cmake", "..", *std_cmake_args, "-DLCB_NO_TESTS=1", "-DLCB_BUILD_LIBEVENT=ON", "-DLCB_BUILD_LIBEV=ON", "-DLCB_BUILD_LIBUV=ON" system "make", "install" end end test do assert_match "LCB_ERR_CONNECTION_REFUSED", shell_output("#{bin}/cbc cat document_id -U couchbase://localhost:1 2>&1", 1).strip end end
38.307692
109
0.706827
79ea139ed7953b37f1440d26da2dc59521d26cb1
338
# # rm-macl/lib/rm-macl/xpan/easer/quint-inout.rb # dc 24/03/2013 # dm 24/03/2013 # vr 1.0.0 module MACL class Easer class Quint::InOut < Quint register(:quint_inout) def _ease(t, st, ch, d) if (t /= d / 2.0) < 1 ch / 2.0 * t ** 5 + st else ch / 2.0 * ((t -= 2) * t ** 4 + 2) + st end end end end end
14.695652
47
0.529586
617075cfe61a2d4c13ee6358d38e453249183aaa
156
require 'test_helper' class WorkflowToHashTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::WorkflowToHash::VERSION end end
19.5
41
0.807692
ed5f7d04421901f79c7c573481390646941a4547
645
class Answers::CommentsController < CommentsController before_action :set_commentable def create super respond_to do |format| format.html { redirect_to url_for(@commentable.question) } format.js end end def destroy @comment = @commentable.comments.find_by(commentable_id: params[:answer_id], id: params[:id]) if @comment.destroy flash[:success] = 'Der Kommentar wurde erfolgreich gelöscht.' end redirect_to url_for(@commentable.question) end private def set_commentable @commentable = Answer.find(params[:answer_id]) end end
24.807692
80
0.658915
4aec41b834d24125510dc6ce109f6b1f332a21ce
5,225
# frozen_string_literal: true require 'spec_helper' RSpec.describe Mutations::Vulnerabilities::Create do include GraphqlHelpers let_it_be(:user) { create(:user) } let(:project) { create(:project) } let(:mutated_vulnerability) { subject[:vulnerability] } before do stub_licensed_features(security_dashboard: true) end describe '#resolve' do using RSpec::Parameterized::TableSyntax let(:identifier_attributes) do { name: "Test identifier", url: "https://vulnerabilities.com/test" } end let(:scanner_attributes) do { id: "my-custom-scanner", name: "My Custom Scanner", url: "https://superscanner.com", vendor: vendor_attributes, version: "21.37.00" } end let(:vendor_attributes) do { name: "Custom Scanner Vendor" } end let(:attributes) do { project: project_gid, name: "Test vulnerability", description: "Test vulnerability created via GraphQL", scanner: scanner_attributes, identifiers: [identifier_attributes], state: "detected", severity: "unknown", confidence: "unknown", solution: "rm -rf --no-preserve-root /", message: "You can't fix this" } end context 'when a vulnerability with the same identifier already exists' do subject { resolve(described_class, args: attributes, ctx: { current_user: user }) } let(:project_gid) { GitlabSchema.id_from_object(project) } before do project.add_developer(user) resolve(described_class, args: attributes, ctx: { current_user: user }) end it 'returns the created vulnerability' do expect(subject[:errors]).to contain_exactly("Vulnerability with those details already exists") end end context 'with valid parameters' do before do project.add_developer(user) end subject { resolve(described_class, args: attributes, ctx: { current_user: user }) } let(:project_gid) { GitlabSchema.id_from_object(project) } context 'when feature flag is disabled' do before do stub_feature_flags(create_vulnerabilities_via_api: false) end it 'raises an error' do expect { subject }.to raise_error(Gitlab::Graphql::Errors::ResourceNotAvailable) end end context 'when feature flag is enabled' do before do stub_feature_flags(create_vulnerabilities_via_api: project) end it 'returns the created vulnerability' do expect(mutated_vulnerability).to be_detected expect(mutated_vulnerability.description).to eq(attributes.dig(:description)) expect(mutated_vulnerability.finding_description).to eq(attributes.dig(:description)) expect(mutated_vulnerability.finding_message).to eq(attributes.dig(:message)) expect(mutated_vulnerability.solution).to eq(attributes.dig(:solution)) expect(subject[:errors]).to be_empty end context 'with custom state' do let(:custom_timestamp) { Time.new(2020, 6, 21, 14, 22, 20) } where(:state, :detected_at, :confirmed_at, :confirmed_by, :resolved_at, :resolved_by, :dismissed_at, :dismissed_by) do [ ['confirmed', ref(:custom_timestamp), ref(:custom_timestamp), ref(:user), nil, nil, nil, nil], ['resolved', ref(:custom_timestamp), nil, nil, ref(:custom_timestamp), ref(:user), nil, nil], ['dismissed', ref(:custom_timestamp), nil, nil, nil, nil, ref(:custom_timestamp), ref(:user)] ] end with_them do let(:attributes) do { project: project_gid, name: "Test vulnerability", description: "Test vulnerability created via GraphQL", scanner: scanner_attributes, identifiers: [identifier_attributes], state: state, severity: "unknown", confidence: "unknown", detected_at: detected_at, confirmed_at: confirmed_at, resolved_at: resolved_at, dismissed_at: dismissed_at, solution: "rm -rf --no-preserve-root /", message: "You can't fix this" } end it "returns a #{params[:state]} vulnerability", :aggregate_failures do expect(mutated_vulnerability.state).to eq(state) expect(mutated_vulnerability.detected_at).to eq(detected_at) expect(mutated_vulnerability.confirmed_at).to eq(confirmed_at) expect(mutated_vulnerability.confirmed_by).to eq(confirmed_by) expect(mutated_vulnerability.resolved_at).to eq(resolved_at) expect(mutated_vulnerability.resolved_by).to eq(resolved_by) expect(mutated_vulnerability.dismissed_at).to eq(dismissed_at) expect(mutated_vulnerability.dismissed_by).to eq(dismissed_by) expect(subject[:errors]).to be_empty end end end end end end end
33.280255
128
0.620096
21df399eb3b94f8ef6ad12f4ad42867fe343f78a
836
module MockleyCrew class Configuration attr_accessor :crew_folder, :factories, :crew_header, :heroku def initialize args = {} @crew_header = args["crew_header"] || "crew-man-badge" @crew_folder = args["crew_folder"] || "#{Rails.root}/db/crew" @heroku = args["heroku"] || false end def default_database_path "#{@crew_folder}/default_database.db" end def database_files_path "#{@crew_folder}/databases/" end def database_files Dir["#{database_files_path}*.db"] end def database_codes database_files.map do |filename| File.basename(filename, ".db").split("_").last end end def registered_factory? factory_name FactoryBot.factories.registered?(factory_name) end def heroku? @heroku == true end end end
22.594595
67
0.642344
bf8728f5286c2b4693bc07725333e89510220fac
939
Pod::Spec.new do |s| s.name = 'Legible' s.version = '0.1.0' s.summary = 'Quick and Nimble Behaviors and Helpers' s.description = <<-DESC Set of Quick and Nimble Behaviors and Helpers to make spec more readable DESC s.homepage = 'https://github.com/sparta-science/Legible' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'sparta-science' => 'www.spartascience.com' } s.source = { :git => 'https://github.com/sparta-science/Legible.git', :tag => s.version.to_s } s.ios.deployment_target = '9.0' s.osx.deployment_target = '11.0' s.tvos.deployment_target = '9.0' s.source_files = 'Legible/Classes/**/*' s.requires_arc = true s.weak_framework = 'XCTest' s.cocoapods_version = '>= 1.4.0' s.swift_versions = ['5.0'] s.dependency 'Nimble', '~> 9.0' s.dependency 'Quick', '~> 4.0' end
32.37931
70
0.576145
116854d88e91f4f21b657a0e7ca1052b56dcfd13
335
# frozen_string_literal: true module Renalware log "Adding HD Providers" do unit = Hospitals::Unit.find_by(unit_code: "MOUNT") provider = HD::Provider.find_by(name: "Diaverum") HD::ProviderUnit.find_or_create_by!( hospital_unit: unit, hd_provider: provider, providers_reference: "1831" ) end end
23.928571
54
0.695522
6a61f0a8463241172a4a29264f6f5f25f1d911e2
1,455
module BackgroundCache class Client attr_reader :redis_1, :redis_2 def initialize(root) if File.exists?(yaml = "#{root}/config/background_cache.yml") options = YAML.load(File.read(yaml)) else puts "\nFAIL: config/background_cache.yml not found" shutdown end @redis_1 = Redis.connect(:url => "redis://#{options['redis']}") @redis_2 = Redis.connect(:url => "redis://#{options['redis']}") end def cache(options) wait = options.delete(:wait) subscribe_to = options[:channel] = Digest::SHA1.hexdigest("#{rand}") options = Yajl::Encoder.encode(options) response = nil if wait != false Timeout.timeout(60) do @redis_1.subscribe("background_cache:response:#{subscribe_to}") do |on| on.subscribe do |channel, subscriptions| @redis_2.rpush "background_cache:request", options end on.message do |channel, message| if message.include?('[SUCCESS]') response = true @redis_1.unsubscribe end end end end else @redis_1.rpush "background_cache:request", options end response end def queued queues = @redis_2.keys 'background_cache:queue:*' queues.collect do |q| Hash[*eval(q['background_cache:queue:'.length..-1]).flatten] end end end end
27.45283
81
0.579381
080cfaeb8c9abdc7fd02802b91cbcf17fa4eb5ae
4,549
require 'ddtrace/contrib/configuration/resolver' require 'ddtrace/vendor/active_record/connection_specification' module Datadog module Contrib module ActiveRecord module Configuration # Converts Symbols, Strings, and Hashes to a normalized connection settings Hash. # # When matching using a Hash, these are the valid fields: # ``` # { # adapter: ..., # host: ..., # port: ..., # database: ..., # username: ..., # role: ..., # } # ``` # # Partial matching is supported: not including certain fields or setting them to `nil` # will cause them to matching all values for that field. For example: `database: nil` # will match any database, given the remaining fields match. # # Any fields not listed above are discarded. # # When more than one configuration could be matched, the last one to match is selected, # based on addition order (`#add`). class Resolver < Contrib::Configuration::Resolver def initialize(active_record_configuration = nil) super() @active_record_configuration = active_record_configuration end def active_record_configuration @active_record_configuration || ::ActiveRecord::Base.configurations end def add(matcher, value) parsed = parse_matcher(matcher) # In case of error parsing, don't store `nil` key # as it wouldn't be useful for matching configuration # hashes in `#resolve`. super(parsed, value) if parsed end def resolve(db_config) active_record_config = resolve_connection_key(db_config).symbolize_keys hash = normalize(active_record_config) # Hashes in Ruby maintain insertion order _, config = @configurations.reverse_each.find do |matcher, _| matcher.none? do |key, value| value != hash[key] end end config rescue => e Datadog.logger.error( "Failed to resolve ActiveRecord configuration key #{db_config.inspect}. " \ "Cause: #{e.message} Source: #{e.backtrace.first}" ) nil end protected def parse_matcher(matcher) resolved_pattern = resolve_connection_key(matcher).symbolize_keys normalized = normalize(resolved_pattern) # Remove empty fields to allow for partial matching normalized.reject! { |_, v| v.nil? } normalized rescue => e Datadog.logger.error( "Failed to resolve ActiveRecord configuration key #{matcher.inspect}. " \ "Cause: #{e.message} Source: #{e.backtrace.first}" ) end def connection_resolver @resolver ||= if defined?(::ActiveRecord::Base.configurations.resolve) ::ActiveRecord::DatabaseConfigurations.new(active_record_configuration) elsif defined?(::ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver) ::ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new( active_record_configuration ) else ::Datadog::Vendor::ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new( active_record_configuration ) end end def resolve_connection_key(key) result = connection_resolver.resolve(key) if result.respond_to?(:configuration_hash) # Rails >= 6.1 result.configuration_hash else # Rails < 6.1 result end end # Extract only fields we'd like to match # from the ActiveRecord configuration. def normalize(active_record_config) { adapter: active_record_config[:adapter], host: active_record_config[:host], port: active_record_config[:port], database: active_record_config[:database], username: active_record_config[:username] } end end end end end end
35.263566
119
0.560123
bfd4543b4fcb1d3161763e657c67aa54559fac39
1,864
require 'spec_helper' describe TrackingController do it_should_behave_like(:tracking_extensions) describe 'GET new' do let(:valid_options) { { 'aid' => '1732', 'c' => 'BIGLONGHASH', 'campaign_id' => nil, 'pathID' => '123', 'subID' => 'Subid 1', 'subID2' => 'Subid 2', 'subID3' => 'Subid 3', 'subID4' => 'Subid 4' }} it 'can be successful' do get :new response.should redirect_to root_path end it 'stores url variables into a structured hash in the session' do tracking_hash = {affiliate_id: '1732'} hash_stub = double(to_hash: tracking_hash) TrackingObject.should_receive(:from_params).with(valid_options).and_return { hash_stub } get :new, aid: 1732, subID: 'Subid 1', subID2: 'Subid 2', subID3: 'Subid 3', subID4: 'Subid 4', pathID: '123', c: 'BIGLONGHASH' session[:tracking_params].should == tracking_hash end it 'redirects to a given url if present in the params' do get :new, redirect_user_to: wallet_path response.should redirect_to wallet_path end end describe 'GET hero_promotion_click' do before do set_current_user({id: 134}) set_virtual_currency end it 'is non-blocking with an invalid request' do get :hero_promotion_click response.should be_success end it 'requires an authenticated user' do controller.should_receive(:require_authentication) get :hero_promotion_click end it 'creates a HeroPromotionClick record' do Plink::HeroPromotionClickRecord.should_receive(:create). with( hero_promotion_id: '1', image: 'http://googlez.forshizzle/mynizzle', user_id: 134 ) get :hero_promotion_click, hero_promotion_id: 1, image: 'http://googlez.forshizzle/mynizzle' end end end
27.411765
133
0.651824
1c32996711cfa267a2175c13ee92092cec8fd199
1,045
cask "retro-virtual-machine" do version "2.0,1.r7" sha256 "75e94f2df589ead3fb1eab529713312a17dc16e6b2ba547594cd9d5975def566" url "https://retrovirtualmachine.ams3.digitaloceanspaces.com/release/beta#{version.csv.second.major}/macos/RetroVirtualMachine.#{version.csv.first}.beta-#{version.csv.second}.macos.dmg", verified: "retrovirtualmachine.ams3.digitaloceanspaces.com/" name "Retro Virtual Machine" desc "ZX Spectrum and Amstrad CPC emulator" homepage "https://www.retrovirtualmachine.org/en/" livecheck do url "https://www.retrovirtualmachine.org/en/downloads" strategy :page_match do |page| match = page.match(/RetroVirtualMachine\.(\d+(?:\.\d+)*)\.beta-(\d+(?:\..\d+)*)\.macos\.dmg/i) next if match.blank? "#{match[1]},#{match[2]}" end end app "Retro Virtual Machine #{version.major}.app" zap trash: [ "~/Library/Application Support/Retro Virtual Machine v#{version.major}.x", "~/Library/Preferences/com.madeinalacant.RetroVirtualMachine#{version.major}.plist", ] end
37.321429
188
0.714833
ed6dd4e8964e260562ed57c19b6b17ecc76432f5
1,997
# encoding: UTF-8 # # Copyright (c) 2010-2015 GoodData Corporation. All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. require_relative '../rest/resource' require_relative '../extensions/hash' module GoodData class ExecutionDetail < Rest::Resource attr_reader :dirty, :json alias_method :data, :json alias_method :raw_data, :json alias_method :to_hash, :json # Initializes object instance from raw wire JSON # # @param json Json used for initialization def initialize(json) super @json = json end # Timestamp when execution was created def created Time.parse(json['executionDetail']['created']) end # Has execution failed? def error? status == :error end # Timestamp when execution was finished def finished Time.parse(json['executionDetail']['finished']) end # Log for execution def log @client.get(json['executionDetail']['links']['log']) end # Filename of log def log_filename @client.get(json['executionDetail']['logFileName']) end # Is execution ok? def ok? status == :ok end # Timestamp when execution was started def started Time.parse(json['executionDetail']['started']) end # Status of execution def status json['executionDetail']['status'].downcase.to_sym end # Timestamp when execution was updated def updated Time.parse(json['executionDetail']['updated']) end # Returns URL # # @return [String] Schedule URL def uri @json['executionDetail']['links']['self'] if @json && @json['executionDetail'] && @json['executionDetail']['links'] end # Compares two executions - based on their URI def ==(other) other.respond_to?(:uri) && other.uri == uri && other.respond_to?(:to_hash) && other.to_hash == to_hash end end end
23.77381
121
0.649975
26e41d857487442600385aa91e0fd2505bddc4bb
187
class ChangeAppointmentSummariesValueOfPensionPotsToString < ActiveRecord::Migration[4.2] def change change_column :appointment_summaries, :value_of_pension_pots, :string end end
31.166667
89
0.834225
28d8093b81ffce679735b3be21ca9bb795c18a96
563
#!/usr/bin/ruby -w # PART 7 # The rand method can generate random numbers! # In the IO section we will see how these things work! p rand(1..100) # => 30 p Kernel.rand(1..100) # => 94 p Random.rand(1..100) # => 73 # When you call rand it calls Kernel.rand! # Random.rand is not Kernel.rand, but it's similar... # Note that you can't create alphabetical ranges! # Except: p 10.times.map { rand(97..122).chr }.join # => "oodfbjagyc"
37.533333
75
0.516874
033ff82b458ec5f6c716c36b8e425feeefa6951f
1,826
module MobileFu module Helper def js_enabled_mobile_device? is_device?('iphone') || is_device?('ipod') || is_device?('ipad') || is_device?('mobileexplorer') || is_device?('android') end def stylesheet_link_tag_with_mobilization(*sources) mobilized_sources = Array.new # Figure out where stylesheets live, which differs depending if the asset # pipeline is used or not. stylesheets_dir = config.stylesheets_dir # Rails.root/public/stylesheets # Look for mobilized stylesheets in the app/assets path if asset pipeline # is enabled, because public/stylesheets will be missing in development # mode without precompiling assets first, and may also contain multiple # stylesheets with similar names because of checksumming during # precompilation. if Rails.application.config.respond_to?(:assets) # don't break pre-rails3.1 if Rails.application.config.assets.enabled stylesheets_dir = File.join(Rails.root, 'app/assets/stylesheets/') end end device_names = respond_to?(:is_mobile_device?) && is_mobile_device? ? ['mobile', mobile_device.downcase] : [] sources.each do |source| mobilized_sources << source device_names.compact.each do |device_name| # support ERB and/or SCSS extensions (e.g., mobile.css.erb, mobile.css.scss.erb) possible_source = source.to_s.sub(/\.css.*$/, '') + "_#{device_name}" mobilized_files = Dir.glob(File.join(stylesheets_dir, "#{possible_source}.css*")).map { |f| f.sub(stylesheets_dir, '') } mobilized_sources += mobilized_files.map { |f| f.sub(/\.css.*/, '') } end end stylesheet_link_tag_without_mobilization *mobilized_sources end end end
42.465116
130
0.663198
62245162c3509672aba4ecb570d537f220b76815
186
Deface::Override.new( virtual_path: 'spree/layouts/admin', name: 'panels_admin_sidebar_menu', insert_bottom: '#main-sidebar', partial: 'spree/admin/shared/panels_sidebar_menu' )
26.571429
51
0.758065
bfa36005347d7873430b01985810add5f54ac493
1,429
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "rbcore/version" Gem::Specification.new do |spec| spec.name = "rbcore" spec.version = Rbcore::VERSION spec.authors = ["stephenw"] spec.email = ["[email protected]"] spec.summary = %q{rbcore command line tool} spec.description = %q{rbcore command line tool} spec.homepage = "http://www.stephenw.cc" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency "thor", "~> 0" spec.add_runtime_dependency "rainbow", "~> 2.2" spec.add_runtime_dependency "filewatcher", "~> 0" spec.add_development_dependency "bundler", "~> 1.15" spec.add_development_dependency "rake", "~> 10.0" end
35.725
96
0.659202
33d8676bd916b5edf8e7e442f2c0a16884efb0f7
2,618
=begin #Custom Workflow Actions #Create custom workflow actions The version of the OpenAPI document: v4 Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.3.1 =end require 'spec_helper' require 'json' require 'date' # Unit tests for Hubspot::Automation::Actions::ExtensionActionDefinitionInput # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'ExtensionActionDefinitionInput' do before do # run before each test @instance = Hubspot::Automation::Actions::ExtensionActionDefinitionInput.new end after do # run after each test end describe 'test an instance of ExtensionActionDefinitionInput' do it 'should create an instance of ExtensionActionDefinitionInput' do expect(@instance).to be_instance_of(Hubspot::Automation::Actions::ExtensionActionDefinitionInput) end end describe 'test attribute "functions"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "action_url"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "published"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "archived_at"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "input_fields"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "object_request_options"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "input_field_dependencies"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "labels"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "object_types"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
29.088889
103
0.73071
019362099ff9224e4dd6179e7d5902c19daa4cf9
295
require 'twilio-ruby' response = Twilio::TwiML::VoiceResponse.new response.dial do |dial| dial.client do |client| client.identity('user_jane') client.parameter(name: 'FirstName', value: 'Jane') client.parameter(name: 'LastName', value: 'Doe') end end puts response
22.692308
58
0.681356
1843acb0cc084beca299eef2d6db6c660c9e9415
10,928
# frozen_string_literal: true require 'spec_helper' describe Gitlab::QuickActions::Extractor do let(:definitions) do Class.new do include Gitlab::QuickActions::Dsl command(:reopen, :open) { } command(:assign) { } command(:labels) { } command(:power) { } command(:noop_command) substitution(:substitution) { 'foo' } substitution :shrug do |comment| "#{comment} SHRUG" end end.command_definitions end let(:extractor) { described_class.new(definitions) } shared_examples 'command with no argument' do it 'extracts command' do msg, commands = extractor.extract_commands(original_msg) expect(commands).to eq [['reopen']] expect(msg).to eq final_msg end end shared_examples 'command with a single argument' do it 'extracts command' do msg, commands = extractor.extract_commands(original_msg) expect(commands).to eq [['assign', '@joe']] expect(msg).to eq final_msg end end shared_examples 'command with multiple arguments' do it 'extracts command' do msg, commands = extractor.extract_commands(original_msg) expect(commands).to eq [['labels', '~foo ~"bar baz" label']] expect(msg).to eq final_msg end end describe '#extract_commands' do describe 'command with no argument' do context 'at the start of content' do it_behaves_like 'command with no argument' do let(:original_msg) { "/reopen\nworld" } let(:final_msg) { "world" } end end context 'in the middle of content' do it_behaves_like 'command with no argument' do let(:original_msg) { "hello\n/reopen\nworld" } let(:final_msg) { "hello\nworld" } end end context 'in the middle of a line' do it 'does not extract command' do msg = "hello\nworld /reopen" msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq "hello\nworld /reopen" end end context 'at the end of content' do it_behaves_like 'command with no argument' do let(:original_msg) { "hello\n/reopen" } let(:final_msg) { "hello" } end end end describe 'command with a single argument' do context 'at the start of content' do it_behaves_like 'command with a single argument' do let(:original_msg) { "/assign @joe\nworld" } let(:final_msg) { "world" } end it 'allows slash in command arguments' do msg = "/assign @joe / @jane\nworld" msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['assign', '@joe / @jane']] expect(msg).to eq 'world' end end context 'in the middle of content' do it_behaves_like 'command with a single argument' do let(:original_msg) { "hello\n/assign @joe\nworld" } let(:final_msg) { "hello\nworld" } end end context 'in the middle of a line' do it 'does not extract command' do msg = "hello\nworld /assign @joe" msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq "hello\nworld /assign @joe" end end context 'at the end of content' do it_behaves_like 'command with a single argument' do let(:original_msg) { "hello\n/assign @joe" } let(:final_msg) { "hello" } end end context 'when argument is not separated with a space' do it 'does not extract command' do msg = "hello\n/assign@joe\nworld" msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq "hello\n/assign@joe\nworld" end end end describe 'command with multiple arguments' do context 'at the start of content' do it_behaves_like 'command with multiple arguments' do let(:original_msg) { %(/labels ~foo ~"bar baz" label\nworld) } let(:final_msg) { "world" } end end context 'in the middle of content' do it_behaves_like 'command with multiple arguments' do let(:original_msg) { %(hello\n/labels ~foo ~"bar baz" label\nworld) } let(:final_msg) { "hello\nworld" } end end context 'in the middle of a line' do it 'does not extract command' do msg = %(hello\nworld /labels ~foo ~"bar baz" label) msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq %(hello\nworld /labels ~foo ~"bar baz" label) end end context 'at the end of content' do it_behaves_like 'command with multiple arguments' do let(:original_msg) { %(hello\n/labels ~foo ~"bar baz" label) } let(:final_msg) { "hello" } end end context 'when argument is not separated with a space' do it 'does not extract command' do msg = %(hello\n/labels~foo ~"bar baz" label\nworld) msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq %(hello\n/labels~foo ~"bar baz" label\nworld) end end end it 'extracts command with multiple arguments and various prefixes' do msg = %(hello\n/power @user.name %9.10 ~"bar baz.2"\nworld) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['power', '@user.name %9.10 ~"bar baz.2"']] expect(msg).to eq "hello\nworld" end it 'extracts command case insensitive' do msg = %(hello\n/PoWer @user.name %9.10 ~"bar baz.2"\nworld) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['power', '@user.name %9.10 ~"bar baz.2"']] expect(msg).to eq "hello\nworld" end it 'does not extract noop commands' do msg = %(hello\nworld\n/reopen\n/noop_command) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen']] expect(msg).to eq "hello\nworld\n/noop_command" end it 'extracts and performs substitution commands' do msg = %(hello\nworld\n/reopen\n/substitution) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen'], ['substitution']] expect(msg).to eq "hello\nworld\nfoo" end it 'extracts and performs substitution commands' do msg = %(hello\nworld\n/reopen\n/shrug this is great?) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen'], ['shrug', 'this is great?']] expect(msg).to eq "hello\nworld\nthis is great? SHRUG" end it 'extracts and performs multiple substitution commands' do msg = %(hello\nworld\n/reopen\n/shrug this is great?\n/shrug meh) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen'], ['shrug', 'this is great?'], %w(shrug meh)] expect(msg).to eq "hello\nworld\nthis is great? SHRUG\nmeh SHRUG" end it 'does not extract substitution command in inline code' do msg = %(hello\nworld\n/reopen\n`/tableflip this is great`?) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen']] expect(msg).to eq "hello\nworld\n`/tableflip this is great`?" end it 'extracts and performs substitution commands case insensitive' do msg = %(hello\nworld\n/reOpen\n/sHRuG this is great?) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen'], ['shrug', 'this is great?']] expect(msg).to eq "hello\nworld\nthis is great? SHRUG" end it 'extracts and performs substitution commands with comments' do msg = %(hello\nworld\n/reopen\n/substitution wow this is a thing.) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['reopen'], ['substitution', 'wow this is a thing.']] expect(msg).to eq "hello\nworld\nfoo" end it 'extracts multiple commands' do msg = %(hello\n/power @user.name %9.10 ~"bar baz.2" label\nworld\n/reopen) msg, commands = extractor.extract_commands(msg) expect(commands).to eq [['power', '@user.name %9.10 ~"bar baz.2" label'], ['reopen']] expect(msg).to eq "hello\nworld" end it 'does not alter original content if no command is found' do msg = 'Fixes #123' msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq 'Fixes #123' end it 'does not extract commands inside a blockcode' do msg = "Hello\r\n```\r\nThis is some text\r\n/close\r\n/assign @user\r\n```\r\n\r\nWorld" expected = msg.delete("\r") msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq expected end it 'does not extract commands inside a blockquote' do msg = "Hello\r\n>>>\r\nThis is some text\r\n/close\r\n/assign @user\r\n>>>\r\n\r\nWorld" expected = msg.delete("\r") msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq expected end it 'does not extract commands inside a HTML tag' do msg = "Hello\r\n<div>\r\nThis is some text\r\n/close\r\n/assign @user\r\n</div>\r\n\r\nWorld" expected = msg.delete("\r") msg, commands = extractor.extract_commands(msg) expect(commands).to be_empty expect(msg).to eq expected end it 'limits to passed commands when they are passed' do msg = <<~MSG.strip Hello, we should only extract the commands passed /reopen /labels hello world /power MSG expected_msg = <<~EXPECTED.strip Hello, we should only extract the commands passed /power EXPECTED expected_commands = [['reopen'], ['labels', 'hello world']] msg, commands = extractor.extract_commands(msg, only: [:open, :labels]) expect(commands).to eq(expected_commands) expect(msg).to eq expected_msg end end describe '#redact_commands' do using RSpec::Parameterized::TableSyntax where(:text, :expected) do "hello\n/labels ~label1 ~label2\nworld" | "hello\n`/labels ~label1 ~label2`\nworld" "hello\n/open\n/labels ~label1\nworld" | "hello\n`/open`\n`/labels ~label1`\nworld" "hello\n/reopen\nworld" | "hello\n`/reopen`\nworld" "/reopen\nworld" | "`/reopen`\nworld" "hello\n/open" | "hello\n`/open`" end with_them do it 'encloses quick actions with code span markdown' do expect(extractor.redact_commands(text)).to eq(expected) end end end end
32.915663
99
0.621065
039f8e48a5967c5291ffaadbcb0cf1e0300fa038
1,459
# 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. require 'spec_helper' describe 'client#terms_enum' do let(:expected_args) do [ method, 'foo/_terms_enum', {}, body, {} ] end context 'without a body' do let(:method) { 'GET' } let(:body) { nil } it 'performs a GET request' do expect(client_double.terms_enum(index: 'foo')).to eq({}) end end context 'with a body' do let(:method) { 'POST' } let(:body) { {} } it 'performs a POST request' do expect(client_double.terms_enum(index: 'foo', body: body)).to eq({}) end end it 'requires the :index argument' do expect { client.terms_enum }.to raise_exception(ArgumentError) end end
27.528302
74
0.689513
394a6a014a4e05ef03ce474d0b4ea1349c9b752f
948
module Bmg class OutputPreferences DEFAULT_PREFS = { attributes_ordering: nil, extra_attributes: :after } def initialize(options) @options = DEFAULT_PREFS.merge(options) end attr_reader :options def self.dress(arg) return arg if arg.is_a?(OutputPreferences) arg = {} if arg.nil? new(arg) end def attributes_ordering options[:attributes_ordering] end def extra_attributes options[:extra_attributes] end def order_attrlist(attrlist) return attrlist if attributes_ordering.nil? index = Hash[attributes_ordering.each_with_index.to_a] attrlist.sort{|a,b| ai, bi = index[a], index[b] if ai && bi ai <=> bi elsif ai extra_attributes == :after ? -1 : 1 else extra_attributes == :after ? 1 : -1 end } end end # class OutputPreferences end # module Bmg
21.066667
60
0.607595
21f00cfc2d65abfc680a76cf2d1e7ee459216f08
12,577
# -------------------------------------------------------------------------- # # Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # require "OpenNebulaDriver" require "CommandManager" require 'base64' require 'rexml/document' # This class provides basic messaging and logging functionality # to implement OpenNebula Drivers. A driver is a program that # specialize the OpenNebula behavior by interfacing with specific # infrastructure functionalities. # # A Driver inherits this class and only has to provide methods # for each action it wants to receive. The method must be associated # with the action name through the register_action function class VirtualMachineDriver < OpenNebulaDriver # Virtual Machine Driver Protocol constants ACTION = { :deploy => "DEPLOY", :shutdown => "SHUTDOWN", :reboot => "REBOOT", :reset => "RESET", :cancel => "CANCEL", :save => "SAVE", :restore => "RESTORE", :migrate => "MIGRATE", :poll => "POLL", :log => "LOG", :attach_disk => "ATTACHDISK", :detach_disk => "DETACHDISK", :snapshot_create => "SNAPSHOTCREATE", :snapshot_revert => "SNAPSHOTREVERT", :snapshot_delete => "SNAPSHOTDELETE", :cleanup => "CLEANUP", :attach_nic => "ATTACHNIC", :detach_nic => "DETACHNIC" } POLL_ATTRIBUTE = { :usedmemory => "USEDMEMORY", :usedcpu => "USEDCPU", :nettx => "NETTX", :netrx => "NETRX", :state => "STATE" } VM_STATE = { :active => 'a', :paused => 'p', :error => 'e', :deleted => 'd', :unknown => '-' } HOST_ARG = 1 # Register default actions for the protocol. # # @param [String] directory path inside remotes path where the scripts # reside # @param [Hash] options options for OpenNebula driver (check the available # options in {OpenNebulaDriver#initialize}) # @option options [Boolean] :threaded (true) enables or disables threads def initialize(directory, options={}) @options={ :threaded => true, :single_host => true }.merge!(options) super(directory, @options) @hosts = Array.new register_action(ACTION[:deploy].to_sym, method("deploy")) register_action(ACTION[:shutdown].to_sym, method("shutdown")) register_action(ACTION[:reboot].to_sym, method("reboot")) register_action(ACTION[:reset].to_sym, method("reset")) register_action(ACTION[:cancel].to_sym, method("cancel")) register_action(ACTION[:save].to_sym, method("save")) register_action(ACTION[:restore].to_sym, method("restore")) register_action(ACTION[:migrate].to_sym, method("migrate")) register_action(ACTION[:poll].to_sym, method("poll")) register_action(ACTION[:attach_disk].to_sym, method("attach_disk")) register_action(ACTION[:detach_disk].to_sym, method("detach_disk")) register_action(ACTION[:snapshot_create].to_sym, method("snapshot_create")) register_action(ACTION[:snapshot_revert].to_sym, method("snapshot_revert")) register_action(ACTION[:snapshot_delete].to_sym, method("snapshot_delete")) register_action(ACTION[:cleanup].to_sym, method("cleanup")) register_action(ACTION[:attach_nic].to_sym, method("attach_nic")) register_action(ACTION[:detach_nic].to_sym, method("detach_nic")) end # Decodes the encoded XML driver message received from the core # # @param [String] drv_message the driver message # @return [REXML::Element] the root element of the decoded XML message def decode(drv_message) message = Base64.decode64(drv_message) xml_doc = REXML::Document.new(message) xml_doc.root end # Execute a command associated to an action and id in a remote host. def remotes_action(command, id, host, action, remote_dir, std_in=nil) super(command,id,host,ACTION[action],remote_dir,std_in) end # Execute a command associated to an action and id on localhost def local_action(command, id, action) super(command,id,ACTION[action]) end # Virtual Machine Manager Protocol Actions (generic implementation) def deploy(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:deploy],RESULT[:failure],id,error) end def shutdown(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:shutdown],RESULT[:failure],id,error) end def reboot(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:reboot],RESULT[:failure],id,error) end def reset(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:reset],RESULT[:failure],id,error) end def cancel(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:cancel],RESULT[:failure],id,error) end def save(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:save],RESULT[:failure],id,error) end def restore(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:restore],RESULT[:failure],id,error) end def migrate(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:migrate],RESULT[:failure],id,error) end def poll(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:poll],RESULT[:failure],id,error) end def attach_disk(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:attach_disk],RESULT[:failure],id,error) end def detach_disk(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:detach_disk],RESULT[:failure],id,error) end def attach_nic(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:attach_nic],RESULT[:failure],id,error) end def detach_nic(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:detach_nic],RESULT[:failure],id,error) end def snapshot_create(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:snapshot_create],RESULT[:failure],id,error) end def snapshot_revert(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:snapshot_revert],RESULT[:failure],id,error) end def snapshot_delete(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:snapshot_delete],RESULT[:failure],id,error) end def cleanup(id, drv_message) error = "Action not implemented by driver #{self.class}" send_message(ACTION[:cleanup],RESULT[:failure],id,error) end private # Interface to handle the pending events from the ActionManager Interface def delete_running_action(action_id) if @options[:single_host] delete_running_action_single_host(action_id) else super(action_id) end end def delete_running_action_single_host(action_id) action=@action_running[action_id] if action @hosts.delete(action[:host]) @action_running.delete(action_id) end end def get_first_runable if @options[:single_host] get_first_runable_single_host else super end end def get_first_runable_single_host action_index=nil @action_queue.each_with_index do |action, index| if !action.keys.include?(:host) if action[:args].length == 2 begin xml=decode(action[:args].last) host=xml.elements['HOST'] action[:host]=host.text if host rescue action[:host]=nil end else action[:host]=nil end end if action.keys.include?(:host) && action[:host] if [email protected]?(action[:host]) action_index=index break end else action_index=index break end end return action_index end def get_runable_action if @options[:single_host] get_runable_action_single_host else super end end def get_runable_action_single_host action_index=get_first_runable if action_index action=@action_queue[action_index] else action=nil end if action @hosts << action[:host] if action[:host] @action_queue.delete_at(action_index) end return action end def empty_queue if @options[:single_host] empty_queue_single_host else super end end def empty_queue_single_host get_first_runable==nil end end ################################################################ ################################################################ if __FILE__ == $0 class TemplateDriver < VirtualMachineDriver def initialize super('vmm/dummy', :concurrency => 15, :threaded => true) end def deploy(id, host, remote_dfile, not_used) #MUST return deploy_id if deployment was successfull deploy_id = "-" send_message(ACTION[:deploy],RESULT[:success],id,deploy_id) end def shutdown(id, host, deploy_id, not_used) send_message(ACTION[:shutdown],RESULT[:success],id) end def cancel(id, host, deploy_id, not_used) send_message(ACTION[:cancel],RESULT[:success],id) end def save(id, host, deploy_id, file) send_message(ACTION[:save],RESULT[:success],id) end def restore(id, host, deploy_id , file) send_message(ACTION[:restore],RESULT[:success],id) end def migrate(id, host, deploy_id, dest_host) send_message(ACTION[:migrate],RESULT[:success],id) end def poll(id, host, deploy_id, not_used) # monitor_info: string in the form "VAR=VAL VAR=VAL ... VAR=VAL" # known VAR are in POLL_ATTRIBUTES. VM states VM_STATES monitor_info = "#{POLL_ATTRIBUTE[:state]}=#{VM_STATE[:active]} " \ "#{POLL_ATTRIBUTE[:nettx]}=12345" send_message(ACTION[:poll],RESULT[:success],id,monitor_info) end end sd = TemplateDriver.new sd.start_driver end
34.552198
79
0.576608
b9126b87faec746ff3887a772169dd8eba67de5d
1,286
require_relative "../task2" describe Frequency do before { @file = "sample_files/fasta/sample.fasta" } let(:fasta) { Frequency.new(@file) } before { fasta.get_freq } describe '#get_freq' do it "is defined" do expect(Frequency.method_defined?(:get_freq)).to be true end end describe 'parse' do it "parses file by odd line and puts in array" do expect(fasta.parsed).to be_instance_of(Array) end it "only accepts strings of sequences" do expect(fasta.parsed.sample).to be_instance_of(String) end it "only accpets character from A-Z" do expect(/[^A-Z]/.match(fasta.parsed.sample)).to equal nil end end describe '#get_occurence' do before { @hash = fasta.freq } it "gets the frequencies of the sequences in the file" do expect(fasta.freq).to be_instance_of(Hash) end it "in freq hash key is a string" do expect(@hash.keys.sample).to be_instance_of(String) end it "in freq hash value is a number" do expect(@hash.values.sample).to be_instance_of(Fixnum) end end describe '#sort_top10_freq' do it "gathers top 10 frequencies from freq hash" do expect(fasta.top10.count).to equal 10 end it "sorts the frequency hash" do expect(fasta.top10.values.first).to be > (fasta.top10.values[1]) end end end
23.381818
67
0.70451
797fdadc4f6508fd80bda8021399bfd67d6d11ee
160
class AddTitleAndPostToPosts < ActiveRecord::Migration[6.0] def change add_column :posts, :title, :string add_column :posts, :post, :string end end
22.857143
59
0.725
f7bebb46eff007ea44832c31e3385a85371f0209
796
class HomeController < ApplicationController def index require 'net/http' require 'json' @url = 'https://api.coinmarketcap.com/v1/ticker/' @uri = URI(@url) @response = Net::HTTP.get(@uri) @coins = JSON.parse(@response) @my_coins = ['BTC','XRP','ADA','STEEM'] end def lookup @url = 'https://api.coinmarketcap.com/v1/ticker/' @uri = URI(@url) @response = Net::HTTP.get(@uri) @lookup_coin = JSON.parse(@response) @symbol = params[:search] if @symbol @symbol = @symbol.upcase end end def about require 'net/http' require 'json' @url = 'https://api.coinmarketcap.com/v2/ticker/' @uri = URI(@url) @response = Net::HTTP.get(@uri) @coins = JSON.parse(@response) @my_coins = ['BTC','XRP','ADA','STEEM'] end end
22.111111
55
0.609296
1a49e806644718622452881382740b2441cf181d
1,060
class Stylist attr_reader(:stylist_name, :client_id, :id) define_method(:initialize) do |attributes| @stylist_name = attributes.fetch(:stylist_name) if attributes.has_key?(:client_id) @client_id = attributes.fetch(:client_id) if attributes.has_key?(:id) @id = attributes.fetch(:id) end end define_singleton_method(:all) do stylists = [] sql = "SELECT * FROM stylists" results = DB.exec(sql) results.each do |result| stylist_name = result.fetch('stylist_name') client_id = result.fetch('client_id') stylists.push(Stylist.new({ :stylist_name => stylist_name, :id => id, :client_id => client_id})) end stylists end end define_method(:save) do sql = "INSERT INTO stylists (stylist_name, client_id) VALUES ('#{@stylist_name}', #{@client_id}) RETURNING id;" result = DB.exec(sql) @id = result.first().fetch("id").to_i() end define_singleton_method(:find) do |id| Stylist.all().each() do |stylist| if stylist.id() == id return stylist end end end end
25.238095
114
0.661321
7997eacebb21e4cdfa5076db61394f7cc08a1c63
1,718
# # Be sure to run `pod lib lint ZJBTableViewModel.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 = 'ZJBTableViewModel' s.version = '0.3.0' s.summary = 'TableViewModel方便UITableView的开发' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TableViewModel方便UITableView的开发,便于UI修改迭代 DESC s.homepage = 'https://github.com/jiabibi888/ZJBTableViewModel' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Jabir' => '[email protected]' } s.source = { :git => 'https://github.com/jiabibi888/ZJBTableViewModel.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' # s.source_files = 'ZJBTableViewModel/Classes/**/*' s.vendored_frameworks = "ZJBTableViewModel/FrameWork/ZJBTableViewModel.framework" # s.resource_bundles = { # 'ZJBTableViewModel' => ['ZJBTableViewModel/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
39.045455
112
0.66298
18470260dd4878f3c80a1f14d9c79c783256a5d7
2,437
require 'chunks/wiki' # Includes the contents of another page for rendering. # The include command looks like this: "[[!include PageName]]". # It is a WikiReference since it refers to another page (PageName) # and the wiki content using this command must be notified # of changes to that page. # If the included page could not be found, a warning is displayed. class Include < WikiChunk::WikiReference INCLUDE_PATTERN = /\[\[!include\s+([^\]\s][^\]]*?)\s*\]\]/i def self.pattern() INCLUDE_PATTERN end def initialize(match_data, content) super @page_name = match_data[1].strip rendering_mode = content.options[:mode] || :show add_to_include_list @unmask_text = get_unmask_text_avoiding_recursion_loops(rendering_mode) end private def get_unmask_text_avoiding_recursion_loops(rendering_mode) if refpage return "<em>Recursive include detected: #{@content.page_name} " + "&#x2192; #{@content.page_name}</em>\n" if self_inclusion(refpage) renderer = PageRenderer.new(refpage.current_revision) included_content = case rendering_mode when :show then renderer.display_content when :publish then renderer.display_published when :export then renderer.display_content_for_export when :s5 then renderer.display_s5 else raise "Unsupported rendering mode #{@mode.inspect}" end # redirects and categories of included pages should not be inherited @content.merge_chunks(included_content.delete_chunks!([Redirect, Category])) clear_include_list return included_content.pre_rendered else clear_include_list return "<em>Could not include #{@page_name}</em>\n" end end # We track included pages in a thread-local variable. # This allows a multi-threaded Rails to handle multiple # simultaneous requests (one request/thread), without # getting confused. def add_to_include_list Thread.current[:chunk_included_by] ? Thread.current[:chunk_included_by].push(@content.page_name) : Thread.current[:chunk_included_by] = [@content.page_name] end def clear_include_list Thread.current[:chunk_included_by] = [] end def self_inclusion(refpage) if Thread.current[:chunk_included_by].include?(refpage.page.name) @content.delete_chunk(self) clear_include_list else return false end end end
32.932432
82
0.707838
1aeb3f7099e3eb10d36d6d3454989aa411a7df4b
2,521
# 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! module Google module Ads module GoogleAds module V6 module Services module AdGroupBidModifierService # Path helper methods for the AdGroupBidModifierService API. module Paths ## # Create a fully-qualified AdGroup resource string. # # The resource will be in the following format: # # `customers/{customer_id}/adGroups/{ad_group_id}` # # @param customer_id [String] # @param ad_group_id [String] # # @return [::String] def ad_group_path customer_id:, ad_group_id: raise ::ArgumentError, "customer_id cannot contain /" if customer_id.to_s.include? "/" "customers/#{customer_id}/adGroups/#{ad_group_id}" end ## # Create a fully-qualified AdGroupBidModifier resource string. # # The resource will be in the following format: # # `customers/{customer_id}/adGroupBidModifiers/{ad_group_id}~{criterion_id}` # # @param customer_id [String] # @param ad_group_id [String] # @param criterion_id [String] # # @return [::String] def ad_group_bid_modifier_path customer_id:, ad_group_id:, criterion_id: raise ::ArgumentError, "customer_id cannot contain /" if customer_id.to_s.include? "/" raise ::ArgumentError, "ad_group_id cannot contain /" if ad_group_id.to_s.include? "/" "customers/#{customer_id}/adGroupBidModifiers/#{ad_group_id}~#{criterion_id}" end extend self end end end end end end end
35.013889
102
0.594605
871ebc6fdc1c5617b1ab88bb2f6f42eaf63caf36
38
module Rdupes VERSION = '0.3.0' end
9.5
19
0.657895
2112165411f261cd383c2c37d76fe0f9e8184ecf
881
# frozen_string_literal: true require "rails_helper" describe DiscourseCalendar::EnsureConsistency do before { SiteSetting.calendar_enabled = true } it "works" do op = create_post(raw: "[calendar]\n[/calendar]") SiteSetting.holiday_calendar_topic_id = op.topic_id post = create_post(raw: "Some Event [date=2019-09-10]", topic: op.topic) CookedPostProcessor.new(post).post_process op.reload expect(op.calendar_details[post.post_number.to_s]).to be_present DiscourseCalendar::EnsureConsistency.new.execute(nil) op.reload expect(op.calendar_details[post.post_number.to_s]).to be_present PostMover .new(op.topic, Discourse.system_user, [post.id]) .to_new_topic("A topic with some dates in it") DiscourseCalendar::EnsureConsistency.new.execute(nil) op.reload expect(op.calendar_details).to eq({}) end end
25.911765
76
0.730988
4afe1e2bf9dc864c099f622493efda94decbc831
9,169
# frozen_string_literal: true require 'spec_helper' require 'middleman-core' describe Middleman::Util do describe '::path_match' do it 'matches a literal string' do expect(Middleman::Util.path_match('/index.html', '/index.html')).to be true end it "won't match a wrong string" do expect(Middleman::Util.path_match('/foo.html', '/index.html')).to be false end it "won't match a partial string" do expect(Middleman::Util.path_match('ind', '/index.html')).to be false end it 'works with a regex' do expect(Middleman::Util.path_match(/\.html$/, '/index.html')).to be true expect(Middleman::Util.path_match(/\.js$/, '/index.html')).to be false end it 'works with a proc' do matcher = ->(p) { p.length > 5 } expect(Middleman::Util.path_match(matcher, '/index.html')).to be true expect(Middleman::Util.path_match(matcher, '/i')).to be false end it 'works with globs' do expect(Middleman::Util.path_match('/foo/*.html', '/foo/index.html')).to be true expect(Middleman::Util.path_match('/foo/*.html', '/foo/index.js')).to be false expect(Middleman::Util.path_match('/bar/*.html', '/foo/index.js')).to be false expect(Middleman::Util.path_match('/foo/*', '/foo/bar/index.html')).to be true expect(Middleman::Util.path_match('/foo/**/*', '/foo/bar/index.html')).to be true expect(Middleman::Util.path_match('/foo/**', '/foo/bar/index.html')).to be true end end describe '::binary?' do %w[plain.txt unicode.txt unicode].each do |file| it "recognizes #{file} as not binary" do expect(Middleman::Util.binary?(File.join(File.dirname(__FILE__), "binary_spec/#{file}"))).to be false end end %w[middleman.png middleman stars.svgz].each do |file| it "recognizes #{file} as binary" do expect(Middleman::Util.binary?(File.join(File.dirname(__FILE__), "binary_spec/#{file}"))).to be true end end end describe '::recursively_enhance' do it 'returns Hashie extended Hash if given a hash' do input = { test: 'subject' } subject = Middleman::Util.recursively_enhance input expect(subject.test).to eq 'subject' end it 'returns Array with strings, or IndifferentHash, true, false' do indifferent_hash = { test: 'subject' } regular_hash = { regular: 'hash' } input = [indifferent_hash, regular_hash, true, false] subject = Middleman::Util.recursively_enhance input expect(subject[1].regular).to eq 'hash' expect(subject[2]).to eq true expect(subject[3]).to eq false end end describe '::asset_url' do after(:each) do Given.cleanup! end context 'when http_prefix is activated' do before(:each) do Given.fixture 'clean-dir-app' Given.file 'source/images/blank.gif', '' @mm = Middleman::Application.new do config[:http_prefix] = 'http_prefix' end end it 'returns path with http_prefix pre-pended if resource is found' do expect(Middleman::Util.asset_url(@mm, 'blank.gif', 'images', http_prefix: 'http_prefix')).to eq 'http_prefix/images/blank.gif' end it 'returns path with http_prefix pre-pended if resource is not found' do expect(Middleman::Util.asset_url(@mm, 'missing.gif', 'images', http_prefix: 'http_prefix')).to eq 'http_prefix/images/missing.gif' end end it 'returns path relative to the provided current_resource' do Given.fixture 'clean-dir-app' Given.file 'source/a-path/index.html', '' Given.file 'source/a-path/images/blank.gif', '' @mm = Middleman::Application.new current_resource = @mm.sitemap.by_path('a-path/index.html') expect(Middleman::Util.asset_url(@mm, 'images/blank.gif', 'images', current_resource: current_resource)).to eq '/a-path/images/blank.gif' end context 'when relative is true' do before(:each) do Given.fixture 'relative-assets-app' @mm = Middleman::Application.new end it 'returns path relative to the provided current_resource' do current_resource = instance_double('Middleman::Sitemap::Resource', destination_path: 'a-path/index.html', path: 'a-path/index.html') expect(Middleman::Util.asset_url(@mm, 'blank.gif', 'images', current_resource: current_resource, relative: true)).to eq '../images/blank.gif' end context 'when the asset is stored in the same directory as current_resource' do before do Given.file 'source/a-path/index.html', '' Given.file 'source/a-path/blank.gif', '' @mm = Middleman::Application.new end it 'returns path relative to the provided current_resource' do current_resource = @mm.sitemap.by_path('a-path/index.html') expect(Middleman::Util.asset_url(@mm, 'blank.gif', 'images', current_resource: current_resource, relative: true)).to eq 'blank.gif' end end it 'raises error if not given a current_resource' do expect do Middleman::Util.asset_url(@mm, 'blank.gif', 'images', relative: true) end.to raise_error ArgumentError end end it 'returns path if it is already a full path' do expect(Middleman::Util.asset_url(@mm, 'http://example.com')).to eq 'http://example.com' expect(Middleman::Util.asset_url(@mm, 'data:example')).to eq 'data:example' end it "returns a resource url if given a resource's destination path" do Given.fixture 'clean-dir-app' # includes directory indexes extension Given.file 'source/how/about/that.html', '' @mm = Middleman::Application.new expect(Middleman::Util.asset_url(@mm, '/how/about/that/index.html')).to eq '/how/about/that/' end it 'returns a resource url if given a resources path' do Given.fixture 'clean-dir-app' # includes directory indexes extension Given.file 'source/how/about/that.html', '' @mm = Middleman::Application.new expect(Middleman::Util.asset_url(@mm, '/how/about/that.html')).to eq '/how/about/that/' end it 'returns a resource url when asset_hash is on' do Given.fixture 'asset-hash-app' @mm = Middleman::Application.new expect(Middleman::Util.asset_url(@mm, '100px.png', 'images')).to match %r{/images/100px-[a-f0-9]+.png} end end describe '::find_related_files' do after(:each) do Given.cleanup! end before(:each) do Given.fixture 'related-files-app' @mm = Middleman::Application.new end def source_file(path) Pathname(File.expand_path("source/#{path}")) end it 'Finds partials possibly related to ERb files' do related = Middleman::Util.find_related_files(@mm, [source_file('partials/_test.erb')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/index.html.erb') related = Middleman::Util.find_related_files(@mm, [source_file('partials/_test2.haml')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/index.html.erb') end it 'Finds partials possible related to Scss files' do related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/_include4.scss')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/stylesheets/site.css.scss') expect(related).to include File.expand_path('source/stylesheets/include2.css.scss') related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/include2.css.scss')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/stylesheets/site.css.scss') expect(related).not_to include File.expand_path('source/stylesheets/include2.css.scss') related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/include1.css')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/stylesheets/site.css.scss') expect(related).to include File.expand_path('source/stylesheets/include2.css.scss') related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/_include3.sass')]).map { |f| f[:full_path].to_s } expect(related).to include File.expand_path('source/stylesheets/site.css.scss') expect(related).to include File.expand_path('source/stylesheets/include2.css.scss') end end describe '::step_through_extensions' do it 'returns the base name after templating engine extensions are removed' do result = Middleman::Util.step_through_extensions('my_file.html.haml.erb') expect(result).to eq 'my_file.html' end it 'does not loop infinitely when file name is a possible templating engine' do expect do Timeout.timeout(3.0) do result = Middleman::Util.step_through_extensions('markdown.scss') expect(result).to eq 'markdown' end end.not_to raise_error end end end
40.214912
143
0.658196
edfcc94175c0e7be4eb6109e4bcd3e76b4ec29b8
1,076
# frozen_string_literal: true module LeetCode # 150. Evaluate Reverse Polish Notation module LC150 # Description: # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # Valid operators are +, -, *, /. # Each operand may be an integer or another expression. # # Examples: # - 1: # Input: ["2", "1", "+", "3", "*"] # Output: 9 # # - 2: # Input: ["4", "13", "5", "/", "+"] # Output: 5 # # @param tokens {Array<String>} # @return {Integer} def eval_rpn(tokens) stack = [] tokens.each { |token| case token when "*" stack.push(stack.pop * stack.pop) when "/" right = stack.pop left = stack.pop stack.push((left / right.to_f).to_i) when "+" stack.push(stack.pop + stack.pop) when "-" right = stack.pop left = stack.pop stack.push(left - right) else stack.push(token.to_i) end } stack.pop end end end
22.416667
80
0.502788
ede96e38e7e070311424887cf40c2dc8dbc4b847
3,999
#============================================================================== # ** Scene_Character #------------------------------------------------------------------------------ # Esta classe lida com cena de seleção e criação de personagens. #------------------------------------------------------------------------------ # Autor: Valentine #============================================================================== class Scene_Character < Scene_Base attr_reader :config_icon, :loading_bar def start super # Reseta o gráfico do cursor se retornou da cena do mapa $cursor.sprite_index = Enums::Cursor::NONE SceneManager.clear Graphics.freeze create_background create_all_windows @loading_count = 0 end def terminate super dispose_background end def create_background @sprite1 = Sprite.new @sprite2 = Sprite.new @sprite2.bitmap = Cache.title2($data_system.title2_name) center_sprite(@sprite2) end def refresh_sprite1 @sprite1.bitmap.dispose if @sprite1.bitmap @sprite1.bitmap = Bitmap.new(Graphics.width, Graphics.height) bitmap = Cache.title1('Title2') @sprite1.bitmap.stretch_blt(@sprite1.bitmap.rect, bitmap, bitmap.rect) center_sprite(@sprite1) end def change_background(title) bitmap = Cache.title1(title) @sprite1.bitmap.clear @sprite1.bitmap.stretch_blt(@sprite1.bitmap.rect, bitmap, bitmap.rect) end def dispose_background @sprite1.bitmap.dispose @sprite1.dispose @sprite2.bitmap.dispose @sprite2.dispose end def center_sprite(sprite) sprite.ox = sprite.bitmap.width / 2 sprite.oy = sprite.bitmap.height / 2 sprite.x = Graphics.width / 2 sprite.y = Graphics.height / 2 end def create_all_windows $windows = {} $windows[:vip_time] = Window_VIPTime.new $windows[:create_char] = Window_CreateChar.new # A Window_Password é instanciada logo para que #a sua caixa de texto fique ativa ao clicar no botão #Apagar da janela de seleção de personagens, que é #instanciada em seguida $windows[:password] = Window_Password.new $windows[:use_char] = Window_UseChar.new $windows[:alert] = Window_Alert.new $windows[:config] = Window_Config.new @config_icon = Icon.new(nil, 0, 0, Configs::CONFIG_ICON, Vocab::Configs) { $windows[:config].trigger } @loading_bar = Progress_Bar.new(nil, 0, 0, Graphics.width - 100, 100) @loading_bar.visible = false adjust_windows_position end def adjust_windows_position $windows[:vip_time].x = $windows[:vip_time].adjust_x $windows[:vip_time].y = $windows[:vip_time].adjust_y $windows[:create_char].x = $windows[:create_char].adjust_x $windows[:create_char].y = $windows[:create_char].adjust_y $windows[:use_char].x = $windows[:use_char].adjust_x $windows[:use_char].y = $windows[:use_char].adjust_y $windows[:alert].x = $windows[:alert].adjust_x $windows[:password].x = $windows[:password].adjust_x $windows[:config].x = $windows[:config].adjust_x @config_icon.x = Graphics.width - 48 @config_icon.y = Graphics.height - 58 # Primeiro recria a barra de carregamento, depois #define as coordenadas x e y @loading_bar.width = Graphics.width - 100 @loading_bar.x = (Graphics.width - @loading_bar.width) / 2 @loading_bar.y = Graphics.height - 100 refresh_sprite1 end def update_all_windows super @config_icon.update @loading_bar.update update_loading end def update_loading return unless @loading_bar.visible return if @loading_bar.index == 100 @loading_count += 1 if @loading_count >= Configs::LOADING_TIME / 2.5 @loading_bar.index += 1 @loading_bar.text = "#{@loading_bar.index}%" @loading_count = 0 end $network.send_use_actor($actor_id) if @loading_bar.index == 100 end def dispose_all_windows super @config_icon.dispose @loading_bar.dispose end end
31.242188
106
0.63866
b957158b478d0ac08ecf8fd4f314ecc1aeaf82a0
2,613
Gem::Specification.new do |s| s.name = 'wice_grid' s.version = '4.1.0' s.authors = ['Yuri Leikind and contributors'] s.email = ['[email protected]'] s.homepage = 'https://github.com/patricklindsay/wice_grid' s.summary = 'A Rails grid plugin to quickly create grids with sorting, pagination, and filters.' s.description = 'A Rails grid plugin to create grids with sorting, pagination, and filters generated automatically based on column types. ' \ 'The contents of the cell are up for the developer, just like one does when rendering a collection via a simple table. ' \ 'WiceGrid automates implementation of filters, ordering, paginations, CSV export, and so on. ' \ 'Ruby blocks provide an elegant means for this.' s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) s.license = 'MIT' s.require_paths = ['lib'] s.date = '2018-11-28' s.add_dependency 'rails', '>= 5.2' s.add_dependency 'kaminari', ['~> 1.2.1'] s.add_dependency 'coffee-rails', ['> 3.2'] s.add_development_dependency('rake', '~> 10.1') s.add_development_dependency('byebug') s.add_development_dependency('appraisal') s.add_development_dependency('rspec', '~> 3.6.0') s.add_development_dependency('rspec-rails', '~> 3.6.0') s.add_development_dependency('shoulda-matchers', '2.8.0') s.add_development_dependency('capybara', '~> 2.2.0') s.add_development_dependency('faker', '~> 1.8.7') s.add_development_dependency('poltergeist', '~> 1.9.0') s.add_development_dependency('capybara-screenshot', '~> 1.0.11') s.add_development_dependency('selenium-webdriver', '~> 2.51.0') # Required by the test app. s.add_development_dependency('haml', '~> 5.0.4') s.add_development_dependency('coderay', '~> 1.1.0') s.add_development_dependency('jquery-rails', '~> 4.3.3') s.add_development_dependency('jquery-ui-rails', '~> 5.0.5') s.add_development_dependency('jquery-ui-themes', '~> 0.0.11') s.add_development_dependency('sass-rails', '>= 3.2') s.add_development_dependency('bootstrap-sass', '3.1.1.1') s.add_development_dependency('font-awesome-sass', '4.4.0') s.add_development_dependency('turbolinks', '~> 5.1.1') s.add_development_dependency('therubyracer') s.add_development_dependency('bundler', '~> 1.3') s.add_development_dependency('simplecov', '~> 0.7') s.add_development_dependency('sqlite3', '~> 1.3') s.add_development_dependency('yard', '~> 0.8') s.add_development_dependency('inch', '~> 0.6.4') s.add_development_dependency('rdoc', '~> 4.2.0') end
47.509091
145
0.68274
18c352490301e3bdb4a73785e622f4a839df3c1c
1,620
# # Be sure to run `pod lib lint HFSuperImages.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 = 'HFSuperImages' s.version = '0.1.0' s.summary = 'A Quick course for cocoaPods from Lynda.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/ksrini73/HFSuperImages' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'ksrini73' => '[email protected]' } s.source = { :git => 'https://github.com/ksrini73/HFSuperImages.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'HFSuperImages/Classes/**/*' # s.resource_bundles = { # 'HFSuperImages' => ['HFSuperImages/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
37.674419
106
0.641975
0139caf8905f185a0d2d7029455bdaa232a8e546
1,216
module TextFilters include ActionView::Helpers::DateHelper include ActionView::Helpers::TextHelper def markdown(text) RDiscount.new(text).to_html end def shorten(input, words = 15, truncate_string = "…") if input.nil? return "" end wordlist = input.split(/ /).reject{ |s| s == "" } l = words.to_i - 1 l = 0 if l < 0 shortened_string = wordlist.length > l ? wordlist[0..l].join(" ") : input shortened_string = close_tags( shortened_string ).strip shortened_string += truncate_string if wordlist.length > l shortened_string end def pluralized(count, singular, plural = nil) pluralize(count.to_i, singular, plural) end def fuzzy_time(date) date = DateTime.parse(date) time_ago_in_words(date).to_s + " ago" end def word_count(text) (text.split(/[^a-zA-Z]/).join(' ').size / 4.5).round end private def close_tags(text) open_tags = [] text.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| open_tags.unshift(t) } text.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| open_tags.slice!(open_tags.index(t)) } open_tags.each {|t| text += "</#{t}>" } text end end
27.022222
94
0.585526
f7e06ae8f06cdc6859fb915461b009a0cc285550
192
module EnjuTrunk class Engine < ::Rails::Engine config.generators do |g| g.test_framework :rspec g.fixture_replacement :factory_girl, dir: 'spec/factories' end end end
21.333333
64
0.692708
b965a6732b683e6c866b343e16192836f87929c8
1,865
# encoding: utf-8 # This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # /spec/fixtures/responses/whois.domainregistry.ie/property_nameservers_with_ip.expected # # and regenerate the tests with the following rake task # # $ rake genspec:parsers # require 'spec_helper' require 'whois/record/parser/whois.domainregistry.ie.rb' describe Whois::Record::Parser::WhoisDomainregistryIe, "property_nameservers_with_ip.expected" do before(:each) do file = fixture("responses", "whois.domainregistry.ie/property_nameservers_with_ip.txt") part = Whois::Record::Part.new(:body => File.read(file)) @parser = klass.new(part) end context "#nameservers" do it do @parser.nameservers.should be_a(Array) @parser.nameservers.should have(6).items @parser.nameservers[0].should be_a(_nameserver) @parser.nameservers[0].name.should == "ns1.dns.ie" @parser.nameservers[0].ipv4.should == "208.94.148.4" @parser.nameservers[1].should be_a(_nameserver) @parser.nameservers[1].name.should == "ns2.dns.ie" @parser.nameservers[1].ipv4.should == "208.80.124.4" @parser.nameservers[2].should be_a(_nameserver) @parser.nameservers[2].name.should == "ns3.dns.ie" @parser.nameservers[2].ipv4.should == "208.80.126.4" @parser.nameservers[3].should be_a(_nameserver) @parser.nameservers[3].name.should == "ns4.dns.ie" @parser.nameservers[3].ipv4.should == "208.80.125.4" @parser.nameservers[4].should be_a(_nameserver) @parser.nameservers[4].name.should == "ns5.dns.ie" @parser.nameservers[4].ipv4.should == "208.80.127.4" @parser.nameservers[5].should be_a(_nameserver) @parser.nameservers[5].name.should == "ns6.dns.ie" @parser.nameservers[5].ipv4.should == "208.94.149.4" end end end
38.061224
97
0.694906
5d3b3d51d0ee71dbeef3cc28e0bbf600add37805
1,942
require "set" require "../utils" def load_data(input_file) lines = File.read(input_file).strip.split("\n") lines.map { |a| a.chars } end def enumerate_cuke_map(cukemap, &fn) e = Enumerator.new do |yielder| cukemap.each_with_index do |row, i| row.each_with_index do |x, j| yielder << [x, i, j] end end end return e unless fn e.each(&fn) end # modulus is 1-based so we need to account for that in zero-based indexes def index_mod(base, x) ((x + 1) % base) - 1 end def identify_east_moves(cukemap) moves = [] enumerate_cuke_map(cukemap) do |x, i, j| nextj = index_mod(cukemap[0].length, j + 1) if x == ">" && cukemap[i][nextj] == "." moves << [i, j] end end moves end def identify_south_moves(cukemap) moves = [] enumerate_cuke_map(cukemap) do |x, i, j| nexti = index_mod(cukemap.length, i + 1) if x == "v" && cukemap[nexti][j] == "." moves << [i, j] end end moves end def execute_east_moves(cukemap, moves) moves.each do |i, j| nextj = index_mod(cukemap[0].length, j + 1) cukemap[i][j] = "." cukemap[i][nextj] = ">" end cukemap end def execute_south_moves(cukemap, moves) moves.each do |i, j| nexti = index_mod(cukemap.length, i + 1) cukemap[i][j] = "." cukemap[nexti][j] = "v" end cukemap end def run_step(cukemap) emoves = identify_east_moves(cukemap) cukemap = execute_east_moves(cukemap, emoves) smoves = identify_south_moves(cukemap) cukemap = execute_south_moves(cukemap, smoves) [cukemap, emoves.length + smoves.length] end def simulate(cukemap) steps = 1 loop do cukemap, move_count = run_step(cukemap) if move_count == 0 # || steps > 10 return steps end steps += 1 end end def part1(input) simulate(input) end def main # input_file = "inputSample.txt" input_file = "input.txt" print "Part1 Answer: ", part1(load_data(input_file)), "\n" end main
19.816327
73
0.639032