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
7aaf419d7ba1c1ec0443d2bdab09099c0cf873fc
822
class TextField < FormGroup def initialize(form, attribute, options) @input_data = options.fetch :input_data, nil @input_class = options.fetch :input_class, nil super end private def content_body(inner_body) labelled_text_field + inner_body end def input_options @input_options ||= {}.tap { |opts| opts[:class] = @input_class opts[:data] = @input_data opts[:maxlength] = max_length }.compact end def labelled_text_field [label, value].join("\n").html_safe end def value f.text_field attribute, input_options end def max_length if validator = validators.detect{ |x| x.is_a?(ActiveModel::Validations::LengthValidator) } validator.options[:maximum] end end def validators f.object.class.validators_on attribute end end
20.04878
94
0.687348
5dbb818455a49e980d48b2a1f6672f4f9f9fb6a9
2,057
require 'date' require_relative "../lib/blogish" describe Blogish do before :each do Blogish.stub!(:entries).and_return(['2013-02-03_hello-world.mkd', '2013-02-05_an-example-post.mkd', '2013-02-04_another-example-post.mkd']) File.stub!(:read).with('views/blog/2013-02-03_hello-world.mkd').and_return("Hello World\n---\nThis is an introduction.\n\nLorem ipsum dolor et sans.") File.stub!(:read).with('views/blog/2013-02-05_an-example-post.mkd').and_return("An Example Post\n---\nLorem ipsum dolor et sans.") File.stub!(:read).with('views/blog/2013-02-04_another-example-post.mkd').and_return("Another Example Post\n---\nLorem ipsum dolor et sans.") end describe "#fetch" do context "when the slug is invalid" do it "should return nil" do Blogish.fetch('an-invalid-slug').should be nil end end context "when the slug is valid" do it "should return a hash of post information" do Blogish.fetch('hello-world').should be_a_kind_of Hash end it "should contain the title" do Blogish.fetch('hello-world')[:title].should eql 'Hello World' end it "should contain the date" do Blogish.fetch('hello-world')[:date].to_s.should eql '2013-02-03' end it "should contain the slug" do Blogish.fetch('hello-world')[:slug].should eql 'hello-world' end it "should contain the body as html" do Blogish.fetch('hello-world')[:body].should eql "<p>This is an introduction.</p>\n\n<p>Lorem ipsum dolor et sans.</p>" end it "should contain the introductory paragraph as html" do Blogish.fetch('hello-world')[:intro].should eql "<p>This is an introduction.</p>" end end end describe "#fetch_all" do it "should return all entries" do Blogish.fetch_all.size.should eql 3 end it "should order the entries most recent first" do dates = Blogish.fetch_all.map {|x| x[:date].to_s } dates.should eql ["2013-02-05", "2013-02-04", "2013-02-03"] end end end
30.701493
154
0.657754
e23360ad3702b008915a0111b2fc108c814a24b3
6,882
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a route file to make sure all auto-generated routes have corresponding actions in controller. # # See the best practice details here https://rails-bestpractices.com/posts/2011/08/19/restrict-auto-generated-routes/ # # Implementation: # # Review process: # check all resources and resource method calls, # compare the generated routes and corresponding actions in controller, # if there is a route generated, but there is not action in that controller, # then you should restrict your routes. class RestrictAutoGeneratedRoutesReview < Review interesting_nodes :command, :command_call, :method_add_block interesting_files ROUTE_FILES url 'https://rails-bestpractices.com/posts/2011/08/19/restrict-auto-generated-routes/' def resource_methods if Prepares.configs['config.api_only'] %w[show create update destroy] else %w[show new create edit update destroy] end end def resources_methods resource_methods + ['index'] end def initialize(options = {}) super(options) @namespaces = [] @resource_controllers = [] end # check if the generated routes have the corresponding actions in controller for rails routes. add_callback :start_command, :start_command_call do |node| if node.message.to_s == 'resources' if (mod = module_option(node)) @namespaces << mod end check_resources(node) @resource_controllers << node.arguments.all.first.to_s elsif node.message.to_s == 'resource' check_resource(node) @resource_controllers << node.arguments.all.first.to_s end end add_callback :end_command do |node| if node.message.to_s == 'resources' @resource_controllers.pop @namespaces.pop if module_option(node) elsif node.message.to_s == 'resource' @resource_controllers.pop end end # remember the namespace. add_callback :start_method_add_block do |node| case node.message.to_s when 'namespace' @namespaces << node.arguments.all.first.to_s if check_method_add_block?(node) when 'resources', 'resource' @resource_controllers << node.arguments.all.first.to_s if check_method_add_block?(node) when 'scope' if check_method_add_block?(node) && (mod = module_option(node)) @namespaces << mod end end end # end of namespace call. add_callback :end_method_add_block do |node| if check_method_add_block?(node) case node.message.to_s when 'namespace' @namespaces.pop when 'resources', 'resource' @resource_controllers.pop when 'scope' if check_method_add_block?(node) && module_option(node) @namespaces.pop end end end end def check_method_add_block?(node) node[1].sexp_type == :command || (node[1].sexp_type == :command_call && node.receiver.to_s != 'map') end private # check resources call, if the routes generated by resources does not exist in the controller. def check_resources(node) _check(node, resources_methods) end # check resource call, if the routes generated by resources does not exist in the controller. def check_resource(node) _check(node, resource_methods) end # get the controller name. def controller_name(node) if option_with_hash(node) option_node = node.arguments.all[1] if hash_key_exist?(option_node, 'controller') name = option_node.hash_value('controller').to_s else name = node.arguments.all.first.to_s.gsub('::', '').tableize end else name = node.arguments.all.first.to_s.gsub('::', '').tableize end namespaced_class_name(name) end # get the class name with namespace. def namespaced_class_name(name) class_name = "#{name.split('/').map(&:camelize).join('::')}Controller" if @namespaces.empty? class_name else @namespaces.map { |namespace| "#{namespace.camelize}::" }.join('') + class_name end end def _check(node, methods) controller_name = controller_name(node) return unless Prepares.controllers.include? controller_name _methods = _methods(node, methods) unless _methods.all? { |meth| Prepares.controller_methods.has_method?(controller_name, meth) } prepared_method_names = Prepares.controller_methods.get_methods(controller_name).map(&:method_name) only_methods = (_methods & prepared_method_names).map { |meth| ":#{meth}" } routes_message = if only_methods.size > 3 "except: [#{(methods.map { |meth| ':' + meth } - only_methods).join(', ')}]" else "only: [#{only_methods.join(', ')}]" end add_error "restrict auto-generated routes #{friendly_route_name(node)} (#{routes_message})" end end def _methods(node, methods) if option_with_hash(node) option_node = node.arguments.all[1] if hash_key_exist?(option_node, 'only') option_node.hash_value('only').to_s == 'none' ? [] : Array(option_node.hash_value('only').to_object) elsif hash_key_exist?(option_node, 'except') if option_node.hash_value('except').to_s == 'all' [] else (methods - Array(option_node.hash_value('except').to_object)) end else methods end else methods end end def module_option(node) option_node = node.arguments[1].last if option_node && option_node.sexp_type == :bare_assoc_hash && hash_key_exist?(option_node, 'module') option_node.hash_value('module').to_s end end def option_with_hash(node) node.arguments.all.size > 1 && node.arguments.all[1].sexp_type == :bare_assoc_hash end def hash_key_exist?(node, key) node.hash_keys && node.hash_keys.include?(key) end def friendly_route_name(node) if @resource_controllers.last == node.arguments.to_s [@namespaces.join('/'), @resource_controllers.join('/')].delete_if(&:blank?).join('/') else [@namespaces.join('/'), @resource_controllers.join('/'), node.arguments.to_s].delete_if(&:blank?).join('/') end end end end end
35.658031
121
0.611305
03f15766a35ee0a250e0d6cd9d68a439adb1d9b0
450
# frozen_string_literal: true class Category < ActiveRecord::Base mount_uploader :category_logo, CategoryLogoUploader enum language: { English: 0, Español: 1 , Italiano: 2, Tagalog: 3 } has_and_belongs_to_many :recommended_feeds def self.current_language language = Hash.new language = { en: "English", es: "Español", it: "Italiano", tl: "Tagalog"} @current_language = language[I18n.locale] return @current_language end end
21.428571
74
0.735556
91468e0157a23176dedf78d88dd8b9834075ab00
7,283
# frozen_string_literal: true # EffectiveMembershipsCategory # # Mark your category model with effective_memberships_category to get all the includes module EffectiveMembershipsCategory extend ActiveSupport::Concern module Base def effective_memberships_category include ::EffectiveMembershipsCategory end end module ClassMethods def effective_memberships_category?; true; end def category_types ['Individual', 'Organization'] end def categories [] end end included do log_changes(except: :memberships) if respond_to?(:log_changes) # rich_text_body - Used by the select step has_many_rich_texts # rich_text_applicant_all_steps_content # rich_text_applicant_start_content # rich_text_applicant_select_content # rich_text_applicant_select_content has_many :membership_categories, class_name: 'Effective::MembershipCategory', as: :category effective_resource do category_type :string title :string category :string position :integer # Applicants can_apply_new :boolean can_apply_existing :boolean can_apply_restricted :boolean can_apply_restricted_ids :text applicant_fee :integer applicant_wizard_steps :text min_applicant_educations :integer min_applicant_experiences_months :integer min_applicant_references :integer min_applicant_courses :integer min_applicant_files :integer # Applicant Reviews min_applicant_reviews :integer applicant_review_wizard_steps :text # Prorated Fees prorated_jan :integer prorated_feb :integer prorated_mar :integer prorated_apr :integer prorated_may :integer prorated_jun :integer prorated_jul :integer prorated_aug :integer prorated_sep :integer prorated_oct :integer prorated_nov :integer prorated_dec :integer # Fee Payments fee_payment_wizard_steps :text # Renewals create_renewal_fees :boolean renewal_fee :integer create_late_fees :boolean late_fee :integer create_bad_standing :boolean # Pricing qb_item_name :string tax_exempt :boolean timestamps end serialize :can_apply_restricted_ids, Array serialize :applicant_wizard_steps, Array serialize :fee_payment_wizard_steps, Array scope :deep, -> { includes(:rich_texts) } scope :sorted, -> { order(:position) } scope :can_apply, -> { where(can_apply_new: true) .or(where(can_apply_existing: true)) .or(where(can_apply_restricted: true)) } validates :title, presence: true, uniqueness: true validates :category_type, presence: true validates :position, presence: true before_validation do self.applicant_wizard_steps = EffectiveMemberships.Applicant.all_wizard_steps if applicant_wizard_steps.blank? self.applicant_review_wizard_steps = EffectiveMemberships.ApplicantReview.all_wizard_steps if applicant_review_wizard_steps.blank? self.fee_payment_wizard_steps = EffectiveMemberships.FeePayment.all_wizard_steps if fee_payment_wizard_steps.blank? end before_validation do self.position ||= (self.class.pluck(:position).compact.max || -1) + 1 self.category_type ||= self.class.category_types.first end with_options(if: -> { can_apply? }) do validates :can_apply_restricted_ids, presence: true, if: -> { can_apply_restricted? } validates :applicant_fee, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_jan, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_feb, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_mar, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_apr, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_may, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_jun, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_jul, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_aug, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_sep, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_oct, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_nov, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :prorated_dec, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :qb_item_name, presence: true validates :tax_exempt, inclusion: { in: [true, false] } end end # Instance Methods def to_s title.presence || 'New Membership Category' end def can_apply? can_apply_new? || can_apply_existing? || can_apply_restricted? end def individual? category_type == 'Individual' end def organization? category_type == 'Organization' end def prorated_fee(date:) send("prorated_#{date.strftime('%b').downcase}").to_i end def discount_fee(date:) 0 - prorated_fee(date: date) end def can_apply_restricted_ids Array(self[:can_apply_restricted_ids]) - [nil, ''] end def optional_applicant_wizard_steps applicant_wizard_steps - EffectiveMemberships.Applicant.required_wizard_steps end def optional_fee_payment_wizard_steps fee_payment_wizard_steps - EffectiveMemberships.FeePayment.required_wizard_steps end def optional_applicant_review_wizard_steps applicant_review_wizard_steps - EffectiveMemberships.ApplicantReview.required_wizard_steps end def applicant_wizard_steps (Array(self[:applicant_wizard_steps]) - [nil, '']).map(&:to_sym) end def fee_payment_wizard_steps (Array(self[:fee_payment_wizard_steps]) - [nil, '']).map(&:to_sym) end def applicant_review_wizard_steps (Array(self[:applicant_review_wizard_steps]) - [nil, '']).map(&:to_sym) end def applicant_wizard_steps_collection wizard_steps = EffectiveMemberships.Applicant.wizard_steps_hash required_steps = EffectiveMemberships.Applicant.required_wizard_steps wizard_steps.map do |step, title| [title, step, 'disabled' => required_steps.include?(step)] end end def fee_payment_wizard_steps_collection wizard_steps = EffectiveMemberships.FeePayment.wizard_steps_hash required_steps = EffectiveMemberships.FeePayment.required_wizard_steps wizard_steps.map do |step, title| [title, step, 'disabled' => required_steps.include?(step)] end end def applicant_fee_qb_item_name 'Applicant' end def applicant_fee_tax_exempt tax_exempt end def stamp_fee 0 end def stamp_fee_qb_item_name qb_item_name end def stamp_fee_tax_exempt tax_exempt end end
29.971193
136
0.705753
4a95d283f83a68f5439f7ee4b34e27c8f6774d74
220
Sequel.migration do up do alter_table :data_imports do add_column :original_url, :text, default: '' end end down do alter_table :data_imports do drop_column :original_url end end end
15.714286
50
0.672727
080fdeb945005a81c7ac95d1b218230b7a5b1e24
290
class School::BeforeCanOrderController < School::ChromebooksController def edit @chromebook_information_form = ChromebookInformationForm.new( school: impersonated_or_current_user.school, ) end private def after_updated_redirect_location home_school_path end end
20.714286
70
0.793103
bbe053c39cf31ad1d838f2d52f16a35d16855a8f
2,344
#-- # Copyright (c) 2009 Ryan Grove <[email protected]> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of this project nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #++ module Thoth class TagApiController < Controller map '/api/tag' layout nil # Returns a JSON array of existing tag names and usage counts for tags that # begin with the specified query string. # # ==== Query Parameters # # q:: query string # limit:: (optional) maximum number of tags to return # # ==== Sample Response # # [["foo",15],["foobar",11],["foosball",2]] def suggest error_403 unless auth_key_valid? unless request[:q] error_400('Missing required parameter: q') end query = request[:q].lstrip limit = request[:limit] ? request[:limit].to_i : 1000 response['Content-Type'] = 'application/json' JSON.generate(Tag.suggest(query, limit)) end end end
39.066667
80
0.71971
01fea1e13efb6dd520b35a7e3e863f44f070058c
882
require 'rails_helper' RSpec.describe AvatarHelper do describe '#gravatar_url' do it "returns an https URL to the gravatar image" do expect(helper.gravatar_url('[email protected]', 128)) .to eq 'https://gravatar.com/avatar/2caa5cfcd25eb9cf3371e5dc6adc8ec9.png?s=128' end end describe '#avatar_for' do let(:user) { User.new(email: '[email protected]') } it "returns a gravatar link with an image" do expect(helper.avatar_for(user)) .to include(user.email) .and include('<img ') .and include(' src="https://gravatar.com/avatar/') .and include('.png?s=32') end it "accepts an image size type" do expect(helper.avatar_for(user, :big)) .to include(user.email) .and include('<img ') .and include(' src="https://gravatar.com/avatar/') .and include('.png?s=64') end end end
28.451613
87
0.62585
61d4558c4fa053f31f32fbaaa2d02d2935afac73
6,734
# frozen_string_literal: true require 'test_helper' class Micro::Authorization::ModelTest < Minitest::Test require 'ostruct' def setup @user = OpenStruct.new(id: 1) @role_permissions = { 'visit' => {'any' => true}, 'export' => {'except' => ['sales', 'foo']} } end def test_permissions authorization = Micro::Authorization::Model.build( permissions: @role_permissions, context: { user: @user, to_permit: ['sales', 'index'] # Rails like [controller_name, action_name] } ) assert authorization.permissions.to?('visit') refute authorization.permissions.to?('export') end def test_multiple_permissions authorization = Micro::Authorization::Model.build( permissions: [ { 'visit' => {'any' => true}, 'export' => {'except' => ['sales', 'foo']} }, { 'visit' => {'any' => false}, 'export' => {'any' => true} } ], context: { user: @user, to_permit: ['dashboard', 'controllers', 'sales', 'index'] # Hanami like } ) assert authorization.permissions.to?('visit') assert authorization.permissions.to?('export') end class FooPolicy < Micro::Authorization::Policy def index? !user.id.nil? end end class BarPolicy < Micro::Authorization::Policy def index? true end end class BazPolicy < Micro::Authorization::Policy def index?(value) value == true end end class NumericSubjectPolicy < Micro::Authorization::Policy def valid? subject.is_a? Numeric end def number subject end end def test_policies_using_the_method_to authorization = Micro::Authorization::Model.build( permissions: {}, context: { user: @user } ) refute authorization.to(:foo).index?, "forbids if the policy wasn't added" refute authorization.to(:bar).index?, "forbids if the policy wasn't added" refute authorization.to(:baz).index?(true), "forbids if the policy wasn't added" refute authorization.to(:numeric_subject).valid?, "forbids if the policy wasn't added" authorization.add_policies(foo: FooPolicy, bar: BarPolicy, baz: BazPolicy) assert authorization.to(:foo).index? assert authorization.to(:bar).index? assert authorization.to(:baz).index?(true) authorization.add_policy(:numeric_subject, NumericSubjectPolicy) assert authorization.to(:numeric_subject, subject: 1).valid? end def test_erro_when_add_policies_with_invalid_data authorization = Micro::Authorization::Model.build( permissions: {}, context: { user: @user } ) err = assert_raises(ArgumentError) do authorization.add_policies([:foo, FooPolicy]) end assert_equal('policies must be a Hash. e.g: `{policy_name: Micro::Authorization::Policy}`', err.message) end def test_default_policy_via_to_method authorization = Micro::Authorization::Model.build( permissions: {}, context: { user: @user } ) assert authorization.to(:foo).class == Micro::Authorization::Policy assert authorization.to(:bar).class == Micro::Authorization::Policy authorization.add_policy(:default, FooPolicy) assert authorization.to(:foo).class == FooPolicy assert authorization.to(:bar).class == FooPolicy end def test_policy_cache_strategy_via_to_method authorization = Micro::Authorization::Model.build( permissions: {}, policies: { bar: BarPolicy }, context: { user: @user } ) assert authorization.to(:bar).index? authorization.to(:bar).class.class_eval do class << self alias_method :original_new, :new end def self.new(*args, **kargs) raise end end assert authorization.to(:bar).index? authorization.to(:bar).class.class_eval do class << self alias_method :new, :original_new end end end def test_default_policy_via_policy_method authorization1 = Micro::Authorization::Model.build( permissions: {}, policies: { foo: FooPolicy }, context: { user: @user } ) assert authorization1.policy.class == authorization1.to(:default).class authorization2 = Micro::Authorization::Model.build( permissions: {}, policies: { default: :foo, foo: FooPolicy }, context: { user: @user } ) assert authorization2.policy.class == authorization2.to(:default).class end def test_that_to_and_policy_method_has_the_same_behavior authorization = Micro::Authorization::Model.build( permissions: {}, policies: { default: FooPolicy, baz: BazPolicy, numeric_subject: NumericSubjectPolicy }, context: { user: @user } ) assert authorization.policy(:baz).class == authorization.to(:baz).class assert authorization.policy(:unknow).class == authorization.to(:unknow).class numeric_subject_policy_a = authorization.to(:numeric_subject, subject: 1) numeric_subject_policy_b = authorization.policy(:numeric_subject, subject: 1) assert numeric_subject_policy_a.number == numeric_subject_policy_b.number end def test_map_context authorization = Micro::Authorization::Model.build( permissions: @role_permissions, policies: { default: FooPolicy, baz: BazPolicy, numeric_subject: NumericSubjectPolicy }, context: { user: @user, permissions: ['dashboard', 'controllers', 'sales', 'index'] } ) new_authorization = authorization.map(context: [ 'dashboard', 'controllers', 'releases', 'index' ]) refute authorization == new_authorization assert new_authorization.permissions.to?('visit') assert new_authorization.permissions.to?('export') end def test_map_policies @user.id = nil authorization = Micro::Authorization::Model.build( permissions: @role_permissions, policies: { default: FooPolicy }, context: { user: @user, to_permit: ['sales'] } ) refute authorization.policy.index? assert authorization.permissions.to_not?('export') new_authorization = authorization.map(policies: { default: BarPolicy }) assert new_authorization.policy.index? assert authorization.permissions.to_not?('export') end def test_map_with_an_invalid_context authorization = Micro::Authorization::Model.build( permissions: @role_permissions, policies: { default: FooPolicy }, context: { user: @user, permissions: ['sales'] } ) err = assert_raises(ArgumentError) { authorization.map({}) } assert_equal('context or policies keywords args must be defined', err.message) end end
27.263158
108
0.66038
1c919f0b57763e728d3c315f3a81f9542b93c209
3,802
require "cases/helper" require 'models/author' require 'models/post' require 'models/comment' require 'models/developer' require 'models/computer' require 'models/project' require 'models/reader' require 'models/person' class ReadOnlyTest < ActiveRecord::TestCase fixtures :authors, :posts, :comments, :developers, :projects, :developers_projects, :people, :readers def test_cant_save_readonly_record dev = Developer.find(1) assert !dev.readonly? dev.readonly! assert dev.readonly? assert_nothing_raised do dev.name = 'Luscious forbidden fruit.' assert !dev.save dev.name = 'Forbidden.' end e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save } assert_equal "Developer is marked as readonly", e.message e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! } assert_equal "Developer is marked as readonly", e.message e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy } assert_equal "Developer is marked as readonly", e.message end def test_find_with_readonly_option Developer.all.each { |d| assert !d.readonly? } Developer.readonly(false).each { |d| assert !d.readonly? } Developer.readonly(true).each { |d| assert d.readonly? } Developer.readonly.each { |d| assert d.readonly? } end def test_find_with_joins_option_does_not_imply_readonly Developer.joins(' ').each { |d| assert_not d.readonly? } Developer.joins(' ').readonly(true).each { |d| assert d.readonly? } Developer.joins(', projects').each { |d| assert_not d.readonly? } Developer.joins(', projects').readonly(true).each { |d| assert d.readonly? } end def test_has_many_find_readonly post = Post.find(1) assert !post.comments.empty? assert !post.comments.any?(&:readonly?) assert !post.comments.to_a.any?(&:readonly?) assert post.comments.readonly(true).all?(&:readonly?) end def test_has_many_with_through_is_not_implicitly_marked_readonly assert people = Post.find(1).people assert !people.any?(&:readonly?) end def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id assert !posts(:welcome).people.find(1).readonly? end def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first assert !posts(:welcome).people.first.readonly? end def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last assert !posts(:welcome).people.last.readonly? end def test_readonly_scoping Post.where('1=1').scoping do assert !Post.find(1).readonly? assert Post.readonly(true).find(1).readonly? assert !Post.readonly(false).find(1).readonly? end Post.joins(' ').scoping do assert !Post.find(1).readonly? assert Post.readonly.find(1).readonly? assert !Post.readonly(false).find(1).readonly? end # Oracle barfs on this because the join includes unqualified and # conflicting column names unless current_adapter?(:OracleAdapter) Post.joins(', developers').scoping do assert_not Post.find(1).readonly? assert Post.readonly.find(1).readonly? assert !Post.readonly(false).find(1).readonly? end end Post.readonly(true).scoping do assert Post.find(1).readonly? assert Post.readonly.find(1).readonly? assert !Post.readonly(false).find(1).readonly? end end def test_association_collection_method_missing_scoping_not_readonly developer = Developer.find(1) project = Post.find(1) assert !developer.projects.all_as_method.first.readonly? assert !developer.projects.all_as_scope.first.readonly? assert !project.comments.all_as_method.first.readonly? assert !project.comments.all_as_scope.first.readonly? end end
31.94958
103
0.723041
ff8a711fd0f83f910baaa1d9435733635e421dad
1,641
module Proteus module Templates class TemplateBinding include Proteus::Helpers::PathHelpers include Proteus::Helpers::StringHelpers def initialize(context:, environment:, module_name:, data: {}, defaults: []) @context = context @environment = environment @module_name = module_name data.each do |key, value| set(key, value) end @defaults = defaults end def set(name, value) instance_variable_set("@#{name}", value) end def get_binding binding end def render_defaults(context, demo: false) @defaults.inject("") do |memo, default| if context.has_key?(default[0]) memo << "#{demo ? "# " : ""}#{default[0]} = \"#{context[default[0]]}\"\n" else memo end end end # return output of partial template # name: symbol (template_name) def render_partial(name:, data:, data_context: nil, force_rendering: true, deep_merge: false, scope_resources: nil) partial = Partial.new( name: name.to_s, context: @context, environment: @environment, module_name: @module_name, data: data, data_context: data_context, force_rendering: force_rendering, deep_merge: deep_merge, terraform_variables: @terraform_variables, scope_resources: scope_resources ) partial.render end def default_true(context, key) return context.has_key?(key) ? context[key] : true end end end end
26.047619
121
0.581353
9167a653e8e8fce1c2505858b8bd98fccf6dfcea
5,578
module Fastlane # This class is responsible for checking the ARGV # to see if the user wants to launch another fastlane # tool or fastlane itself class CLIToolsDistributor class << self def running_version_command? ARGV.include?('-v') || ARGV.include?('--version') end def running_help_command? ARGV.include?('-h') || ARGV.include?('--help') end def take_off before_import_time = Time.now require "fastlane" # this might take a long time if there is no Gemfile :( # We want to avoid printing output other than the version number if we are running `fastlane -v` if Time.now - before_import_time > 3 && !running_version_command? print_slow_fastlane_warning end FastlaneCore::UpdateChecker.start_looking_for_update('fastlane') ARGV.unshift("spaceship") if ARGV.first == "spaceauth" tool_name = ARGV.first ? ARGV.first.downcase : nil tool_name = process_emojis(tool_name) if tool_name && Fastlane::TOOLS.include?(tool_name.to_sym) && !available_lanes.include?(tool_name.to_sym) # Triggering a specific tool # This happens when the users uses things like # # fastlane sigh # fastlane snapshot # require tool_name begin # First, remove the tool's name from the arguments # Since it will be parsed by the `commander` at a later point # and it must not contain the binary name ARGV.shift # Import the CommandsGenerator class, which is used to parse # the user input require File.join(tool_name, "commands_generator") # Call the tool's CommandsGenerator class and let it do its thing commands_generator = Object.const_get(tool_name.fastlane_module)::CommandsGenerator rescue LoadError # This will only happen if the tool we call here, doesn't provide # a CommandsGenerator class yet # When we launch this feature, this should never be the case abort("#{tool_name} can't be called via `fastlane #{tool_name}`, run '#{tool_name}' directly instead".red) end commands_generator.start elsif tool_name == "fastlane-credentials" require 'credentials_manager' ARGV.shift CredentialsManager::CLI.new.run else # Triggering fastlane to call a lane require "fastlane/commands_generator" Fastlane::CommandsGenerator.start end ensure FastlaneCore::UpdateChecker.show_update_status('fastlane', Fastlane::VERSION) end # Since fastlane also supports the rocket and biceps emoji as executable # we need to map those to the appropriate tools def process_emojis(tool_name) return { "🚀" => "fastlane", "💪" => "gym" }[tool_name] || tool_name end def print_slow_fastlane_warning # `BUNDLE_BIN_PATH` is used when the user uses `bundle exec` return if FastlaneCore::Env.truthy?('BUNDLE_BIN_PATH') || FastlaneCore::Env.truthy?('SKIP_SLOW_FASTLANE_WARNING') || FastlaneCore::Helper.contained_fastlane? gemfile_path = PluginManager.new.gemfile_path if gemfile_path # The user has a Gemfile, but fastlane is still slow # Let's tell the user how to use `bundle exec` UI.important "Seems like launching fastlane takes a while" UI.important "fastlane detected a Gemfile in this directory" UI.important "however it seems like you don't use `bundle exec`" UI.important "to launch fastlane faster, please use" UI.message "" UI.command "bundle exec fastlane #{ARGV.join(' ')}" else # fastlane is slow and there is no Gemfile # Let's tell the user how to use `gem cleanup` and how to # start using a Gemfile UI.important "Seems like launching fastlane takes a while - please run" UI.message "" UI.command "[sudo] gem cleanup" UI.message "" UI.important "to uninstall outdated gems and make fastlane launch faster" UI.important "Alternatively it's recommended to start using a Gemfile to lock your dependencies" UI.important "To get started with a Gemfile, run" UI.message "" UI.command "bundle init" UI.command "echo 'gem \"fastlane\"' >> Gemfile" UI.command "bundle install" UI.message "" UI.important "After creating the Gemfile and Gemfile.lock, commit those files into version control" end UI.important "For more information, check out https://guides.cocoapods.org/using/a-gemfile.html" sleep 1 end # Returns an array of symbols for the available lanes for the Fastfile # This doesn't actually use the Fastfile parser, but only # the available lanes. This way it's much faster, which # is very important in this case, since it will be executed # every time one of the tools is launched # Use this only if performance is :key: def available_lanes fastfile_path = FastlaneCore::FastlaneFolder.fastfile_path return [] if fastfile_path.nil? output = `cat #{fastfile_path.shellescape} | grep \"^\s*lane \:\" | awk -F ':' '{print $2}' | awk -F ' ' '{print $1}'` return output.strip.split(" ").collect(&:to_sym) end end end end
41.93985
165
0.635174
87b568a48e7509e23f6f9e3af85c29970bf88d9b
3,176
require 'spec_helper' describe Forem::FormattingHelper do describe "as_formatted_html(text)" do let(:raw_html) {"<p>html</p>"} let(:text) {'three blind mice'} before { Forem.formatter = nil } describe "unsafe html" do subject { helper.as_formatted_html("<script>alert('HELLO')</script> LOL") } it "is escaped" do expect(subject).to eq("alert('HELLO') LOL") end it {is_expected.to be_html_safe} end describe "safe html" do subject { helper.as_formatted_html(raw_html.html_safe) } specify "is not escaped" do expect(subject).to eq("<p>html</p>") end it {is_expected.to be_html_safe} end end describe "as_quoted_text" do let(:raw_html) {"<p>html</p>"} describe "default formatter" do before { Forem.formatter = nil } describe "unsafe html" do subject { helper.as_quoted_text(raw_html) } it "is escaped" do expect(subject).to eq("<blockquote>" + ERB::Util.h(raw_html) + "</blockquote>\n\n") end it {is_expected.to be_html_safe} end describe "safe html" do subject { helper.as_quoted_text(raw_html.html_safe) } specify "is not escaped" do expect(subject).to eq("<blockquote>" + raw_html + "</blockquote>\n\n") end it {is_expected.to be_html_safe} end end describe "Markdown" do let(:markdown) { "**strong text**" } before { # MRI-specific C-extention tests if Forem::Platform.mri? Forem.formatter = Forem::Formatters::Redcarpet else Forem.formatter = Forem::Formatters::Kramdown end } describe "uses <blockquote> if no blockquote method" do subject { helper.as_quoted_text(markdown) } before { allow(Forem.formatter).to receive('respond_to?').with(:blockquote).and_return(false) } it "wraps the content in blockquotes" do expect(subject).to eq("<blockquote>#{markdown}</blockquote>\n\n") end it {is_expected.to be_html_safe} end describe "uses formatter quoting method if exists" do subject { helper.as_quoted_text(raw_html) } before do allow(Forem.formatter).to receive('respond_to?').with(:blockquote).and_return(true) allow(Forem.formatter).to receive('respond_to?').with(:sanitize).and_return(false) allow(Forem.formatter).to receive(:blockquote).and_return("> #{markdown}") end it "quotes the original content" do expect(subject).to eq("> #{markdown}") end it {is_expected.to be_html_safe} end describe "uses formatter sanitize method if exists" do subject { helper.as_formatted_html(markdown) } before { allow(Forem.formatter).to receive('respond_to?').with(:blockquote).and_return(false) allow(Forem.formatter).to receive('respond_to?').with(:sanitize).and_return(true) allow(Forem.formatter).to receive(:sanitize).and_return("sanitized it") } it {expect(subject).to match(%r{\A<p>sanitized it</p>$})} end end end end
32.080808
103
0.621222
7967c58dcee2cc4d2f6e4dd00be00aff4f942e53
446
require 'webmock' require 'gds_api/test_helpers/content_api' require 'gds_api/test_helpers/imminence' RSpec.configure do |config| config.include GdsApi::TestHelpers::ContentApi, :type => :controller config.include GdsApi::TestHelpers::ContentApi, :type => :feature config.before(:each, :type => :feature) do setup_content_api_business_support_schemes_stubs end config.include GdsApi::TestHelpers::Imminence, :type => :feature end
31.857143
70
0.775785
3305bc867524d444f60a28d2c42b770ba74bf55a
315
module Glimmer module DataBinding module ObservableElement def method_missing(method, *args, &block) method_name = method.to_s if method_name.start_with?('on_') handle_observation_request(method_name, block) else super end end end end end
21
56
0.628571
5d456765b423369f14b6f610023728e129866db7
1,207
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-wafv2' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - WAFV2' spec.description = 'Official AWS Ruby gem for AWS WAFV2 (WAFV2). This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-wafv2', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-wafv2/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0') spec.add_dependency('aws-sigv4', '~> 1.1') end
37.71875
111
0.659486
b96b85c79ca73c9a314b8f244c10112099111332
247
# frozen_string_literal: true require 'spec_helper' describe 'fc_mariadb::galera::start' do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) { os_facts } it { is_expected.to compile } end end end
17.642857
40
0.668016
1d1f37566574247b6c45507ab41760b48bd684b0
3,394
require File.join(File.dirname(__FILE__), "spec_helper") class FakeController < Merb::Controller def check_recaptcha return recaptcha_valid?.to_s end end describe "FakeController#check_recaptcha" do def do_request(ssl = false) @response = dispatch_to(FakeController, :check_recaptcha, { :recaptcha_challenge_field => "blabla", :recaptcha_response_field => "blabla" }, { "HTTPS" => ssl ? "on" : "off" }) end def stub_response(body) Net::HTTP.stubs(:post_form).returns stub("Net::HTTPResponse", :body => body) end describe "with non-SSL request" do it "should use non-ssl API server" do cond = proc { |*args| args.first.is_a?(URI::HTTP) && args.first.scheme == "http" && args.first.host == "api-verify.recaptcha.net" } Net::HTTP.expects(:post_form).with(&cond).returns(stub("Net::HTTPResponse", :body => "true")) do_request(false) end end describe "with SSL request" do it "should use non-ssl API server" do cond = proc { |*args| args.first.is_a?(URI::HTTP) && args.first.scheme == "http" && args.first.host == "api-verify.recaptcha.net" } Net::HTTP.expects(:post_form).with(&cond).returns(stub("Net::HTTPResponse", :body => "true")) do_request(true) end end describe "with correct response" do before(:each) do stub_response("true\n") end it "should render 'true'" do do_request @response.should have_selector("*:contains('true')") end it "should not raise any exception" do lambda { do_request }.should_not raise_error end end describe "with incorrect response" do before(:each) do stub_response("false\nincorrect-captcha-sol\n") end it "should render 'false'" do do_request @response.should have_selector("*:contains('false')") end it "should not raise any exception" do lambda { do_request }.should_not raise_error end end describe "with incorrect public key" do before(:each) do stub_response("false\ninvalid-site-public-key\n") end it "should raise Merb::Recaptcha::InvalidSitePublicKey" do lambda { do_request }.should raise_error(Merb::Recaptcha::InvalidSitePublicKey) end end describe "with incorrect private key" do before(:each) do stub_response("false\ninvalid-site-private-key\n") end it "should raise Merb::Recaptcha::InvalidSitePrivateKey" do lambda { do_request }.should raise_error(Merb::Recaptcha::InvalidSitePrivateKey) end end describe "with invalid request cookie" do before(:each) do stub_response("false\ninvalid-request-cookie\n") end it "should raise Merb::Recaptcha::InvalidRequestCookie" do lambda { do_request }.should raise_error(Merb::Recaptcha::InvalidRequestCookie) end end describe "with verify parameters incorrect" do before(:each) do stub_response("false\nverify-params-incorrect\n") end it "should raise Merb::Recaptcha::VerifyParamsIncorrect" do lambda { do_request }.should raise_error(Merb::Recaptcha::VerifyParamsIncorrect) end end describe "with invalid referrer" do before(:each) do stub_response("false\ninvalid-referrer\n") end it "should raise Merb::Recaptcha::IvalidReferrer" do lambda { do_request }.should raise_error(Merb::Recaptcha::InvalidReferrer) end end end
29.77193
179
0.681202
26bec3c1621d22240be3ebfb6e73d0045307162c
541
module TransactionService::Gateway class FreeSettingsAdapter < SettingsAdapter CommunityModel = ::Community def configured?(community_id:, author_id:) true end def tx_process_settings(opts_tx) minimum_commission = Maybe(opts_tx[:unit_price]).map { |price| Money.new(0, price.currency) }.or_else(Money.new(0)) c = CommunityModel.find(opts_tx[:community_id]) {minimum_commission: minimum_commission, commission_from_seller: 0, automatic_confirmation_after_days: 0} end end end
27.05
121
0.719039
bb5651d4813ea406b386e3293482ba12934ac731
702
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "jekyll-new-theme" spec.version = "0.1.0" spec.authors = ["chzos"] spec.email = ["[email protected]"] spec.summary = "TODO: Write a short summary, because Rubygems requires one." spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README)!i) } spec.add_runtime_dependency "jekyll", "~> 3.9" spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency "rake", "~> 12.0" end
35.1
132
0.635328
1d19b85c2c971d361ef23bfc93f12f68d9c755b8
5,403
# random users User.create!( username: "admin", address_line_1: "633 Folsom", address_line_2: "6th Floor", city: "San Francisco", state: "CA", zip: "94107", email: "[email protected]", password: "adminadmin", avatar: "https://pbs.twimg.com/profile_images/2370446440/6e2jwf7ztbr5t1yjq4c5.jpeg", first_name: "Admin", last_name: "Istrator" ) 50.times do User.create!( username: FFaker::Internet.user_name, address_line_1: FFaker::AddressUS.street_address, address_line_2: FFaker::AddressUS.secondary_address, city: FFaker::AddressUS.city, state: FFaker::AddressUS.state_abbr, zip: FFaker::AddressUS.zip_code, email: FFaker::Internet.disposable_email, password: FFaker::Internet.password, avatar: Faker::Avatar.image, first_name: FFaker::Name.first_name, last_name: Faker::Name.last_name ) end #Admin events 5.times do random_size = rand(1..10) Event.create!( public_location: FFaker::Venue.name, address_line_1: FFaker::AddressUS.street_address, address_line_2: FFaker::AddressUS.secondary_address, city: FFaker::AddressUS.city, state: FFaker::AddressUS.state_abbr, zip: FFaker::AddressUS.zip_code, max_size: random_size, time_start: Faker::Time.between(DateTime.now - 1, DateTime.now), time_end: Faker::Time.forward(1), name: FFaker::Company.catch_phrase, description: FFaker::HipsterIpsum.phrase, category: FFaker::Sport.name, approval_required: FFaker::Boolean.sample, host_id: 1, status: FFaker::Boolean.sample ) end # random events 100.times do random_size = rand(1..10) random_user = rand(1..User.count) Event.create!( public_location: FFaker::Venue.name, address_line_1: FFaker::AddressUS.street_address, address_line_2: FFaker::AddressUS.secondary_address, city: FFaker::AddressUS.city, state: FFaker::AddressUS.state_abbr, zip: FFaker::AddressUS.zip_code, max_size: random_size, time_start: Faker::Time.between(DateTime.now - 1, DateTime.now), time_end: Faker::Time.forward(1), name: FFaker::Company.catch_phrase, description: Faker::Hacker.say_something_smart, category: FFaker::Sport.name, approval_required: FFaker::Boolean.sample, host_id: random_user, status: FFaker::Boolean.sample ) end # Admin comments 20.times do random_event = rand(1..Event.count) Comment.create!( event_id: random_event, user_id: 1, body: FFaker::BaconIpsum.phrase, is_private: FFaker::Boolean.sample ) end # random comments (public and private) 200.times do random_event = rand(1..Event.count) random_user = rand(1..User.count) Comment.create!( event_id: random_event, user_id: random_user, body: FFaker::BaconIpsum.phrase, is_private: FFaker::Boolean.sample ) end # random pending rsvps (id # 1-25) 100.times do random_guest = rand(10..User.count) random_event = rand(1..Event.count) new_event = Rsvp.create!( guest_id: random_guest, event_id: random_event, message: Faker::Hacker.say_something_smart, pending: true ) end #Admin pending rsvps 10.times do random_event = rand(1..Event.count) new_event = Rsvp.create!( guest_id: 1, event_id: random_event, message: Faker::Hacker.say_something_smart, pending: true ) end # Admin (not pending) rsvps 10.times do random_guest = rand(10..User.count) random_event = rand(1..Event.count) new_event = Rsvp.create!( guest_id: random_guest, event_id: random_event, message: Faker::Hacker.say_something_smart, pending: false, confirmed: FFaker::Boolean.sample ) end # random not-pending rsvps (true and false; id #26-50) 100.times do random_guest = rand(10..User.count) random_host = rand(1..9) random_event = rand(1..Event.count) new_event = Rsvp.create!( guest_id: random_guest, event_id: random_event, pending: false, message: Faker::Hacker.say_something_smart, confirmed: FFaker::Boolean.sample ) end # random confirmed rsvps (id #51-75) 100.times do random_guest = rand(10..User.count) random_host = rand(1..9) random_event = rand(1..Event.count) new_event = Rsvp.create!( guest_id: random_guest, event_id: random_event, pending: false, message: Faker::Hacker.say_something_smart, confirmed: true ) end # random ratings (from confirmed rsvps) 150.times do count = 1 current_event = Event.find(count) Rating.create!( event_id: count, rating: rand(1.0..5.0), rating_feedback: FFaker::HipsterIpsum.phrase, rater_id: current_event.host.id, ratee_id: current_event.guests.sample.id ) count += 1 end # random ratings (switched roles) 150.times do count = 1 current_event = Event.find(count) Rating.create!( event_id: count, rating: rand(1.0..5.0), rating_feedback: FFaker::HipsterIpsum.phrase, ratee_id: current_event.host.id, rater_id: current_event.guests.sample.id ) count += 1 end
24.898618
92
0.648529
875994cd508788c66e983a4cc3a648bea5469d38
718
require "spec_helper" describe Mongoid::Extensions::Array::DeepCopy do describe "#_deep_copy" do context "when the array hash clonable objects" do let(:one) do "one" end let(:two) do "two" end let(:array) do [ one, two ] end let(:copy) do array._deep_copy end it "clones the array" do copy.should eq(array) end it "returns a new instance" do copy.should_not equal(array) end it "deep copies the first element" do copy.first.should_not equal(one) end it "deep copies the last element" do copy.last.should_not equal(two) end end end end
16.697674
53
0.564067
7a8b1940c2663d3ead76a33193b2b4bb80351484
380
require 'rails_helper' RSpec.shared_examples 'Authable' do describe '#logged_in' do describe 'When logged in' do it { session[:user_id] = 1 expect(subject.logged_in?).to eq(true) } end describe "When logged out" do it { session[:user_id] = nil expect(subject.logged_in?).to eq(false) } end end end
19
47
0.584211
e2a6753a7919dc412ad4145eaa667d2aeb0f7dcc
211
class CreateArtists < ActiveRecord::Migration def change create_table :artists do |t| t.string :name t.string :genre t.integer :age t.string :hometown end end end
19.181818
46
0.606635
1aa2e38e09bb50a7417d34fb3abba0c7d2fdd3b1
320
class AddSuspendedToUsers < ActiveRecord::Migration[4.2] def self.up add_column :users, :suspended_at, :datetime rename_column :accounts, :tall_free_phone, :toll_free_phone end def self.down rename_column :accounts, :toll_free_phone, :tall_free_phone remove_column :users, :suspended_at end end
26.666667
63
0.759375
28bbca9af0d95d27f81a6610503ade91006cacb7
2,879
require_relative 'boot' require 'rails' # Pick the frameworks you want: require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' require 'active_storage/engine' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_mailbox/engine' # require "action_text/engine" require 'action_view/railtie' # require "action_cable/engine" # require "sprockets/railtie" require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Tapp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # Only loads a smaller set of middleware suitable for API only apps. # Middleware like session, flash, cookies can be added back manually. # Skip views, helpers and assets when generating a new resource. config.api_only = true # Set up the the directories where persistent files are stored config.contract_template_dir = ENV.fetch('CONTRACT_TEMPLATE_DIR', '/storage/contract_templates') .presence || '/storage/contract_templates' # This was added to use in the emails that send contract links. config.base_url = ENV.fetch('BASE_URL', 'localhost:3000').presence || 'localhost:3000' config.ta_coordinator_name = ENV.fetch('TA_COORDINATOR_NAME', 'TA Coordinator').presence || 'TA Coordinator' config.ta_coordinator_email = ENV.fetch('TA_COORDINATOR_EMAIL', '[email protected]').presence || '[email protected]' # email configuration email_server = ENV.fetch('EMAIL_SERVER', 'localhost').presence || 'localhost' email_port = ENV.fetch('EMAIL_PORT', 25).presence || 25 config.action_mailer.raise_delivery_errors = true config.action_mailer.default_url_options = { host: '${confit.base_url}' } config.action_mailer.perform_caching = true config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: email_server, port: email_port } # Authorization config.allow_basic_auth = %w[true 1].include?(ENV.fetch('ALLOW_BASIC_AUTH', '').downcase) config.always_admin = ENV.fetch('TAPP_ADMINS', '').split(',').map(&:strip) end end
39.438356
86
0.680792
6a49b25430b34769104969b3d8c2cf5d0dd7d9f6
1,980
require 'active_record' require 'models/status' require 'models/harvest_job' module Stash module Harvester module Models class HarvestedRecord < ActiveRecord::Base belongs_to :harvest_job has_many :indexed_records # 1. find the most recent harvest/index operation for each identifier # (record identifier, *not* database ID), and # 2. of those, find the earliest with index status `FAILED` FIND_OLDEST_FAILED = <<-SQL.freeze SELECT all_records.* FROM (SELECT harvested_records.id, harvested_records.identifier, MAX(harvested_records.timestamp), indexed_records.status FROM harvested_records, indexed_records WHERE harvested_records.id == indexed_records.harvested_record_id GROUP BY identifier ORDER BY timestamp DESC ) AS latest_BY_identifier, harvested_records AS all_records WHERE all_records.id = latest_BY_identifier.id AND latest_BY_identifier.status = #{Status::FAILED} ORDER BY all_records.timestamp LIMIT 1 SQL # @return [HarvestedRecord] the most recent successfully indexed record def self.find_newest_indexed HarvestedRecord .joins(:indexed_records) .where(indexed_records: { status: Status::COMPLETED }) .order(timestamp: :desc) .first end # @return [HarvestedRecord] the oldest record that failed to index and # for which no later corresponding successfully indexed record exists def self.find_oldest_failed HarvestedRecord.find_by_sql(FIND_OLDEST_FAILED).first end end end end end
32.459016
79
0.582828
e9c220dd8365be7e1f590ffcb00ec97cfb99c478
7,598
require 'chef/provisioning/aws_driver/aws_provider' require 'retryable' class Chef::Provider::AwsRouteTable < Chef::Provisioning::AWSDriver::AWSProvider include Chef::Provisioning::AWSDriver::TaggingStrategy::EC2ConvergeTags provides :aws_route_table def action_create route_table = super if !new_resource.routes.nil? update_routes(vpc, route_table, new_resource.ignore_route_targets) end update_virtual_private_gateways(route_table, new_resource.virtual_private_gateways) end protected def create_aws_object options = {} options[:vpc_id] = new_resource.vpc options = AWSResource.lookup_options(options, resource: new_resource) ec2_resource = new_resource.driver.ec2_resource self.vpc = ec2_resource.vpc(options[:vpc_id]) converge_by "create route table #{new_resource.name} in VPC #{new_resource.vpc} (#{vpc.id}) and region #{region}" do route_table = vpc.create_route_table retry_with_backoff(::Aws::EC2::Errors::ServiceError) do route_table.create_tags({ :tags => [ { :key => "Name", :value => new_resource.name } ] }) end route_table end end def update_aws_object(route_table) self.vpc = route_table.vpc if new_resource.vpc desired_vpc_id = Chef::Resource::AwsVpc.get_aws_object_id(new_resource.vpc, resource: new_resource) if vpc.id != desired_vpc_id raise "VPC of route table #{new_resource.to_s} is #{vpc.id}, but desired VPC is #{desired_vpc_id}! The AWS SDK does not support updating the main route table except by creating a new route table." end end end def destroy_aws_object(route_table) converge_by "delete #{new_resource.to_s} in #{region}" do begin route_table.delete rescue ::Aws::EC2::Errors::DependencyViolation raise "#{new_resource.to_s} could not be deleted because it is the main route table for #{route_table.vpc.id} or it is being used by a subnet" end end end private attr_accessor :vpc def update_routes(vpc, route_table, ignore_route_targets = []) # Collect current routes current_routes = {} route_table.routes.each do |route| # Ignore the automatic local route route_target = route.gateway_id || route.instance_id || route.network_interface_id || route.vpc_peering_connection_id next if route_target == 'local' next if ignore_route_targets.find { |target| route_target.match(/#{target}/) } current_routes[route.destination_cidr_block] = route end # Add or replace routes from `routes` new_resource.routes.each do |destination_cidr_block, route_target| options = get_route_target(vpc, route_target) target = options.values.first # If we already have a route to that CIDR block, replace it. if current_routes[destination_cidr_block] current_route = current_routes.delete(destination_cidr_block) current_target = current_route.gateway_id || current_route.instance_id || current_route.network_interface_id || current_route.vpc_peering_connection_id if current_target != target action_handler.perform_action "reroute #{destination_cidr_block} to #{route_target} (#{target}) instead of #{current_target}" do current_route.replace(options) end end else action_handler.perform_action "route #{destination_cidr_block} to #{route_target} (#{target})" do route_table.create_route({ :destination_cidr_block => destination_cidr_block }.merge(options)) end end end # Delete anything that's left (that wasn't replaced) current_routes.values.each do |current_route| current_target = current_route.gateway_id || current_route.instance_id || current_route.network_interface_id || current_route.vpc_peering_connection_id action_handler.perform_action "remove route sending #{current_route.destination_cidr_block} to #{current_target}" do current_route.delete end end end def update_virtual_private_gateways(route_table, gateway_ids) current_propagating_vgw_set = route_table.propagating_vgws # Add propagated routes if gateway_ids gateway_ids.each do |gateway_id| if !current_propagating_vgw_set.reject! { |vgw_set| vgw_set[:gateway_id] == gateway_id } action_handler.perform_action "enable route propagation for route table #{route_table.id} to virtual private gateway #{gateway_id}" do route_table.client.enable_vgw_route_propagation(route_table_id: route_table.id, gateway_id: gateway_id) end end end end # Delete anything that's left if current_propagating_vgw_set current_propagating_vgw_set.each do |vgw_set| action_handler.perform_action "disabling route propagation for route table #{route_table.id} from virtual private gateway #{vgw_set[:gateway_id]}" do route_table.client.disable_vgw_route_propagation(route_table_id: route_table.id, gateway_id: vgw_set[:gateway_id]) end end end end def get_route_target(vpc, route_target) case route_target when :internet_gateway route_target = { internet_gateway: vpc.internet_gateways.first.id } if !route_target[:internet_gateway] raise "VPC #{new_resource.vpc} (#{vpc.id}) does not have an internet gateway to route to! Use `internet_gateway true` on the VPC itself to create one." end when /^igw-[A-Fa-f0-9]{8}$/, Chef::Resource::AwsInternetGateway, AWS::EC2::InternetGateway route_target = { internet_gateway: route_target } when /^eni-[A-Fa-f0-9]{8}$/, Chef::Resource::AwsNetworkInterface, AWS::EC2::NetworkInterface route_target = { network_interface: route_target } when /^pcx-[A-Fa-f0-9]{8}$/, Chef::Resource::AwsVpcPeeringConnection, ::Aws::EC2::VpcPeeringConnection route_target = { vpc_peering_connection: route_target } when /^vgw-[A-Fa-f0-9]{8}$/ route_target = { virtual_private_gateway: route_target } when String, Chef::Resource::AwsInstance route_target = { instance: route_target } when Chef::Resource::Machine route_target = { instance: route_target.name } when AWS::EC2::Instance, ::Aws::EC2::Instance route_target = { instance: route_target.id } when Hash if route_target.size != 1 raise "Route target #{route_target} must have exactly one key, either :internet_gateway, :instance or :network_interface!" end route_target = route_target.dup else raise "Unrecognized route destination #{route_target.inspect}" end updated_route_target = {} route_target.each do |name, value| case name when :instance updated_route_target[:instance_id] = Chef::Resource::AwsInstance.get_aws_object_id(value, resource: new_resource) when :network_interface updated_route_target[:network_interface_id] = Chef::Resource::AwsNetworkInterface.get_aws_object_id(value, resource: new_resource) when :internet_gateway updated_route_target[:gateway_id] = Chef::Resource::AwsInternetGateway.get_aws_object_id(value, resource: new_resource) when :vpc_peering_connection updated_route_target[:vpc_peering_connection_id] = Chef::Resource::AwsVpcPeeringConnection.get_aws_object_id(value, resource: new_resource) when :virtual_private_gateway updated_route_target[:gateway_id] = value end end updated_route_target end end
41.977901
205
0.712688
87e875ac56e4d071e5b6e3d9cc6be6b1660e0a98
934
Pod::Spec.new do |s| s.name = "Sentry" s.version = "6.0.10" s.summary = "Sentry client for cocoa" s.homepage = "https://github.com/getsentry/sentry-cocoa" s.license = "mit" s.authors = "Sentry" s.source = { :git => "https://github.com/getsentry/sentry-cocoa.git", :tag => s.version.to_s } s.ios.deployment_target = "9.0" s.osx.deployment_target = "10.10" s.tvos.deployment_target = "9.0" s.watchos.deployment_target = "2.0" s.module_name = "Sentry" s.requires_arc = true s.frameworks = 'Foundation' s.libraries = 'z', 'c++' s.xcconfig = { 'GCC_ENABLE_CPP_EXCEPTIONS' => 'YES' } s.default_subspecs = ['Core'] s.subspec 'Core' do |sp| sp.source_files = "Sources/Sentry/**/*.{h,m}", "Sources/SentryCrash/**/*.{h,m,mm,c,cpp}" sp.public_header_files = "Sources/Sentry/Public/*.h" end end
27.470588
77
0.574946
873d26df5e1208dc2f0b846350b7507c60f3210b
763
# coding: utf-8 # 外出旅行, 可以有很多方式, 自行车, 自驾, 火车, 飞机 等等, # 如果通过条件判断去计算需要花费的时间或者金钱, 那么代码会类似下面的样子: class Travel def initialize(vehicle, mile) @vehicle = vehicle @mile = mile end def calculate case @vehicle when '自行车' 1 when '自驾' 2 when '火车' 3 when '飞机' 4 end end end # test t = Travel.new('自行车', 1) p t.calculate # 缺点: # 1. 当需要计算新的工具所需要话费的时间的时候 需要不断的改变Travel类 # 2. 工具的计算方式和Travel类耦合 # 3. 不容易扩展组合交通工具的计算 # refactoring class Travel def initialize(vehicle, mile) @vehicle = vehicle @mile = mile end def calculate @vehicle.calculate end end class Bike def calculate 1 end end class Compose def calculate end end # test t = Travel.new(Bike.new, 1) p t.calculate # 职责区分
12.508197
40
0.636959
e2783f6770fc6c3c97f5deb6095eb7459a89410e
6,543
require 'rails_helper' require 'skirmish/factories' require 'json' require 'pp' RSpec.describe GameStateController, :type => :controller do describe 'show' do let(:user) { User.create( email: '[email protected]', password: 'swordfish', password_confirmation: 'swordfish' ) } before do @game = Skirmish::Game.create @game.players = [Skirmish::Factories::Player.make] allow(Skirmish::Game).to receive(:find).and_return(@game) end describe "GET 'show'" do before do allow(user).to receive(:current_game).and_return(@game) sign_in(user) get 'show' end it 'returns http success' do expect(response).to be_success end it 'returns game_state in json' do pattern = { game: { id: Fixnum, winner: wildcard_matcher, players: [ { id: Fixnum, name: String, user_id: wildcard_matcher, gravatar_hash: String, cities: [ { id: Fixnum, name: String, latitude: Float, longitude: Float, population: Fixnum, units: [ {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}, {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}, {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}] }, { id: Fixnum, name: String, latitude: Float, longitude: Float, population: Fixnum, units: [ {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}, {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}, {id: Fixnum, unit_type: String, attack: Fixnum, defense: Fixnum}] }] }] } } expect(response.body).to match_json_expression(pattern) end end describe "GET 'new'", slow: true do let(:user) {User.create( email: '[email protected]', password: 'swordfish', password_confirmation: 'swordfish' )} context 'gets new game state' do before do sign_in(user) get 'new' end it 'returns http success' do expect(response).to be_success end it 'gets a board for logged in user with a new player_id in it' do game_state = JSON.parse(response.body) ids = game_state['game']['players'].map{|player| player['id']} expect(ids).to include(user.players.last.id) end end context 'doesnt get new game state' do it 'returns error if user already in game' do sign_in(user) allow(Skirmish::Game).to receive(:is_user_in_latest_game?).with(user).and_return(true) get 'new' expect(response).to be_forbidden end end end end describe 'skip_turn' do context 'signed in' do it 'skips the current turn for the current player' do game = double(:game, process_turn_if_required: nil) player = double(:player, id: 1, has_skipped?: false, name: 'UberMouse') turn = stub_model(Skirmish::Turn) expect(Skirmish::Turn).to receive(:current_turn_for_game).with(game).and_return(turn) expect(turn.skips).to receive(:create).with(player_id: player.id) expect(ClientNotifier).to receive(:notification).with(String, String) sign_in double(:user, is_in_a_game?: true, current_player: player, current_game: game) get 'skip_turn' end it 'returns 403 if you attempt to skip a turn more than once' do player = double(:player, has_skipped?: true, id: 1) sign_in double(:user, is_in_a_game?: true, current_player: player) expect(ClientNotifier).to receive(:notification).with(String, String, player.id) get 'skip_turn' expect(response.status).to eq(403) end end end describe 'GET new' do before do user = instance_double('User') allow(controller).to receive(:authenticate_user!) { true } allow(controller).to receive(:current_user) { user } end context 'when user is already in the game' do before { allow(Skirmish::Game).to receive(:is_user_in_latest_game?) { true } } it 'returns a forbidden status' do get 'new' expect(response).to be_forbidden end end context 'when user is not already in the game' do before { allow(Skirmish::Game).to receive(:is_user_in_latest_game?) { false } } it 'returns json for the current game' do fake_data = { game_id: 3 } allow(Skirmish::Game).to receive(:join_new_game) { fake_data } get 'new' expect(response.body).to include(fake_data.to_json) end end end describe 'GET show' do let(:user) { instance_double('User') } before do allow(controller).to receive(:authenticate_user!) { true } allow(controller).to receive(:current_user) { user } end context 'when user is already in a game' do before { allow(user).to receive(:is_in_a_game?) { true } } it 'returns json for the current game' do fake_data = { game_id: 3 } allow(user).to receive(:current_game) { fake_data } get 'show' expect(response.body).to include(fake_data.to_json) end end context 'when user is not already in a game' do before { allow(user).to receive(:is_in_a_game?) { false } } it 'returns a forbidden status' do get 'show' expect(response).to be_forbidden end end describe 'GET process_turn' do let(:turn) { double :turn } it "causes the last game's turn to process" do allow(Skirmish::Turn).to receive(:last).and_return(turn) expect(Skirmish::Game).to receive(:process_turn).with(turn) get 'process_turn' end end end end
30.291667
97
0.548067
113e0d96039195f952d0773c18af8a6092f20dcb
2,146
# encoding: utf-8 class Nanoc::DataSources::StaticTest < MiniTest::Unit::TestCase include Nanoc::TestHelpers def new_data_source(params=nil) # Mock site site = Nanoc::Site.new({}) # Create data source data_source = Nanoc::DataSources::Static.new(site, nil, nil, params) # Done data_source end def test_items # Create data source data_source = new_data_source(:prefix => 'foo') # Create sample files FileUtils.mkdir_p('foo') FileUtils.mkdir_p('foo/a/b') File.open('foo/bar.png', 'w') { |io| io.write("random binary data") } File.open('foo/b.c.css', 'w') { |io| io.write("more binary data") } File.open('foo/a/b/c.gif', 'w') { |io| io.write("yet more binary data") } # Get expected and actual output expected_out = [ Nanoc::Item.new( 'foo/bar.png', { :extension => 'png', :filename => 'foo/bar.png' }, '/bar.png/', :binary => true, :mtime => File.mtime('foo/bar.png'), :checksum => Pathname.new('foo/bar.png').checksum ), Nanoc::Item.new( 'foo/b.c.css', { :extension => 'css', :filename => 'foo/b.c.css' }, '/b.c.css/', :binary => true, :mtime => File.mtime('foo/b.c.css'), :checksum => Pathname.new('foo/b.c.css').checksum ), Nanoc::Item.new( 'foo/a/b/c.gif', { :extension => 'gif', :filename => 'foo/a/b/c.gif' }, '/a/b/c.gif/', :binary => true, :mtime => File.mtime('foo/a/b/c.gif'), :checksum => Pathname.new('foo/a/b/c.gif').checksum ) ].sort_by { |i| i.identifier } actual_out = data_source.send(:items).sort_by { |i| i.identifier } (0..expected_out.size-1).each do |i| assert_equal expected_out[i].raw_content, actual_out[i].raw_content, 'content must match' assert_equal expected_out[i].identifier, actual_out[i].identifier, 'identifier must match' assert_equal expected_out[i].mtime, actual_out[i].mtime, 'mtime must match' assert_equal expected_out[i].raw_filename, actual_out[i].raw_filename, 'file paths must match' end end end
32.029851
100
0.590867
01e5a40e1b627ee27fefdba119fe8bd4bae281c7
2,655
class User < ApplicationRecord has_many :microposts, dependent: :destroy has_many :active_relationships, class_name: "Relationship", foreign_key: 'follower_id', dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: 'followed_id', dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: true has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end def authenticated?(attribute, token) digest = self.send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end def forget update_attribute(:remember_digest, nil) end def active update_columns(activated: true, activated_at: Time.zone.now) end def send_activate_email UserMailer.account_activation(self).deliver_now end def create_reset_digest self.reset_token = User.new_token update_columns(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now) end def send_password_reset_email UserMailer.password_reset(self).deliver_now end def password_reset_expired? reset_sent_at < 2.hours.ago end def feed Micropost.where("user_id IN (:following_ids) OR user_id = :user_id", following_ids: following_ids, user_id: id) end def follow(other_user) following << other_user end def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end def following?(other_user) following.include?(other_user) end class << self def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def new_token SecureRandom.urlsafe_base64 end end private def downcase_email self.email = email.downcase end def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
29.5
115
0.73371
18a5834c80c15364edc0f4696b20893c8d1dd8cf
153
require File.expand_path('../../../../spec_helper', __FILE__) describe "Process::Sys.setregid" do it "needs to be reviewed for spec completeness" end
25.5
61
0.718954
7a597ef9c28087ddfe57b6ead0b3c234d388a5e5
1,745
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rails routes". # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # You can have the root of your site routed with "root" root 'home#index' resources :authors resources :papers # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
28.606557
101
0.655587
914a1fe49f15bfbbf9bcfee0d193eb03215ebb0c
366
#!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__)+'/../config/environment') course_id = ARGV[0] @course = Course.find(course_id) exit if !@course #require(File.expand_path("app/models/gradebook_cache.rb")) #begin # CacheUpdater.update_cache(@course.id) #rescue StandardError => error # puts 'AHHHHHHHHHHH' # notify_about_exception(error) #end
21.529412
73
0.756831
bb31bb218cd27c96b45599c08d8ea93856c3ac33
8,599
require 'spec_helper' describe 'cis_hardening::auth::ssh' do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) { os_facts } # Check for default class it { is_expected.to contain_class('cis_hardening::auth::ssh') } # Ensure that Ensure permissions on /etc/ssh/sshd_config are configured - Section 5.2.1 it { is_expected.to contain_file('/etc/ssh/sshd_config').with( 'ensure' => 'file', 'owner' => 'root', 'group' => 'root', 'mode' => '0600', ) } # Ensure permissions on SSH private host key files are configured - Section 5.2.2 it { is_expected.to contain_exec('set_sshprivkey_perms').with( 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', 'command' => "find /etc/ssh -xdev -type f -name 'ssh_host_*_key' -exec chmod u-x,g-wx,o-rwx {} \\;", ) } it { is_expected.to contain_exec('set_sshprivkey_owner').with( 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', 'command' => "find /etc/ssh -xdev -type f -name 'ssh_host_*_key' -exec chown root:ssh_keys {} \\;", ) } # Ensure permissions on SSH public host key files are configured - Section 5.2.3 it { is_expected.to contain_exec('set_sshpubkey_perms').with( 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', 'command' => "find /etc/ssh -xdev -type f -name 'ssh_host_*_key.pub' -exec chmod u-x,go-wx {} \\;", ) } it { is_expected.to contain_exec('set_sshpubkey_owner').with( 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', 'command' => "find /etc/ssh -xdev -type f -name 'ssh_host_*_key.pub' -exec chown root:root {} \\;", ) } # Ensure SSH access is limited - Section 5.2.4 # Currently commented. Up to the discretion of the user as to whether to enable # Ensure that Ensure SSH LogLevel is appropriate - Section 5.2.5 it { is_expected.to contain_file_line('set_ssh_loglevel').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'LogLevel INFO', 'match' => '^LogLevel\ ', ) } # Ensure that Ensure SSH X11 Forwarding is disabled - Section 5.2.6 it { is_expected.to contain_file_line('set_x11_forwarding').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'X11Forwarding no', ) } # Ensure SSH MaxAuthTries is set to 4 or less - Section 5.2.7 it { is_expected.to contain_file_line('set_ssh_maxauthtries').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'MaxAuthTries 4', 'match' => '^MaxAuthTries\ ', ) } # Ensure that Ensure SSH IgnoreRhosts is enabled - Section 5.2.8 it { is_expected.to contain_file_line('set_ssh_ignore_rhosts').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'IgnoreRhosts yes', 'match' => '^IgnoreRhosts\ ', ) } # Ensure that Ensure SSH HostBased Authentication is Disabled - Section 5.2.9 it { is_expected.to contain_file_line('set_hostbasedauth_off').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'HostBasedAuthentication no', 'match' => '^HostBasedAuthentication\ ', ) } # Ensure that Ensure SSH Root Login is Disabled - Section 5.2.10 it { is_expected.to contain_file_line('set_rootlogin_no').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'PermitRootLogin no', 'match' => '^PermitRootLogin\ ', ) } # Ensure that Ensure PermitEmptyPasswords is Disabled - Section 5.2.11 it { is_expected.to contain_file_line('set_emptypasswords_off').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'PermitEmptyPasswords no', 'match' => '^PermitEmptyPasswords\ ', ) } # Ensure that Ensure SSH PermitUserEnvironment is Disabled - Section 5.2.12 it { is_expected.to contain_file_line('set_permituserenv_off').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'PermitUserEnvironment no', 'match' => '^PermitUserEnvironment\ ', ) } # Ensure only strong ciphers are used - Section 5.2.13 it { is_expected.to contain_file_line('set_ssh_ciphers').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr', 'match' => '^Ciphers\ ', ) } # Ensure only strong MAC algorithms are used - Section 4.2.14 it { is_expected.to contain_file_line('set_ssh_macs').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'MACs [email protected],[email protected],hmac-sha2-512,hmac-sha2-256', 'match' => '^MACs\ ', ) } # Ensure only strong Key Exchange algorithms are used - Section 5.2.15 it { is_expected.to contain_file_line('ssh_keyexchange_algos').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group14-sha256,diffie-helman-group16-sha512,diffie-hellman-group18-sha512,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-helman-group-exchange-sha256', 'match' => '^KexAlgorithms\ ', ) } # Ensure that Ensure SSH Idle Timeout Interval is configured - Section 5.2.16 it { is_expected.to contain_file_line('client_alive_interval').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'ClientAliveInterval 300', 'match' => '^ClientAliveInterval\ ', ) } # Ensure that Ensure SSH LoginGraceTime is set to One Minute or Less - Section 5.2.17 it { is_expected.to contain_file_line('login_grace_time').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'LoginGraceTime 60', 'match' => '^LoginGraceTime\ ', ) } # Ensure SSH Warning Banner is Configured - Section 5.2.18 it { is_expected.to contain_file_line('set_ssh_banner').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'Banner /etc/issue.net', 'match' => '^Banner\ ', ) } # Ensure SSH PAM is enabled - Section 5.2.19 it { is_expected.to contain_file_line('set_ssh_pam').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'UsePAM yes', 'match' => '^UsePAM\ ', ) } # Ensure SSH AllowTcpForwarding is disabled - Section 5.2.20 it { is_expected.to contain_file_line('ssh_allowtcpforwarding').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'allowtcpforwarding no', 'match' => '^allowtcpforwarding\ ', ) } # Ensure SSH MaxStartups is configured - Section 5.2.21 it { is_expected.to contain_file_line('ssh_maxstartups').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'maxstartups 10:30:60', 'match' => '^maxstartups\ ', ) } # Ensure SSH MaxSessions is limited - Section 5.2.22 it { is_expected.to contain_file_line('ssh_maxsessions').with( 'ensure' => 'present', 'path' => '/etc/ssh/sshd_config', 'line' => 'maxsessions 10', 'match' => '^maxsessions\ ', ) } # Ensure manifest compiles with all dependencies it { is_expected.to compile.with_all_deps } end end end
35.533058
267
0.555065
ab9bcda5ee8fc0cb762b105f1993f91868c059ad
1,784
# 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::Logic::Mgmt::V2018_07_01_preview module Models # # The artifact properties definition. # class ArtifactProperties include MsRestAzure # @return [DateTime] The artifact creation time. attr_accessor :created_time # @return [DateTime] The artifact changed time. attr_accessor :changed_time # @return attr_accessor :metadata # # Mapper for ArtifactProperties class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ArtifactProperties', type: { name: 'Composite', class_name: 'ArtifactProperties', model_properties: { created_time: { client_side_validation: true, required: false, serialized_name: 'createdTime', type: { name: 'DateTime' } }, changed_time: { client_side_validation: true, required: false, serialized_name: 'changedTime', type: { name: 'DateTime' } }, metadata: { client_side_validation: true, required: false, serialized_name: 'metadata', type: { name: 'Object' } } } } } end end end end
25.855072
70
0.511771
ac5a096b40072eead8a7bef15247cd1e8f40a7fb
2,558
# frozen_string_literal: true # # Author:: Pavel Yudin (<[email protected]>) # Author:: Tim Smith (<[email protected]>) # Copyright:: Copyright (c) 2015 Pavel Yudin # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Ohai.plugin(:Virtualization) do provides "virtualization" depends "hardware" def vboxmanage_exists? which("VBoxManage") end def prlctl_exists? which("prlctl") end def ioreg_exists? which("ioreg") end def fusion_exists? file_exist?("/Applications/VMware\ Fusion.app/") end def docker_exists? which("docker") end collect_data(:darwin) do virtualization Mash.new unless virtualization virtualization[:systems] ||= Mash.new if docker_exists? virtualization[:system] = "docker" virtualization[:role] = "host" virtualization[:systems][:docker] = "host" end if vboxmanage_exists? virtualization[:system] = "vbox" virtualization[:role] = "host" virtualization[:systems][:vbox] = "host" end if hardware[:boot_rom_version].match?(/VirtualBox/i) virtualization[:system] = "vbox" virtualization[:role] = "guest" virtualization[:systems][:vbox] = "guest" end if fusion_exists? virtualization[:system] = "vmware" virtualization[:role] = "host" virtualization[:systems][:vmware] = "host" end if hardware[:boot_rom_version].match?(/VMW/i) virtualization[:system] = "vmware" virtualization[:role] = "guest" virtualization[:systems][:vmware] = "guest" end if prlctl_exists? virtualization[:system] = "parallels" virtualization[:role] = "host" virtualization[:systems][:parallels] = "host" elsif ioreg_exists? so = shell_out("ioreg -l") if /pci1ab8,4000/.match?(so.stdout) virtualization[:system] = "parallels" virtualization[:role] = "guest" virtualization[:systems][:parallels] = "guest" end end end end
27.212766
74
0.673182
f89951171a7e8513a683e66b41df3d0d10c92c12
1,308
# -*- encoding: utf-8 -*- # REXML is an XML toolkit for Ruby[http://www.ruby-lang.org], in Ruby. # # REXML is a _pure_ Ruby, XML 1.0 conforming, # non-validating[http://www.w3.org/TR/2004/REC-xml-20040204/#sec-conformance] # toolkit with an intuitive API. REXML passes 100% of the non-validating Oasis # tests[http://www.oasis-open.org/committees/xml-conformance/xml-test-suite.shtml], # and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also # includes a full XPath[http://www.w3c.org/tr/xpath] 1.0 implementation. Since # Ruby 1.8, REXML is included in the standard Ruby distribution. # # Main page:: http://www.germane-software.com/software/rexml # Author:: Sean Russell <serATgermaneHYPHENsoftwareDOTcom> # Date:: 2008/019 # Version:: 3.1.7.3 # # This API documentation can be downloaded from the REXML home page, or can # be accessed online[http://www.germane-software.com/software/rexml_doc] # # A tutorial is available in the REXML distribution in docs/tutorial.html, # or can be accessed # online[http://www.germane-software.com/software/rexml/docs/tutorial.html] module REXML COPYRIGHT = "Copyright © 2001-2008 Sean Russell <[email protected]>" DATE = "2008/019" VERSION = "3.1.7.3" REVISION = %w$Revision$[1] || '' Copyright = COPYRIGHT Version = VERSION end
40.875
83
0.733945
b93ee8439f0b5a6eb840b9b18d2b4b5513e18e7b
1,799
# -*- encoding: utf-8 -*- require File.expand_path('../lib/functional-light-service/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Boscolo Michele"] gem.email = ["[email protected]"] gem.description = %q{A service skeleton with an emphasis on simplicity with a pinch a functional programming} gem.summary = %q{A service skeleton with an emphasis on simplicity with a pinch a functional programming} gem.homepage = "https://github.com/sphynx79/functional-light-service" gem.license = "MIT" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "functional-light-service" gem.require_paths = ["lib"] gem.version = FunctionalLightService::VERSION gem.required_ruby_version = '>= 2.6.0' gem.add_runtime_dependency("dry-inflector", "~> 0.2", ">= 0.2.1") gem.add_runtime_dependency("i18n", "~> 1.8", ">= 1.8.11") gem.add_development_dependency("rake", "~> 13.0.6", ">= 13.0.6") gem.add_development_dependency("i18n", "~> 1.8", ">= 1.8.11") gem.add_development_dependency("dry-inflector", "~> 0.2", ">= 0.2.1") gem.add_development_dependency("rspec", "~> 3.10.0") gem.add_development_dependency("rspec-mocks", "= 3.10.2") gem.add_development_dependency("simplecov", "~> 0.21.2") gem.add_development_dependency("simplecov-cobertura", "~> 2.1.0") gem.add_development_dependency("rubocop", "~> 1.25.0") gem.add_development_dependency("rubocop-performance", "~> 1.13.2") gem.add_development_dependency("pry", "~> 0.14.1") gem.add_development_dependency("solargraph", "~> 0.44.2") gem.add_development_dependency("nokogiri", "~> 1.12.5") end
48.621622
113
0.669261
6188e0e7951fc8ebac73f1776e9dda6c0b07fe95
720
# 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::KeyVault::Mgmt::V2015_06_01 module Models # # Defines values for KeyPermissions # module KeyPermissions All = "all" Encrypt = "encrypt" Decrypt = "decrypt" WrapKey = "wrapKey" UnwrapKey = "unwrapKey" Sign = "sign" Verify = "verify" Get = "get" List = "list" Create = "create" Update = "update" Import = "import" Delete = "delete" Backup = "backup" Restore = "restore" Recover = "recover" Purge = "purge" end end end
22.5
70
0.594444
1a598628763005ebfbba5e5ba767092c1d9573d1
607
cask "sapmachine-jdk" do version "14.0.2" sha256 "9c11682ba91c4285f8ca56682114a46c2e0bf723b65b81060b6f8403d681ff1f" # github.com/SAP/SapMachine/ was verified as official when first introduced to the cask url "https://github.com/SAP/SapMachine/releases/download/sapmachine-#{version}/sapmachine-jdk-#{version}_osx-x64_bin.dmg" appcast "https://sap.github.io/SapMachine/latest/#{version.major}" name "SapMachine OpenJDK Development Kit" homepage "https://sapmachine.io/" artifact "sapmachine-jdk-#{version}.jdk", target: "/Library/Java/JavaVirtualMachines/sapmachine-jdk-#{version}.jdk" end
46.692308
123
0.777595
ab293174d4037f5e4da83cadc8d7872f1ec2dc64
2,697
# # Author:: John Keiser (<[email protected]>) # Copyright:: Copyright 2013-2019, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "support/shared/integration/integration_helper" require "chef/knife/serve" require "chef/server_api" describe "knife serve", :workstation do include IntegrationSupport include KnifeSupport def with_knife_serve exception = nil t = Thread.new do begin knife("serve --chef-zero-port=8890") rescue exception = $! end end begin Chef::Config.log_level = :debug Chef::Config.chef_server_url = "http://localhost:8890" Chef::Config.node_name = nil Chef::Config.client_key = nil api = Chef::ServerAPI.new yield api rescue if exception raise exception else raise end ensure t.kill sleep 0.5 end end when_the_repository "also has one of each thing" do before do file "nodes/a_node_in_json.json", { "foo" => "bar" } file "nodes/a_node_in_ruby.rb", "name 'a_node_in_ruby'" file "roles/a_role_in_json.json", { "foo" => "bar" } file "roles/a_role_in_ruby.rb", "name 'a_role_in_ruby'" end %w{a_node_in_json a_node_in_ruby}.each do |file_type| context file_type do it "knife serve serves up /nodes" do with_knife_serve do |api| expect(api.get("nodes")).to have_key(file_type) end end it "knife serve serves up /nodes/#{file_type}" do with_knife_serve do |api| expect(api.get("nodes/#{file_type}")["name"]).to eq(file_type) end end end end %w{a_role_in_json a_role_in_ruby}.each do |file_type| context file_type do it "knife serve serves up /roles" do with_knife_serve do |api| expect(api.get("roles")).to have_key(file_type) end end it "knife serve serves up /roles/#{file_type}" do with_knife_serve do |api| expect(api.get("roles/#{file_type}")["name"]).to eq(file_type) end end end end end end
29
74
0.6396
629d91535649ad98bc47d253a71454353bfa0ffe
913
module DeviseGoogleAuthenticator module Controllers # :nodoc: module Helpers # :nodoc: def google_authenticator_qrcode(user, qualifier=nil, issuer=nil) username = username_from_email(user.email) app = user.class.ga_appname || Rails.application.class.try(:module_parent_name) || Rails.application.class.parent_name data = "otpauth://totp/#{otpauth_user(username, app, qualifier)}?secret=#{user.gauth_secret}" data << "&issuer=#{issuer}" if !issuer.nil? data = Rack::Utils.escape(data) url = "https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=#{data}" return image_tag(url, :alt => 'Google Authenticator QRCode') end def otpauth_user(username, app, qualifier=nil) "#{username}@#{app}#{qualifier}" end def username_from_email(email) (/^(.*)@/).match(email)[1] end end end end
36.52
126
0.652793
5dd94996a8ba06dc5f8c5fe746587a62429c4854
9,520
# frozen_string_literal: true # Redmine - project management software # Copyright (C) 2006-2019 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. require File.expand_path('../../test_helper', __FILE__) class SettingsControllerTest < Redmine::ControllerTest fixtures :projects, :trackers, :issue_statuses, :issues, :users, :email_addresses def setup User.current = nil @request.session[:user_id] = 1 # admin end def teardown Setting.delete_all Setting.clear_cache end def test_index get :index assert_response :success assert_select 'input[name=?][value=?]', 'settings[app_title]', Setting.app_title end def test_get_edit get :edit assert_response :success assert_select 'input[name=?][value=""]', 'settings[enabled_scm][]' end def test_get_edit_should_preselect_default_issue_list_columns with_settings :issue_list_default_columns => %w(tracker subject status updated_on) do get :edit assert_response :success end assert_select 'select[name=?]', 'settings[issue_list_default_columns][]' do assert_select 'option', 4 assert_select 'option[value=tracker]', :text => 'Tracker' assert_select 'option[value=subject]', :text => 'Subject' assert_select 'option[value=status]', :text => 'Status' assert_select 'option[value=updated_on]', :text => 'Updated' end assert_select 'select[name=?]', 'available_columns[]' do assert_select 'option[value=tracker]', 0 assert_select 'option[value=priority]', :text => 'Priority' end end def test_get_edit_without_trackers_should_succeed Tracker.delete_all get :edit assert_response :success end def test_post_edit_notifications post :edit, :params => { :settings => { :mail_from => '[email protected]', :bcc_recipients => '0', :notified_events => %w(issue_added issue_updated news_added), :emails_footer => 'Test footer' } } assert_redirected_to '/settings' assert_equal '[email protected]', Setting.mail_from assert !Setting.bcc_recipients? assert_equal %w(issue_added issue_updated news_added), Setting.notified_events assert_equal 'Test footer', Setting.emails_footer end def test_edit_commit_update_keywords with_settings :commit_update_keywords => [ { "keywords" => "fixes, resolves", "status_id" => "3" }, { "keywords" => "closes", "status_id" => "5", "done_ratio" => "100", "if_tracker_id" => "2" } ] do get :edit end assert_response :success assert_select 'tr.commit-keywords', 2 assert_select 'tr.commit-keywords:nth-child(1)' do assert_select 'input[name=?][value=?]', 'settings[commit_update_keywords][keywords][]', 'fixes, resolves' assert_select 'select[name=?]', 'settings[commit_update_keywords][status_id][]' do assert_select 'option[value="3"][selected=selected]' end end assert_select 'tr.commit-keywords:nth-child(2)' do assert_select 'input[name=?][value=?]', 'settings[commit_update_keywords][keywords][]', 'closes' assert_select 'select[name=?]', 'settings[commit_update_keywords][status_id][]' do assert_select 'option[value="5"][selected=selected]', :text => 'Closed' end assert_select 'select[name=?]', 'settings[commit_update_keywords][done_ratio][]' do assert_select 'option[value="100"][selected=selected]', :text => '100 %' end assert_select 'select[name=?]', 'settings[commit_update_keywords][if_tracker_id][]' do assert_select 'option[value="2"][selected=selected]', :text => 'Feature request' end end end def test_edit_without_commit_update_keywords_should_show_blank_line with_settings :commit_update_keywords => [] do get :edit end assert_response :success assert_select 'tr.commit-keywords', 1 do assert_select 'input[name=?]:not([value])', 'settings[commit_update_keywords][keywords][]' end end def test_post_edit_commit_update_keywords post :edit, :params => { :settings => { :commit_update_keywords => { :keywords => ["resolves", "closes"], :status_id => ["3", "5"], :done_ratio => ["", "100"], :if_tracker_id => ["", "2"] } } } assert_redirected_to '/settings' assert_equal([ { "keywords" => "resolves", "status_id" => "3" }, { "keywords" => "closes", "status_id" => "5", "done_ratio" => "100", "if_tracker_id" => "2" } ], Setting.commit_update_keywords) end def test_post_edit_with_invalid_setting_should_not_error post :edit, :params => { :settings => { :invalid_setting => '1' } } assert_redirected_to '/settings' end def test_post_edit_should_send_security_notification_for_notified_settings ActionMailer::Base.deliveries.clear post :edit, :params => { :settings => { :login_required => 1 } } assert_not_nil (mail = ActionMailer::Base.deliveries.last) assert_mail_body_match '0.0.0.0', mail assert_mail_body_match I18n.t(:setting_login_required), mail assert_select_email do assert_select 'a[href^=?]', 'http://localhost:3000/settings' end # All admins should receive this recipients = [mail.bcc, mail.cc].flatten User.active.where(admin: true).each do |admin| assert_include admin.mail, recipients end end def test_post_edit_should_not_send_security_notification_for_non_notified_settings ActionMailer::Base.deliveries.clear post :edit, :params => { :settings => { :app_title => 'MineRed' } } assert_nil (mail = ActionMailer::Base.deliveries.last) end def test_post_edit_should_not_send_security_notification_for_unchanged_settings ActionMailer::Base.deliveries.clear post :edit, :params => { :settings => { :login_required => 0 } } assert_nil (mail = ActionMailer::Base.deliveries.last) end def test_get_plugin_settings ActionController::Base.append_view_path(File.join(Rails.root, "test/fixtures/plugins")) Redmine::Plugin.register :foo do settings :partial => "foo_plugin/foo_plugin_settings" directory 'test/fixtures/plugins/foo_plugin' end Setting.plugin_foo = { 'sample_setting' => 'Plugin setting value' } get :plugin, :params => { :id => 'foo' } assert_response :success assert_select 'form[action="/settings/plugin/foo"]' do assert_select 'input[name=?][value=?]', 'settings[sample_setting]', 'Plugin setting value' end ensure Redmine::Plugin.unregister(:foo) end def test_get_invalid_plugin_settings get :plugin, :params => { :id => 'none' } assert_response 404 end def test_get_non_configurable_plugin_settings Redmine::Plugin.register(:foo) do directory 'test/fixtures/plugins/foo_plugin' end get :plugin, :params => { :id => 'foo' } assert_response 404 ensure Redmine::Plugin.unregister(:foo) end def test_post_plugin_settings Redmine::Plugin.register(:foo) do settings :partial => 'not blank', # so that configurable? is true :default => { 'sample_setting' => 'Plugin setting value' } directory 'test/fixtures/plugins/foo_plugin' end post :plugin, :params => { :id => 'foo', :settings => { 'sample_setting' => 'Value' } } assert_redirected_to '/settings/plugin/foo' assert_equal({ 'sample_setting' => 'Value' }, Setting.plugin_foo) end def test_post_empty_plugin_settings Redmine::Plugin.register(:foo) do settings :partial => 'not blank', # so that configurable? is true :default => { 'sample_setting' => 'Plugin setting value' } directory 'test/fixtures/plugins/foo_plugin' end post :plugin, :params => { :id => 'foo' } assert_redirected_to '/settings/plugin/foo' assert_equal({}, Setting.plugin_foo) end def test_post_non_configurable_plugin_settings Redmine::Plugin.register(:foo) do directory 'test/fixtures/plugins/foo_plugin' end post :plugin, :params => { :id => 'foo', :settings => { 'sample_setting' => 'Value' } } assert_response 404 ensure Redmine::Plugin.unregister(:foo) end def test_post_mail_handler_delimiters_should_not_save_invalid_regex_delimiters post :edit, :params => { :settings => { :mail_handler_enable_regex_delimiters => '1', :mail_handler_body_delimiters => 'Abc[', } } assert_response :success assert_equal '0', Setting.mail_handler_enable_regex_delimiters assert_equal '', Setting.mail_handler_body_delimiters assert_select_error /is not a valid regular expression/ assert_select 'textarea[name=?]', 'settings[mail_handler_body_delimiters]', :text => 'Abc[' end def test_post_mail_handler_delimiters_should_save_valid_regex_delimiters post :edit, :params => { :settings => { :mail_handler_enable_regex_delimiters => '1', :mail_handler_body_delimiters => 'On .*, .* at .*, .* <.*<mailto:.*>> wrote:', } } assert_redirected_to '/settings' assert_equal '1', Setting.mail_handler_enable_regex_delimiters assert_equal 'On .*, .* at .*, .* <.*<mailto:.*>> wrote:', Setting.mail_handler_body_delimiters end end
30.809061
108
0.714391
9120075fd30cd961cc05ee75da49d84db59179ab
1,110
# Ta-Lib function mapping class # Function: 'LINEARREG_SLOPE' # Description: 'Linear Regression Slope' # This file has been autogenerated - Do Not Edit. class Indicator::AutoGen::LinearRegSlope < Indicator::Base # Time Period <Integer> attr_accessor :time_period def initialize(*args) if args.first.is_a? Hash h = args.first @time_period = h[:time_period] || 14 else @time_period = args[0] || 14 end @func = TaLib::Function.new("LINEARREG_SLOPE") end # Is price data required as an input def self.price_input? false end # The list of arguments def self.arguments [ :time_period ] end # The minimum set of inputs required def self.inputs [ :in_real ] end # The outputs generated by this function def self.outputs [ :out_real ] end def run(in_real) len = in_real.length @func.in_real(0, map(in_real)) @func.opt_int(0, @time_period) out_real = Array.new(len) @func.out_real(0, out_real) @func.call(0, len - 1) out_real end end
20.555556
59
0.624324
33674d90c4100bd8da1c657f599281e0c0800816
20
action :run do end
5
14
0.7
f77c89bac32454a744df0c5348e01395be9a03ca
803
class TeachersController < ApplicationController before_action :redirect_if_not_logged_in, only: :show def new render :layout => "login" @teacher = Teacher.new end def create @teacher = Teacher.new(teacher_params) if @teacher.save session[:teacher_id]= @teacher.id redirect_to teacher_path(@teacher) else render :new , layout: 'login' end end def show @teacher = Teacher.find(params[:id]) if @teacher != current_teacher redirect_to teacher_path(@current_teacher), alert: "You are not allowed to view other teachers dashboard" end end private def teacher_params params.require(:teacher).permit(:username, :email,:password) end end
25.903226
117
0.62142
b980f97c7bdf41928babfa50314f0d16ace68439
12,733
require_relative '../spec_helper' require_relative '../../app/controllers/visualizations_controller_helper' describe VisualizationsControllerHelper do include VisualizationsControllerHelper include CartoDB::Factories include Carto::Factories::Visualizations before(:all) do @organization = create_organization_with_users @org_user = Carto::User.find(@organization.users.first.id) @org_user_shared = Carto::User.find(@organization.users.last.id) @free_user = create(:carto_user) @free_map, @free_table, @free_table_visualization, @free_visualization = create_full_visualization(@free_user) @org_map, @org_table, @org_table_visualization, @org_visualization = create_full_visualization(@org_user) @free_visualization.name = 'free viz' @free_visualization.save end after(:all) do destroy_full_visualization(@org_map, @org_table, @org_table_visualization, @org_visualization) destroy_full_visualization(@map, @table, @table_visualization, @visualization) end def setup_for_user(user) user_request = mock user_request.stubs(:params).returns(user_domain: user.username) stubs(:request).returns(user_request) end describe '#free_user' do before(:each) do setup_for_user(@free_user) end describe '#derived_visualization' do it 'locates derived visualization by id' do visualization = load_visualization_from_id_or_name(@free_visualization.id) visualization.should eq @free_visualization end it 'locates derived visualization by name' do visualization = load_visualization_from_id_or_name(@free_visualization.name) visualization.should eq @free_visualization end it 'locates derived visualization by schema and id' do visualization = load_visualization_from_id_or_name("public.#{@free_visualization.id}") visualization.should eq @free_visualization end it 'locates derived visualization by schema and name' do visualization = load_visualization_from_id_or_name("public.#{@free_visualization.name}") visualization.should eq @free_visualization end it 'does locate derived visualization by another user and id' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name(@free_visualization.id) visualization.should eq @free_visualization end it 'does not locate derived visualization by another user and name' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name(@free_visualization.name) visualization.should be_nil end it 'does not locate derived visualization by another user and schema.name' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name("public.#{@free_visualization.name}") visualization.should be_nil end it 'does not locate derived visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("invalid.#{@free_visualization.name}") visualization.should be_nil end end describe '#table_visualization' do it 'locates table visualization by id' do visualization = load_visualization_from_id_or_name(@free_table_visualization.id) visualization.should eq @free_table_visualization end it 'locates table visualization by name' do visualization = load_visualization_from_id_or_name(@free_table_visualization.name) visualization.should eq @free_table_visualization end it 'locates table visualization by schema and id' do visualization = load_visualization_from_id_or_name("public.#{@free_table_visualization.id}") visualization.should eq @free_table_visualization end it 'locates table visualization by schema and name' do visualization = load_visualization_from_id_or_name("public.#{@free_table_visualization.name}") visualization.should eq @free_table_visualization end it 'does locate table visualization by another user and id' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name(@free_table_visualization.id) visualization.should eq @free_table_visualization end it 'does not locate table visualization by another user and name' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name(@free_table_visualization.name) visualization.should be_nil end it 'does not locate table visualization by another user and schema.name' do setup_for_user(@org_user) visualization = load_visualization_from_id_or_name("public.#{@free_table_visualization.name}") visualization.should be_nil end it 'does not locate table visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("invalid.#{@free_table_visualization.name}") visualization.should be_nil end end end describe '#org_user' do before(:each) do setup_for_user(@org_user) end describe '#derived_visualization' do it 'locates derived visualization by id' do visualization = load_visualization_from_id_or_name(@org_visualization.id) visualization.should eq @org_visualization end it 'locates derived visualization by name' do visualization = load_visualization_from_id_or_name(@org_visualization.name) visualization.should eq @org_visualization end it 'locates derived visualization by schema and id' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.id}") visualization.should eq @org_visualization end it 'locates derived visualization by schema and name' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.name}") visualization.should eq @org_visualization end it 'does locate derived visualization by another user and id' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name(@org_visualization.id) visualization.should eq @org_visualization end it 'does not locate derived visualization by another user and name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name(@org_visualization.name) visualization.should be_nil end it 'does not locate derived visualization by another user and schema.name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.name}") visualization.should be_nil end it 'does not locate derived visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("#{@org_user_shared.database_schema}.#{@org_visualization.name}") visualization.should be_nil end end describe '#table_visualization' do it 'locates table visualization by id' do visualization = load_visualization_from_id_or_name(@org_table_visualization.id) visualization.should eq @org_table_visualization end it 'locates table visualization by name' do visualization = load_visualization_from_id_or_name(@org_table_visualization.name) visualization.should eq @org_table_visualization end it 'locates table visualization by schema and id' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.id}") visualization.should eq @org_table_visualization end it 'locates table visualization by schema and name' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.name}") visualization.should eq @org_table_visualization end it 'does locate table visualization by another user and id' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name(@org_table_visualization.id) visualization.should eq @org_table_visualization end it 'does not locate table visualization by another user and name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name(@org_table_visualization.name) visualization.should be_nil end it 'does not locate table visualization by another user and schema.name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.name}") visualization.should be_nil end it 'does not locate table visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("#{@org_user_shared.database_schema}.#{@org_table_visualization.name}") visualization.should be_nil end end end describe '#org_shared' do before(:each) do setup_for_user(@org_user_shared) end describe '#derived_visualization' do it 'locates shared derived visualization by id' do visualization = load_visualization_from_id_or_name(@org_visualization.id) visualization.should eq @org_visualization end it 'locates shared derived visualization by schema and id' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.id}") visualization.should eq @org_visualization end it 'locates shared derived visualization by schema and name' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.name}") visualization.should eq @org_visualization end it 'does locate shared derived visualization by another user and id' do visualization = load_visualization_from_id_or_name(@org_visualization.id) visualization.should eq @org_visualization end it 'does not locate shared derived visualization by another user and name' do visualization = load_visualization_from_id_or_name(@org_visualization.name) visualization.should be_nil end it 'does not locate shared derived visualization by another user and schema.name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_visualization.name}") visualization.should be_nil end it 'does not locate shared derived visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("#{@org_user_shared.database_schema}.#{@org_visualization.name}") visualization.should be_nil end end describe '#table_visualization' do it 'locates shared table visualization by id' do visualization = load_visualization_from_id_or_name(@org_table_visualization.id) visualization.should eq @org_table_visualization end it 'locates shared table visualization by schema and id' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.id}") visualization.should eq @org_table_visualization end it 'locates shared table visualization by schema and name' do visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.name}") visualization.should eq @org_table_visualization end it 'does locate shared table visualization by another user and id' do visualization = load_visualization_from_id_or_name(@org_table_visualization.id) visualization.should eq @org_table_visualization end it 'does not locate shared table visualization by another user and name' do visualization = load_visualization_from_id_or_name(@org_table_visualization.name) visualization.should be_nil end it 'does not locate shared table visualization by another user and schema.name' do setup_for_user(@free_user) visualization = load_visualization_from_id_or_name("#{@org_user.database_schema}.#{@org_table_visualization.name}") visualization.should be_nil end it 'does not locate shared table visualization with incorrect schema' do visualization = load_visualization_from_id_or_name("#{@org_user_shared.database_schema}.#{@org_table_visualization.name}") visualization.should be_nil end end end end
39.666667
130
0.735412
ab4ebf0d524fb1def0ccb3428a3263afdb77ed04
443
describe :hash_value_p, shared: true do it "returns true if the value exists in the hash" do new_hash(a: :b).send(@method, :a).should == false new_hash(1 => 2).send(@method, 2).should == true h = new_hash 5 h.send(@method, 5).should == false h = new_hash { 5 } h.send(@method, 5).should == false end it "uses == semantics for comparing values" do new_hash(5 => 2.0).send(@method, 2).should == true end end
29.533333
54
0.625282
39794a42c0b011ba0b738811f450a84354c6fc23
646
require 'spec_helper' describe JsonServiceRowPresenter do describe '#name' do it 'returns the handlebar template tag for name' do expect(subject.name).to eq '{{name}}' end end describe '#service_url' do it 'exposes the handlebar template tag for service_url' do expect(subject.service_url).to eq '{{service_url}}' end end describe '#status' do it 'exposes the handlebar template tag for status' do expect(subject.status).to eq '{{status}}' end end describe '#icon' do it 'exposes the handlebar template tag for icon' do expect(subject.icon).to eq '{{icon}}' end end end
23.071429
62
0.671827
b9c780549fcad71707e022f4c2defea0997fb9cb
89
service "apache2" do action :restart end service "shibd" do action :restart end
11.125
20
0.696629
ffc941e72b210eb589c76f4e2e9b844f509239dc
7,710
# # Cookbook Name:: nova # Recipe:: database # # Copyright 2010-2011, Opscode, Inc. # Copyright 2011, Dell, Inc. # Copyright 2012, SUSE Linux Products GmbH. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe "database::client" ha_enabled = node[:nova][:ha][:enabled] db_settings = fetch_database_settings crowbar_pacemaker_sync_mark "wait-nova_database" do # the db sync is very slow for nova timeout 300 only_if { ha_enabled } end [node[:nova][:db], node[:nova][:api_db], node[:nova][:placement_db]].each do |d| # Creates empty nova database database "create #{d[:database]} database" do connection db_settings[:connection] database_name d[:database] provider db_settings[:provider] action :create only_if { !ha_enabled || CrowbarPacemakerHelper.is_cluster_founder?(node) } end database_user "create #{d[:user]} database user" do connection db_settings[:connection] username d[:user] password d[:password] provider db_settings[:user_provider] host "%" action :create only_if { !ha_enabled || CrowbarPacemakerHelper.is_cluster_founder?(node) } end database_user "grant privileges to the #{d[:user]} database user" do connection db_settings[:connection] database_name d[:database] username d[:user] password d[:password] host "%" privileges db_settings[:privs] provider db_settings[:user_provider] require_ssl db_settings[:connection][:ssl][:enabled] action :grant only_if { !ha_enabled || CrowbarPacemakerHelper.is_cluster_founder?(node) } end end # create the nova_cell0 database (similar to nova_api) and give the # nova DB user the correct privileges database "create nova_cell0 database" do connection db_settings[:connection] database_name "nova_cell0" provider db_settings[:provider] action :create only_if { !ha_enabled || CrowbarPacemakerHelper.is_cluster_founder?(node) } end database_user "grant privileges to the #{node[:nova][:db][:user]} database user" do connection db_settings[:connection] database_name "nova_cell0" username node[:nova][:db][:user] password node[:nova][:db][:password] host "%" privileges db_settings[:privs] provider db_settings[:user_provider] require_ssl db_settings[:connection][:ssl][:enabled] action :grant only_if { !ha_enabled || CrowbarPacemakerHelper.is_cluster_founder?(node) } end execute "nova-manage api_db sync" do user node[:nova][:user] group node[:nova][:group] command "nova-manage api_db sync" action :run # We only do the sync the first time, and only if we're not doing HA or if we # are the founder of the HA cluster (so that it's really only done once). only_if do !node[:nova][:api_db_synced] && !CrowbarPacemakerHelper.being_upgraded?(node) && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end # handle cell0 and cell1 before doing the db sync execute "nova-manage create cell0" do user node[:nova][:user] group node[:nova][:group] command "nova-manage cell_v2 map_cell0" action :run # TODO: Does not work on Newton (14.x.x). Remove when switched to Ocata not_if 'rpm -qa --qf "%{VERSION}\n" openstack-nova|grep ^14\.' only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end execute "nova-manage create cell1" do user node[:nova][:user] group node[:nova][:group] command "nova-manage cell_v2 create_cell --name cell1 --verbose" action :run # TODO: Does not work on Newton (14.x.x). Remove when switched to Ocata not_if 'rpm -qa --qf "%{VERSION}\n" openstack-nova|grep ^14\.' only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end # During upgrade to Pike, execute api_db sync after 'cell_v2 map_cell0' and 'cell_v2 create_cell' execute "nova-manage api_db sync" do user node[:nova][:user] group node[:nova][:group] command "nova-manage api_db sync" action :run # We only do the sync the first time, and only if we're not doing HA or if we # are the founder of the HA cluster (so that it's really only done once). only_if do !node[:nova][:api_db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end execute "nova-manage db sync up to revision 329" do user node[:nova][:user] group node[:nova][:group] command "nova-manage db sync 329" action :run # We only do the sync the first time, and only if we're not doing HA or if we # are the founder of the HA cluster (so that it's really only done once). only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) && (`nova-manage --log-file /dev/null db version`.to_i < 329) end end # Perform online migrations up to revision 329 (the ones for later revisions # will fail. These errors can probably be ignored (hence the ignore_failure usage) execute "nova-manage db online_data_migrations" do user node[:nova][:user] group node[:nova][:group] command "nova-manage db online_data_migrations" ignore_failure true action :run only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) && (`nova-manage --log-file /dev/null db version`.to_i == 329) end end # Update Nova DB to latest revision execute "nova-manage db sync" do user node[:nova][:user] group node[:nova][:group] command "nova-manage db sync" action :run only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end # Run online migration again to cover the ones that failed in the first pass. execute "nova-manage db online_data_migrations (continue)" do user node[:nova][:user] group node[:nova][:group] command "nova-manage db online_data_migrations" action :run only_if do !node[:nova][:db_synced] && (!node[:nova][:ha][:enabled] || CrowbarPacemakerHelper.is_cluster_founder?(node)) end end # We want to keep a note that we've done db_sync, so we don't do it again. # If we were doing that outside a ruby_block, we would add the note in the # compile phase, before the actual db_sync is done (which is wrong, since it # could possibly not be reached in case of errors). ruby_block "mark node for nova db_sync" do block do node.set[:nova][:db_synced] = true node.save end action :nothing subscribes :create, "execute[nova-manage db sync]", :immediately end # We want to keep a note that we've done db_sync, so we don't do it again. # If we were doing that outside a ruby_block, we would add the note in the # compile phase, before the actual db_sync is done (which is wrong, since it # could possibly not be reached in case of errors). ruby_block "mark node for nova api_db_sync" do block do node.set[:nova][:api_db_synced] = true node.save end action :nothing subscribes :create, "execute[nova-manage api_db sync]", :immediately end crowbar_pacemaker_sync_mark "create-nova_database" if ha_enabled
34.115044
97
0.716602
387ee3ba598fd0969bc84d7dc7cba88367d0b3b1
1,584
require "spec_helper" RSpec.describe Amazon::XML::Envelope::Prices do include_context :product include_context :child_product let(:instance) { described_class.new products, options } let(:products) do [ product, child_product, ] end let(:options) do { credentials: { merchant_id: 1, }, type: :Product, operation: :Update } end let(:expected_xml) do <<~XML.strip_heredoc <?xml version="1.0" encoding="UTF-8"?> <AmazonEnvelope> <Header> <DocumentVersion>1.02</DocumentVersion> <MerchantIdentifier>1</MerchantIdentifier> </Header> <MessageType>Price</MessageType> <PurgeAndReplace>false</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <Price> <SKU>abcdef123</SKU> <StandardPrice currency="GBP">123.45</StandardPrice> </Price> </Message> <Message> <MessageID>2</MessageID> <OperationType>Update</OperationType> <Price> <SKU>ghijkl456</SKU> <StandardPrice currency="GBP">678.90</StandardPrice> </Price> </Message> </AmazonEnvelope> XML end it 'generates valid xml' do expect(instance.to_xml).to eql expected_xml validator = AmazonFeedValidator.new instance.xml_builder.to_xml, name: 'amzn-envelope' valid = validator.validate expect(validator.errors).to be_empty expect(valid).to be_truthy end end
24
90
0.606061
382b06285c9fd420bc463094f9234419d9fa7722
83
module AEAD autoload :Cipher, 'aead/cipher' autoload :Nonce, 'aead/nonce' end
16.6
33
0.710843
ff1c2a0d82307cad7211b684ac25de38fd46bb7a
4,728
require 'cases/helper' require 'models/author' require 'models/comment' require 'models/developer' require 'models/post' require 'models/project' class RelationMergingTest < ActiveRecord::TestCase fixtures :developers, :comments, :authors, :posts def test_relation_merging devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order('id ASC').where("id < 3")) assert_equal [developers(:david), developers(:jamis)], devs.to_a dev_with_count = Developer.limit(1).merge(Developer.order('id DESC')).merge(Developer.select('developers.*')) assert_equal [developers(:poor_jamis)], dev_with_count.to_a end def test_relation_to_sql sql = Post.first.comments.to_sql assert_no_match(/\?/, sql) end def test_relation_merging_with_arel_equalities_keeps_last_equality devs = Developer.where(Developer.arel_table[:salary].eq(80000)).merge( Developer.where(Developer.arel_table[:salary].eq(9000)) ) assert_equal [developers(:poor_jamis)], devs.to_a end def test_relation_merging_with_arel_equalities_keeps_last_equality_with_non_attribute_left_hand salary_attr = Developer.arel_table[:salary] devs = Developer.where( Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(80000) ).merge( Developer.where( Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(9000) ) ) assert_equal [developers(:poor_jamis)], devs.to_a end def test_relation_merging_with_eager_load relations = [] relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.all) relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.all) relations.each do |posts| post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end end def test_relation_merging_with_locks devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2)) assert devs.locked.present? end def test_relation_merging_with_preload [Post.all.merge(Post.preload(:author)), Post.preload(:author).merge(Post.all)].each do |posts| assert_queries(2) { assert posts.first.author } end end def test_relation_merging_with_joins comments = Comment.joins(:post).where(:body => 'Thank you for the welcome').merge(Post.where(:body => 'Such a lovely day')) assert_equal 1, comments.count end def test_relation_merging_with_association assert_queries(2) do # one for loading post, and another one merged query post = Post.where(:body => 'Such a lovely day').first comments = Comment.where(:body => 'Thank you for the welcome').merge(post.comments) assert_equal 1, comments.count end end test "merge collapses wheres from the LHS only" do left = Post.where(title: "omg").where(comments_count: 1) right = Post.where(title: "wtf").where(title: "bbq") expected = [left.bind_values[1]] + right.bind_values merged = left.merge(right) assert_equal expected, merged.bind_values assert !merged.to_sql.include?("omg") assert merged.to_sql.include?("wtf") assert merged.to_sql.include?("bbq") end def test_merging_keeps_lhs_bind_parameters column = Post.columns_hash['id'] binds = [[column, 20]] right = Post.where(id: 20) left = Post.where(id: 10) merged = left.merge(right) assert_equal binds, merged.bind_values end def test_merging_reorders_bind_params post = Post.first right = Post.where(id: 1) left = Post.where(title: post.title) merged = left.merge(right) assert_equal post, merged.first end end class MergingDifferentRelationsTest < ActiveRecord::TestCase fixtures :posts, :authors test "merging where relations" do hello_by_bob = Post.where(body: "hello").joins(:author). merge(Author.where(name: "Bob")).order("posts.id").pluck("posts.id") assert_equal [posts(:misc_by_bob).id, posts(:other_by_bob).id], hello_by_bob end test "merging order relations" do posts_by_author_name = Post.limit(3).joins(:author). merge(Author.order(:name)).pluck("authors.name") assert_equal ["Bob", "Bob", "David"], posts_by_author_name posts_by_author_name = Post.limit(3).joins(:author). merge(Author.order("name")).pluck("authors.name") assert_equal ["Bob", "Bob", "David"], posts_by_author_name end test "merging order relations (using a hash argument)" do posts_by_author_name = Post.limit(4).joins(:author). merge(Author.order(name: :desc)).pluck("authors.name") assert_equal ["Mary", "Mary", "Mary", "David"], posts_by_author_name end end
33.295775
127
0.705161
8788af57a678cd99faeceff2481222333b34ee66
5,159
## # This class is compatible with IO class (https://ruby-doc.org/core-2.3.1/IO.html) # source: https://gitlab.com/snippets/1685610 module Gitlab module Ci class Trace class HttpIO BUFFER_SIZE = 128.kilobytes InvalidURLError = Class.new(StandardError) FailedToGetChunkError = Class.new(StandardError) attr_reader :uri, :size attr_reader :tell attr_reader :chunk, :chunk_range alias_method :pos, :tell def initialize(url, size) raise InvalidURLError unless ::Gitlab::UrlSanitizer.valid?(url) @uri = URI(url) @size = size @tell = 0 end def close # no-op end def binmode # no-op end def binmode? true end def path nil end def url @uri.to_s end def seek(pos, where = IO::SEEK_SET) new_pos = case where when IO::SEEK_END size + pos when IO::SEEK_SET pos when IO::SEEK_CUR tell + pos else -1 end raise 'new position is outside of file' if new_pos < 0 || new_pos > size @tell = new_pos end def eof? tell == size end def each_line until eof? line = readline break if line.nil? yield(line) end end def read(length = nil, outbuf = "") out = "" length ||= size - tell until length <= 0 || eof? data = get_chunk break if data.empty? chunk_bytes = [BUFFER_SIZE - chunk_offset, length].min chunk_data = data.byteslice(0, chunk_bytes) out << chunk_data @tell += chunk_data.bytesize length -= chunk_data.bytesize end # If outbuf is passed, we put the output into the buffer. This supports IO.copy_stream functionality if outbuf outbuf.slice!(0, outbuf.bytesize) outbuf << out end out end def readline out = "" until eof? data = get_chunk new_line = data.index("\n") if !new_line.nil? out << data[0..new_line] @tell += new_line + 1 break else out << data @tell += data.bytesize end end out end def write(data) raise NotImplementedError end def truncate(offset) raise NotImplementedError end def flush raise NotImplementedError end def present? true end private ## # The below methods are not implemented in IO class # def in_range? @chunk_range&.include?(tell) end def get_chunk unless in_range? response = Net::HTTP.start(uri.hostname, uri.port, proxy_from_env: true, use_ssl: uri.scheme == 'https') do |http| http.request(request) end raise FailedToGetChunkError unless response.code == '200' || response.code == '206' @chunk = response.body.force_encoding(Encoding::BINARY) @chunk_range = response.content_range ## # Note: If provider does not return content_range, then we set it as we requested # Provider: minio # - When the file size is larger than requested Content-range, the Content-range is included in responces with Net::HTTPPartialContent 206 # - When the file size is smaller than requested Content-range, the Content-range is included in responces with Net::HTTPPartialContent 206 # Provider: AWS # - When the file size is larger than requested Content-range, the Content-range is included in responces with Net::HTTPPartialContent 206 # - When the file size is smaller than requested Content-range, the Content-range is included in responces with Net::HTTPPartialContent 206 # Provider: GCS # - When the file size is larger than requested Content-range, the Content-range is included in responces with Net::HTTPPartialContent 206 # - When the file size is smaller than requested Content-range, the Content-range is included in responces with Net::HTTPOK 200 @chunk_range ||= (chunk_start...(chunk_start + @chunk.bytesize)) end @chunk[chunk_offset..BUFFER_SIZE] end def request Net::HTTP::Get.new(uri).tap do |request| request.set_range(chunk_start, BUFFER_SIZE) end end def chunk_offset tell % BUFFER_SIZE end def chunk_start (tell / BUFFER_SIZE) * BUFFER_SIZE end def chunk_end [chunk_start + BUFFER_SIZE, size].min end end end end end
26.055556
151
0.539252
1c3f0daa39770c0bc2086fe4c77c0235e225a48e
149
module RbDbg APP_NAME = "rbdbg" VERSION = "0.0.1" end require 'optparse' require 'ffi' require 'rbdbg/debugger/base' require 'rbdbg/debugger/osx'
14.9
29
0.731544
e81c04ba84766a2f2381ca423abcabf2393171a6
670
require 'eventide/postgres' require 'user_email_address/client' require 'registration_component/load' require 'registration_component/registration' require 'registration_component/projection' require 'registration_component/store' require 'registration_component/encode_email_address' require 'registration_component/handlers/commands' require 'registration_component/handlers/events' require 'registration_component/handlers/user_email_address/events' require 'registration_component/consumers/commands' require 'registration_component/consumers/events' require 'registration_component/consumers/user_email_address/events' require 'registration_component/start'
30.454545
68
0.873134
335bf55cc899f161f8718ead226731419043281f
64
module Omniauth module Fedena VERSION = "0.1.1" end end
10.666667
21
0.65625
1c3186d8005a15a4b7fc6d7990781d7ff665c05c
1,313
require 'base32-alphabets' Base32.format = :electrologica # use the Electrologica Alphabet / Variant # hexadecimal (base 16) genome = 0x00004a52931ce4085c14bdce014a0318846a0c808c60294a6314a34a1295b9ce # kitty 1001 p Base32.encode( genome ) #=> "09-09-09-09-06-07-07-04-01-01-14-01-09-15-14-14-00-05-05-00-06-06-04-04-13-08-06-08-01-03-03-00-05-05-05-06-06-05-05-03-09-08-09-09-11-14-14-14" genome = 0x000042d28390864842e7b9c900c6321086438c6098ca298c728867425cf6b1ac # kitty 1111 p Base32.encode( genome ) #=> "08-11-09-08-07-04-04-06-09-01-01-14-15-14-14-09-00-03-03-03-04-04-04-06-08-14-06-06-01-06-06-10-05-06-06-07-05-02-03-07-08-09-14-15-13-12-13-12" Base32.format = :kai # use the Kai Alphabet / Variant genome = 0x00004a52931ce4085c14bdce014a0318846a0c808c60294a6314a34a1295b9ce # kitty 1001 p Base32.encode( genome ) #=> "aaaa788522f2agff16617755e979244166677664a9aacfff" p Base32.fmt( Base32.encode( genome )) #=> "aaaa 7885 22f2 agff 1661 7755 e979 2441 6667 7664 a9aa cfff" genome = 0x000042d28390864842e7b9c900c6321086438c6098ca298c728867425cf6b1ac # kitty 1111 p Base32.encode( genome ) #=> "9ca98557a22fgffa144455579f77277b677863489afgeded" p Base32.fmt( Base32.encode( genome )) #=> "9ca9 8557 a22f gffa 1444 5557 9f77 277b 6778 6348 9afg eded"
37.514286
150
0.744097
bb36d8d3916f44ec3c4d0febcee95a6d606683f9
465
module Capachrome module DriverExtensions module HasInputDevices # # @return [ActionBuilder] # @api public # def action ActionBuilder.new mouse, keyboard end # # @api private # def mouse Mouse.new @bridge end # # @api private # def keyboard Keyboard.new @bridge end end # HasInputDevices end # DriverExtensions end # Selenium
14.090909
41
0.541935
01b5d18822086b638048bb8f380addf410b7f817
1,848
require 'spec_helper' describe 'Shipments', type: :feature do stub_authorization! let!(:order) { create(:order_ready_to_ship, number: 'R100', state: 'complete', line_items_count: 5) } # Regression test for #4025 context 'a shipment without a shipping method' do before do order.shipments.each do |s| # Deleting the shipping rates causes there to be no shipping methods s.shipping_rates.delete_all end end it 'can still be displayed' do expect { visit spree.edit_admin_order_path(order) }.not_to raise_error end end context 'shipping an order', js: true do before do visit spree.admin_orders_path within_row(1) do click_link 'R100' end end it 'can ship a completed order' do click_on 'Ship' wait_for_ajax expect(page).to have_content('shipped package') expect(order.reload.shipment_state).to eq('shipped') end end context 'moving variants between shipments', js: true do before do create(:stock_location, name: 'LA') visit spree.admin_orders_path within_row(1) do click_link 'R100' end end it 'can move a variant to a new and to an existing shipment' do expect(order.shipments.count).to eq(1) within_row(1) { click_icon :split } targetted_select2 'LA', from: '#s2id_item_stock_location' spree_accept_alert do click_icon :save wait_for_ajax end expect(page.find("#shipment_#{order.shipments.first.id}")).to be_present within_row(2) { click_icon :split } targetted_select2 "LA(#{order.reload.shipments.last.number})", from: '#s2id_item_stock_location' click_icon :save wait_for_ajax expect(page.find("#shipment_#{order.reload.shipments.last.id}")).to be_present end end end
26.782609
103
0.66829
398aa5f749b0a46537d3d899f63434ee31224a92
1,133
class SetMysqlCollationToUtf8mb4Unicode < ActiveRecord::Migration[5.0] def change unless ActiveRecord::Base.connection.adapter_name.downcase =~ /^mysql/ return end reversible do |dir| dir.up do update_collation!('utf8mb4_unicode_ci') # Updating to mb4 switches TEXT columns to MEDIUMTEXT. This isn't needed # for commit messages. change_column :commits, :message, :text, limit: 64.kilobytes - 1 end dir.down { update_collation!('utf8mb4_general_ci') } end end private def update_collation!(collation) say_with_time 'Updating database' do ActiveRecord::Base.connection.execute(<<~SQL) ALTER DATABASE #{ActiveRecord::Base.connection.current_database} CHARACTER SET = utf8mb4 COLLATE = #{collation} SQL end ActiveRecord::Base.connection.tables.each do |table| say_with_time "Updating #{table}" do ActiveRecord::Base.connection.execute(<<~SQL) ALTER TABLE #{table} CONVERT TO CHARACTER SET utf8mb4 COLLATE #{collation} SQL end end end end
26.97619
80
0.656664
d5692a2a321714a81c8416367b1da302fc92e1ea
1,039
# Encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = "refinerycms-<%= plural_name %>" s.version = "1.0.0" s.description = "Ruby on Rails <%= plural_name.titleize %> forms-extension for Refinery CMS" s.date = "<%= Time.now.strftime('%Y-%m-%d') %>" s.summary = "<%= plural_name.titleize %> forms-extension for Refinery CMS" s.require_paths = %w(lib) s.files = Dir["{app,config,db,lib}/**/*"] + ["readme.md"] s.authors = <%= extension_authors %> # Runtime dependencies s.add_dependency "refinerycms-core", "~> <%= Refinery::Version %>" s.add_dependency "refinerycms-settings", "~> <%= [Refinery::Version.major, Refinery::Version.minor, 0].join(".") %>" s.add_dependency "filters_spam", "~> 0.3" s.add_dependency "actionmailer" # Development dependencies (usually used for testing) s.add_development_dependency "refinerycms-testing", "~> <%= Refinery::Version %>" end
45.173913
121
0.600577
e8ba543d4b3e3a75a78d3ab98336864219cb975b
28,371
# frozen_string_literal: true # Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe ContactsController do before(:each) do login set_current_tab(:contacts) end # GET /contacts # GET /contacts.xml #---------------------------------------------------------------------------- describe "responding to GET index" do it "should expose all contacts as @contacts and render [index] template" do @contacts = [create(:contact, user: current_user)] get :index expect(assigns[:contacts].count).to eq(@contacts.count) expect(assigns[:contacts]).to eq(@contacts) expect(response).to render_template("contacts/index") end it "should perform lookup using query string" do @billy_bones = create(:contact, user: current_user, first_name: "Billy", last_name: "Bones") @captain_flint = create(:contact, user: current_user, first_name: "Captain", last_name: "Flint") get :index, params: { query: @billy_bones.email } expect(assigns[:contacts]).to eq([@billy_bones]) expect(assigns[:current_query]).to eq(@billy_bones.email) expect(session[:contacts_current_query]).to eq(@billy_bones.email) end describe "AJAX pagination" do it "should pick up page number from params" do @contacts = [create(:contact, user: current_user)] get :index, params: { page: 42 }, xhr: true expect(assigns[:current_page].to_i).to eq(42) expect(assigns[:contacts]).to eq([]) # page #42 should be empty if there's only one contact ;-) expect(session[:contacts_current_page].to_i).to eq(42) expect(response).to render_template("contacts/index") end it "should pick up saved page number from session" do session[:contacts_current_page] = 42 @contacts = [create(:contact, user: current_user)] get :index, xhr: true expect(assigns[:current_page]).to eq(42) expect(assigns[:contacts]).to eq([]) expect(response).to render_template("contacts/index") end it "should reset current_page when query is altered" do session[:contacts_current_page] = 42 session[:contacts_current_query] = "bill" @contacts = [create(:contact, user: current_user)] get :index, xhr: true expect(assigns[:current_page]).to eq(1) expect(assigns[:contacts]).to eq(@contacts) expect(response).to render_template("contacts/index") end end describe "with mime type of JSON" do it "should render all contacts as JSON" do expect(@controller).to receive(:get_contacts).and_return(contacts = double("Array of Contacts")) expect(contacts).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :index expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render all contacts as xml" do expect(@controller).to receive(:get_contacts).and_return(contacts = double("Array of Contacts")) expect(contacts).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :index expect(response.body).to eq("generated XML") end end end # GET /contacts/1 # GET /contacts/1.xml HTML #---------------------------------------------------------------------------- describe "responding to GET show" do describe "with mime type of HTML" do before(:each) do @contact = create(:contact, id: 42) @stage = Setting.unroll(:opportunity_stage) @comment = Comment.new end it "should expose the requested contact as @contact" do get :show, params: { id: 42 } expect(assigns[:contact]).to eq(@contact) expect(assigns[:stage]).to eq(@stage) expect(assigns[:comment].attributes).to eq(@comment.attributes) expect(response).to render_template("contacts/show") end it "should update an activity when viewing the contact" do get :show, params: { id: @contact.id } expect(@contact.versions.last.event).to eq('view') end end describe "with mime type of JSON" do it "should render the requested contact as JSON" do @contact = create(:contact, id: 42) expect(Contact).to receive(:find).and_return(@contact) expect(@contact).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :show, params: { id: 42 } expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render the requested contact as xml" do @contact = create(:contact, id: 42) expect(Contact).to receive(:find).and_return(@contact) expect(@contact).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :show, params: { id: 42 } expect(response.body).to eq("generated XML") end end describe "contact got deleted or otherwise unavailable" do it "should redirect to contact index if the contact got deleted" do @contact = create(:contact, user: current_user) @contact.destroy get :show, params: { id: @contact.id } expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(contacts_path) end it "should redirect to contact index if the contact is protected" do @private = create(:contact, user: create(:user), access: "Private") get :show, params: { id: @private.id } expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(contacts_path) end it "should return 404 (Not Found) XML error" do @contact = create(:contact, user: current_user) @contact.destroy request.env["HTTP_ACCEPT"] = "application/xml" get :show, params: { id: @contact.id } expect(response.code).to eq("404") # :not_found end end end # GET /contacts/new # GET /contacts/new.xml AJAX #---------------------------------------------------------------------------- describe "responding to GET new" do it "should expose a new contact as @contact and render [new] template" do @contact = Contact.new(user: current_user, access: Setting.default_access) @account = Account.new(user: current_user) @accounts = [create(:account, user: current_user)] get :new, xhr: true expect(assigns[:contact].attributes).to eq(@contact.attributes) expect(assigns[:account].attributes).to eq(@account.attributes) expect(assigns[:accounts]).to eq(@accounts) expect(assigns[:opportunity]).to eq(nil) expect(response).to render_template("contacts/new") end it "should created an instance of related object when necessary" do @opportunity = create(:opportunity) get :new, params: { related: "opportunity_#{@opportunity.id}" }, xhr: true expect(assigns[:opportunity]).to eq(@opportunity) end describe "(when creating related contact)" do it "should redirect to parent asset's index page with the message if parent asset got deleted" do @account = create(:account) @account.destroy get :new, params: { related: "account_#{@account.id}" }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq('window.location.href = "/accounts";') end it "should redirect to parent asset's index page with the message if parent asset got protected" do @account = create(:account, access: "Private") get :new, params: { related: "account_#{@account.id}" }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq('window.location.href = "/accounts";') end end end # GET /contacts/field_group AJAX #---------------------------------------------------------------------------- describe "responding to GET field_group" do context "with an existing tag" do before :each do @tag = create(:tag) end it "should return with an existing tag name" do get :field_group, params: { tag: @tag.name }, xhr: true assigns[:tag].name == @tag.name end it "should have the same count of tags" do get :field_group, params: { tag: @tag.name }, xhr: true expect(Tag.count).to equal(1) end end context "without an existing tag" do it "should not find a tag" do tag_name = "New-Tag" get :field_group, params: { tag: tag_name }, xhr: true expect(assigns[:tag]).to eql(nil) end it "should have the same count of tags" do tag_name = "New-Tag-1" get :field_group, params: { tag: tag_name }, xhr: true expect(Tag.count).to equal(0) end end end # GET /contacts/1/edit AJAX #---------------------------------------------------------------------------- describe "responding to GET edit" do it "should expose the requested contact as @contact and render [edit] template" do @contact = create(:contact, id: 42, user: current_user, lead: nil) @account = Account.new(user: current_user) get :edit, params: { id: 42 }, xhr: true expect(assigns[:contact]).to eq(@contact) expect(assigns[:account].attributes).to eq(@account.attributes) expect(assigns[:previous]).to eq(nil) expect(response).to render_template("contacts/edit") end it "should expose the requested contact as @contact and linked account as @account" do @account = create(:account, id: 99) @contact = create(:contact, id: 42, user: current_user, lead: nil) create(:account_contact, account: @account, contact: @contact) get :edit, params: { id: 42 }, xhr: true expect(assigns[:contact]).to eq(@contact) expect(assigns[:account]).to eq(@account) end it "should expose previous contact as @previous when necessary" do @contact = create(:contact, id: 42) @previous = create(:contact, id: 1992) get :edit, params: { id: 42, previous: 1992 }, xhr: true expect(assigns[:previous]).to eq(@previous) end describe "(contact got deleted or is otherwise unavailable)" do it "should reload current page with the flash message if the contact got deleted" do @contact = create(:contact, user: current_user) @contact.destroy get :edit, params: { id: @contact.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the contact is protected" do @private = create(:contact, user: create(:user), access: "Private") get :edit, params: { id: @private.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end describe "(previous contact got deleted or is otherwise unavailable)" do before(:each) do @contact = create(:contact, user: current_user) @previous = create(:contact, user: create(:user)) end it "should notify the view if previous contact got deleted" do @previous.destroy get :edit, params: { id: @contact.id, previous: @previous.id }, xhr: true expect(flash[:warning]).to eq(nil) expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("contacts/edit") end it "should notify the view if previous contact got protected" do @previous.update_attribute(:access, "Private") get :edit, params: { id: @contact.id, previous: @previous.id }, xhr: true expect(flash[:warning]).to eq(nil) expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("contacts/edit") end end end # POST /contacts # POST /contacts.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST create" do describe "with valid params" do it "should expose a newly created contact as @contact and render [create] template" do @contact = build(:contact, first_name: "Billy", last_name: "Bones") allow(Contact).to receive(:new).and_return(@contact) post :create, params: { contact: { first_name: "Billy", last_name: "Bones" }, account: { name: "Hello world" } }, xhr: true expect(assigns(:contact)).to eq(@contact) expect(assigns(:contact).reload.account.name).to eq("Hello world") expect(response).to render_template("contacts/create") end it "should be able to associate newly created contact with the opportunity" do @opportunity = create(:opportunity, id: 987) @contact = build(:contact) allow(Contact).to receive(:new).and_return(@contact) post :create, params: { contact: { first_name: "Billy" }, account: {}, opportunity: 987 }, xhr: true expect(assigns(:contact).opportunities).to include(@opportunity) expect(response).to render_template("contacts/create") end it "should reload contacts to update pagination if called from contacts index" do @contact = build(:contact, user: current_user) allow(Contact).to receive(:new).and_return(@contact) request.env["HTTP_REFERER"] = "http://localhost/contacts" post :create, params: { contact: { first_name: "Billy", last_name: "Bones" }, account: {} }, xhr: true expect(assigns[:contacts]).to eq([@contact]) end it "should add a new comment to the newly created contact when specified" do @contact = build(:contact, user: current_user) allow(Contact).to receive(:new).and_return(@contact) post :create, params: { contact: { first_name: "Testy", last_name: "McTest" }, account: { name: "Hello world" }, comment_body: "Awesome comment is awesome" }, xhr: true expect(assigns[:contact].comments.map(&:comment)).to include("Awesome comment is awesome") end end describe "with invalid params" do before(:each) do @contact = build(:contact, first_name: nil, user: current_user, lead: nil) allow(Contact).to receive(:new).and_return(@contact) end # Redraw [create] form with selected account. it "should redraw [Create Contact] form with selected account" do @account = create(:account, id: 42, user: current_user) # This redraws [create] form with blank account. post :create, params: { contact: {}, account: { id: 42, user_id: current_user.id } }, xhr: true expect(assigns(:contact)).to eq(@contact) expect(assigns(:account)).to eq(@account) expect(assigns(:accounts)).to eq([@account]) expect(response).to render_template("contacts/create") end # Redraw [create] form with related account. it "should redraw [Create Contact] form with related account" do @account = create(:account, id: 123, user: current_user) request.env["HTTP_REFERER"] = "http://localhost/accounts/123" post :create, params: { contact: { first_name: nil }, account: { name: nil, user_id: current_user.id } }, xhr: true expect(assigns(:contact)).to eq(@contact) expect(assigns(:account)).to eq(@account) expect(assigns(:accounts)).to eq([@account]) expect(response).to render_template("contacts/create") end it "should redraw [Create Contact] form with blank account" do @accounts = [create(:account, user: current_user)] @account = Account.new(user: current_user) post :create, params: { contact: { first_name: nil }, account: { name: nil, user_id: current_user.id } }, xhr: true expect(assigns(:contact)).to eq(@contact) expect(assigns(:account).attributes).to eq(@account.attributes) expect(assigns(:accounts)).to eq(@accounts) expect(response).to render_template("contacts/create") end it "should preserve Opportunity when called from Oppotuunity page" do @opportunity = create(:opportunity, id: 987) post :create, params: { contact: {}, account: {}, opportunity: 987 }, xhr: true expect(assigns(:opportunity)).to eq(@opportunity) expect(response).to render_template("contacts/create") end end end # PUT /contacts/1 # PUT /contacts/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT update" do describe "with valid params" do it "should update the requested contact and render [update] template" do @contact = create(:contact, id: 42, first_name: "Billy") put :update, params: { id: 42, contact: { first_name: "Bones" }, account: {} }, xhr: true expect(assigns[:contact].first_name).to eq("Bones") expect(assigns[:contact]).to eq(@contact) expect(response).to render_template("contacts/update") end it "should be able to create a new account and link it to the contact" do @contact = create(:contact, id: 42, first_name: "Billy") put :update, params: { id: 42, contact: { first_name: "Bones" }, account: { name: "new account" } }, xhr: true expect(assigns[:contact].first_name).to eq("Bones") expect(assigns[:contact].account.name).to eq("new account") end it "should be able to link existing account with the contact" do @account = create(:account, id: 99, name: "Hello world") @contact = create(:contact, id: 42, first_name: "Billy") put :update, params: { id: 42, contact: { first_name: "Bones" }, account: { id: 99 } }, xhr: true expect(assigns[:contact].first_name).to eq("Bones") expect(assigns[:contact].account.id).to eq(99) end it "should update contact permissions when sharing with specific users" do @contact = create(:contact, id: 42, access: "Public") put :update, params: { id: 42, contact: { first_name: "Hello", access: "Shared", user_ids: [7, 8] }, account: {} }, xhr: true expect(assigns[:contact].access).to eq("Shared") expect(assigns[:contact].user_ids.sort).to eq([7, 8]) expect(assigns[:contact]).to eq(@contact) end describe "contact got deleted or otherwise unavailable" do it "should reload current page is the contact got deleted" do @contact = create(:contact, user: current_user) @contact.destroy put :update, params: { id: @contact.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the contact is protected" do @private = create(:contact, user: create(:user), access: "Private") put :update, params: { id: @private.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "with invalid params" do it "should not update the contact, but still expose it as @contact and render [update] template" do @contact = create(:contact, id: 42, user: current_user, first_name: "Billy", lead: nil) put :update, params: { id: 42, contact: { first_name: nil }, account: {} }, xhr: true expect(assigns[:contact].reload.first_name).to eq("Billy") expect(assigns[:contact]).to eq(@contact) expect(response).to render_template("contacts/update") end it "should expose existing account as @account if selected" do @account = create(:account, id: 99) @contact = create(:contact, id: 42, account: @account) put :update, params: { id: 42, contact: { first_name: nil }, account: { id: 99 } }, xhr: true expect(assigns[:account]).to eq(@account) end end end # DELETE /contacts/1 # DELETE /contacts/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to DELETE destroy" do before(:each) do @contact = create(:contact, user: current_user) end describe "AJAX request" do it "should destroy the requested contact and render [destroy] template" do delete :destroy, params: { id: @contact.id }, xhr: true expect { Contact.find(@contact.id) }.to raise_error(ActiveRecord::RecordNotFound) expect(response).to render_template("contacts/destroy") end describe "when called from Contacts index page" do before(:each) do request.env["HTTP_REFERER"] = "http://localhost/contacts" end it "should try previous page and render index action if current page has no contacts" do session[:contacts_current_page] = 42 delete :destroy, params: { id: @contact.id }, xhr: true expect(session[:contacts_current_page]).to eq(41) expect(response).to render_template("contacts/index") end it "should render index action when deleting last contact" do session[:contacts_current_page] = 1 delete :destroy, params: { id: @contact.id }, xhr: true expect(session[:contacts_current_page]).to eq(1) expect(response).to render_template("contacts/index") end end describe "when called from related asset page page" do it "should reset current page to 1" do request.env["HTTP_REFERER"] = "http://localhost/accounts/123" delete :destroy, params: { id: @contact.id }, xhr: true expect(session[:contacts_current_page]).to eq(1) expect(response).to render_template("contacts/destroy") end end describe "contact got deleted or otherwise unavailable" do it "should reload current page is the contact got deleted" do @contact = create(:contact, user: current_user) @contact.destroy delete :destroy, params: { id: @contact.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the contact is protected" do @private = create(:contact, user: create(:user), access: "Private") delete :destroy, params: { id: @private.id }, xhr: true expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "HTML request" do it "should redirect to Contacts index when a contact gets deleted from its landing page" do delete :destroy, params: { id: @contact.id } expect(flash[:notice]).not_to eq(nil) expect(response).to redirect_to(contacts_path) end it "should redirect to contact index with the flash message is the contact got deleted" do @contact = create(:contact, user: current_user) @contact.destroy delete :destroy, params: { id: @contact.id } expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(contacts_path) end it "should redirect to contact index with the flash message if the contact is protected" do @private = create(:contact, user: create(:user), access: "Private") delete :destroy, params: { id: @private.id } expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(contacts_path) end end end # PUT /contacts/1/attach # PUT /contacts/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = create(:contact) @attachment = create(:task, asset: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = create(:contact) @attachment = create(:opportunity) end it_should_behave_like("attach") end end # PUT /contacts/1/attach # PUT /contacts/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = create(:contact) @attachment = create(:task, asset: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = create(:contact) @attachment = create(:opportunity) end it_should_behave_like("attach") end end # POST /contacts/1/discard # POST /contacts/1/discard.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST discard" do describe "tasks" do before do @model = create(:contact) @attachment = create(:task, asset: @model) end it_should_behave_like("discard") end describe "opportunities" do before do @attachment = create(:opportunity) @model = create(:contact) @model.opportunities << @attachment end it_should_behave_like("discard") end end # POST /contacts/auto_complete/query AJAX #---------------------------------------------------------------------------- describe "responding to POST auto_complete" do before(:each) do @auto_complete_matches = [create(:contact, first_name: "Hello", last_name: "World", user: current_user)] end it_should_behave_like("auto complete") end # GET /contacts/redraw AJAX #---------------------------------------------------------------------------- describe "responding to POST redraw" do it "should save user selected contact preference" do get :redraw, params: { per_page: 42, view: "long", sort_by: "first_name", naming: "after" }, xhr: true expect(current_user.preference[:contacts_per_page].to_i).to eq(42) expect(current_user.preference[:contacts_index_view]).to eq("long") expect(current_user.preference[:contacts_sort_by]).to eq("contacts.first_name ASC") expect(current_user.preference[:contacts_naming]).to eq("after") end it "should set similar options for Leads" do get :redraw, params: { sort_by: "first_name", naming: "after" }, xhr: true expect(current_user.pref[:leads_sort_by]).to eq("leads.first_name ASC") expect(current_user.pref[:leads_naming]).to eq("after") end it "should reset current page to 1" do get :redraw, params: { per_page: 42, view: "long", sort_by: "first_name", naming: "after" }, xhr: true expect(session[:contacts_current_page]).to eq(1) end it "should select @contacts and render [index] template" do @contacts = [ create(:contact, first_name: "Alice", user: current_user), create(:contact, first_name: "Bobby", user: current_user) ] get :redraw, params: { per_page: 1, sort_by: "first_name" }, xhr: true expect(assigns(:contacts)).to eq([@contacts.first]) expect(response).to render_template("contacts/index") end end end
40.242553
176
0.603997
28fdc40b5eb11fe14ae81339c8b5838f3f6287e7
182
class CreateEnquiries < ActiveRecord::Migration[5.2] def change create_table :enquiries do |t| t.string :name t.text :message t.timestamps end end end
16.545455
52
0.653846
612711011b893b56c273f6e124b698386895443a
48
module SortNames VERSION = '0.1.0'.freeze end
12
26
0.708333
bbffbbacade452768ff915c2d99aa0fef343b797
685
Spree::Core::Engine.routes.draw do namespace :admin do resources :reports, only: [:index] do collection do get :total_sales_of_each_variant post :total_sales_of_each_variant get :ten_days_order_count get :thirty_days_order_count get :stock_report post :stock_report get :stockout_report post :stockout_report get :sales_total_net post :sales_total_net get :sales_total_by_country post :sales_total_by_country get :total_sales_by_product post :total_sales_by_product get :reimbursement_total post :reimbursement_total end end end end
27.4
41
0.665693
bfe958d1deae7eee7d123bf99273c4143dcfe12a
359
require 'forwardable' require 'apitizer' require_relative 'typekit/core' require_relative 'typekit/error' require_relative 'typekit/helper' require_relative 'typekit/converter' require_relative 'typekit/client' require_relative 'typekit/element' require_relative 'typekit/collection' require_relative 'typekit/record' require_relative 'typekit/version'
19.944444
37
0.835655
87914848ccc796318a2d79e6c5e0e3a53cf35eff
3,532
# 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::ServiceFabric::V6_4_0_36 module Models # # Application Created event. # class ApplicationCreatedEvent < ApplicationEvent include MsRestAzure def initialize @Kind = "ApplicationCreated" end attr_accessor :Kind # @return [String] Application type name. attr_accessor :application_type_name # @return [String] Application type version. attr_accessor :application_type_version # @return [String] Application definition kind. attr_accessor :application_definition_kind # # Mapper for ApplicationCreatedEvent class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ApplicationCreated', type: { name: 'Composite', class_name: 'ApplicationCreatedEvent', model_properties: { event_instance_id: { client_side_validation: true, required: true, serialized_name: 'EventInstanceId', type: { name: 'String' } }, category: { client_side_validation: true, required: false, serialized_name: 'Category', type: { name: 'String' } }, time_stamp: { client_side_validation: true, required: true, serialized_name: 'TimeStamp', type: { name: 'DateTime' } }, has_correlated_events: { client_side_validation: true, required: false, serialized_name: 'HasCorrelatedEvents', type: { name: 'Boolean' } }, Kind: { client_side_validation: true, required: true, serialized_name: 'Kind', type: { name: 'String' } }, application_id: { client_side_validation: true, required: true, serialized_name: 'ApplicationId', type: { name: 'String' } }, application_type_name: { client_side_validation: true, required: true, serialized_name: 'ApplicationTypeName', type: { name: 'String' } }, application_type_version: { client_side_validation: true, required: true, serialized_name: 'ApplicationTypeVersion', type: { name: 'String' } }, application_definition_kind: { client_side_validation: true, required: true, serialized_name: 'ApplicationDefinitionKind', type: { name: 'String' } } } } } end end end end
28.483871
70
0.471687
e2c01ea135049f861049d3db4a9c9fcf15939bdc
575
require 'spec_helper' describe Facter::Util::Fact.to_s do before(:each) do Facter.clear end describe 'mysqld_version' do context 'with value' do before :each do Facter::Util::Resolution.stubs(:exec).with('mysqld -V 2>/dev/null').returns('mysqld Ver 5.5.49-37.9 for Linux on x86_64 (Percona Server (GPL), Release 37.9, Revision efa0073)') end it { expect(Facter.fact(:mysqld_version).value).to eq('mysqld Ver 5.5.49-37.9 for Linux on x86_64 (Percona Server (GPL), Release 37.9, Revision efa0073)') } end end end
30.263158
185
0.66087
28c41902002b403b49a02dee000c0952ecc04c1b
3,273
# encoding: UTF-8 require 'test_helper' class Wankel::OneOffParseTest < Minitest::Test test "should parse 23456789012E666 as Infinity" do infinity = (1.0/0) assert_equal({'key' => infinity}, Wankel.parse('{"key": 23456789012E999}')) end test "should not parse JSON with a comment, with :allow_comments set to false" do assert_raises Wankel::ParseError do Wankel.parse('{"key": /* this is a comment */ "value"}', :allow_comments => false) end end test "should not parse invalid UTF8 with :validate_utf8 set to true" do assert_raises Wankel::ParseError do Wankel.parse("[\"#{"\201\203"}\"]", :validate_utf8 => true) end end test "should parse invalid UTF8 with :validate_utf8 set to false" do Wankel.parse("[\"#{"\201\203"}\"]", :validate_utf8 => false) end test "should not allow trailing garbage with :allow_trailing_garbage set to false" do assert_raises Wankel::ParseError do Wankel.parse('{"key": "value"}gar', :allow_trailing_garbage => false) end end test "should allow trailing garbage with :allow_trailing_garbage set to true" do assert_equal( {"key" => "value"}, Wankel.parse('{"key": "value"}gar', :allow_trailing_garbage => true) ) end test "should parse using it's class method, from an IO" do io = StringIO.new('{"key": 1234}') assert_equal({'key' => 1234}, Wankel.parse(io)) end test "should parse using it's class method, from a string with symbolized keys" do assert_equal({:key => 1234}, Wankel.parse('{"key": 1234}', :symbolize_keys => true)) end test "should parse using it's class method, from a utf-8 string with multibyte characters, with symbolized keys" do assert_equal({:"日本語" => 1234}, Wankel.parse('{"日本語": 1234}', :symbolize_keys => true)) end test "should parse using it's class method, from a string" do assert_equal({"key" => 1234}, Wankel.parse('{"key": 1234}')) end test "should parse numbers greater than 2,147,483,648" do assert_equal({"id" => 2147483649}, Wankel.parse("{\"id\": 2147483649}")) assert_equal({"id" => 5687389800}, Wankel.parse("{\"id\": 5687389800}")) assert_equal({"id" => 1046289770033519442869495707521600000000}, Wankel.parse("{\"id\": 1046289770033519442869495707521600000000}")) end test "should return strings and hash keys in utf-8 if Encoding.default_internal is nil" do Encoding.default_internal = nil assert_equal(Encoding.find('utf-8'), Wankel.parse('{"key": "value"}').keys.first.encoding) assert_equal(Encoding.find('utf-8'), Wankel.parse('{"key": "value"}').values.first.encoding) end test "should return strings and hash keys encoded as specified in Encoding.default_internal if it's set" do Encoding.default_internal = Encoding.find('utf-8') assert_equal(Encoding.default_internal, Wankel.parse('{"key": "value"}').keys.first.encoding) assert_equal(Encoding.default_internal, Wankel.parse('{"key": "value"}').values.first.encoding) Encoding.default_internal = Encoding.find('us-ascii') assert_equal(Encoding.default_internal, Wankel.parse('{"key": "value"}').keys.first.encoding) assert_equal(Encoding.default_internal, Wankel.parse('{"key": "value"}').values.first.encoding) end end
41.961538
136
0.68897
3895ebcfd8c89f570e42ff041ca78b2621fe1510
1,020
# frozen_string_literal: true require 'aws_backend' class AWSCloudFrontOriginRequestPolicy < AwsResourceBase name 'aws_cloudfront_origin_request_policy' desc 'Describes an origin request policy.' example " describe aws_cloudfront_origin_request_policy(id: 'ID') do it { should exist } end " def initialize(opts = {}) opts = { id: opts } if opts.is_a?(String) super(opts) validate_parameters(required: [:id]) raise ArgumentError, "#{@__resource_name__}: id must be provided" unless opts[:id] && !opts[:id].empty? @display_name = opts[:id] resp = @aws.cloudfront_client.get_origin_request_policy({ id: opts[:id] }) @origin_request_policy= resp.origin_request_policy.to_h create_resource_methods(@origin_request_policy) end def id return nil unless exists? @origin_request_policy[:id] end def exists? !@origin_request_policy.nil? && !@origin_request_policy.empty? end def to_s "Origin Request Policy ID: #{@display_name}" end end
26.153846
107
0.714706
26e173c4e96e316bc6bb2a32be509d77cf6b87e1
6,583
require 'rails_helper' RSpec.describe TasksController, type: :controller do let!(:user) { create(:user, username: 'the_user') } #I have used let! instead of let because let is lazily evaluated describe 'index' do it 'should creates the user received if it is not already' do expect(User.count).to eq(1) get :index, params: { user: 'the_user' } expect(User.count).to eq(1) get :index, params: { user: 'another_user' } expect(User.count).to eq(2) expect(User.all[1].username).to eq('another_user') end describe 'returns all projects' do it 'when user already exists' do user.projects.create(name: 'any project') user.projects.create(name: 'another project') expect(Project.count).to eq(2) get :index, params: { user: 'the_user' } expect(assigns(:user).projects.map(&:name)).to eq(['any project', 'another project']) end it 'when user does not exist' do get :index, params: { user: 'new_user' } expect(assigns(:user).projects).to be_empty end end it 'should assigns to the task the last project used' do user.projects.create!(name: 'any project') user.projects.create!(name: 'another project') user.projects.create!(name: 'last project') user.projects[0].tasks.create!(description: 'any description') user.projects[1].tasks.create!(description: 'another description') expect(Task.count).to eq(2) get :index, params: { user: 'the_user' } expect(assigns(:task).project.name).to eq('another project') end end describe 'create' do it 'should creates the project if it doesnt exist yet' do post :create, params: { project: 'any project', user: 'the_user' }, xhr: true expect(Project.where(user: user).count).to eq(1) end it 'should not creates the project if it already exists' do project = Project.create(user: user, name: 'any project') post :create, params: { project: 'any project', user: 'the_user' }, xhr: true expect(Project.where(user: user).count).to eq(1) expect(Project.where(user: user).first).to eq(project) end it 'should creates a task' do post :create, params: { project: 'any project', user: 'the_user' }, xhr: true project = Project.where(name: 'any project', user: user).first expect(Task.where(project: project).count).to eq(1) expect(assigns(:task)).not_to be_nil expect(assigns(:task_period).started_at).not_to be_nil expect(assigns(:task_period).started?).to be_truthy end end describe 'update' do let(:project) { create(:project, user: user) } let(:task) { create(:task, project: project) } it 'should creates a new task period within the existing task' do previous_size = TaskPeriod.where(task: task).count post :update, params: {user: 'the_user', id: task.id}, xhr: true expect(TaskPeriod.where(task: task).count).to eq(1+previous_size) expect(TaskPeriod.where(task: task).last.started?).to be_truthy end end describe 'pause' do let(:project) { create(:project, user: user) } let(:task) { create(:task, project: project) } it 'should add a finished date to the task period already opened' do task_period = TaskPeriod.create!(task: task, started_at: Time.now) post :pause, params: {user: 'the_user', id: task_period.id}, xhr: true expect(TaskPeriod.find(task_period.id).finished_at?).not_to be_nil expect(TaskPeriod.find(task_period.id).started?).to be_falsy end it 'should not allow to finish a task from other user' do task_period = TaskPeriod.create!(task: task, started_at: Time.now) post :pause, params: {user: 'another_user', id: task_period.id}, xhr: true expect(TaskPeriod.find(task_period.id).finished_at).to be_nil end end describe 'stop' do let(:project) { create(:project, user: user) } let(:task) { create(:task, project: project) } let(:task_period) { create(:task_period, task: task) } let!(:default_params) { { user: 'the_user', id: task_period.id, task: {billable: true, description: 'hi', project: project.name, client: 'any'} } } it 'should add a finished date to the task period already opened' do post :stop, params: default_params expect(TaskPeriod.find(task_period.id).finished_at?).not_to be_nil expect(TaskPeriod.find(task_period.id).started?).to be_falsy end it 'should not allow to finish a task from other user' do task_period = create(:task_period_started) post :stop, params: default_params.merge(user: 'another_user') task_period.reload expect(task_period.finished_at).to be_nil expect(response).to redirect_to '/another_user' end it 'should redirects to index after closing the last task' do post :stop, params: default_params expect(response).to redirect_to '/the_user' end it 'should save the task information' do default_params[:task] = default_params[:task].merge({description: 'new description', billable: false}) post :stop, params: default_params task.reload expect(task.description).to eq('new description') expect(task.billable).to be_falsy end it 'should change the project if it is changed' do another_project = create(:project, name: 'another project', user: user) default_params[:task] = default_params[:task].merge({project: 'another project'}) post :stop, params: default_params task.reload expect(task.project.id).to eq(another_project.id) end it 'should change the project if it is changed' do default_params[:task] = default_params[:task].merge({project: 'new project'}) post :stop, params: default_params task.reload expect(task.project.name).to eq('new project') end it 'should change the client if it is changed when client already exists' do another_client = create(:client, name: 'another client', user: user) default_params[:task] = default_params[:task].merge({client: 'another client'}) post :stop, params: default_params task.reload expect(task.project.client.id).to eq(another_client.id) end it 'should create the client if it is changed' do default_params[:task] = default_params[:task].merge({client: 'new client'}) post :stop, params: default_params task.reload expect(task.project.client.name).to eq('new client') end end end
33.080402
151
0.664591
79a9a9486dee2b3f39b8de11c2b35b5820f8c7fe
556
# encoding: utf-8 require 'spec_helper' describe Function::Predicate::GreaterThanOrEqualTo, '.call' do subject { object.call(left, right) } let(:object) { described_class } context 'when left is equal to right' do let(:left) { 1 } let(:right) { 1 } it { should be(true) } end context 'when left is greater than right' do let(:left) { 2 } let(:right) { 1 } it { should be(true) } end context 'when left is less than right' do let(:left) { 1 } let(:right) { 2 } it { should be(false) } end end
17.935484
62
0.602518
1dc8abf74658803c7ecb0c06490e92e86150e47e
1,350
# frozen_string_literal: true version = File.read(File.expand_path("../RAILS_VERSION", __dir__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = "actionpack" s.version = version s.summary = "Web-flow and rendering framework putting the VC in MVC (part of Rails)." s.description = "Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server." s.required_ruby_version = ">= 2.4.1" s.license = "MIT" s.author = "David Heinemeier Hansson" s.email = "[email protected]" s.homepage = "http://rubyonrails.org" s.files = Dir["CHANGELOG.md", "README.rdoc", "MIT-LICENSE", "lib/**/*"] s.require_path = "lib" s.requirements << "none" s.metadata = { "source_code_uri" => "https://github.com/rails/rails/tree/v#{version}/actionpack", "changelog_uri" => "https://github.com/rails/rails/blob/v#{version}/actionpack/CHANGELOG.md" } s.add_dependency "activesupport", version s.add_dependency "rack", "~> 2.0" s.add_dependency "rack-test", ">= 0.6.3" s.add_dependency "rails-html-sanitizer", "~> 1.0", ">= 1.0.2" s.add_dependency "rails-dom-testing", "~> 2.0" s.add_dependency "actionview", version s.add_development_dependency "activemodel", version end
34.615385
158
0.675556
ed26565b59906f96d50782d8c6e331fe06f7ebaf
255
#! /usr/bin/ruby # encoding: utf-8 require 'xcodeproj' projectPath = ARGV[0] targetId = ARGV[1] project = Xcodeproj::Project.open(projectPath) project.root_object.attributes["TargetAttributes"][targetId]["ProvisioningStyle"]="Manual" project.save
15.9375
90
0.74902
bf8caa1e0d5953839e84b4681c4c41ebc153dc72
13,254
require_relative "../../aws_refresher_spec_common" require_relative "../../aws_refresher_spec_counts" describe ManageIQ::Providers::Amazon::CloudManager::Refresher do include AwsRefresherSpecCommon include AwsRefresherSpecCounts ###################################################################################################################### # Spec scenarios for making sure targeted refresh stays in it's scope ###################################################################################################################### # # We test every that every targeted refresh we do is staying in it's scope. The simplest test for this is that # after full refresh, targeted refresh should not change anything (just update existing items). So this verify the # targeted refresh is not deleting records that are out of its scope. before(:each) do @ems = FactoryBot.create(:ems_amazon_with_vcr_authentication) end it ".ems_type" do expect(described_class.ems_type).to eq(:ec2) end # Lets test only the fastest setting, since we test all settings elsewhere [ :inventory_object_refresh => true, :inventory_collections => { :saver_strategy => "batch", :use_ar_object => false, }, ].each do |settings| context "with settings #{settings}" do before(:each) do stub_refresh_settings(settings) create_tag_mapping end it "will refresh an EC2 classic VM powered on and LB full targeted refresh" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager => @ems, :association => :vms, :manager_ref => {:ems_ref => "i-680071e9"}) lb_target = InventoryRefresh::Target.new(:manager => @ems, :association => :load_balancers, :manager_ref => {:ems_ref => "EmsRefreshSpec-LoadBalancer"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/ec2_classic_vm_and_lb_full_refresh") do EmsRefresh.refresh([vm_target, lb_target]) end @ems.reload assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group assert_specific_template assert_specific_load_balancer_non_vpc assert_specific_load_balancer_non_vpc_vms assert_specific_vm_powered_on end end end it "will refresh a VPC VM with floating IP and connected LBs" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-8b5739f2"}) lb_target_1 = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :load_balancers, :manager_ref => {:ems_ref => "EmSRefreshSpecVPCELB"}) lb_target_2 = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :load_balancers, :manager_ref => {:ems_ref => "EmSRefreshSpecVPCELB2"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/vpc_vm_with_floating_ip_and_lbs_full_refresh") do EmsRefresh.refresh([vm_target, lb_target_1, lb_target_2]) end @ems.reload assert_vpc assert_vpc_subnet_1 assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group_on_cloud_network assert_specific_template assert_specific_load_balancer_vpc assert_specific_load_balancer_vpc2 assert_specific_load_balancer_listeners_vpc_and_vpc_2 assert_specific_cloud_volume_vm_on_cloud_network assert_specific_vm_on_cloud_network end end end it "will refresh a VPC VM with public IP" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new(:manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-c72af2f6"}) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/vpc_vm_with_public_ip_and_template") do EmsRefresh.refresh([vm_target]) end @ems.reload assert_vpc assert_vpc_subnet_1 assert_specific_flavor assert_specific_key_pair assert_specific_az assert_specific_security_group_on_cloud_network assert_specific_template_2 assert_specific_cloud_volume_vm_on_cloud_network_public_ip assert_specific_vm_on_cloud_network_public_ip end end end it "will refresh an orchestration stack" do assert_targeted_refresh_scope do orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stack") do EmsRefresh.refresh([orchestration_stack_target]) end @ems.reload assert_specific_orchestration_template assert_specific_orchestration_stack_data assert_specific_orchestration_stack_parameters assert_specific_orchestration_stack_resources assert_specific_orchestration_stack_outputs # orchestration stack belongs to a provider expect(@orch_stack.ext_management_system).to eq(@ems) # orchestration stack belongs to an orchestration template expect(@orch_stack.orchestration_template).to eq(@orch_template) end end end it "will refresh a nested orchestration stacks" do assert_targeted_refresh_scope do orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack/"\ "b4e06950-2fed-11e7-bd93-500c286374d1" } ) orchestration_stack_target_nested = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stacks_nested") do EmsRefresh.refresh([orchestration_stack_target, orchestration_stack_target_nested]) end @ems.reload assert_specific_orchestration_template assert_specific_parent_orchestration_stack_data assert_specific_orchestration_stack_data assert_specific_orchestration_stack_parameters assert_specific_orchestration_stack_resources assert_specific_orchestration_stack_outputs # orchestration stack belongs to a provider expect(@orch_stack.ext_management_system).to eq(@ems) # orchestration stack belongs to an orchestration template expect(@orch_stack.orchestration_template).to eq(@orch_template) # orchestration stack can be nested expect(@orch_stack.parent).to eq(@parent_stack) expect(@parent_stack.children).to match_array([@orch_stack]) end end end it "will refresh a nested orchestration stacks with Vm" do assert_targeted_refresh_scope do vm_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :vms, :manager_ref => {:ems_ref => "i-0bca58e6e540ddc39"} ) orchestration_stack_target = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack/"\ "b4e06950-2fed-11e7-bd93-500c286374d1" } ) orchestration_stack_target_nested = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :orchestration_stacks, :manager_ref => { :ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-"\ "WebServerInstance-1CTHQS2P5WJ7S/d3bb46b0-2fed-11e7-a3d9-503f23fb55fe" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/orchestration_stacks_nested_with_vm") do EmsRefresh.refresh([vm_target, orchestration_stack_target, orchestration_stack_target_nested]) end @ems.reload assert_specific_orchestration_template assert_specific_orchestration_stack end end end it "will refresh a volume with volume_snapshot" do assert_targeted_refresh_scope do base_volume = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volumes, :manager_ref => { :ems_ref => "vol-0e1613cacf4688009" } ) volume = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volumes, :manager_ref => { :ems_ref => "vol-0e4c86c12b28cead8" } ) snapshot = InventoryRefresh::Target.new( :manager_id => @ems.id, :association => :cloud_volume_snapshots, :manager_ref => { :ems_ref => "snap-055095f47fab5e749" } ) 2.times do # Run twice to verify that a second run with existing data does not change anything @ems.reload VCR.use_cassette(described_class.name.underscore + "_targeted/cloud_volume_with_snapshot") do EmsRefresh.refresh([base_volume, volume, snapshot]) end @ems.reload assert_specific_cloud_volume_vm_on_cloud_network assert_specific_cloud_volume_snapshot end end end end end def assert_targeted_refresh_scope stored_table_counts = make_full_refresh yield assert_all(stored_table_counts) end def make_full_refresh stored_table_counts = nil @ems.reload VCR.use_cassette(described_class.name.underscore + '_inventory_object') do EmsRefresh.refresh(@ems) EmsRefresh.refresh(@ems.network_manager) EmsRefresh.refresh(@ems.ebs_storage_manager) @ems.reload stored_table_counts = table_counts_from_api assert_counts(stored_table_counts) end assert_common assert_mapped_tags_on_template stored_table_counts end def assert_all(stored_table_counts) assert_counts(stored_table_counts) assert_common assert_mapped_tags_on_template end def table_counts_from_api counts = super counts[:flavor] = counts[:flavor] + 5 # Graph refresh collect all flavors, not filtering them by known_flavors counts[:service_instances] = 3 counts[:service_offerings] = 3 counts[:service_parameters_sets] = 5 counts end end
39.213018
131
0.606458
ac90841a695a50df9842d8e369ef471700475264
1,212
$:.unshift(File.join(File.expand_path("."), "src")) require 'pathname' require 'unlight' $arg = ARGV.shift module Unlight # デバッグ用アイテム追加 puts "アイテムを追加しますか?(y/n)" answer = gets.chomp if answer == "y" || answer == "Y" || answer == "yes" || answer == "Yes" puts "追加するアバターのIDを指定してください" avatar_id = gets.chomp.to_i puts "追加するアイテムを指定してください" puts "Format例:[チケット×] => [9,3]" list_str = gets.chomp list = list_str.split(",") item_id = list.shift.to_i num = list.shift.to_i AT_TIME = Time.now.utc import_list = [] set_list = [] cnt = 0 num.times do tmp = [avatar_id, item_id, AT_TIME, AT_TIME] set_list << tmp if set_list.size > 500 import_list << set_list set_list = [] end cnt += 1 if cnt > 0 && cnt % 1000 == 0 puts "ins set cnt:#{cnt} ..." end end if set_list.size > 0 import_list << set_list set_list = [] end columns = [:avatar_id, :avatar_item_id, :created_at, :updated_at] puts "import_list:#{import_list.size}" DB.transaction do import_list.each do |import_set| ItemInventory.import(columns, import_set) end end end end
22.867925
73
0.589109
e909d659d822f5314131180e94aec4c186fe13e1
125
require 'test_helper' class StaticValueTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
15.625
47
0.712
1cbcf3065d5ab6d82794070f8c8b43930c558352
669
cask 'sqlpro-studio' do version '1.0.423' sha256 '921bdd2e2a185a4c45f61c5d5f24503dfb944abf15a1ab243c621558d082891e' # d3fwkemdw8spx3.cloudfront.net/studio was verified as official when first introduced to the cask url "https://d3fwkemdw8spx3.cloudfront.net/studio/SQLProStudio.#{version}.app.zip" name 'SQLPro Studio' homepage 'https://www.sqlprostudio.com/' app 'SQLPro Studio.app' zap trash: [ '~/Library/Containers/com.hankinsoft.osx.sqlprostudio', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.hankinsoft.osx.sqlprostudio.sfl*', ] end
39.352941
163
0.7429
bbf1028d2a0240bb6fe306d3ec0374223e316d55
213
class CreateFoodLogs < ActiveRecord::Migration[5.1] def change create_table :food_logs do |t| t.integer :user_id t.integer :recipe_id t.datetime :date t.timestamps end end end
17.75
51
0.657277
016343e8c46cb1a41ceb862c251df89180f18dea
2,470
# encoding: UTF-8 # frozen_string_literal: true describe Blockchain do context 'validations' do subject { build(:blockchain, 'eth-mainet') } it 'checks valid record' do expect(subject).to be_valid end it 'validates presence of key' do subject.key = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Key can't be blank"] end it 'validates client' do subject.client = 'zephyreum' expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Client is not included in the list"] end it 'validates presence of name' do subject.name = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Name can't be blank"] end it 'validates presence of client' do subject.client = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include "Client can't be blank" end it 'validates inclusion of status' do subject.status = 'abc' expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Status is not included in the list"] end it 'validates height should be greater than or equal to 1' do subject.height = 0 expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Height must be greater than or equal to 1"] end it 'validates min_confirmations should be greater than or equal to 1' do subject.min_confirmations = 0 expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Min confirmations must be greater than or equal to 1"] end it 'validates structure of server' do subject.server = 'Wrong URL' expect(subject).to_not be_valid expect(subject.errors.full_messages).to eq ["Server is not a valid URL"] end it 'saves server in encrypted column' do subject.save expect { subject.server = 'http://parity:8545/' subject.save }.to change { subject.server_encrypted } end it 'does not update server_encrypted before model is saved' do subject.save expect { subject.server = 'http://geth:8545/' }.not_to change { subject.server_encrypted } end it 'updates server field' do expect { subject.server = 'http://geth:8545/' }.to change { subject.server }.to 'http://geth:8545/' end end end
29.759036
105
0.665587
28c8ac05e6b1885316b5dd146add3342d1a8ba09
5,176
module RailsAdmin module Config # Provides accessors and autoregistering of model's fields. module HasFields # Defines a configuration for a field. def field(name, type = nil, add_to_section = true, &block) field = _fields.detect { |f| name == f.name } # some fields are hidden by default (belongs_to keys, has_many associations in list views.) # unhide them if config specifically defines them if field field.show unless field.instance_variable_get("@#{field.name}_registered").is_a?(Proc) end # Specify field as virtual if type is not specifically set and field was not # found in default stack if field.nil? && type.nil? field = (_fields << RailsAdmin::Config::Fields::Types.load(:string).new(self, name, nil)).last # Register a custom field type if one is provided and it is different from # one found in default stack elsif type && type != (field.nil? ? nil : field.type) _fields.delete(field) unless field.nil? properties = abstract_model.properties.detect { |p| name == p.name } field = (_fields << RailsAdmin::Config::Fields::Types.load(type).new(self, name, properties)).last end # If field has not been yet defined add some default properties if add_to_section && !field.defined field.defined = true field.order = _fields.select(&:defined).length end # If a block has been given evaluate it and sort fields after that field.instance_eval(&block) if block field end # configure a field without adding it. def configure(name, type = nil, &block) field(name, type, false, &block) end # include fields by name and apply an optionnal block to each (through a call to fields), # or include fields by conditions if no field names def include_fields(*field_names, &block) if field_names.empty? _fields.select { |f| f.instance_eval(&block) }.each do |f| unless f.defined f.defined = true f.order = _fields.select(&:defined).length end end else fields(*field_names, &block) end end # exclude fields by name or by condition (block) def exclude_fields(*field_names, &block) block ||= lambda { |f| field_names.include?(f.name) } _fields.each { |f| f.defined = true } if _fields.select(&:defined).empty? _fields.select { |f| f.instance_eval(&block) }.each { |f| f.defined = false } end # API candy alias_method :exclude_fields_if, :exclude_fields alias_method :include_fields_if, :include_fields def include_all_fields include_fields_if { true } end # Returns all field configurations for the model configuration instance. If no fields # have been defined returns all fields. Defined fields are sorted to match their # order property. If order was not specified it will match the order in which fields # were defined. # # If a block is passed it will be evaluated in the context of each field def fields(*field_names, &block) return all_fields if field_names.empty? && !block if field_names.empty? defined = _fields.select { |f| f.defined } defined = _fields if defined.empty? else defined = field_names.collect { |field_name| _fields.detect { |f| f.name == field_name } } end defined.collect do |f| unless f.defined f.defined = true f.order = _fields.select(&:defined).length end f.instance_eval(&block) if block f end end # Defines configuration for fields by their type. def fields_of_type(type, &block) _fields.select { |f| type == f.type }.map! { |f| f.instance_eval(&block) } if block end # Accessor for all fields def all_fields ((ro_fields = _fields(true)).select(&:defined).presence || ro_fields).collect do |f| f.section = self f end end # Get all fields defined as visible, in the correct order. def visible_fields i = 0 all_fields.collect { |f| f.with(bindings) }.select(&:visible?).sort_by { |f| [f.order, i += 1] } # stable sort, damn end protected # Raw fields. # Recursively returns parent section's raw fields # Duping it if accessed for modification. def _fields(readonly = false) return @_fields if @_fields return @_ro_fields if readonly && @_ro_fields if self.class == RailsAdmin::Config::Sections::Base @_ro_fields = @_fields = RailsAdmin::Config::Fields.factory(self) else # parent is RailsAdmin::Config::Model, recursion is on Section's classes @_ro_fields ||= parent.send(self.class.superclass.to_s.underscore.split('/').last)._fields(true).freeze end readonly ? @_ro_fields : (@_fields ||= @_ro_fields.collect(&:clone)) end end end end
37.781022
124
0.619011
7a7fb7f09cc1984d824a5de6c30727905e748c30
3,301
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar") end test "should be valid" do assert @user.valid? end test "name should be present" do @user.name = " " assert_not @user.valid? end test "email should be present" do @user.email = " " assert_not @user.valid? end test "name should not be too long" do @user.name = "a" * 51 assert_not @user.valid? end test "email should not be too long" do @user.email = "a" * 244 + "@example.com" assert_not @user.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[[email protected] [email protected] [email protected] [email protected] [email protected]] valid_addresses.each do |valid_address| @user.email = valid_address assert @user.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[user@example,com user_at_foo.org [email protected]@bar_baz.com foo@bar+baz.com [email protected]] invalid_addresses.each do |invalid_address| @user.email = invalid_address assert_not @user.valid?, "#{invalid_address.inspect} should invalid" end end test "email addresses should be unique" do duplicate_user = @user.dup duplicate_user.email = @user.email.upcase @user.save assert_not duplicate_user.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "[email protected]" @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test "password should be present (nonblank)" do @user.password = @user.password_confirmation = " " * 6 assert_not @user.valid? end test "password should have a minimum length" do @user.password = @user.password_confirmation = "a" * 5 assert_not @user.valid? end test "authenticated? should return false for a user with nil digest" do assert_not @user.authenticated?(:remember, '') end test "associated microposts should be destroyed" do @user.save @user.microposts.create!(content: "Lorem ipsum") assert_difference 'Micropost.count', -1 do @user.destroy end end test "should follow and unfollow a user" do michael = users(:michael) archer = users(:archer) assert_not michael.following?(archer) michael.follow(archer) assert michael.following?(archer) assert archer.followers.include?(michael) michael.unfollow(archer) assert_not michael.following?(archer) end test "feed should have the right posts" do michael = users(:michael) archer = users(:archer) lana = users(:lana) # フォローしているユーザーの投稿を確認 lana.microposts.each do |post_following| assert michael.feed.include?(post_following) end # 自分自身の投稿を確認 michael.microposts.each do |post_self| assert michael.feed.include?(post_self) end # フォローしていないユーザーの投稿を確認 archer.microposts.each do |post_unfollowed| assert_not michael.feed.include?(post_unfollowed) end end end
28.704348
123
0.684035
62431fb05a1dd943265838191fe0c3562e0140a4
253
require 'lib/templatemailer' class Alert < TemplateMailer def initialize(options) super(ALERT_SMTP_SERVER, ALERT_TEMPLATE, options) end def mail to = ALERT_TO if defined?(ALERT_TO) cc = ALERT_CC if defined?(ALERT_CC) super(to, cc) end end
18.071429
51
0.750988
3900a7fed34ecc46143f35a0a2cf5bf0898e59ae
87
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "stewart_view_tool"
29
58
0.758621
1857fa853a234ebd77ea096aeab2d60040f141d9
2,178
#-- # Copyright 2003-2010 by Jim Weirich ([email protected]) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #++ module Rake VERSION = '11.1.1' end require 'rake/version' require 'rbconfig' require 'fileutils' require 'singleton' require 'monitor' require 'optparse' require 'ostruct' require 'rake/ext/string' require 'rake/ext/fixnum' require 'rake/win32' require 'rake/linked_list' require 'rake/cpu_counter' require 'rake/scope' require 'rake/task_argument_error' require 'rake/rule_recursion_overflow_error' require 'rake/rake_module' require 'rake/trace_output' require 'rake/pseudo_status' require 'rake/task_arguments' require 'rake/invocation_chain' require 'rake/task' require 'rake/file_task' require 'rake/file_creation_task' require 'rake/multi_task' require 'rake/dsl_definition' require 'rake/file_utils_ext' require 'rake/file_list' require 'rake/default_loader' require 'rake/early_time' require 'rake/late_time' require 'rake/name_space' require 'rake/task_manager' require 'rake/application' require 'rake/backtrace' $trace = false # :stopdoc: # # Some top level Constants. FileList = Rake::FileList RakeFileUtils = Rake::FileUtilsExt
29.432432
78
0.783287
bfb500ac33c48f24a0a286e24439ba00d4b441c5
3,812
# frozen_string_literal: true # See LICENSE.txt at root of repository # GENERATED FILE - DO NOT EDIT!! require 'ansible/ruby/modules/base' module Ansible module Ruby module Modules # Create, update and delete blob containers and blob objects. Use to upload a file and store it as a blob object, or download a blob object to a file. class Azure_rm_storageblob < Base # @return [String] Name of the storage account to use. attribute :storage_account_name validates :storage_account_name, presence: true, type: String # @return [String, nil] Name of a blob object within the container. attribute :blob validates :blob, type: String # @return [:block, :page, nil] Type of Blob Object. attribute :blob_type validates :blob_type, expression_inclusion: {:in=>[:block, :page], :message=>"%{value} needs to be :block, :page"}, allow_nil: true # @return [String] Name of a blob container within the storage account. attribute :container validates :container, presence: true, type: String # @return [String, nil] Set the blob content-type header. For example, 'image/png'. attribute :content_type validates :content_type, type: String # @return [Object, nil] Set the blob cache-control header. attribute :cache_control # @return [Object, nil] Set the blob content-disposition header. attribute :content_disposition # @return [Object, nil] Set the blob encoding header. attribute :content_encoding # @return [Object, nil] Set the blob content-language header. attribute :content_language # @return [Object, nil] Set the blob md5 hash value. attribute :content_md5 # @return [String, nil] Destination file path. Use with state 'present' to download a blob. attribute :dest validates :dest, type: String # @return [Symbol, nil] Overwrite existing blob or file when uploading or downloading. Force deletion of a container that contains blobs. attribute :force validates :force, type: Symbol # @return [String] Name of the resource group to use. attribute :resource_group validates :resource_group, presence: true, type: String # @return [String, nil] Source file path. Use with state 'present' to upload a blob. attribute :src validates :src, type: String # @return [:absent, :present, nil] Assert the state of a container or blob.,Use state 'absent' with a container value only to delete a container. Include a blob value to remove a specific blob. A container will not be deleted, if it contains blobs. Use the force option to override, deleting the container and all associated blobs.,Use state 'present' to create or update a container and upload or download a blob. If the container does not exist, it will be created. If it exists, it will be updated with configuration options. Provide a blob name and either src or dest to upload or download. Provide a src path to upload and a dest path to download. If a blob (uploading) or a file (downloading) already exists, it will not be overwritten unless the force parameter is true. attribute :state validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>"%{value} needs to be :absent, :present"}, allow_nil: true # @return [:container, :blob, nil] Determine a container's level of public access. By default containers are private. Can only be set at time of container creation. attribute :public_access validates :public_access, expression_inclusion: {:in=>[:container, :blob], :message=>"%{value} needs to be :container, :blob"}, allow_nil: true end end end end
52.219178
785
0.690976
4ad27f711706e075e561797a9f73426edabc3e83
1,640
class Admin::PagesController < Admin::ResourceController before_filter :initialize_meta_rows_and_buttons, :only => [:new, :edit, :create, :update] before_filter :count_deleted_pages, :only => [:destroy] responses do |r| r.plural.js do @level = params[:level].to_i @template_name = 'index' response.headers['Content-Type'] = 'text/html;charset=utf-8' render :action => 'children.html.haml', :layout => false end end def index @homepage = Page.find_by_parent_id(nil) response_for :plural end def show respond_to do |format| format.xml { super } format.html { redirect_to edit_admin_page_path(params[:id]) } end end def new self.model = model_class.new_with_defaults(config) if params[:page_id].blank? self.model.slug = '/' end response_for :singular end private def model_class if params[:page_id] Page.find(params[:page_id]).children else Page end end def count_deleted_pages @count = model.children.count + 1 end def initialize_meta_rows_and_buttons @buttons_partials ||= [] @meta ||= [] @meta << {:field => "slug", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 100}]} @meta << {:field => "breadcrumb", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 160}]} @meta << {:field => "description", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 200}]} @meta << {:field => "keywords", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 200}]} end end
29.285714
116
0.609146
919d4146109f0a07c78b40f24c06d67882c0ca18
233
# frozen_string_literal: true require Hyrax::Engine.root.join('app/services/hyrax/user_stat_importer.rb') module Hyrax class UserStatImporter require 'legato' require 'hyrax/pageview' require 'hyrax/download' end end
23.3
75
0.763948
e91d05e29e5c2d2959b0ecf2ecea94b16e69f2ad
1,376
require "spec_helper" describe Sunspot::Queue::DelayedJob::Backend do # Mock DelayedJobJob class CustomDelayedJobJob < Struct.new(:klass, :id) def perform end end subject(:backend) { described_class.new(configuration) } let(:configuration) { ::Sunspot::Queue::Configuration.new } describe "#index" do it "uses the index job set in the global configuration" do configuration.index_job = CustomDelayedJobJob Delayed::Job.should_receive(:enqueue) do |args| args.first.is_a? CustomDelayedJobJob end backend.index(Person, 3) end it "uses the default index job if one is not configured" do Delayed::Job.should_receive(:enqueue) do |args| args.first.is_a? Sunspot::Queue::DelayedJob::IndexJob end backend.index(Person, 12) end end describe "#remove" do it "uses the removal job set in the global configuration" do configuration.removal_job = CustomDelayedJobJob Delayed::Job.should_receive(:enqueue) do |args| args.first.is_a? CustomDelayedJobJob end backend.remove(Person, 3) end it "uses the default index job if one is not configured" do Delayed::Job.should_receive(:enqueue) do |args| args.first.is_a? Sunspot::Queue::DelayedJob::RemovalJob end backend.remove(Person, 12) end end end
25.018182
64
0.678052
f8403bfe1aa9616aef9dffe8c118abd0a92c24d0
9,131
require "cases/helper" require 'support/connection_helper' module ActiveRecord class PostgresqlConnectionTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper class NonExistentTable < ActiveRecord::Base end fixtures :comments def setup super @subscriber = SQLSubscriber.new @subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber) @connection = ActiveRecord::Base.connection end def teardown ActiveSupport::Notifications.unsubscribe(@subscription) super end def test_truncate count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i assert_operator count, :>, 0 ActiveRecord::Base.connection.truncate("comments") count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i assert_equal 0, count end def test_encoding assert_not_nil @connection.encoding end def test_collation assert_not_nil @connection.collation end def test_ctype assert_not_nil @connection.ctype end def test_default_client_min_messages assert_equal "warning", @connection.client_min_messages end # Ensure, we can set connection params using the example of Generic # Query Optimizer (geqo). It is 'on' per default. def test_connection_options params = ActiveRecord::Base.connection_config.dup params[:options] = "-c geqo=off" NonExistentTable.establish_connection(params) # Verify the connection param has been applied. expect = NonExistentTable.connection.query('show geqo').first.first assert_equal 'off', expect end def test_reset @connection.query('ROLLBACK') @connection.query('SET geqo TO off') # Verify the setting has been applied. expect = @connection.query('show geqo').first.first assert_equal 'off', expect @connection.reset! # Verify the setting has been cleared. expect = @connection.query('show geqo').first.first assert_equal 'on', expect end def test_reset_with_transaction @connection.query('ROLLBACK') @connection.query('SET geqo TO off') # Verify the setting has been applied. expect = @connection.query('show geqo').first.first assert_equal 'off', expect @connection.query('BEGIN') @connection.reset! # Verify the setting has been cleared. expect = @connection.query('show geqo').first.first assert_equal 'on', expect end def test_tables_logs_name ActiveSupport::Deprecation.silence { @connection.tables('hello') } assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_indexes_logs_name @connection.indexes('items', 'hello') assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_table_exists_logs_name ActiveSupport::Deprecation.silence { @connection.table_exists?('items') } assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_table_alias_length_logs_name @connection.instance_variable_set("@table_alias_length", nil) @connection.table_alias_length assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_current_database_logs_name @connection.current_database assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_encoding_logs_name @connection.encoding assert_equal 'SCHEMA', @subscriber.logged[0][1] end def test_schema_names_logs_name @connection.schema_names assert_equal 'SCHEMA', @subscriber.logged[0][1] end if ActiveRecord::Base.connection.prepared_statements def test_statement_key_is_logged bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new) @connection.exec_query('SELECT $1::integer', 'SQL', [bind], prepare: true) name = @subscriber.payloads.last[:statement_name] assert name res = @connection.exec_query("EXPLAIN (FORMAT JSON) EXECUTE #{name}(1)") plan = res.column_types['QUERY PLAN'].deserialize res.rows.first.first assert_operator plan.length, :>, 0 end end # Must have PostgreSQL >= 9.2, or with_manual_interventions set to # true for this test to run. # # When prompted, restart the PostgreSQL server with the # "-m fast" option or kill the individual connection assuming # you know the incantation to do that. # To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ... # sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast" def test_reconnection_after_actual_disconnection_with_verify original_connection_pid = @connection.query('select pg_backend_pid()') # Sanity check. assert @connection.active? if @connection.send(:postgresql_version) >= 90200 secondary_connection = ActiveRecord::Base.connection_pool.checkout secondary_connection.query("select pg_terminate_backend(#{original_connection_pid.first.first})") ActiveRecord::Base.connection_pool.checkin(secondary_connection) elsif ARTest.config['with_manual_interventions'] puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' + 'server with the "-m fast" option) and then press enter.' $stdin.gets else # We're not capable of terminating the backend ourselves, and # we're not allowed to seek assistance; bail out without # actually testing anything. return end @connection.verify! assert @connection.active? # If we get no exception here, then either we re-connected successfully, or # we never actually got disconnected. new_connection_pid = @connection.query('select pg_backend_pid()') assert_not_equal original_connection_pid, new_connection_pid, "umm -- looks like you didn't break the connection, because we're still " + "successfully querying with the same connection pid." # Repair all fixture connections so other tests won't break. @fixture_connections.each(&:verify!) end def test_set_session_variable_true run_without_connection do |orig_connection| ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => true}})) set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_true.rows, [["on"]] end end def test_set_session_variable_false run_without_connection do |orig_connection| ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => false}})) set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_false.rows, [["off"]] end end def test_set_session_variable_nil run_without_connection do |orig_connection| # This should be a no-op that does not raise an error ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => nil}})) end end def test_set_session_variable_default run_without_connection do |orig_connection| # This should execute a query that does not raise an error ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => :default}})) end end def test_get_and_release_advisory_lock lock_id = 5295901941911233559 list_advisory_locks = <<-SQL SELECT locktype, (classid::bigint << 32) | objid::bigint AS lock_id FROM pg_locks WHERE locktype = 'advisory' SQL got_lock = @connection.get_advisory_lock(lock_id) assert got_lock, "get_advisory_lock should have returned true but it didn't" advisory_lock = @connection.query(list_advisory_locks).find {|l| l[1] == lock_id} assert advisory_lock, "expected to find an advisory lock with lock_id #{lock_id} but there wasn't one" released_lock = @connection.release_advisory_lock(lock_id) assert released_lock, "expected release_advisory_lock to return true but it didn't" advisory_locks = @connection.query(list_advisory_locks).select {|l| l[1] == lock_id} assert_empty advisory_locks, "expected to have released advisory lock with lock_id #{lock_id} but it was still held" end def test_release_non_existent_advisory_lock fake_lock_id = 2940075057017742022 with_warning_suppression do released_non_existent_lock = @connection.release_advisory_lock(fake_lock_id) assert_equal released_non_existent_lock, false, 'expected release_advisory_lock to return false when there was no lock to release' end end protected def with_warning_suppression log_level = @connection.client_min_messages @connection.client_min_messages = 'error' yield @connection.client_min_messages = log_level end end end
35.391473
124
0.701566
d5115b36923753cd121d51b0c7b71be4c6adc0ee
2,361
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module DoorkeeperProvider class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' # Force the application to not access the DB or load models when precompiling your assets. config.assets.initialize_on_precompile = false config.to_prepare do # Base layout. Uses app/views/layouts/my_layout.html.erb Doorkeeper::ApplicationController.layout "application" end end end
41.421053
99
0.726387
28703bd4e5bb0715baf329bef3aa0d46e87600b1
2,090
module Blueprints # Contains configuration of blueprints. Instance of this is yielded in Blueprints.enable block. # @example Configuring through Blueprints.enable block # Blueprints.enable do |config| # config.prebuild = :user, :profile # end # @example Configuring directly # Blueprints.config.transactions = false class Configuration # Allows passing custom filename pattern in case blueprints are held in place other than spec/blueprint, test/blueprint, blueprint. attr_reader :filename # Allows passing scenarios that should be prebuilt and available in all tests. Works similarly to fixtures. attr_accessor :prebuild # Allows passing custom root folder to use in case of non rails project. Defaults to Rails.root or current folder if Rails is not defined. attr_reader :root # By default blueprints runs each test in it's own transaction. This may sometimes be not desirable so this options allows to turn this off. attr_accessor :transactions # Default attributes are used when blueprints has no name specified. attr_reader :default_attributes # Initializes new Configuration object with default attributes. # By defaults filename patterns are: blueprint.rb and blueprint/*.rb in spec, test and root directories. # Also by default prebuildable blueprints list is empty, transactions are enabled and root is set to Rails.root or current directory. def initialize self.filename = [nil, "spec", "test"].map do |dir| ["blueprint"].map do |file| path = File.join([dir, file].compact) ["#{path}.rb", File.join(path, "*.rb")] end end.flatten @prebuild = [] @transactions = true @root = defined?(Rails) ? Rails.root : Pathname.pwd @default_attributes = [:name] end def filename=(value) @filename = Array(value).flatten.collect {|path| Pathname.new(path) } end def root=(value) @root = Pathname.new(value) end def default_attributes=(value) @default_attributes = Array(value) end end end
41.8
144
0.704306
1a5de31c1aeabaf3e44c782e37743eba85f79bff
723
# == Schema Information # # Table name: repositories # # id :integer not null, primary key # name :string(255) default(""), not null # namespace_id :integer # created_at :datetime not null # updated_at :datetime not null # marked :boolean default("0") # # Indexes # # fulltext_index_repositories_on_name (name) # index_repositories_on_name_and_namespace_id (name,namespace_id) UNIQUE # index_repositories_on_namespace_id (namespace_id) # FactoryGirl.define do factory :repository do sequence :name do |n| "repository#{n}" end trait :starred do stars { |t| [t.association(:star)] } end end end
24.1
74
0.622407
6a91a16c9c37082014760137c2747db3fdc62fb9
25
module MenteesHelper end
8.333333
20
0.88