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
|
---|---|---|---|---|---|
b94138f05706ae90d0169844a86ce77c2734a97f | 2,232 | require 'lru_redux'
module Stitches::ApiClientAccessWrapper
def self.fetch_for_key(key, configuration)
if cache_enabled
fetch_for_key_from_cache(key, configuration)
else
fetch_for_key_from_db(key, configuration)
end
end
def self.fetch_for_key_from_cache(key, configuration)
api_key_cache.getset(key) do
fetch_for_key_from_db(key, configuration)
end
end
def self.fetch_for_key_from_db(key, configuration)
api_client = ::ApiClient.find_by(key: key)
return unless api_client
unless api_client.respond_to?(:enabled?)
logger.warn('api_keys is missing "enabled" column. Run "rails g stitches:add_enabled_to_api_clients"')
return api_client
end
unless api_client.respond_to?(:disabled_at)
logger.warn('api_keys is missing "disabled_at" column. Run "rails g stitches:add_disabled_at_to_api_clients"')
end
return api_client if api_client.enabled?
disabled_at = api_client.respond_to?(:disabled_at) ? api_client.disabled_at : nil
if disabled_at && disabled_at > configuration.disabled_key_leniency_in_seconds.seconds.ago
message = "Allowing disabled ApiClient: #{api_client.name} with key #{redact_key(api_client)} disabled at #{disabled_at}"
if disabled_at > configuration.disabled_key_leniency_error_log_threshold_in_seconds.seconds.ago
logger.warn(message)
else
logger.error(message)
end
return api_client
else
logger.error("Rejecting disabled ApiClient: #{api_client.name} with key #{redact_key(api_client)}")
end
nil
end
def self.redact_key(api_client)
"*****#{api_client.key.to_s[-8..-1]}"
end
def self.logger
if defined?(StitchFix::Logger::LogWriter)
StitchFix::Logger::LogWriter
elsif defined?(Rails.logger)
Rails.logger
else
::Logger.new('/dev/null')
end
end
def self.clear_api_cache
api_key_cache.clear if cache_enabled
end
def self.api_key_cache
@api_key_cache ||= LruRedux::TTL::ThreadSafeCache.new(
Stitches.configuration.max_cache_size,
Stitches.configuration.max_cache_ttl,
)
end
def self.cache_enabled
Stitches.configuration.max_cache_ttl.positive?
end
end
| 28.615385 | 127 | 0.72491 |
e97e3b9fcccc0dec453d81a3aa2a70419ff6602a | 1,994 | require 'parslet'
require 'gitsh/argument_builder'
require 'gitsh/commands/factory'
require 'gitsh/commands/git_command'
require 'gitsh/commands/internal_command'
require 'gitsh/commands/noop'
require 'gitsh/commands/shell_command'
require 'gitsh/commands/tree'
require 'gitsh/interpreter'
module Gitsh
class Transformer < Parslet::Transform
def self.command_rule(type, command_class)
rule(type => simple(:command)) do |context|
Commands::Factory.new(command_class, context).build
end
rule(type => simple(:command), args: sequence(:args)) do |context|
Commands::Factory.new(command_class, context).build
end
end
rule(literal: simple(:literal)) do
lambda { |arg_builder| arg_builder.add_literal(literal) }
end
rule(empty_string: simple(:empty_string)) do
lambda { |arg_builder| arg_builder.add_literal('') }
end
rule(var: simple(:var)) do
lambda { |arg_builder| arg_builder.add_variable(var) }
end
rule(subshell: simple(:subshell)) do
lambda { |arg_builder| arg_builder.add_subshell(subshell.to_s) }
end
rule(arg: subtree(:parts)) do
Gitsh::ArgumentBuilder.build do |arg_builder|
Array(parts).each do |part|
part.call(arg_builder)
end
end
end
rule(blank: simple(:blank)) do |context|
Commands::Noop.new
end
rule(comment: simple(:comment)) do |context|
Commands::Noop.new
end
command_rule(:git_cmd, Commands::GitCommand)
command_rule(:internal_cmd, Commands::InternalCommand)
command_rule(:shell_cmd, Commands::ShellCommand)
rule(multi: { left: subtree(:left), right: subtree(:right) }) do
Commands::Tree::Multi.new(left, right)
end
rule(or: { left: subtree(:left), right: subtree(:right) }) do
Commands::Tree::Or.new(left, right)
end
rule(and: { left: subtree(:left), right: subtree(:right) }) do
Commands::Tree::And.new(left, right)
end
end
end
| 27.694444 | 72 | 0.672518 |
01b441407bd19562c6ad3b80ae009fe8d752490e | 1,273 | class User < ApplicationRecord
attr_accessor :remember_token
before_save { self.email = email.downcase }
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: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# 渡された文字列のハッシュ値を返す
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# ランダムなトークンを返す
def User.new_token
SecureRandom.urlsafe_base64
end
# 永続セッションのためにユーザーをデータベースに記憶する
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# 渡されたトークンがダイジェストと一致したらtrueを返す
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# ユーザーのログイン情報を破棄する
def forget
update_attribute(:remember_digest, nil)
end
end
| 30.309524 | 78 | 0.681854 |
4ab1555cb283689edbaafc17458abcc42c4e75b5 | 4,399 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v8/errors/extension_setting_error.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v8/errors/extension_setting_error.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v8.errors.ExtensionSettingErrorEnum" do
end
add_enum "google.ads.googleads.v8.errors.ExtensionSettingErrorEnum.ExtensionSettingError" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :EXTENSIONS_REQUIRED, 2
value :FEED_TYPE_EXTENSION_TYPE_MISMATCH, 3
value :INVALID_FEED_TYPE, 4
value :INVALID_FEED_TYPE_FOR_CUSTOMER_EXTENSION_SETTING, 5
value :CANNOT_CHANGE_FEED_ITEM_ON_CREATE, 6
value :CANNOT_UPDATE_NEWLY_CREATED_EXTENSION, 7
value :NO_EXISTING_AD_GROUP_EXTENSION_SETTING_FOR_TYPE, 8
value :NO_EXISTING_CAMPAIGN_EXTENSION_SETTING_FOR_TYPE, 9
value :NO_EXISTING_CUSTOMER_EXTENSION_SETTING_FOR_TYPE, 10
value :AD_GROUP_EXTENSION_SETTING_ALREADY_EXISTS, 11
value :CAMPAIGN_EXTENSION_SETTING_ALREADY_EXISTS, 12
value :CUSTOMER_EXTENSION_SETTING_ALREADY_EXISTS, 13
value :AD_GROUP_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE, 14
value :CAMPAIGN_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE, 15
value :CUSTOMER_FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE, 16
value :VALUE_OUT_OF_RANGE, 17
value :CANNOT_SET_FIELD_WITH_FINAL_URLS, 18
value :FINAL_URLS_NOT_SET, 19
value :INVALID_PHONE_NUMBER, 20
value :PHONE_NUMBER_NOT_SUPPORTED_FOR_COUNTRY, 21
value :CARRIER_SPECIFIC_SHORT_NUMBER_NOT_ALLOWED, 22
value :PREMIUM_RATE_NUMBER_NOT_ALLOWED, 23
value :DISALLOWED_NUMBER_TYPE, 24
value :INVALID_DOMESTIC_PHONE_NUMBER_FORMAT, 25
value :VANITY_PHONE_NUMBER_NOT_ALLOWED, 26
value :INVALID_COUNTRY_CODE, 27
value :INVALID_CALL_CONVERSION_TYPE_ID, 28
value :CUSTOMER_NOT_IN_ALLOWLIST_FOR_CALLTRACKING, 69
value :CALLTRACKING_NOT_SUPPORTED_FOR_COUNTRY, 30
value :INVALID_APP_ID, 31
value :QUOTES_IN_REVIEW_EXTENSION_SNIPPET, 32
value :HYPHENS_IN_REVIEW_EXTENSION_SNIPPET, 33
value :REVIEW_EXTENSION_SOURCE_NOT_ELIGIBLE, 34
value :SOURCE_NAME_IN_REVIEW_EXTENSION_TEXT, 35
value :MISSING_FIELD, 36
value :INCONSISTENT_CURRENCY_CODES, 37
value :PRICE_EXTENSION_HAS_DUPLICATED_HEADERS, 38
value :PRICE_ITEM_HAS_DUPLICATED_HEADER_AND_DESCRIPTION, 39
value :PRICE_EXTENSION_HAS_TOO_FEW_ITEMS, 40
value :PRICE_EXTENSION_HAS_TOO_MANY_ITEMS, 41
value :UNSUPPORTED_VALUE, 42
value :INVALID_DEVICE_PREFERENCE, 43
value :INVALID_SCHEDULE_END, 45
value :DATE_TIME_MUST_BE_IN_ACCOUNT_TIME_ZONE, 47
value :OVERLAPPING_SCHEDULES_NOT_ALLOWED, 48
value :SCHEDULE_END_NOT_AFTER_START, 49
value :TOO_MANY_SCHEDULES_PER_DAY, 50
value :DUPLICATE_EXTENSION_FEED_ITEM_EDIT, 51
value :INVALID_SNIPPETS_HEADER, 52
value :PHONE_NUMBER_NOT_SUPPORTED_WITH_CALLTRACKING_FOR_COUNTRY, 53
value :CAMPAIGN_TARGETING_MISMATCH, 54
value :CANNOT_OPERATE_ON_REMOVED_FEED, 55
value :EXTENSION_TYPE_REQUIRED, 56
value :INCOMPATIBLE_UNDERLYING_MATCHING_FUNCTION, 57
value :START_DATE_AFTER_END_DATE, 58
value :INVALID_PRICE_FORMAT, 59
value :PROMOTION_INVALID_TIME, 60
value :PROMOTION_CANNOT_SET_PERCENT_DISCOUNT_AND_MONEY_DISCOUNT, 61
value :PROMOTION_CANNOT_SET_PROMOTION_CODE_AND_ORDERS_OVER_AMOUNT, 62
value :TOO_MANY_DECIMAL_PLACES_SPECIFIED, 63
value :INVALID_LANGUAGE_CODE, 64
value :UNSUPPORTED_LANGUAGE, 65
value :CUSTOMER_CONSENT_FOR_CALL_RECORDING_REQUIRED, 66
value :EXTENSION_SETTING_UPDATE_IS_A_NOOP, 67
value :DISALLOWED_TEXT, 68
end
end
end
module Google
module Ads
module GoogleAds
module V8
module Errors
ExtensionSettingErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.errors.ExtensionSettingErrorEnum").msgclass
ExtensionSettingErrorEnum::ExtensionSettingError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v8.errors.ExtensionSettingErrorEnum.ExtensionSettingError").enummodule
end
end
end
end
end
| 46.305263 | 210 | 0.779268 |
38833d2b57029107a35515bff98794e6331b414c | 5,170 | require 'spec_helper'
describe Spree::Admin::ProductsController, type: :controller do
stub_authorization!
context '#index' do
let(:ability_user) { stub_model(Spree::LegacyUser, has_spree_role?: true) }
# Regression test for #1259
it 'can find a product by SKU' do
product = create(:product, sku: 'ABC123', stores: Spree::Store.all)
get :index, params: { q: { sku_start: 'ABC123' } }
expect(assigns[:collection]).not_to be_empty
expect(assigns[:collection]).to include(product)
end
end
# regression test for #1370
context 'adding properties to a product' do
let!(:product) { create(:product, stores: Spree::Store.all) }
specify do
put :update, params: {
id: product.to_param,
product: { product_properties_attributes: { '1' => { property_name: 'Foo', value: 'bar' } } }
}
expect(flash[:success]).to eq("Product #{product.name.inspect} has been successfully updated!")
end
end
# regression test for #801
describe '#destroy' do
let(:product) { mock_model(Spree::Product) }
let(:products) { double(ActiveRecord::Relation) }
def send_request
delete :destroy, params: { id: product, format: :js }
end
context 'will successfully destroy product' do
before do
allow(Spree::Product).to receive(:friendly).and_return(products)
allow(products).to receive(:find).with(product.id.to_s).and_return(product)
allow(product).to receive(:destroy).and_return(true)
end
describe 'expects to receive' do
after { send_request }
it { expect(Spree::Product).to receive(:friendly).and_return(products) }
it { expect(products).to receive(:find).with(product.id.to_s).and_return(product) }
it { expect(product).to receive(:destroy).and_return(true) }
end
describe 'assigns' do
before { send_request }
it { expect(assigns(:product)).to eq(product) }
end
describe 'response' do
before { send_request }
it { expect(response).to have_http_status(:ok) }
it { expect(flash[:success]).to eq(Spree.t('notice_messages.product_deleted')) }
end
end
context 'will not successfully destroy product' do
let(:error_msg) { 'Failed to delete' }
before do
allow(Spree::Product).to receive(:friendly).and_return(products)
allow(products).to receive(:find).with(product.id.to_s).and_return(product)
allow(product).to receive_message_chain(:errors, :full_messages).and_return([error_msg])
allow(product).to receive(:destroy).and_return(false)
end
describe 'expects to receive' do
after { send_request }
it { expect(Spree::Product).to receive(:friendly).and_return(products) }
it { expect(products).to receive(:find).with(product.id.to_s).and_return(product) }
it { expect(product).to receive(:destroy).and_return(false) }
end
describe 'assigns' do
before { send_request }
it { expect(assigns(:product)).to eq(product) }
end
describe 'response' do
before { send_request }
it { expect(response).to have_http_status(:ok) }
it 'set flash error' do
expected_error = Spree.t('notice_messages.product_not_deleted', error: error_msg)
expect(flash[:error]).to eq(expected_error)
end
end
end
end
describe '#clone' do
subject(:send_request) do
post :clone, params: { id: product, format: :js }
end
let!(:product) { create(:custom_product, name: 'MyProduct', sku: 'MySku') }
let(:product2) { create(:custom_product, name: 'COPY OF MyProduct', sku: 'COPY OF MySku') }
let(:variant) { create(:master_variant, name: 'COPY OF MyProduct', sku: 'COPY OF MySku', created_at: product.created_at - 1.day) }
context 'will successfully clone product' do
before do
Timecop.freeze(Date.today + 30)
allow(product).to receive(:duplicate).and_return(product2)
send_request
end
after do
Timecop.return
end
describe 'response' do
it { expect(response).to have_http_status(:found) }
it { expect(response).to be_redirect }
it { expect(flash[:success]).to eq(Spree.t('notice_messages.product_cloned')) }
end
end
context 'will not successfully clone product' do
before do
variant
end
describe 'response' do
before { send_request }
it { expect(response).to have_http_status(:found) }
it { expect(response).to be_redirect }
it 'set flash error' do
expected_error = Spree.t('notice_messages.product_not_cloned', error: 'Validation failed: Sku has already been taken')
expect(flash[:error]).to eq(expected_error)
end
end
end
end
context 'stock' do
let(:product) { create(:product, stores: Spree::Store.all) }
it 'restricts stock location based on accessible attributes' do
expect(Spree::StockLocation).to receive(:accessible_by).and_return([])
get :stock, params: { id: product }
end
end
end
| 32.111801 | 134 | 0.64236 |
acab10e96eeef45e8d60df2e0560c8575e7b9938 | 316 | # service center are the editional part for the system
# user will be assigned to different ServiceCenters to structured the system
class ServiceCenter < ActiveRecord::Base
# associations
has_many :profiles
# validations
validates_presence_of :name, :address, :phone
# scopes
# instance methods
end
| 19.75 | 76 | 0.765823 |
8709b8453d7f30b36f11d481f31fda8109e4fbfc | 1,618 | class Exploitdb < Formula
desc "Database of public exploits and corresponding vulnerable software"
homepage "https://www.exploit-db.com/"
url "https://github.com/offensive-security/exploitdb.git",
tag: "2021-07-24",
revision: "e9439759d73fffb91f8ce63bc234f9f0f5150a84"
version "2021-07-24"
license "GPL-2.0-or-later"
head "https://github.com/offensive-security/exploitdb.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0b0d082a838e855305825c20a495ecfda9bd03f61a3a80617a11d482e1e8e9d0"
sha256 cellar: :any_skip_relocation, big_sur: "4c0cd4c977d024da6ffa316754435213f8c6d2168548cf0df270e7118b3cada4"
sha256 cellar: :any_skip_relocation, catalina: "ce0b951ed7df45551e210c480d67567ef297209db81b532b9b125866cf7e6a30"
sha256 cellar: :any_skip_relocation, mojave: "83bbb528073177ebc5451b1c9e3f2e314ee6b86f3feb4d07951e4e3e4221429e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "b4afca5931d37bf3e467cb2693324847a523b9d910156cae5de44cffcdc18b9e"
end
def install
inreplace "searchsploit",
"rc_file=\"\"", "rc_file=\"#{etc}/searchsploit_rc\""
optpath = opt_share/"exploitdb"
inreplace ".searchsploit_rc" do |s|
s.gsub! "\"/opt/exploitdb\"", optpath
s.gsub! "\"/opt/exploitdb-papers\"", "#{optpath}-papers"
end
bin.install "searchsploit"
etc.install ".searchsploit_rc" => "searchsploit_rc"
pkgshare.install %w[.git exploits files_exploits.csv files_shellcodes.csv
shellcodes]
end
test do
system "#{bin}/searchsploit", "sendpage"
end
end
| 40.45 | 122 | 0.733004 |
08fa8263dcf5e47bfb8aaacd9221a093ad147da5 | 924 | # -*- coding: utf-8 -*-
require 'helper'
class TestRegressionChartDoughnut06 < Test::Unit::TestCase
def setup
setup_dir_var
end
def teardown
File.delete(@xlsx) if File.exist?(@xlsx)
end
def test_chart_doughnut06
@xlsx = 'chart_doughnut06.xlsx'
workbook = WriteXLSX.new(@xlsx)
worksheet = workbook.add_worksheet
chart = workbook.add_chart(:type => 'doughnut', :embedded => 1)
data = [
[ 2, 4, 6 ],
[ 60, 30, 10 ]
]
worksheet.write('A1', data)
chart.add_series(:values => 'Sheet1!$A$1:$A$3')
chart.add_series(:values => 'Sheet1!$B$1:$B$3')
worksheet.insert_chart('E9', chart)
workbook.close
compare_xlsx_for_regression(File.join(@regression_output, @xlsx),
@xlsx,
nil,
nil
)
end
end
| 23.692308 | 71 | 0.53355 |
b9c4f61fb6bf1174594ced8a406bce99a4b081e7 | 52,810 | # NOTE: Please do not add any further tests to the Rails 2 application unless
# the issue being tested specifically applies to Rails 2 and not the other
# versions.
# If possible, please use the rails5 app.
require_relative '../test'
class Rails2Tests < Minitest::Test
include BrakemanTester::FindWarning
include BrakemanTester::CheckExpected
def expected
@expected ||= {
:controller => 1,
:model => 4,
:template => 47,
:generic => 58 }
end
def report
@@report ||= BrakemanTester.run_scan "rails2", "Rails 2", :run_all_checks => true, :collapse_mass_assignment => true
end
def test_no_errors
assert_equal 0, report[:errors].length
end
def test_config_sanity
assert_equal 'UTC', report[:config].rails[:time_zone].value
end
def test_eval
assert_warning :warning_type => "Dangerous Eval",
:line => 40,
:message => /^User input in eval/,
:format_code => /eval\(params\[:dangerous_input\]\)/,
:file => /home_controller.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_default_routes
assert_warning :warning_type => "Default Routes",
:line => 54,
:message => /All public methods in controllers are available as actions/,
:file => /routes\.rb/,
:relative_path => "config/routes.rb"
end
def test_command_injection_interpolate
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 34,
:message => /^Possible command injection/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_command_injection_direct
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 36,
:message => /^Possible command injection/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb",
:format_code => /params\[:user_input\]/
end
def test_file_access_concatenation
assert_warning :type => :warning,
:warning_type => "File Access",
:line => 24,
:message => /^Parameter value used in file name/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_mass_assignment
assert_warning :type => :warning,
:warning_type => "Mass Assignment",
:line => 54,
:message => /^Unprotected mass assignment/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_update_attribute_no_mass_assignment
assert_no_warning :type => :warning,
:warning_type => "Mass Assignment",
:line => 26,
:message => /^Unprotected mass assignment/,
:confidence => 0,
:file => /other_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_mass_assignment_with_or_equals_in_filter
assert_warning :type => :warning,
:warning_type => "Mass Assignment",
:line => 127,
:message => /^Unprotected\ mass\ assignment/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_redirect
assert_warning :type => :warning,
:warning_type => "Redirect",
:line => 45,
:message => /^Possible unprotected redirect/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
assert_warning :type => :warning,
:warning_type => "Redirect",
:line => 182,
:message => /^Possible unprotected redirect/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_dynamic_render_path
assert_warning :type => :warning,
:warning_type => "Dynamic Render Path",
:line => 59,
:message => /^Render path contains parameter value near line 59: render/,
:confidence => 1,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_dynamic_render_path_high_confidence
assert_warning :type => :warning,
:warning_code => 99,
:fingerprint => "d77e92530f810b945b9bd04db2e25afab968b4379d08062f7c5a822671a159a6",
:warning_type => "Remote Code Execution",
:line => 77,
:message => /^Passing\ query\ parameters\ to\ `render` is\ /,
:confidence => 0,
:relative_path => "app/controllers/home_controller.rb",
:code => s(:render, :action, s(:call, s(:params), :[], s(:lit, :my_action)), s(:hash)),
:user_input => s(:call, s(:params), :[], s(:lit, :my_action))
end
def test_file_access
assert_warning :type => :warning,
:warning_type => "File Access",
:line => 21,
:message => /^Parameter value used in file name/,
:confidence => 0,
:file => /other_controller\.rb/,
:relative_path => "app/controllers/other_controller.rb"
end
def test_file_access_with_load
assert_warning :type => :warning,
:warning_type => "File Access",
:line => 63,
:message => /^Parameter value used in file name/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_file_access_load_false
warnings = find :type => :warning,
:warning_type => "File Access",
:line => 64,
:message => /^Parameter value used in file name/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
assert_equal 0, warnings.length, "False positive found."
end
def test_session_secret
assert_warning :type => :warning,
:warning_type => "Session Setting",
:line => 9,
:message => /^Session\ secret\ should\ not\ be\ included\ in/,
:confidence => 0,
:file => /session_store\.rb/,
:relative_path => "config/initializers/session_store.rb"
end
def test_session_cookies
assert_warning :type => :warning,
:warning_type => "Session Setting",
:line => 10,
:message => /^Session cookies should be set to HTTP on/,
:confidence => 0,
:file => /session_store\.rb/,
:relative_path => "config/initializers/session_store.rb"
end
def test_rails_cve_2012_2660
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:message => /CVE-2012-2660/,
:confidence => 0
end
def test_rails_cve_2012_2695
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:message => /CVE-2012-2695/,
:confidence => 0
end
def test_sql_injection_find_by_sql
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 28,
:message => /^Possible SQL injection/,
:confidence => 1,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_sql_injection_conditions_local
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 29,
:message => /^Possible SQL injection/,
:confidence => 1,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_sql_injection_params
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 30,
:message => /^Possible SQL injection/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_sql_injection_named_scope
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 4,
:message => /^Possible SQL injection near line 4: named_scope\(:phooey/,
:confidence => 0,
:file => /user\.rb/,
:relative_path => "app/models/user.rb"
end
def test_sql_injection_named_scope_lambda
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 2,
:message => /^Possible SQL injection near line 2: named_scope\(:dah, lambda/,
:confidence => 1,
:file => /user\.rb/,
:relative_path => "app/models/user.rb"
end
def test_sql_injection_named_scope_conditional
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 6,
:message => /^Possible SQL injection near line 6: named_scope\(:with_state, lambda/,
:confidence => 1,
:file => /user\.rb/,
:relative_path => "app/models/user.rb"
end
def test_sql_injection_in_self_call
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 15,
:message => /^Possible SQL injection near line 15: self\.find/,
:confidence => 1,
:file => /user\.rb/,
:relative_path => "app/models/user.rb"
end
def test_sql_user_input_in_find_by
assert_no_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 116,
:message => /^Possible SQL injection near line 116: User.find_or_create_by_name/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
# ensure that the warning is generated for the line which contains the input, not
# the line of the beginning of the string
def test_sql_user_input_multiline
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 121,
:message => /^Possible SQL injection near line 121: User.find_by_sql/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_sql_injection_false_positive_quote_value
assert_no_warning :type => :warning,
:warning_code => 0,
:fingerprint => "6ea8fe3abe8eac86e5ecb790b53fb064b1152b2574b14d9354a40d07269a952e",
:warning_type => "SQL Injection",
:line => 30,
:message => /^Possible\ SQL\ injection/,
:confidence => 1,
:relative_path => "app/models/user.rb",
:user_input => s(:call, s(:call, s(:str, "DELETE FROM cool_table WHERE cool_id="), :+, s(:call, nil, :quote_value, s(:call, s(:self), :cool_id))), :+, s(:str, " AND my_id="))
end
def test_sql_injection_sanitize_sql
assert_no_warning :type => :warning,
:warning_code => 0,
:fingerprint => "7481ff666ae949b8442400cf516615ce8b04b87f7e11e33e29d4ad1303d24dd0",
:warning_type => "SQL Injection",
:line => 26,
:message => /^Possible\ SQL\ injection/,
:confidence => 1,
:relative_path => "app/models/user.rb",
:user_input => s(:call, s(:str, "select * from cool_table where stuff = "), :+, s(:call, s(:self), :sanitize_sql, s(:lvar, :input)))
end
def test_csrf_protection
assert_warning :type => :controller,
:warning_type => "Cross-Site Request Forgery",
:message => /^`protect_from_forgery` should be called /,
:confidence => 0,
:file => /application_controller\.rb/,
:relative_path => "app/controllers/application_controller.rb"
end
def test_attribute_restriction_1
assert_warning :type => :model,
:warning_code => 19,
:fingerprint => "91d73b1b9d6920156b920729c0146292eb9f10f4ba9515740442dbe82d4dee78",
:warning_type => "Attribute Restriction",
:line => 1,
:message => /^Mass\ assignment\ is\ not\ restricted\ using\ /,
:confidence => 0,
:relative_path => "app/models/account.rb",
:code => nil,
:user_input => nil
end
def test_attribute_restriction_2
assert_warning :type => :model,
:warning_code => 19,
:fingerprint => "b325ae8a4570599cde146875ae86427506befae36a3b4a97ce2223930846fec5",
:warning_type => "Attribute Restriction",
:line => 1,
:message => /^Mass\ assignment\ is\ not\ restricted\ using\ /,
:confidence => 0,
:relative_path => "app/models/user.rb",
:code => nil,
:user_input => nil
end
def test_format_validation
assert_warning :type => :model,
:warning_type => "Format Validation",
:line => 2,
:message => /^Insufficient validation for `name` using/,
:confidence => 0,
:file => /account\.rb/,
:relative_path => "app/models/account.rb"
end
def test_unescaped_parameter
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /index\.html\.erb/,
:relative_path => "app/views/home/index.html.erb"
end
def test_unescaped_request_env
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped request value/,
:confidence => 0,
:file => /test_env\.html\.erb/,
:relative_path => "app/views/other/test_env.html.erb"
end
def test_params_from_controller
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 4,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
def test_unrendered_sanitized_params_from_controller
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /test_sanitized_param\.html\.erb/,
:relative_path => "app/views/home/test_sanitized_param.html.erb"
end
def test_sanitized_params_from_controller
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /test_sanitized_param\.html\.erb/,
:relative_path => "app/views/home/test_sanitized_param.html.erb"
end
def test_indirect_xss
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 6,
:message => /^Unescaped parameter value/,
:confidence => 2,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
def test_cross_site_scripting_alias_u
assert_no_warning :type => :template,
:warning_code => 2,
:fingerprint => "a1f78b7e1ff25f81054b5ed38d04457e76278ba38444cb65f93cd559f9545bd9",
:warning_type => "Cross-Site Scripting",
:line => 20,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:relative_path => "app/views/home/test_params.html.erb",
:code => s(:call, s(:params), :[], s(:lit, :w00t)),
:user_input => nil
end
def test_model_attribute_from_controller
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /test_model\.html\.erb/,
:relative_path => "app/views/home/test_model.html.erb"
end
def test_model_from_controller_indirect_bad
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /test_model\.html\.erb/,
:relative_path => "app/views/home/test_model.html.erb"
end
def test_model_in_link_to
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped model attribute in `link_to`/,
:confidence => 0,
:file => /test_model\.html\.erb/,
:relative_path => "app/views/home/test_model.html.erb"
end
def test_indirect_model_in_link_to
assert_warning :type => :template,
:warning_code => 3,
:fingerprint => "8941c902e7c71d0df4ebb1888c8ed9ac99affaf385be657838452ac3eefe563c",
:warning_type => "Cross-Site Scripting",
:line => 9,
:message => /^Unescaped\ model\ attribute\ in\ `l/,
:confidence => 1,
:relative_path => "app/views/home/test_link_to.html.erb"
end
def test_escaped_parameter_in_link_to
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 10,
:message => /^Unescaped parameter value in `link_to`/,
:confidence => 1,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
def test_cross_site_scripting_alias_u_for_link_to
assert_no_warning :type => :template,
:warning_code => 3,
:fingerprint => "1803557ac730919bef3de68329461c47d5bee2a6bcdc8f467e6ee896504e6355",
:warning_type => "Cross-Site Scripting",
:line => 22,
:message => /^Unescaped\ parameter\ value\ in\ `link_to`/,
:confidence => 0,
:relative_path => "app/views/home/test_params.html.erb",
:code => s(:call, nil, :link_to, s(:call, s(:params), :[], s(:lit, :w00t)), s(:str, "some_url")),
:user_input => s(:call, s(:params), :[], s(:lit, :w00t))
end
def test_encoded_href_parameter_in_link_to
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 12,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 0,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
def test_href_parameter_in_link_to
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 14,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 0,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 16,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 1,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 18,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 0,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
def test_polymorphic_url_in_href
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 9,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 1,
:file => /test_model\.html\.erb/,
:relative_path => "app/views/home/test_model.html.erb"
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 11,
:message => /^Unsafe parameter value in `link_to` href/,
:confidence => 1,
:file => /test_model\.html\.erb/,
:relative_path => "app/views/home/test_model.html.erb"
end
def test_cross_site_scripting_alias_u_for_link_to_href
assert_no_warning :type => :template,
:warning_code => 4,
:fingerprint => "395a4782d1e015e32c62aff7b3811533d91015935bc1b4258ad17b264dcdf6fe",
:warning_type => "Cross-Site Scripting",
:line => 15,
:message => /^Unsafe\ parameter\ value\ in\ `link_to`\ href/,
:confidence => 0,
:relative_path => "app/views/home/test_model.html.erb",
:code => s(:call, nil, :link_to, s(:str, "test"), s(:call, s(:params), :[], s(:lit, :user_id))),
:user_input => s(:call, s(:params), :[], s(:lit, :user_id))
end
def test_unescaped_body_in_link_to
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped parameter value in `link_to`/,
:confidence => 0,
:file => /test_link_to\.html\.erb/,
:relative_path => "app/views/home/test_link_to.html.erb"
end
def test_filter
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /test_filter\.html\.erb/,
:relative_path => "app/views/home/test_filter.html.erb"
end
def test_unescaped_model
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 4,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /test_sql\.html\.erb/,
:relative_path => "app/views/home/test_sql.html.erb"
end
def test_param_from_filter
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /index\.html\.erb/,
:relative_path => "app/views/home/index.html.erb"
end
def test_params_from_locals_hash
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 4,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /app\/views\/other\/test_locals\.html\.erb/,
:relative_path => "app/views/other/test_locals.html.erb"
end
def test_model_attribute_from_collection
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /_user\.html\.erb/,
:relative_path => "app/views/other/_user.html.erb"
end
def test_model_attribute_from_iteration
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /test_iteration\.html\.erb/,
:relative_path => "app/views/other/test_iteration.html.erb"
end
def test_other_model_attribute_from_iteration
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 4,
:message => /^Unescaped model attribute/,
:confidence => 0,
:file => /test_iteration\.html\.erb/,
:relative_path => "app/views/other/test_iteration.html.erb"
end
def test_sql_injection_in_template
assert_no_warning :type => :template,
:warning_type => "SQL Injection",
:line => 4,
:message => /^Possible SQL injection/,
:confidence => 0,
:file => /test_sql\.html\.erb/,
:relative_path => "app/views/home/test_sql.html.erb"
end
def test_sql_injection_call_chain
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 73,
:message => /^Possible SQL injection near line 73: User.humans.alive.find/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_sql_injection_merge_conditions
assert_no_warning :type => :warning,
:warning_type => "SQL Injection",
:line => 22,
:message => /^Possible SQL injection near line 22: find/,
:confidence => 0,
:file => /user\.rb/,
:relative_path => "app/models/user.rb"
end
def test_sql_injection_active_record_base_connection
assert_warning :type => :warning,
:warning_code => 0,
:fingerprint => "4918bccd67257c7f691718b4bb10bbbf176bc4bd3ad80cce9df11032cc73515d",
:warning_type => "SQL Injection",
:line => 31,
:message => /^Possible\ SQL\ injection/,
:confidence => 1,
:relative_path => "app/models/user.rb",
:user_input => s(:lvar, :value)
end
def test_escape_once
results = find :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped parameter value/,
:confidence => 2,
:file => /index\.html\.erb/,
:relative_path => "app/views/home/index.html.erb"
assert_equal 0, results.length, "escape_once is a safe method"
end
def test_indirect_cookie
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped cookie value/,
:confidence => 2,
:file => /test_cookie\.html\.erb/,
:relative_path => "app/views/home/test_cookie.html.erb"
end
def test_cookie_from_controller
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped cookie value/,
:confidence => 0,
:file => /test_cookie\.html\.erb/,
:relative_path => "app/views/home/test_cookie.html.erb"
end
#Check for params that look like params[:x][:y]
def test_params_multidimensional
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 8,
:message => /^Unescaped parameter value/,
:confidence => 0,
:file => /test_params\.html\.erb/,
:relative_path => "app/views/home/test_params.html.erb"
end
#Check for cookies that look like cookies[:blah][:blah]
def test_cookies_multidimensional
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped cookie value/,
:confidence => 0,
:file => /test_cookie\.html\.erb/,
:relative_path => "app/views/home/test_cookie.html.erb"
end
def test_xss_in_unused_template
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => "Unescaped parameter value near line 1: params[:blah]",
:confidence => 0,
:file => /not_used\.html\.erb/,
:relative_path => "app/views/other/not_used.html.erb"
end
def test_select_vulnerability
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Upgrade\ to\ Rails\ 3\ or\ use\ options_for_se/,
:confidence => 1,
:file => /not_used\.html\.erb/,
:relative_path => "app/views/other/not_used.html.erb"
end
def test_explicit_render_template
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped parameter value near line 1: params\[:ba/,
:confidence => 0,
:file => /home\/test_render_template\.html\.haml/,
:relative_path => "app/views/home/test_render_template.html.haml"
end
def test_xss_with_or_in_view
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_xss_with_or\.html\.erb/,
:relative_path => "app/views/home/test_xss_with_or.html.erb"
end
def test_xss_with_or_from_action
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_xss_with_or\.html\.erb/,
:relative_path => "app/views/home/test_xss_with_or.html.erb"
end
def test_xss_with_or_from_if_branches
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_xss_with_or\.html\.erb/,
:relative_path => "app/views/home/test_xss_with_or.html.erb"
end
def test_xss_with_nested_or
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_xss_with_or\.html\.erb/,
:relative_path => "app/views/home/test_xss_with_or.html.erb"
end
def test_xss_with_model_in_or
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 9,
:message => /^Unescaped\ model\ attribute/,
:confidence => 0,
:file => /test_xss_with_or\.html\.erb/,
:relative_path => "app/views/home/test_xss_with_or.html.erb"
end
def test_cross_site_scripting_strip_tags
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_strip_tags\.html\.erb/,
:relative_path => "app/views/home/test_strip_tags.html.erb"
end
def test_xss_content_tag_body
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped\ model\ attribute\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_xss_content_tag_escaped
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 8,
:message => /^Unescaped\ cookie\ value\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_xss_content_tag_attribute_name
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 11,
:message => /^Unescaped\ cookie\ value\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_xss_content_tag_attribute_name_even_with_escape_set
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 17,
:message => /^Unescaped\ model\ attribute\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_cross_site_scripting_escaped_by_default
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 20,
:message => /^Unescaped\ parameter\ value\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_cross_site_scripting_u_alias_for_content_tag
assert_no_warning :type => :template,
:warning_code => 53,
:fingerprint => "e0279d86dea74b0da8c9cf5fce0b38c1023c1c407e84671d03ce0ca3440f03da",
:warning_type => "Cross-Site Scripting",
:line => 29,
:message => /^Unescaped\ parameter\ value\ in\ `content_tag`/,
:confidence => 0,
:relative_path => "app/views/home/test_content_tag.html.erb",
:code => s(:call, nil, :content_tag, s(:lit, :span), s(:call, s(:params), :[], s(:lit, :url))),
:user_input => s(:call, s(:params), :[], s(:lit, :url))
end
#Uh...maybe this shouldn't be a warning
def test_cross_site_scripting_in_sanitize_method
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped\ parameter\ value/,
:confidence => 2,
:file => /not_used\.html\.erb/,
:relative_path => "app/views/other/not_used.html.erb"
end
def test_xss_content_tag_unescaped_on_purpose
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 23,
:message => /^Unescaped\ model\ attribute\ in\ `content_tag`/,
:confidence => 0,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_xss_content_tag_indirect_body
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 26,
:message => /^Unescaped\ parameter\ value\ in\ `content_tag`/,
:confidence => 1,
:file => /test_content_tag\.html\.erb/,
:relative_path => "app/views/home/test_content_tag.html.erb"
end
def test_cross_site_scripting_single_quotes_CVE_2012_3464
assert_warning :type => :warning,
:warning_type => "Cross-Site Scripting",
:message => /^All\ Rails\ 2\.x\ versions\ do\ not\ escape\ sin/,
:confidence => 1,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_check_send
assert_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 83,
:message => /\AUser controlled method execution/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
assert_no_warning :type => :warning,
:warning_code => 23,
:warning_type => "Dangerous Send",
:line => 84,
:message => /^User\ controlled\ method\ execution/,
:confidence => 0,
:relative_path => "app/controllers/home_controller.rb"
assert_no_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 90,
:message => /\AUser defined target of method invocation/,
:confidence => 1,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_strip_tags_CVE_2011_2931
assert_warning :type => :warning,
:warning_type => "Cross-Site Scripting",
:message => /^Versions\ before\ 2\.3\.13\ have\ a\ vulnerabil/,
:confidence => 0,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_strip_tags_CVE_2012_3465_high
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_strip_tags\.html\.erb/,
:relative_path => "app/views/home/test_strip_tags.html.erb"
end
def test_sql_injection_CVE_2012_5664
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:message => /CVE-2012-5664/,
:confidence => 0,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_sql_injection_CVE_2013_0155
assert_warning :type => :warning,
:warning_type => "SQL Injection",
:message => /CVE-2013-0155/,
:confidence => 0,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_remote_code_execution_CVE_2013_0156
assert_warning :type => :warning,
:warning_type => "Remote Code Execution",
:message => /^Rails\ 2\.3\.11\ has\ a\ remote\ code\ execution/,
:confidence => 0,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_remote_code_execution_CVE_2013_0277
assert_warning :type => :model,
:warning_type => "Remote Code Execution",
:message => /^Serialized\ attributes\ are\ vulnerable\ in\ /,
:confidence => 0,
:file => /unprotected\.rb/,
:relative_path => "app/models/unprotected.rb"
end
def test_remote_code_execution_CVE_2013_0333
assert_warning :type => :warning,
:warning_type => "Remote Code Execution",
:message => /^Rails\ 2\.3\.11\ has\ a\ serious\ JSON\ parsing\ /,
:confidence => 0,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_xss_sanitize_CVE_2013_1857
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Rails\ 2\.3\.11\ has\ a\ vulnerability\ in\ `sani/,
:confidence => 0,
:file => /not_used\.html\.erb/,
:relative_path => "app/views/other/not_used.html.erb"
end
def test_denial_of_service_CVE_2013_1854
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:message => /^Rails\ 2\.3\.11\ has\ a\ denial\ of\ service\ vul/,
:confidence => 1,
:file => /environment\.rb/,
:relative_path => "config/environment.rb"
end
def test_number_to_currency_CVE_2014_0081
assert_warning :type => :warning,
:warning_code => 73,
:fingerprint => "dd82650c29c3ec7b77437c32d394641744208b42b2aeb673d54e5f42c51e6c33",
:warning_type => "Cross-Site Scripting",
:line => nil,
:message => /^Rails\ 2\.3\.11\ has\ a\ vulnerability\ in\ numb/,
:confidence => 1,
:relative_path => "config/environment.rb",
:user_input => nil
end
def test_sql_injection_CVE_2013_6417
assert_warning :type => :warning,
:warning_code => 69,
:fingerprint => "378978cda99add8404dd38db466f6ffa0b824ea8c57270d98869241a240d12a6",
:warning_type => "SQL Injection",
:line => nil,
:message => /^Rails\ 2\.3\.11\ contains\ a\ SQL\ injection\ vu/,
:confidence => 0,
:relative_path => "config/environment.rb",
:user_input => nil
end
def test_remote_code_execution_CVE_2014_0130
assert_warning :type => :warning,
:warning_code => 77,
:fingerprint => "93393e44a0232d348e4db62276b18321b4cbc9051b702d43ba2fd3287175283c",
:warning_type => "Remote Code Execution",
:line => nil,
:message => /^Rails\ 2\.3\.11\ with\ globbing\ routes\ is\ vul/,
:confidence => 0,
:relative_path => "config/routes.rb",
:user_input => nil
end
def test_xml_dos_CVE_2015_3227
assert_warning :type => :warning,
:warning_code => 88,
:fingerprint => "73e352cd7b43b0a4045a100d43b7707bebf3caeaec223a191375cde74f7e2b52",
:warning_type => "Denial of Service",
:line => nil,
:message => /^Rails\ 2\.3\.11\ is\ vulnerable\ to\ denial\ of\ /,
:confidence => 1,
:relative_path => "config/environment.rb",
:user_input => nil
end
def test_mime_type_dos_CVE_2016_0751
# Used workaround
assert_no_warning :type => :warning,
:warning_code => 94,
:fingerprint => "dfe71c713bd20a8e1324a38bd89b1667862ba47133fc62c5cc36372dac691a75",
:warning_type => "Denial of Service",
:line => nil,
:message => /^Rails\ 2\.3\.11\ is\ vulnerable\ to\ denial\ of\ /,
:confidence => 1,
:relative_path => "config/environment.rb",
:user_input => nil
end
def test_to_json
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped model attribute in JSON hash/,
:confidence => 0,
:file => /test_to_json\.html\.erb/,
:relative_path => "app/views/home/test_to_json.html.erb"
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped parameter value in JSON hash/,
:confidence => 0,
:file => /test_to_json\.html\.erb/,
:relative_path => "app/views/home/test_to_json.html.erb"
assert_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 11,
:message => /^Unescaped parameter value in JSON hash/,
:confidence => 0,
:file => /test_to_json\.html\.erb/,
:relative_path => "app/views/home/test_to_json.html.erb"
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 14,
:message => /^Unescaped parameter value in JSON hash/,
:confidence => 0,
:file => /test_to_json\.html\.erb/,
:relative_path => "app/views/home/test_to_json.html.erb"
end
def test_xss_with_params_to_i
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:file => /test_to_i\.html\.erb/,
:relative_path => "app/views/home/test_to_i.html.erb"
end
def test_xss_with_request_env_to_i
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 5,
:message => /^Unescaped\ cookie\ value/,
:confidence => 2,
:file => /test_to_i\.html\.erb/,
:relative_path => "app/views/home/test_to_i.html.erb"
end
def test_xss_with_cookie_to_i
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped\ request\ value/,
:confidence => 0,
:file => /test_to_i\.html\.erb/,
:relative_path => "app/views/home/test_to_i.html.erb"
end
def test_xss_with_model_attribute_to_i
assert_no_warning :type => :template,
:warning_type => "Cross-Site Scripting",
:line => 7,
:message => /^Unescaped\ model\ attribute/,
:confidence => 1,
:file => /test_to_i\.html\.erb/,
:relative_path => "app/views/home/test_to_i.html.erb"
end
def test_cross_site_scripting_unresolved_model_id
assert_no_warning :type => :template,
:warning_code => 2,
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped\ model\ attribute/,
:confidence => 0,
:file => /_models\.html\.erb/
end
def test_cross_site_scripting_in_layout_for_dupe
assert_warning :type => :template,
:warning_code => 2,
:fingerprint => "5d9a5790dbcd6ae68a11e8cdb791a8be9585bf0f75b18ef1f763c6965f55e431",
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped\ parameter\ value/,
:confidence => 0,
:relative_path => "app/views/layouts/thing.html.erb"
end
def test_cross_site_scripting_in_layout_weak_dupe
assert_no_warning :type => :template,
:warning_code => 5,
:fingerprint => "56fa0dc161d310062ae4717dd70515269b776fe532352e59f72ed2cdc4932153",
:warning_type => "Cross-Site Scripting",
:line => 1,
:message => /^Unescaped\ parameter\ value/,
:confidence => 2,
:relative_path => "app/views/layouts/thing.html.erb"
end
def test_cross_site_scripting_in_haml
assert_warning :type => :template,
:warning_code => 2,
:fingerprint => "702f9bae476402bb2614794276083849342540bd8b5e8f2fc35b15b40e9f34fc",
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unescaped\ model\ attribute/,
:confidence => 0,
:relative_path => "app/views/other/test_haml_stuff.html.haml",
:user_input => nil
end
def test_cross_site_scripting_in_haml2
assert_warning :type => :template,
:warning_code => 2,
:fingerprint => "79cbc87a06ad9247362be97ba4b6cc12b9619fd0f68d468b81cbed376bfbcc5c",
:warning_type => "Cross-Site Scripting",
:line => 4,
:message => /^Unescaped\ model\ attribute/,
:confidence => 0,
:relative_path => "app/views/other/test_haml_stuff.html.haml",
:user_input => nil
end
def test_cross_site_scripting_in_link_to_with_block
assert_warning :type => :template,
:warning_code => 4,
:fingerprint => "a594a83998a7cbace5d65680e78dbd6e74b7b3ded069c83f8ac5452ef0ada08f",
:warning_type => "Cross-Site Scripting",
:line => 3,
:message => /^Unsafe\ parameter\ value\ in\ `link_to`\ href/,
:confidence => 0,
:relative_path => "app/views/home/test_link_to.html.erb",
:code => s(:call, nil, :link_to, s(:call, s(:call, nil, :params), :[], s(:lit, :evil_url))),
:user_input => s(:call, s(:call, nil, :params), :[], s(:lit, :evil_url))
end
def test_cross_site_scripting_html_entities_in_json
assert_warning :type => :warning,
:warning_code => 114,
:fingerprint => "c96eb07567e2a7b0ded7cda123645c4e736d3a1b124bb7c0ffaf5070f53dfcf3",
:warning_type => "Cross-Site Scripting",
:line => 21,
:message => /^HTML\ entities\ in\ JSON\ are\ not\ escaped\ by/,
:confidence => 1,
:relative_path => "config/environments/production.rb",
:code => s(:attrasgn, s(:const, :ActiveSupport), :escape_html_entities_in_json=, s(:false)),
:user_input => nil
end
def test_dangerous_send_try
assert_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 155,
:message => /^User\ controlled\ method\ execution/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_dangerous_send_underscore
assert_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 156,
:message => /^User\ controlled\ method\ execution/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_dangerous_public_send
assert_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 157,
:message => /^User\ controlled\ method\ execution/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_dangerous_try_on_user_input
assert_no_warning :type => :warning,
:warning_type => "Dangerous Send",
:line => 160,
:message => /^User\ defined\ target\ of\ method\ invocation/,
:confidence => 1,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_unsafe_reflection_constantize
assert_warning :type => :warning,
:warning_type => "Remote Code Execution",
:line => 89,
:message => /^Unsafe\ reflection\ method\ `constantize`\ cal/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
# This is same call, copied to template
assert_no_warning :type => :template,
:warning_code => 24,
:warning_type => "Remote Code Execution",
:line => 1,
:message => /^Unsafe\ reflection\ method\ `constantize`\ cal/,
:confidence => 0,
:relative_path => "app/views/home/test_send_target.html.erb"
end
def test_unsafe_reflection_constantize_2
assert_warning :type => :warning,
:warning_type => "Remote Code Execution",
:line => 160,
:message => /^Unsafe\ reflection\ method\ `constantize`\ cal/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_unsafe_symbol_creation
[41,42].each do |line|
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => line,
:message => /^Symbol\ conversion\ from\ unsafe\ string/,
:confidence => 0,
:file => /application_controller\.rb/,
:relative_path => "app/controllers/application_controller.rb"
end
end
def test_unsafe_symbol_creation_2
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => 83,
:message => /^Symbol\ conversion\ from\ unsafe\ string/,
:confidence => 0,
:file => /home_controller\.rb/,
:relative_path => "app/controllers/home_controller.rb"
end
def test_unsafe_symbol_creation_3
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => 29,
:message => /^Symbol\ conversion\ from\ unsafe\ string/,
:confidence => 1,
:file => /application_controller\.rb/,
:relative_path => "app/controllers/application_controller.rb"
end
def test_unsafe_symbol_creation_4
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => 86,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ in pa/,
:confidence => 0,
:file => /other_controller\.rb/,
:relative_path => "app/controllers/other_controller.rb"
end
def test_unsafe_symbol_creation_5
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => 88,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ in pa/,
:confidence => 1,
:file => /other_controller\.rb/,
:relative_path => "app/controllers/other_controller.rb"
end
def test_unsafe_symbol_creation_6
assert_warning :type => :warning,
:warning_type => "Denial of Service",
:line => 44,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ in pa/,
:confidence => 1,
:file => /application_controller\.rb/,
:relative_path => "app/controllers/application_controller.rb"
end
def test_regex_dos
assert_warning :type => :warning,
:warning_code => 76,
:fingerprint => "de95ff1870e84933cb5a67bdd5c10cfa666b0bcd95cc78d7dd962215be9ed20c",
:warning_type => "Denial of Service",
:line => 74,
:message => /^Parameter\ value\ used\ in\ regular\ expression/,
:confidence => 0,
:relative_path => "app/controllers/other_controller.rb",
:user_input => s(:call, s(:params), :[], s(:lit, :regex))
end
def test_indirect_regex_dos
assert_warning :type => :warning,
:warning_code => 76,
:fingerprint => "afdb18fa56308063ad491b76821fb76724dd6f0bd9d3e6aac83c933af0b4baac",
:warning_type => "Denial of Service",
:line => 82,
:message => /^Parameter\ value\ used\ in\ regular\ expression/,
:confidence => 2,
:relative_path => "app/controllers/other_controller.rb",
:user_input => s(:call, s(:params), :[], s(:lit, :regex))
end
def test_unsafe_symbol_creation_from_param
assert_warning :type => :warning,
:warning_code => 59,
:fingerprint => "b9c29fc37080f827527feb53f29d618b91d9a5aaac9047383baf46361f08c4cc",
:warning_type => "Denial of Service",
:line => 49,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ in pa/,
:confidence => 0,
:relative_path => "app/controllers/other_controller.rb"
end
def test_to_sym_duplicate_as_argument
assert_no_warning :type => :warning,
:warning_code => 59,
:fingerprint => "b9c29fc37080f827527feb53f29d618b91d9a5aaac9047383baf46361f08c4cc",
:warning_type => "Denial of Service",
:line => 53,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ in pa/,
:confidence => 0,
:relative_path => "app/controllers/other_controller.rb"
end
def test_to_sym_duplicate_as_target
assert_no_warning :type => :warning,
:warning_code => 59,
:fingerprint => "b9c29fc37080f827527feb53f29d618b91d9a5aaac9047383baf46361f08c4cc",
:warning_type => "Denial of Service",
:line => 54,
:message => /^Symbol\ conversion\ from\ unsafe\ string\ \(pa/,
:confidence => 0,
:relative_path => "app/controllers/other_controller.rb"
end
def test_ignored_sql_warning
assert_no_warning :type => :template,
:warning_code => 0,
:fingerprint => "f2fa1da45eea252150f6920454822bda3ed5c83a2c376c1296a98037969dd45f",
:warning_type => "SQL Injection",
:line => 2,
:message => /^Possible\ SQL\ injection/,
:confidence => 0,
:relative_path => "app/views/other/ignore_me.html.erb"
end
def test_ignored_xss_warning
assert_no_warning :type => :template,
:warning_code => 2,
:fingerprint => "6300805e44167e6c3446efbd06b97206928855a2bfc6e1f3e61c097795956b13",
:warning_type => "Cross-Site Scripting",
:line => 2,
:message => /^Unescaped\ model\ attribute/,
:confidence => 0,
:relative_path => "app/views/other/ignore_me.html.erb"
end
def test_unscoped_find
assert_warning :type => :warning,
:warning_code => 82,
:fingerprint => "97cfe8a3ca261dfd2dcbd9f3aae6a007bc107c5ab6045e0f9cfaa7e66333c8c8",
:warning_type => "Unscoped Find",
:line => 3,
:message => /^Unscoped\ call\ to\ `Email\#find`/,
:confidence => 2,
:relative_path => "app/controllers/emails_controller.rb",
:user_input => s(:call, s(:params), :[], s(:lit, :email_id))
end
end
class Rails2WithOptionsTests < Minitest::Test
include BrakemanTester::FindWarning
include BrakemanTester::CheckExpected
def expected
@expected ||= {
:controller => 1,
:model => 4,
:template => 47,
:generic => 58 }
end
def report
@@report ||= BrakemanTester.run_scan "rails2", "Rails 2", :run_all_checks => true
end
def test_no_errors
assert_equal 0, report[:errors].length
end
def test_attribute_restriction
assert_warning :type => :model,
:warning_type => "Attribute Restriction",
:warning_code => Brakeman::WarningCodes::Codes[:no_attr_accessible],
:message => /^Mass assignment is not restricted using /,
:confidence => 0,
:file => /account\.rb/
assert_warning :type => :model,
:warning_type => "Attribute Restriction",
:warning_code => Brakeman::WarningCodes::Codes[:no_attr_accessible],
:message => /^Mass assignment is not restricted using /,
:confidence => 0,
:file => /user\.rb/
end
end
| 34.403909 | 181 | 0.636489 |
61a3410d10154ac5cbd447ce48af8ecbf668fc9b | 1,437 | module FilterHelper
def filter_option_link(site, type, options = {})
selected = options[:selected]
link_to filter_site_mappings_path(site),
'class' => "filter-option #{'filter-selected' if selected}",
'data-toggle' => 'dropdown',
'role' => 'button' do
"#{type} <span class=\"glyphicon glyphicon-chevron-down\"></span>".html_safe
end
end
def filter_remove_option_link(_site, type, type_sym)
link_to site_mappings_path(permitted_params(params.except(type_sym, :page))), title: 'Remove filter', class: 'filter-option filter-selected' do
"<span class=\"glyphicon glyphicon-remove\"></span><span class=\"rm\">Remove</span> #{type}".html_safe
end
end
##
# When rendering a single filter form for a dropdown we need to pass through
# all the other existing filter field values
def hidden_filter_fields_except(filter, field)
hidden_fields = (View::Mappings::Filter.fields - [field]).map do |name|
value = filter.try(name)
hidden_field_tag(name, value) unless value.blank?
end
hidden_fields.join("\n").html_safe
end
# receives params that have not been permitted (permited: false)
def permitted_params(unpermitted_params)
unpermitted_params.permit(
:controller,
:action,
:site_id,
:format,
:type,
:path_contains,
:new_url_contains,
:tagged,
)
end
end
| 32.659091 | 147 | 0.660404 |
1c3dbd9ff6693f5e607dfb57549611de6fdb9ca6 | 73 | class DevelopmentController < ApplicationController
def show
end
end
| 14.6 | 51 | 0.821918 |
e9af83fd70f2a0b4273da95c7fefb94da2ca4f71 | 13,752 | # frozen_string_literal: true
require 'spec_helper'
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
describe Bosh::AzureCloud::AzureClient do
let(:logger) { Bosh::Clouds::Config.logger }
let(:azure_client) do
Bosh::AzureCloud::AzureClient.new(
mock_azure_config,
logger
)
end
let(:subscription_id) { mock_azure_config.subscription_id }
let(:tenant_id) { mock_azure_config.tenant_id }
let(:api_version) { AZURE_API_VERSION }
let(:api_version_compute) { AZURE_RESOURCE_PROVIDER_COMPUTE }
let(:resource_group) { 'fake-resource-group-name' }
let(:request_id) { 'fake-request-id' }
let(:token_uri) { "https://login.microsoftonline.com/#{tenant_id}/oauth2/token?api-version=#{api_version}" }
let(:operation_status_link) { "https://management.azure.com/subscriptions/#{subscription_id}/operations/#{request_id}" }
let(:disk_name) { 'fake-disk-name' }
let(:valid_access_token) { 'valid-access-token' }
let(:expires_on) { (Time.new + 1800).to_i.to_s }
before do
allow(azure_client).to receive(:sleep)
end
describe '#create_empty_managed_disk' do
let(:disk_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/disks/#{disk_name}?api-version=#{api_version_compute}" }
context 'when common disk_params are provided' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
disk_size: 'c',
account_type: 'd'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
sku: {
name: 'd'
},
properties: {
creationData: {
createOption: 'Empty'
},
diskSizeGB: 'c'
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_empty_managed_disk(resource_group, disk_params)
end.not_to raise_error
end
end
context 'when zone is specified' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
disk_size: 'c',
account_type: 'd',
zone: 'e'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
zones: ['e'],
sku: {
name: 'd'
},
properties: {
creationData: {
createOption: 'Empty'
},
diskSizeGB: 'c'
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_empty_managed_disk(resource_group, disk_params)
end.not_to raise_error
end
end
end
describe '#create_managed_disk_from_blob' do
let(:disk_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/disks/#{disk_name}?api-version=#{api_version_compute}" }
context 'when common disk_params are provided' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
source_uri: 'c',
account_type: 'd'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
sku: {
name: 'd'
},
properties: {
creationData: {
createOption: 'Import',
sourceUri: 'c'
}
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_managed_disk_from_blob(resource_group, disk_params)
end.not_to raise_error
end
end
context 'when zone is specified' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
source_uri: 'c',
account_type: 'd',
zone: 'e'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
zones: ['e'],
sku: {
name: 'd'
},
properties: {
creationData: {
createOption: 'Import',
sourceUri: 'c'
}
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_managed_disk_from_blob(resource_group, disk_params)
end.not_to raise_error
end
end
end
describe '#create_managed_disk_from_snapshot' do
let(:snapshot_name) { 'fake-snapshot-name' }
let(:disk_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/disks/#{disk_name}?api-version=#{api_version_compute}" }
let(:snapshot_url) { "/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/snapshots/#{snapshot_name}" }
context 'when common disk_params are provided' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
account_type: 'c'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
sku: {
name: 'c'
},
properties: {
creationData: {
createOption: 'Copy',
sourceResourceId: snapshot_url
}
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_managed_disk_from_snapshot(resource_group, disk_params, snapshot_name)
end.not_to raise_error
end
end
context 'when zone is specified' do
let(:disk_params) do
{
name: disk_name,
location: 'b',
tags: { 'foo' => 'bar' },
account_type: 'c',
zone: 'd'
}
end
let(:request_body) do
{
location: 'b',
tags: {
foo: 'bar'
},
zones: ['d'],
sku: {
name: 'c'
},
properties: {
creationData: {
createOption: 'Copy',
sourceResourceId: snapshot_url
}
}
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:put, disk_uri).with(body: request_body).to_return(
status: 200,
body: '',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
stub_request(:get, operation_status_link).to_return(
status: 200,
body: '{"status":"Succeeded"}',
headers: {}
)
expect do
azure_client.create_managed_disk_from_snapshot(resource_group, disk_params, snapshot_name)
end.not_to raise_error
end
end
end
describe '#get_managed_disk_by_name' do
let(:disk_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/disks/#{disk_name}?api-version=#{api_version_compute}" }
let(:response_body) do
{
id: 'a',
name: 'b',
location: 'c',
tags: {
foo: 'bar'
},
sku: {
name: 'f',
tier: 'g'
},
zones: ['fake-zone'],
properties: {
provisioningState: 'd',
diskSizeGB: 'e'
}
}
end
let(:disk) do
{
id: 'a',
name: 'b',
location: 'c',
tags: {
'foo' => 'bar'
},
sku_name: 'f',
sku_tier: 'g',
zone: 'fake-zone',
provisioning_state: 'd',
disk_size: 'e'
}
end
it 'should raise no error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:get, disk_uri).to_return(
status: 200,
body: response_body.to_json,
headers: {}
)
expect(
azure_client.get_managed_disk_by_name(resource_group, disk_name)
).to eq(disk)
end
end
describe '#delete_managed_disk' do
let(:disk_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{resource_group}/providers/Microsoft.Compute/disks/#{disk_name}?api-version=#{api_version_compute}" }
context 'when token is valid, delete operation is accepted and completed' do
it 'should delete the managed disk without error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:delete, disk_uri).to_return(
status: 200,
body: '',
headers: {}
)
expect do
azure_client.delete_managed_disk(resource_group, disk_name)
end.not_to raise_error
end
end
context 'when retry reach max number.' do
it 'should raise error' do
stub_request(:post, token_uri).to_return(
status: 200,
body: {
'access_token' => valid_access_token,
'expires_on' => expires_on
}.to_json,
headers: {}
)
stub_request(:delete, disk_uri).to_return(
status: 202,
body: '{}',
headers: {
'azure-asyncoperation' => operation_status_link
}
)
eleven_failed = []
11.times do
eleven_failed.push(
status: 200,
body: '{"status":"Failed"}',
headers: {
'Retry-After' => '1'
}
)
end
stub_request(:get, operation_status_link).to_return(
eleven_failed
)
expect do
azure_client.delete_managed_disk(resource_group, disk_name)
end.to raise_error(/check_completion - http code: 200/)
end
end
end
end
| 26.702913 | 201 | 0.519706 |
ac6dd2658bd6c3cdc6fbb78a8a16058d5275decd | 1,393 | # This class interacts with puppetdb to pull the facts from the recent
# run of Puppet on a given node. This uses octocatalog-diff on the back end to
# pull the facts from puppetdb.
require "octocatalog-diff"
module OctofactsUpdater
module Service
class PuppetDB
# Get the facts for a specific node.
#
# node - A String with the FQDN for which to retrieve facts
# config - An optional Hash with configuration settings
#
# Returns a Hash with the facts (via octocatalog-diff)
def self.facts(node, config = {})
fact_obj = OctocatalogDiff::Facts.new(
node: node.strip,
backend: :puppetdb,
puppetdb_url: puppetdb_url(config)
)
facts = fact_obj.facts(node)
return facts unless facts.nil?
raise OctocatalogDiff::Errors::FactSourceError, "Fact retrieval failed for #{node}"
end
# Get the puppetdb URL from the configuration or environment.
#
# config - An optional Hash with configuration settings
#
# Returns a String with the PuppetDB URL
def self.puppetdb_url(config = {})
answer = [
config.fetch("puppetdb", {}).fetch("url", nil),
ENV["PUPPETDB_URL"]
].compact
raise "PuppetDB URL not configured or set in environment" unless answer.any?
answer.first
end
end
end
end
| 32.395349 | 91 | 0.641062 |
bf69d29b08557ca3c3c8341f91a60631412bfba2 | 2,172 | module Aws
module Resources
class Documenter
class HasManyOperationDocumenter < BaseOperationDocumenter
def docstring
super + ' ' +<<-DOCSTRING.lstrip
Returns a {Resources::Collection Collection} of {#{target_resource_class_name}}
resources. No API requests are made until you call an enumerable method on the
collection. {#{called_operation}} will be called multiple times until every
{#{target_resource_class_name}} has been yielded.
DOCSTRING
end
def return_tag
tag("@return [Collection<#{target_resource_class_name}>]")
end
def example_tags
tags = super
tags << enumerate_example_tag
tags << enumerate_with_limit_example_tag
tags << batch_examples_tag if target_resource_batches?
tags
end
def enumerate_example_tag
tag(<<-EXAMPLE.strip)
@example Enumerating {#{target_resource_class_name}} resources.
#{variable_name}.#{@operation_name}.each do |#{target_resource_class_name.downcase}|
# yields each #{target_resource_class_name.downcase}
end
EXAMPLE
end
def enumerate_with_limit_example_tag
tag(<<-EXAMPLE.strip)
@example Enumerating {#{target_resource_class_name}} resources with a limit.
#{variable_name}.#{@operation_name}.limit(10).each do |#{target_resource_class_name.downcase}|
# yields at most 10 #{@operation_name}
end
EXAMPLE
end
def batch_examples_tag
example = []
example << "@example Batch operations callable on the returned collection"
target_resource_batch_operations.each do |name, operation|
example << ""
example << " # calls Client##{operation.request.method_name} on each batch"
example << " #{variable_name}.#{@operation_name}.#{name}"
end
tag(example.join("\n"))
end
def target_resource_batches?
target_resource_batch_operations.count > 0
end
def target_resource_batch_operations
target_resource_class.batch_operations
end
end
end
end
end
| 31.941176 | 96 | 0.656538 |
d5f9a3e140edd553e82aa90ad1bcdde37a5fc54d | 15,188 | # frozen_string_literal: true
# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = 'f1927cb145014412a38464d617aa4e2a23e06abe0d10b3a7b715f64df3075ba56c1ceefb4543461c8e2d85ca960c5e5e7c43c00899814a87e4fc515fed8bb4f4'
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [:login]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication.
# For API-only applications to support authentication "out-of-the-box", you will likely want to
# enable this with :database unless you are using a custom strategy.
# The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 12. If
# using other algorithms, it sets how many times you want the password to be hashed.
# The number of stretches used for generating the hashed password are stored
# with the hashed password. This allows you to change the stretches without
# invalidating existing passwords.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 12
# Set up a pepper to generate the hashed password.
# config.pepper = 'b3af99a4e2212b723d1a57d9f7eaefbfcc189dbb1fb57944b9b38da784ca4d241282505a4193074b7307914c8f6dec1e372a37b728ccf298a4cad6992e7c4e9b'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day.
# You can also set it to nil, which will allow the user to access the website
# without confirming their account.
# Default is 0.days, meaning the user cannot access the website without
# confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
# ==> Turbolinks configuration
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
#
# ActiveSupport.on_load(:devise_failure_app) do
# include Turbolinks::Controller
# end
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
end
| 48.679487 | 154 | 0.752634 |
1da7dad12824927fd6113e788fd3cc851d371d2c | 2,848 | # Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "helper"
describe Google::Cloud::Firestore::Transaction, :create, :mock_firestore do
let(:transaction_id) { "transaction123" }
let(:transaction) do
Google::Cloud::Firestore::Transaction.from_client(firestore).tap do |b|
b.instance_variable_set :@transaction_id, transaction_id
end
end
let(:document_path) { "users/mike" }
let(:database_path) { "projects/#{project}/databases/(default)" }
let(:documents_path) { "#{database_path}/documents" }
let(:commit_time) { Time.now }
let :create_writes do
[Google::Firestore::V1::Write.new(
update: Google::Firestore::V1::Document.new(
name: "#{documents_path}/#{document_path}",
fields: Google::Cloud::Firestore::Convert.hash_to_fields({ name: "Mike" })),
current_document: Google::Firestore::V1::Precondition.new(
exists: false)
)]
end
let :commit_resp do
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time),
write_results: [Google::Firestore::V1::WriteResult.new(
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time))]
)
end
it "creates a new document given a string path" do
firestore_mock.expect :commit, commit_resp, [database_path, create_writes, transaction: transaction_id, options: default_options]
transaction.create(document_path, { name: "Mike" })
resp = transaction.commit
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "creates a new document given a DocumentReference" do
firestore_mock.expect :commit, commit_resp, [database_path, create_writes, transaction: transaction_id, options: default_options]
doc = firestore.doc document_path
doc.must_be_kind_of Google::Cloud::Firestore::DocumentReference
transaction.create(doc, { name: "Mike" })
resp = transaction.commit
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "raises if not given a Hash" do
error = expect do
transaction.create document_path, "not a hash"
end.must_raise ArgumentError
error.message.must_equal "data is required"
end
end
| 37.473684 | 133 | 0.73139 |
e2581623ccad52000088b8791618c60ab2558a70 | 387 | require 'shouty'
Given("{person} is located/standing {int} metre(s) from Sean") do |person, distance|
person.move_to(distance)
@lucy = person
end
When("Sean shouts {string}") do |message|
sean = Shouty::Person.new('Sean')
sean.shout(message)
@message_from_sean = message
end
Then("Lucy hears Sean's message") do
expect(@lucy.messages_heard).to eq [@message_from_sean]
end
| 22.764706 | 84 | 0.718346 |
01126b33dcd9dda1fe8ca82ed1da813d0a6368e2 | 64 | class Image < ActiveRecord::Base
has_attached_file :image
end
| 16 | 32 | 0.796875 |
abbaee4d618eae0b97e5e0292ca510311f15b93a | 1,445 | # Require any additional compass plugins here.
# set the css file encoding
Encoding.default_external = "utf-8"
dist_root = "dist/"
http_images_path = "../img/common"
http_generated_images_path = "../../img"
generated_images_dir = dist_root + "img"
# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true
# To disable debugging comments that display the original location of your selectors. Uncomment:
# line_comments = false
# cache buster via parameter
# Increment the deploy_version before every release to force cache busting.
# deploy_version = 1
# asset_cache_buster do |http_path, real_path|
# if File.exists?(real_path)
# hash = Digest::MD5.file(real_path.path).hexdigest
# hash.to_s[0, 8]
# else
# "v=#{deploy_version}"
# end
# end
# cache buster via path md5
asset_cache_buster do |path, real_path|
if File.exists?(real_path)
pathname = Pathname.new(path)
hash = Digest::MD5.file(real_path.path).hexdigest
hash = hash.to_s[0, 8]
new_path = "%s/%s-%s%s" % [http_images_path, pathname.basename(pathname.extname), hash, pathname.extname]
{:path => new_path, :query => nil}
end
end
# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
| 31.413043 | 109 | 0.721799 |
d5a92703bbcd5746c8e01f1bead0ccf1efb4dad7 | 22,067 | require 'spec_helper'
describe Boxr::Client do
#PLEASE NOTE
#This test is intentionally NOT a series of unit tests. The goal is to smoke test the entire code base
#against an actual Box account, making real calls to the Box API. The Box API is subject to frequent
#changes and it is not sufficient to mock responses as those responses will change over time. Successfully
#running this test suite shows that the code base works with the current Box API. The main premise here
#is that an exception will be thrown if anything unexpected happens.
#REQUIRED BOX SETTINGS
# 1. The developer token used must have admin or co-admin priviledges
# 2. Enterprise settings must allow Admin and Co-admins to permanently delete content in Trash
#follow the directions in .env.example to set up your BOX_DEVELOPER_TOKEN
#keep in mind it is only valid for 60 minutes
BOX_CLIENT = Boxr::Client.new #using ENV['BOX_DEVELOPER_TOKEN']
#uncomment this line to see the HTTP request and response debug info in the rspec output
# Boxr::turn_on_debugging
BOX_SERVER_SLEEP = 5
TEST_FOLDER_NAME = 'Boxr Test'
SUB_FOLDER_NAME = 'sub_folder_1'
SUB_FOLDER_DESCRIPTION = 'This was created by the Boxr test suite'
TEST_FILE_NAME = 'test file.txt'
TEST_FILE_NAME_CUSTOM = 'test file custom.txt'
DOWNLOADED_TEST_FILE_NAME = 'downloaded test file.txt'
COMMENT_MESSAGE = 'this is a comment'
REPLY_MESSAGE = 'this is a comment reply'
CHANGED_COMMENT_MESSAGE = 'this comment has been changed'
TEST_USER_LOGIN = "test-boxr-user@#{('a'..'z').to_a.shuffle[0,10].join}.com" #needs to be unique across anyone running this test
TEST_USER_NAME = "Test Boxr User"
TEST_GROUP_NAME= "Test Boxr Group"
TEST_TASK_MESSAGE = "Please review"
TEST_WEB_URL = 'https://www.box.com'
TEST_WEB_URL2 = 'https://www.google.com'
before(:each) do
puts "-----> Resetting Box Environment"
sleep BOX_SERVER_SLEEP
root_folders = BOX_CLIENT.root_folder_items.folders
test_folder = root_folders.find{|f| f.name == TEST_FOLDER_NAME}
if(test_folder)
BOX_CLIENT.delete_folder(test_folder, recursive: true)
end
new_folder = BOX_CLIENT.create_folder(TEST_FOLDER_NAME, Boxr::ROOT)
@test_folder = new_folder
all_users = BOX_CLIENT.all_users
test_users = all_users.select{|u| u.name == TEST_USER_NAME}
test_users.each do |u|
BOX_CLIENT.delete_user(u, force: true)
end
sleep BOX_SERVER_SLEEP
test_user = BOX_CLIENT.create_user(TEST_USER_NAME, login: TEST_USER_LOGIN)
@test_user = test_user
all_groups = BOX_CLIENT.groups
test_group = all_groups.find{|g| g.name == TEST_GROUP_NAME}
if(test_group)
BOX_CLIENT.delete_group(test_group)
end
end
# use this command to just execute this scenario
# rake spec SPEC_OPTS="-e \"invokes folder operations"\"
it 'invokes folder operations' do
puts "get folder using path"
folder = BOX_CLIENT.folder_from_path(TEST_FOLDER_NAME)
expect(folder.id).to eq(@test_folder.id)
puts "get folder info"
folder = BOX_CLIENT.folder(@test_folder)
expect(folder.id).to eq(@test_folder.id)
puts "create new folder"
new_folder = BOX_CLIENT.create_folder(SUB_FOLDER_NAME, @test_folder)
expect(new_folder).to be_a BoxrMash
SUB_FOLDER = new_folder
puts "update folder"
updated_folder = BOX_CLIENT.update_folder(SUB_FOLDER, description: SUB_FOLDER_DESCRIPTION)
expect(updated_folder.description).to eq(SUB_FOLDER_DESCRIPTION)
puts "copy folder"
new_folder = BOX_CLIENT.copy_folder(SUB_FOLDER,@test_folder, name: "copy of #{SUB_FOLDER_NAME}")
expect(new_folder).to be_a BoxrMash
SUB_FOLDER_COPY = new_folder
puts "create shared link for folder"
updated_folder = BOX_CLIENT.create_shared_link_for_folder(@test_folder, access: :open)
expect(updated_folder.shared_link.access).to eq("open")
shared_link = updated_folder.shared_link.url
puts "inspect shared link"
shared_item = BOX_CLIENT.shared_item(shared_link)
expect(shared_item.id).to eq(@test_folder.id)
puts "disable shared link for folder"
updated_folder = BOX_CLIENT.disable_shared_link_for_folder(@test_folder)
expect(updated_folder.shared_link).to be_nil
puts "move folder"
folder_to_move = BOX_CLIENT.create_folder("Folder to move", @test_folder)
folder_to_move_into = BOX_CLIENT.create_folder("Folder to move into", @test_folder)
folder_to_move = BOX_CLIENT.move_folder(folder_to_move, folder_to_move_into)
expect(folder_to_move.parent.id).to eq(folder_to_move_into.id)
puts "delete folder"
result = BOX_CLIENT.delete_folder(SUB_FOLDER_COPY, recursive: true)
expect(result).to eq ({})
puts "inspect the trash"
trash = BOX_CLIENT.trash()
expect(trash).to be_a Array
puts "inspect trashed folder"
trashed_folder = BOX_CLIENT.trashed_folder(SUB_FOLDER_COPY)
expect(trashed_folder.item_status).to eq("trashed")
puts "restore trashed folder"
restored_folder = BOX_CLIENT.restore_trashed_folder(SUB_FOLDER_COPY)
expect(restored_folder.item_status).to eq("active")
puts "trash and permanently delete folder"
BOX_CLIENT.delete_folder(SUB_FOLDER_COPY, recursive: true)
result = BOX_CLIENT.delete_trashed_folder(SUB_FOLDER_COPY)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes file operations"\"
it "invokes file operations" do
puts "upload a file"
new_file = BOX_CLIENT.upload_file("./spec/test_files/#{TEST_FILE_NAME}", @test_folder)
expect(new_file.name).to eq(TEST_FILE_NAME)
test_file = new_file
puts "upload a file with custom name"
new_file = BOX_CLIENT.upload_file("./spec/test_files/#{TEST_FILE_NAME}", @test_folder, name: TEST_FILE_NAME_CUSTOM)
expect(new_file.name).to eq(TEST_FILE_NAME_CUSTOM)
puts "get file using path"
file = BOX_CLIENT.file_from_path("/#{TEST_FOLDER_NAME}/#{TEST_FILE_NAME}")
expect(file.id).to eq(test_file.id)
puts "get file download url"
download_url = BOX_CLIENT.download_url(test_file)
expect(download_url).to start_with("https://")
puts "get file info"
file_info = BOX_CLIENT.file(test_file)
expect(file_info.id).to eq(test_file.id)
puts "get file preview link"
preview_url = BOX_CLIENT.preview_url(test_file)
expect(preview_url).to start_with("https://")
puts "update file"
new_description = 'this file is used to test Boxr'
tags = ['tag one','tag two']
updated_file_info = BOX_CLIENT.update_file(test_file, description: new_description, tags: tags)
expect(updated_file_info.description).to eq(new_description)
tag_file_info = BOX_CLIENT.file(updated_file_info, fields: [:tags])
expect(tag_file_info.tags.length).to eq(2)
puts "lock file"
expires_at_utc = Time.now.utc + (60*60*24) #one day from now
locked_file = BOX_CLIENT.lock_file(test_file, expires_at: expires_at_utc, is_download_prevented: true)
locked_file = BOX_CLIENT.file(locked_file, fields: [:lock])
expect(locked_file.lock.type).to eq('lock')
expect(locked_file.lock.expires_at).to_not be_nil
expect(locked_file.lock.is_download_prevented).to eq(true)
puts "unlock file"
unlocked_file = BOX_CLIENT.unlock_file(locked_file)
unlocked_file = BOX_CLIENT.file(unlocked_file, fields: [:lock])
expect(unlocked_file.lock).to be_nil
puts "download file"
file = BOX_CLIENT.download_file(test_file)
f = File.open("./spec/test_files/#{DOWNLOADED_TEST_FILE_NAME}", 'w+')
f.write(file)
f.close
expect(FileUtils.identical?("./spec/test_files/#{TEST_FILE_NAME}","./spec/test_files/#{DOWNLOADED_TEST_FILE_NAME}")).to eq(true)
File.delete("./spec/test_files/#{DOWNLOADED_TEST_FILE_NAME}")
puts "upload new version of file"
new_version = BOX_CLIENT.upload_new_version_of_file("./spec/test_files/#{TEST_FILE_NAME}", test_file)
expect(new_version.id).to eq(test_file.id)
puts "inspect versions of file"
versions = BOX_CLIENT.versions_of_file(test_file)
expect(versions.count).to eq(1) #the reason this is 1 instead of 2 is that Box considers 'versions' to be a versions other than 'current'
v1 = versions.first
puts "promote old version of file"
newer_version = BOX_CLIENT.promote_old_version_of_file(test_file, v1)
versions = BOX_CLIENT.versions_of_file(test_file)
expect(versions.count).to eq(2)
puts "delete old version of file"
result = BOX_CLIENT.delete_old_version_of_file(test_file,v1)
versions = BOX_CLIENT.versions_of_file(test_file)
expect(versions.count).to eq(2) #this is still 2 because with Box you can restore a trashed old version
puts "get file thumbnail"
thumb = BOX_CLIENT.thumbnail(test_file)
expect(thumb).not_to be_nil
puts "create shared link for file"
updated_file = BOX_CLIENT.create_shared_link_for_file(test_file, access: :open)
expect(updated_file.shared_link.access).to eq("open")
puts "disable shared link for file"
updated_file = BOX_CLIENT.disable_shared_link_for_file(test_file)
expect(updated_file.shared_link).to be_nil
puts "copy file"
new_file_name = "copy of #{TEST_FILE_NAME}"
new_file = BOX_CLIENT.copy_file(test_file, @test_folder, name: new_file_name)
expect(new_file.name).to eq(new_file_name)
NEW_FILE = new_file
puts "move file"
new_folder = BOX_CLIENT.create_folder(SUB_FOLDER_NAME, @test_folder)
test_file = BOX_CLIENT.move_file(test_file, new_folder.id)
expect(test_file.parent.id).to eq(new_folder.id)
puts "delete file"
result = BOX_CLIENT.delete_file(NEW_FILE)
expect(result).to eq({})
puts "get trashed file info"
trashed_file = BOX_CLIENT.trashed_file(NEW_FILE)
expect(trashed_file.item_status).to eq("trashed")
puts "restore trashed file"
restored_file = BOX_CLIENT.restore_trashed_file(NEW_FILE)
expect(restored_file.item_status).to eq("active")
puts "trash and permanently delete file"
BOX_CLIENT.delete_file(NEW_FILE)
result = BOX_CLIENT.delete_trashed_file(NEW_FILE)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes web links operations"\"
it 'invokes web links operations' do
puts "create web link"
web_link = BOX_CLIENT.create_web_link(TEST_WEB_URL, '0', name: "my new link", description: "link description...")
expect(web_link.url).to eq(TEST_WEB_URL)
puts "get web link"
web_link_new = BOX_CLIENT.get_web_link(web_link)
expect(web_link_new.id).to eq(web_link.id)
puts "update web link"
updated_web_link = BOX_CLIENT.update_web_link(web_link, name: 'new name', description: 'new description', url: TEST_WEB_URL2)
expect(updated_web_link.url).to eq(TEST_WEB_URL2)
puts "delete web link"
result = BOX_CLIENT.delete_web_link(web_link)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes user operations"\"
it "invokes user operations" do
puts "inspect current user"
user = BOX_CLIENT.current_user
expect(user.status).to eq('active')
user = BOX_CLIENT.me(fields: [:role])
expect(user.role).to_not be_nil
puts "inspect a user"
user = BOX_CLIENT.user(@test_user)
expect(user.id).to eq(@test_user.id)
puts "inspect all users"
all_users = BOX_CLIENT.all_users()
test_user = all_users.find{|u| u.id == @test_user.id}
expect(test_user).to_not be_nil
#create user is tested in the before method
puts "update user"
new_name = "Chuck Nevitt"
user = BOX_CLIENT.update_user(@test_user, name: new_name)
expect(user.name).to eq(new_name)
puts "add email alias for user"
email_alias = "[email protected]" #{('a'..'z').to_a.shuffle[0,10].join}.com"
new_alias = BOX_CLIENT.add_email_alias_for_user(@test_user, email_alias)
expect(new_alias.type).to eq('email_alias')
puts "get email aliases for user"
email_aliases = BOX_CLIENT.email_aliases_for_user(@test_user)
expect(email_aliases.first.id).to eq(new_alias.id)
puts "remove email alias for user"
result = BOX_CLIENT.remove_email_alias_for_user(@test_user, new_alias.id)
expect(result).to eq({})
puts "delete user"
result = BOX_CLIENT.delete_user(@test_user, force: true)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes group operations"\"
it "invokes group operations" do
puts "create group"
group = BOX_CLIENT.create_group(TEST_GROUP_NAME)
expect(group.name).to eq(TEST_GROUP_NAME)
puts "inspect groups"
groups = BOX_CLIENT.groups
test_group = groups.find{|g| g.name == TEST_GROUP_NAME}
expect(test_group).to_not be_nil
puts "update group"
new_name = "Test Boxr Group Renamed"
group = BOX_CLIENT.update_group(test_group, new_name)
expect(group.name).to eq(new_name)
group = BOX_CLIENT.rename_group(test_group,TEST_GROUP_NAME)
expect(group.name).to eq(TEST_GROUP_NAME)
puts "add user to group"
group_membership = BOX_CLIENT.add_user_to_group(@test_user, test_group)
expect(group_membership.user.id).to eq(@test_user.id)
expect(group_membership.group.id).to eq(test_group.id)
membership = group_membership
puts "inspect group membership"
group_membership = BOX_CLIENT.group_membership(membership)
expect(group_membership.id).to eq(membership.id)
puts "inspect group memberships"
group_memberships = BOX_CLIENT.group_memberships(test_group)
expect(group_memberships.count).to eq(1)
expect(group_memberships.first.id).to eq(membership.id)
puts "inspect group memberships for a user"
group_memberships = BOX_CLIENT.group_memberships_for_user(@test_user)
expect(group_memberships.count).to eq(1)
expect(group_memberships.first.id).to eq(membership.id)
puts "inspect group memberships for me"
#this is whatever user your developer token is tied to
group_memberships = BOX_CLIENT.group_memberships_for_me
expect(group_memberships).to be_a(Array)
puts "update group membership"
group_membership = BOX_CLIENT.update_group_membership(membership, :admin)
expect(group_membership.role).to eq("admin")
puts "delete group membership"
result = BOX_CLIENT.delete_group_membership(membership)
expect(result).to eq({})
group_memberships = BOX_CLIENT.group_memberships_for_user(@test_user)
expect(group_memberships.count).to eq(0)
puts "inspect group collaborations"
group_collaboration = BOX_CLIENT.add_collaboration(@test_folder, {id: test_group.id, type: :group}, :editor)
expect(group_collaboration.accessible_by.id).to eq(test_group.id)
puts "delete group"
response = BOX_CLIENT.delete_group(test_group)
expect(response).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes comment operations"\"
it "invokes comment operations" do
new_file = BOX_CLIENT.upload_file("./spec/test_files/#{TEST_FILE_NAME}", @test_folder)
test_file = new_file
puts "add comment to file"
comment = BOX_CLIENT.add_comment_to_file(test_file, message: COMMENT_MESSAGE)
expect(comment.message).to eq(COMMENT_MESSAGE)
COMMENT = comment
puts "reply to comment"
reply = BOX_CLIENT.reply_to_comment(COMMENT, message: REPLY_MESSAGE)
expect(reply.message).to eq(REPLY_MESSAGE)
puts "get file comments"
comments = BOX_CLIENT.file_comments(test_file)
expect(comments.count).to eq(2)
puts "update a comment"
comment = BOX_CLIENT.change_comment(COMMENT, CHANGED_COMMENT_MESSAGE)
expect(comment.message).to eq(CHANGED_COMMENT_MESSAGE)
puts "get comment info"
comment = BOX_CLIENT.comment(COMMENT)
expect(comment.id).to eq(COMMENT.id)
puts "delete comment"
result = BOX_CLIENT.delete_comment(COMMENT)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes collaborations operations"\"
it "invokes collaborations operations" do
puts "add collaboration"
collaboration = BOX_CLIENT.add_collaboration(@test_folder, {id: @test_user.id, type: :user}, :viewer_uploader)
expect(collaboration.accessible_by.id).to eq(@test_user.id)
COLLABORATION = collaboration
puts "inspect collaboration"
collaboration = BOX_CLIENT.collaboration(COLLABORATION)
expect(collaboration.id).to eq(COLLABORATION.id)
puts "edit collaboration"
collaboration = BOX_CLIENT.edit_collaboration(COLLABORATION, role: "viewer uploader")
expect(collaboration.role).to eq("viewer uploader")
puts "inspect folder collaborations"
collaborations = BOX_CLIENT.folder_collaborations(@test_folder)
expect(collaborations.count).to eq(1)
expect(collaborations[0].id).to eq(COLLABORATION.id)
puts "remove collaboration"
result = BOX_CLIENT.remove_collaboration(COLLABORATION)
expect(result).to eq({})
collaborations = BOX_CLIENT.folder_collaborations(@test_folder)
expect(collaborations.count).to eq(0)
puts "inspect pending collaborations"
pending_collaborations = BOX_CLIENT.pending_collaborations
expect(pending_collaborations).to eq([])
puts "add invalid collaboration"
expect { BOX_CLIENT.add_collaboration(@test_folder, {id: @test_user.id, type: :user}, :invalid_role)}.to raise_error
end
#rake spec SPEC_OPTS="-e \"invokes task operations"\"
it "invokes task operations" do
test_file = BOX_CLIENT.upload_file("./spec/test_files/#{TEST_FILE_NAME}", @test_folder)
collaboration = BOX_CLIENT.add_collaboration(@test_folder, {id: @test_user.id, type: :user}, :editor)
puts "create task"
new_task = BOX_CLIENT.create_task(test_file, message: TEST_TASK_MESSAGE)
expect(new_task.message).to eq(TEST_TASK_MESSAGE)
TEST_TASK = new_task
puts "inspect file tasks"
tasks = BOX_CLIENT.file_tasks(test_file)
expect(tasks.first.id).to eq(TEST_TASK.id)
puts "inspect task"
task = BOX_CLIENT.task(TEST_TASK)
expect(task.id).to eq(TEST_TASK.id)
puts "update task"
NEW_TASK_MESSAGE = "new task message"
updated_task = BOX_CLIENT.update_task(TEST_TASK, message: NEW_TASK_MESSAGE)
expect(updated_task.message).to eq(NEW_TASK_MESSAGE)
puts "create task assignment"
task_assignment = BOX_CLIENT.create_task_assignment(TEST_TASK, assign_to: @test_user.id)
expect(task_assignment.assigned_to.id).to eq(@test_user.id)
TASK_ASSIGNMENT = task_assignment
puts "inspect task assignment"
task_assignment = BOX_CLIENT.task_assignment(TASK_ASSIGNMENT)
expect(task_assignment.id).to eq(TASK_ASSIGNMENT.id)
puts "inspect task assignments"
task_assignments = BOX_CLIENT.task_assignments(TEST_TASK)
expect(task_assignments.count).to eq(1)
expect(task_assignments[0].id).to eq(TASK_ASSIGNMENT.id)
#TODO: can't do this test yet because the test user needs to confirm their email address before you can do this
puts "update task assignment"
expect {
box_client_as_test_user = Boxr::Client.new(ENV['BOX_DEVELOPER_TOKEN'], as_user_id: @test_user.id)
new_message = "Updated task message"
task_assignment = box_client_as_test_user.update_task_assignment(TEST_TASK, resolution_state: :completed)
expect(task_assignment.resolution_state).to eq('completed')
}.to raise_error
puts "delete task assignment"
result = BOX_CLIENT.delete_task_assignment(TASK_ASSIGNMENT)
expect(result).to eq({})
puts "delete task"
result = BOX_CLIENT.delete_task(TEST_TASK)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes file metadata operations"\"
it "invokes file metadata operations" do
test_file = BOX_CLIENT.upload_file("./spec/test_files/#{TEST_FILE_NAME}", @test_folder)
puts "create metadata"
meta = {"a" => "hello", "b" => "world"}
metadata = BOX_CLIENT.create_metadata(test_file, meta)
expect(metadata.a).to eq("hello")
puts "update metadata"
metadata = BOX_CLIENT.update_metadata(test_file, {op: :replace, path: "/b", value: "there"})
expect(metadata.b).to eq("there")
metadata = BOX_CLIENT.update_metadata(test_file, [{op: :replace, path: "/b", value: "friend"}])
expect(metadata.b).to eq("friend")
puts "get metadata"
metadata = BOX_CLIENT.metadata(test_file)
expect(metadata.a).to eq("hello")
puts "delete metadata"
result = BOX_CLIENT.delete_metadata(test_file)
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes folder metadata operations"\"
#NOTE: this test will fail unless you create a metadata template called 'test' with two attributes: 'a' of type text, and 'b' of type text
it "invokes folder metadata operations" do
new_folder = BOX_CLIENT.create_folder(SUB_FOLDER_NAME, @test_folder)
puts "create folder metadata"
meta = {"a" => "hello", "b" => "world"}
metadata = BOX_CLIENT.create_folder_metadata(new_folder, meta, "enterprise", "test")
expect(metadata.a).to eq("hello")
puts "update folder metadata"
metadata = BOX_CLIENT.update_folder_metadata(new_folder, {op: :replace, path: "/b", value: "there"}, "enterprise", "test")
expect(metadata.b).to eq("there")
metadata = BOX_CLIENT.update_folder_metadata(new_folder, [{op: :replace, path: "/b", value: "friend"}], "enterprise", "test")
expect(metadata.b).to eq("friend")
puts "get folder metadata"
metadata = BOX_CLIENT.folder_metadata(new_folder, "enterprise", "test")
expect(metadata.a).to eq("hello")
puts "delete folder metadata"
result = BOX_CLIENT.delete_folder_metadata(new_folder, "enterprise", "test")
expect(result).to eq({})
end
#rake spec SPEC_OPTS="-e \"invokes search operations"\"
it "invokes search operations" do
#the issue with this test is that Box can take between 5-10 minutes to index any content uploaded; this is just a smoke test
#so we are searching for something that should return zero results
puts "perform search"
results = BOX_CLIENT.search("sdlfjuwnsljsdfuqpoiqweouyvnnadsfkjhiuweruywerbjvhvkjlnasoifyukhenlwdflnsdvoiuawfydfjh")
expect(results).to eq([])
end
end
| 40.049002 | 141 | 0.733448 |
1d251b3a2678a611918e8820b01c9b75e29f74e4 | 264 | module BulkBundler
class Command
def initialize(command)
@command = command
end
def run
cmd = IO.popen("#{@command} 2>&1")
$stdout.write(cmd.getc) until cmd.eof?
cmd.close
raise 'error' unless $? == 0
end
end
end
| 17.6 | 44 | 0.583333 |
bbc8ee9ab43e7b7e68b94e09afbf6f4e78e4b48f | 244 | class CommentsController < ApplicationController
include SocialStream::Controllers::Objects
def show
parent = resource.post_activity.parent
redirect_to polymorphic_path(parent.direct_object,:anchor => dom_id(parent))
end
end
| 27.111111 | 80 | 0.782787 |
01513ae95737e7289504e14df233da526fe4cdb4 | 2,474 | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
| 46.679245 | 86 | 0.748989 |
01c575ce95d687c0b2d0fd377ac015b2dc5ed933 | 10,438 | # coding: utf-8
require 'test_helper'
class RemoteBarclaysEpdqExtraPlusTest < Test::Unit::TestCase
def setup
@gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus))
@amount = 100
@credit_card = credit_card('4000100011112224', :verification_value => '987')
@mastercard = credit_card('5399999999999999', :brand => "mastercard")
@declined_card = credit_card('1111111111111111')
@credit_card_d3d = credit_card('4000000000000002', :verification_value => '111')
@options = {
:order_id => generate_unique_id[0...30],
:billing_address => address,
:description => 'Store Purchase',
:currency => fixtures(:barclays_epdq_extra_plus)[:currency] || 'GBP'
}
end
def test_successful_purchase
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
assert_equal @options[:currency], response.params["currency"]
assert_equal @options[:order_id], response.order_id
end
def test_successful_purchase_with_minimal_info
@options.delete(:billing_address)
@options.delete(:description)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
assert_equal @options[:currency], response.params["currency"]
assert_equal @options[:order_id], response.order_id
end
def test_successful_purchase_with_utf8_encoding_1
assert response = @gateway.purchase(@amount, credit_card('4000100011112224', :first_name => "Rémy", :last_name => "Fröåïør"), @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
def test_successful_purchase_with_utf8_encoding_2
assert response = @gateway.purchase(@amount, credit_card('4000100011112224', :first_name => "ワタシ", :last_name => "ёжзийклмнопрсуфхцч"), @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
# NOTE: You have to set the "Hash algorithm" to "SHA-1" in the "Technical information"->"Global security parameters"
# section of your account admin before running this test
def test_successful_purchase_with_signature_encryptor_to_sha1
gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus).merge(:signature_encryptor => 'sha1'))
assert response = gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
# NOTE: You have to set the "Hash algorithm" to "SHA-256" in the "Technical information"->"Global security parameters"
# section of your account admin before running this test
def test_successful_purchase_with_signature_encryptor_to_sha256
gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus).merge(:signature_encryptor => 'sha256'))
assert response = gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
# NOTE: You have to set the "Hash algorithm" to "SHA-512" in the "Technical information"->"Global security parameters"
# section of your account admin before running this test
def test_successful_purchase_with_signature_encryptor_to_sha512
gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus).merge(:signature_encryptor => 'sha512'))
assert response = gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
def test_successful_with_non_numeric_order_id
@options[:order_id] = "##{@options[:order_id][0...26]}.12"
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
def test_successful_purchase_without_explicit_order_id
@options.delete(:order_id)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
end
def test_unsuccessful_purchase
assert response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal 'No brand', response.message
end
def test_successful_authorize_with_mastercard
assert auth = @gateway.authorize(@amount, @mastercard, @options)
assert_success auth
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, auth.message
end
def test_authorize_and_capture
assert auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, auth.message
assert auth.authorization
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
end
def test_unsuccessful_capture
assert response = @gateway.capture(@amount, '')
assert_failure response
assert_equal 'No card no, no exp date, no brand', response.message
end
def test_successful_void
assert auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert auth.authorization
assert void = @gateway.void(auth.authorization)
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, auth.message
assert_success void
end
=begin Enable if/when fully enabled account is available to test
def test_reference_transactions
# Setting an alias
assert response = @gateway.purchase(@amount, credit_card('4000100011112224'), @options.merge(:billing_id => "awesomeman", :order_id=>Time.now.to_i.to_s+"1"))
assert_success response
# Updating an alias
assert response = @gateway.purchase(@amount, credit_card('4111111111111111'), @options.merge(:billing_id => "awesomeman", :order_id=>Time.now.to_i.to_s+"2"))
assert_success response
# Using an alias (i.e. don't provide the credit card)
assert response = @gateway.purchase(@amount, "awesomeman", @options.merge(:order_id => Time.now.to_i.to_s + "3"))
assert_success response
end
def test_successful_store
assert response = @gateway.store(@credit_card, :billing_id => 'test_alias')
assert_success response
assert purchase = @gateway.purchase(@amount, 'test_alias')
assert_success purchase
end
def test_successful_store_generated_alias
assert response = @gateway.store(@credit_card)
assert_success response
assert purchase = @gateway.purchase(@amount, response.billing_id)
assert_success purchase
end
def test_successful_store
assert response = @gateway.store(@credit_card, :billing_id => 'test_alias')
assert_success response
assert purchase = @gateway.purchase(@amount, 'test_alias')
assert_success purchase
end
def test_successful_unreferenced_credit
assert credit = @gateway.credit(@amount, @credit_card, @options)
assert_success credit
assert credit.authorization
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, credit.message
end
# NOTE: You have to allow USD as a supported currency in the "Account"->"Currencies"
# section of your account admin before running this test
def test_successful_purchase_with_custom_currency_at_the_gateway_level
gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus).merge(:currency => 'USD'))
assert response = gateway.purchase(@amount, @credit_card)
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
assert_equal "USD", response.params["currency"]
end
# NOTE: You have to allow USD as a supported currency in the "Account"->"Currencies"
# section of your account admin before running this test
def test_successful_purchase_with_custom_currency
gateway = BarclaysEpdqExtraPlusGateway.new(fixtures(:barclays_epdq_extra_plus).merge(:currency => 'EUR'))
assert response = gateway.purchase(@amount, @credit_card, @options.merge(:currency => 'USD'))
assert_success response
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
assert_equal "USD", response.params["currency"]
end
# NOTE: You have to contact Barclays to make sure your test account allow 3D Secure transactions before running this test
def test_successful_purchase_with_3d_secure
assert response = @gateway.purchase(@amount, @credit_card_d3d, @options.merge(:d3d => true))
assert_success response
assert_equal '46', response.params["STATUS"]
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, response.message
assert response.params["HTML_ANSWER"]
end
=end
def test_successful_refund
assert purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount, purchase.authorization, @options)
assert_success refund
assert refund.authorization
assert_equal BarclaysEpdqExtraPlusGateway::SUCCESS_MESSAGE, refund.message
end
def test_unsuccessful_refund
assert purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount+1, purchase.authorization, @options) # too much refund requested
assert_failure refund
assert refund.authorization
assert_equal 'Overflow in refunds requests', refund.message
end
def test_invalid_login
gateway = BarclaysEpdqExtraPlusGateway.new(
:login => '',
:user => '',
:password => '',
:signature_encryptor => "none"
)
assert response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_equal 'Some of the data entered is incorrect. please retry.', response.message
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@credit_card.verification_value, transcript)
end
end
| 43.857143 | 161 | 0.758574 |
283d7316439c2671e3c7c6d2b3b05ab5ffccf0b0 | 579 | cask 'syncthing' do
version '0.12.16'
sha256 '62f7492ebd7a155f6e66e1ba22c68b829463cb53774f4f91a6d8390263f04d7e'
url "https://github.com/syncthing/syncthing/releases/download/v#{version}/syncthing-macosx-amd64-v#{version}.tar.gz"
appcast 'https://github.com/syncthing/syncthing/releases.atom',
checkpoint: 'e9a49a762ef12e8d4dd4cdec4ec70c0e610fb27bb0eac851d0f4364cc96c294f'
name 'Syncthing'
homepage 'https://syncthing.net/'
license :mpl
binary "syncthing-macosx-amd64-v#{version}/syncthing"
zap delete: '~/Library/Application Support/Syncthing'
end
| 36.1875 | 118 | 0.778929 |
281ee6f39a7a54d3eea02355171b304e1af4493c | 145 | class Views::HelpersSystemSpec::ControllerHelperMethod < Fortitude::Widgets::Html5
def content
text "it is #{decorate('Fred')}!"
end
end
| 24.166667 | 82 | 0.731034 |
26153d4319f69150ae2b40a6451005b01e1502bb | 2,619 | class Cairo < Formula
desc "Vector graphics library with cross-device output support"
homepage "https://cairographics.org/"
url "https://cairographics.org/releases/cairo-1.16.0.tar.xz"
sha256 "5e7b29b3f113ef870d1e3ecf8adf21f923396401604bda16d44be45e66052331"
revision 3
bottle do
sha256 "6a23a68837269a8410a54950fdc8883feda091f221118370f1bfd3adbf5ee89c" => :catalina
sha256 "0984045234fb22fa3e54a337137e9e43a1bf997f5d77692ed02249dfdee2b1bf" => :mojave
sha256 "5c383ad4625fb1bd15e44e99fba1201490fa478b26178abaca5abb0fdb51510e" => :high_sierra
sha256 "2ff97b7c8abbb95791c1dc1e28b42e8f007adaf4f649cb46732c8140ad19dfd1" => :x86_64_linux
end
head do
url "https://anongit.freedesktop.org/git/cairo", :using => :git
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "fontconfig"
depends_on "freetype"
depends_on "glib"
depends_on "libpng"
depends_on "lzo"
depends_on "pixman"
unless OS.mac?
depends_on "zlib"
depends_on "linuxbrew/xorg/libxext"
depends_on "linuxbrew/xorg/libxrender"
end
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--enable-gobject=yes
--enable-svg=yes
--enable-tee=yes
--enable-quartz-image=#{OS.mac? ? "yes" : "no"}
--enable-xcb=#{OS.mac? ? "no" : "yes"}
--enable-xlib=#{OS.mac? ? "no" : "yes"}
--enable-xlib-xrender=#{OS.mac? ? "no" : "yes"}
--enable-valgrind=no
]
if build.head?
ENV["NOCONFIGURE"] = "1"
system "./autogen.sh"
end
system "./configure", *args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <cairo.h>
int main(int argc, char *argv[]) {
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 600, 400);
cairo_t *context = cairo_create(surface);
return 0;
}
EOS
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gettext = Formula["gettext"]
glib = Formula["glib"]
libpng = Formula["libpng"]
pixman = Formula["pixman"]
flags = %W[
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/cairo
-I#{libpng.opt_include}/libpng16
-I#{pixman.opt_include}/pixman-1
-L#{lib}
-lcairo
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 28.467391 | 94 | 0.653303 |
91743c6fd319fae471b2367a2bf8f066d4a1e887 | 540 | require 'uglifier'
activate :automatic_image_sizes
activate :directory_indexes
activate :livereload
activate :syntax
set :page_title, 'GIFPoint'
ready do
sprockets.append_path File.join root, 'bower_components'
end
set :css_dir, 'assets/stylesheets'
set :js_dir, 'assets/javascripts'
set :images_dir, 'assets/images'
set :fonts_dir, 'assets/fonts'
# Build-specific configuration
configure :build do
activate :minify_css
activate :minify_javascript, :compressor => ::Uglifier.new(:mangle => false)
activate :relative_assets
end
| 21.6 | 78 | 0.785185 |
5d930ddc7f11a58dff3e01ea648f68df4c3baff8 | 1,200 | class MacRobber < Formula
desc "Digital investigation tool"
homepage "https://www.sleuthkit.org/mac-robber/"
url "https://downloads.sourceforge.net/project/mac-robber/mac-robber/1.02/mac-robber-1.02.tar.gz"
sha256 "5895d332ec8d87e15f21441c61545b7f68830a2ee2c967d381773bd08504806d"
bottle do
cellar :any_skip_relocation
sha256 "cb1d422835804b5ea784a2b9157ae77a0940902771397b235d4ad784b88f961a" => :catalina
sha256 "e1fc7f112efeac70ca2583db78ad6436d5f6615a9959889f3e4c695aa72a27e8" => :mojave
sha256 "20c99447899b82d2da937aa81a0b3afd2c865f67a97d2ca1183e01151fef9de0" => :high_sierra
sha256 "160983c4988cb22bd68a0beeb48de91a8af3461722a42e65e523c4a6af08f444" => :sierra
sha256 "0647670a38eb3ae5d8085ad1126f8d70b6e9ac99b086c0ec2f3301ac51ecdb3f" => :el_capitan
sha256 "5e8b7656cafbab151ed82702cbd7e712ee30af62b6a6c031f9f440e95c174ed0" => :yosemite
sha256 "87b8de3e43626713461398aac48d12a4b494c36b8da6cd4e6587d352fcb251fe" => :mavericks
sha256 "5713286c509ff4ec129c2ab60ddd41fda7e9782ad2c36b92539853a12254cf1f" => :x86_64_linux # glibc 2.19
end
def install
system "make", "CC=#{ENV.cc}", "GCC_OPT=#{ENV.cflags}"
bin.install "mac-robber"
end
end
| 50 | 107 | 0.811667 |
087f5d3ad2586025488c241601f7c875771e92ef | 612 | # @param {Integer} num
# @return {Integer}
# def add_digits(num)
# while num >= 10
# temp = 0
# while num > 0
# temp += num % 10
# num /= 10
# end
# num = temp
# end
# return num
# end
# def add_digits(num)
# num if num.to_s.length <= 1
# while num >= 10
# num = num.to_s.split("").map {|i| i.to_i}.inject {|sum, n| sum.to_i += n.to_i}
# end
# num
# end
# If an integer is like 100a+10b+c, then (100a+10b+c)%9=(a+99a+b+9b+c)%9=(a+b+c)%9
def add_digits(num)
return 0 if num == 0
return num % 9 if num % 9 != 0
end
p add_digits(38)
p add_digits(199)
| 17 | 84 | 0.545752 |
d559d1f90fe0b3be8f43d457fd234d1174c697b8 | 2,038 | class Reports::ContributionReportsForProjectOwnersController < Reports::BaseController
before_filter :check_if_project_belongs_to_user
def end_of_association_chain
conditions = { project_id: params[:project_id] }
conditions.merge!(reward_id: params[:reward_id]) if params[:reward_id].present?
super.
select(%Q{
user_name as "#{I18n.t('contribution_report_to_project_owner.user_name')}",
contribution_value as "#{I18n.t('contribution_report_to_project_owner.value')}",
reward_minimum_value as "#{I18n.t('contribution_report_to_project_owner.minimum_value')}",
reward_description as "#{I18n.t('contribution_report_to_project_owner.reward_description')}",
created_at as "#{I18n.t('contribution_report_to_project_owner.created_at')}",
confirmed_at as "#{I18n.t('contribution_report_to_project_owner.confirmed_at')}",
service_fee as "#{I18n.t('contribution_report_to_project_owner.service_fee')}",
user_email as "#{I18n.t('contribution_report_to_project_owner.user_email')}",
payment_method as "#{I18n.t('contribution_report_to_project_owner.payment_method')}",
street as "#{I18n.t('contribution_report_to_project_owner.address_street')}",
neighborhood as "#{I18n.t('contribution_report_to_project_owner.address_neighborhood')}",
city as "#{I18n.t('contribution_report_to_project_owner.address_city')}",
state as "#{I18n.t('contribution_report_to_project_owner.address_state')}",
zip_code as "#{I18n.t('contribution_report_to_project_owner.address_zip_code')}",
CASE WHEN anonymous='t' THEN '#{I18n.t('yes')}'
WHEN anonymous='f' THEN '#{I18n.t('no')}'
END as "#{I18n.t('contribution_report_to_project_owner.anonymous')}",
short_note as "#{I18n.t('contribution_report_to_project_owner.short_note')}"
}).
where(conditions)
end
def check_if_project_belongs_to_user
redirect_to root_path unless can? :update, Project.find(params[:project_id])
end
end
| 55.081081 | 101 | 0.7316 |
5d683541d2cd9b15ec6aaf71fcc9a2af32f9ac43 | 2,124 | # frozen_string_literal: true
#
# Copyright:: Copyright 2019, Chef Software Inc.
# Author:: Tim Smith (<[email protected]>)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module RuboCop
module Cop
module Chef
module ChefModernize
# When using properties in a custom resource you should use name_property not the legacy name_attribute from the days of attributes
#
# @example
#
# # bad
# property :bob, String, name_attribute: true
#
# # good
# property :bob, String, name_property: true
#
class PropertyWithNameAttribute < Cop
MSG = 'Resource property sets name_attribute instead of name_property'
# match on a property that has any name and any type and a hash that
# contains name_attribute true. The hash pairs are wrapped in
# <> which means the order doesn't matter in the hash.
def_node_matcher :property_with_name_attribute?, <<-PATTERN
(send nil? :property (sym _) ... (hash <$(pair (sym :name_attribute) (true)) ...>))
PATTERN
def on_send(node)
property_with_name_attribute?(node) do
add_offense(node, location: :expression, message: MSG, severity: :refactor)
end
end
def autocorrect(node)
lambda do |corrector|
property_with_name_attribute?(node) do |name_attribute|
corrector.replace(name_attribute.loc.expression, 'name_property: true')
end
end
end
end
end
end
end
end
| 35.4 | 139 | 0.643597 |
1816939bc1f5e97659b94c895ec7b25fbc4b962f | 219 | class CreateProgramas < ActiveRecord::Migration[7.0]
def change
create_table :programas do |t|
t.string :nombre
t.references :area, null: false, foreign_key: true
t.timestamps
end
end
end
| 19.909091 | 56 | 0.675799 |
392796ed99089c8ff0df248faae4185fc38273eb | 2,045 | =begin
#Datadog API V1 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V1
class UsageAttributionSort
API_PERCENTAGE = "api_percentage".freeze
SNMP_USAGE = "snmp_usage".freeze
LAMBDA_PERCENTAGE = "lambda_percentage".freeze
APM_HOST_USAGE = "apm_host_usage".freeze
API_USAGE = "api_usage".freeze
CONTAINER_USAGE = "container_usage".freeze
CUSTOM_TIMESERIES_PERCENTAGE = "custom_timeseries_percentage".freeze
CONTAINER_PERCENTAGE = "container_percentage".freeze
LAMBDA_USAGE = "lambda_usage".freeze
APM_HOST_PERCENTAGE = "apm_host_percentage".freeze
NPM_HOST_PERCENTAGE = "npm_host_percentage".freeze
BROWSER_PERCENTAGE = "browser_percentage".freeze
BROWSER_USAGE = "browser_usage".freeze
INFRA_HOST_PERCENTAGE = "infra_host_percentage".freeze
SNMP_PERCENTAGE = "snmp_percentage".freeze
NPM_HOST_USAGE = "npm_host_usage".freeze
INFRA_HOST_USAGE = "infra_host_usage".freeze
CUSTOM_TIMESERIES_USAGE = "custom_timeseries_usage".freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def self.build_from_hash(value)
new.build_from_hash(value)
end
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = UsageAttributionSort.constants.select { |c| UsageAttributionSort::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #UsageAttributionSort" if constantValues.empty?
value
end
end
end
| 35.877193 | 112 | 0.756968 |
e8090e387fa5fef3fd65b8b71e57c275b752e0b6 | 655 | require 'spec_helper'
describe DataMapper::Address do
describe ".config" do
before(:each) do
# Force to default state
DataMapper::Address.instance_variable_set(:@config, nil)
end
after(:all) do
# Force to default state for other specs
DataMapper::Address.instance_variable_set(:@config, nil)
end
it 'should initialize with DEFAULTS' do
DataMapper::Address.config.should == DataMapper::Address::DEFAULTS
end
it 'should be writable' do
DataMapper::Address.config[:example] = 1
DataMapper::Address.instance_variable_get(:@config)[:example].should == 1
end
end
end
| 26.2 | 79 | 0.673282 |
f817ed2a5a304a5d5ffc41804d23d6c167beb7c8 | 15,083 | require 'abstract_unit'
require 'active_model'
class Bunny < Struct.new(:Bunny, :id)
extend ActiveModel::Naming
include ActiveModel::Conversion
def to_key() id ? [id] : nil end
end
class Author
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_reader :id
def to_key() id ? [id] : nil end
def save; @id = 1 end
def new_record?; @id.nil? end
def name
@id.nil? ? 'new author' : "author ##{@id}"
end
end
class Article
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_reader :id
attr_reader :author_id
def to_key() id ? [id] : nil end
def save; @id = 1; @author_id = 1 end
def new_record?; @id.nil? end
def name
@id.nil? ? 'new article' : "article ##{@id}"
end
end
class Author::Nested < Author; end
class PrototypeHelperBaseTest < ActionView::TestCase
attr_accessor :formats, :output_buffer
def update_details(details)
@details = details
yield if block_given?
end
def setup
super
@template = self
end
def url_for(options)
if options.is_a?(String)
options
else
url = "http://www.example.com/"
url << options[:action].to_s if options and options[:action]
url << "?a=#{options[:a]}" if options && options[:a]
url << "&b=#{options[:b]}" if options && options[:a] && options[:b]
url
end
end
protected
def request_forgery_protection_token
nil
end
def protect_against_forgery?
false
end
def create_generator
block = Proc.new { |*args| yield(*args) if block_given? }
JavaScriptGenerator.new self, &block
end
end
class PrototypeHelperTest < PrototypeHelperBaseTest
def _evaluate_assigns_and_ivars() end
def setup
@record = @author = Author.new
@article = Article.new
super
end
def test_update_page
old_output_buffer = output_buffer
block = Proc.new { |page| page.replace_html('foo', 'bar') }
assert_equal create_generator(&block).to_s, update_page(&block)
assert_equal old_output_buffer, output_buffer
end
def test_update_page_tag
block = Proc.new { |page| page.replace_html('foo', 'bar') }
assert_equal javascript_tag(create_generator(&block).to_s), update_page_tag(&block)
end
def test_update_page_tag_with_html_options
block = Proc.new { |page| page.replace_html('foo', 'bar') }
assert_equal javascript_tag(create_generator(&block).to_s, {:defer => 'true'}), update_page_tag({:defer => 'true'}, &block)
end
def test_remote_function
res = remote_function(:url => authors_path, :with => "'author[name]='+$F('author_name')+'&author[dob]='+$F('author_dob')")
assert_equal "new Ajax.Request('/authors', {asynchronous:true, evalScripts:true, parameters:'author[name]='+$F('author_name')+'&author[dob]='+$F('author_dob')})", res
assert res.html_safe?
end
protected
def author_path(record)
"/authors/#{record.id}"
end
def authors_path
"/authors"
end
def author_articles_path(author)
"/authors/#{author.id}/articles"
end
def author_article_path(author, article)
"/authors/#{author.id}/articles/#{article.id}"
end
end
class JavaScriptGeneratorTest < PrototypeHelperBaseTest
def setup
super
@generator = create_generator
ActiveSupport.escape_html_entities_in_json = true
end
def teardown
ActiveSupport.escape_html_entities_in_json = false
end
def _evaluate_assigns_and_ivars() end
def test_insert_html_with_string
assert_equal 'Element.insert("element", { top: "\\u003cp\\u003eThis is a test\\u003c/p\\u003e" });',
@generator.insert_html(:top, 'element', '<p>This is a test</p>')
assert_equal 'Element.insert("element", { bottom: "\\u003cp\u003eThis is a test\\u003c/p\u003e" });',
@generator.insert_html(:bottom, 'element', '<p>This is a test</p>')
assert_equal 'Element.insert("element", { before: "\\u003cp\u003eThis is a test\\u003c/p\u003e" });',
@generator.insert_html(:before, 'element', '<p>This is a test</p>')
assert_equal 'Element.insert("element", { after: "\\u003cp\u003eThis is a test\\u003c/p\u003e" });',
@generator.insert_html(:after, 'element', '<p>This is a test</p>')
end
def test_replace_html_with_string
assert_equal 'Element.update("element", "\\u003cp\\u003eThis is a test\\u003c/p\\u003e");',
@generator.replace_html('element', '<p>This is a test</p>')
end
def test_replace_element_with_string
assert_equal 'Element.replace("element", "\\u003cdiv id=\"element\"\\u003e\\u003cp\\u003eThis is a test\\u003c/p\\u003e\\u003c/div\\u003e");',
@generator.replace('element', '<div id="element"><p>This is a test</p></div>')
end
def test_remove
assert_equal 'Element.remove("foo");',
@generator.remove('foo')
assert_equal '["foo","bar","baz"].each(Element.remove);',
@generator.remove('foo', 'bar', 'baz')
end
def test_show
assert_equal 'Element.show("foo");',
@generator.show('foo')
assert_equal '["foo","bar","baz"].each(Element.show);',
@generator.show('foo', 'bar', 'baz')
end
def test_hide
assert_equal 'Element.hide("foo");',
@generator.hide('foo')
assert_equal '["foo","bar","baz"].each(Element.hide);',
@generator.hide('foo', 'bar', 'baz')
end
def test_toggle
assert_equal 'Element.toggle("foo");',
@generator.toggle('foo')
assert_equal '["foo","bar","baz"].each(Element.toggle);',
@generator.toggle('foo', 'bar', 'baz')
end
def test_alert
assert_equal 'alert("hello");', @generator.alert('hello')
end
def test_redirect_to
assert_equal 'window.location.href = "http://www.example.com/welcome";',
@generator.redirect_to(:action => 'welcome')
assert_equal 'window.location.href = "http://www.example.com/welcome?a=b&c=d";',
@generator.redirect_to("http://www.example.com/welcome?a=b&c=d")
end
def test_reload
assert_equal 'window.location.reload();',
@generator.reload
end
def test_delay
@generator.delay(20) do
@generator.hide('foo')
end
assert_equal "setTimeout(function() {\n;\nElement.hide(\"foo\");\n}, 20000);", @generator.to_s
end
def test_to_s
@generator.insert_html(:top, 'element', '<p>This is a test</p>')
@generator.insert_html(:bottom, 'element', '<p>This is a test</p>')
@generator.remove('foo', 'bar')
@generator.replace_html('baz', '<p>This is a test</p>')
assert_equal <<-EOS.chomp, @generator.to_s
Element.insert("element", { top: "\\u003cp\\u003eThis is a test\\u003c/p\\u003e" });
Element.insert("element", { bottom: "\\u003cp\\u003eThis is a test\\u003c/p\\u003e" });
["foo","bar"].each(Element.remove);
Element.update("baz", "\\u003cp\\u003eThis is a test\\u003c/p\\u003e");
EOS
end
def test_element_access
assert_equal %($("hello");), @generator['hello']
end
def test_element_access_on_records
assert_equal %($("bunny_5");), @generator[Bunny.new(:id => 5)]
assert_equal %($("new_bunny");), @generator[Bunny.new]
end
def test_element_proxy_one_deep
@generator['hello'].hide
assert_equal %($("hello").hide();), @generator.to_s
end
def test_element_proxy_variable_access
@generator['hello']['style']
assert_equal %($("hello").style;), @generator.to_s
end
def test_element_proxy_variable_access_with_assignment
@generator['hello']['style']['color'] = 'red'
assert_equal %($("hello").style.color = "red";), @generator.to_s
end
def test_element_proxy_assignment
@generator['hello'].width = 400
assert_equal %($("hello").width = 400;), @generator.to_s
end
def test_element_proxy_two_deep
@generator['hello'].hide("first").clean_whitespace
assert_equal %($("hello").hide("first").cleanWhitespace();), @generator.to_s
end
def test_select_access
assert_equal %($$("div.hello");), @generator.select('div.hello')
end
def test_select_proxy_one_deep
@generator.select('p.welcome b').first.hide
assert_equal %($$("p.welcome b").first().hide();), @generator.to_s
end
def test_visual_effect
assert_equal %(new Effect.Puff("blah",{});),
@generator.visual_effect(:puff,'blah')
end
def test_visual_effect_toggle
assert_equal %(Effect.toggle("blah",'appear',{});),
@generator.visual_effect(:toggle_appear,'blah')
end
def test_sortable
assert_equal %(Sortable.create("blah", {onUpdate:function(){new Ajax.Request('http://www.example.com/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("blah")})}});),
@generator.sortable('blah', :url => { :action => "order" })
assert_equal %(Sortable.create("blah", {onUpdate:function(){new Ajax.Request('http://www.example.com/order', {asynchronous:false, evalScripts:true, parameters:Sortable.serialize("blah")})}});),
@generator.sortable('blah', :url => { :action => "order" }, :type => :synchronous)
end
def test_draggable
assert_equal %(new Draggable("blah", {});),
@generator.draggable('blah')
end
def test_drop_receiving
assert_equal %(Droppables.add("blah", {onDrop:function(element){new Ajax.Request('http://www.example.com/order', {asynchronous:true, evalScripts:true, parameters:'id=' + encodeURIComponent(element.id)})}});),
@generator.drop_receiving('blah', :url => { :action => "order" })
assert_equal %(Droppables.add("blah", {onDrop:function(element){new Ajax.Request('http://www.example.com/order', {asynchronous:false, evalScripts:true, parameters:'id=' + encodeURIComponent(element.id)})}});),
@generator.drop_receiving('blah', :url => { :action => "order" }, :type => :synchronous)
end
def test_collection_first_and_last
@generator.select('p.welcome b').first.hide()
@generator.select('p.welcome b').last.show()
assert_equal <<-EOS.strip, @generator.to_s
$$("p.welcome b").first().hide();
$$("p.welcome b").last().show();
EOS
end
def test_collection_proxy_with_each
@generator.select('p.welcome b').each do |value|
value.remove_class_name 'selected'
end
@generator.select('p.welcome b').each do |value, index|
@generator.visual_effect :highlight, value
end
assert_equal <<-EOS.strip, @generator.to_s
$$("p.welcome b").each(function(value, index) {
value.removeClassName("selected");
});
$$("p.welcome b").each(function(value, index) {
new Effect.Highlight("value",{});
});
EOS
end
def test_collection_proxy_on_collect
@generator.select('p').collect('a') { |para| para.show }
@generator.select('p').collect { |para| para.hide }
assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").collect(function(value, index) {
return value.show();
});
$$("p").collect(function(value, index) {
return value.hide();
});
EOS
@generator = create_generator
end
def test_collection_proxy_with_grep
@generator.select('p').grep 'a', /^a/ do |value|
@generator << '(value.className == "welcome")'
end
@generator.select('p').grep 'b', /b$/ do |value, index|
@generator.call 'alert', value
@generator << '(value.className == "welcome")'
end
assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").grep(/^a/, function(value, index) {
return (value.className == "welcome");
});
var b = $$("p").grep(/b$/, function(value, index) {
alert(value);
return (value.className == "welcome");
});
EOS
end
def test_collection_proxy_with_inject
@generator.select('p').inject 'a', [] do |memo, value|
@generator << '(value.className == "welcome")'
end
@generator.select('p').inject 'b', nil do |memo, value, index|
@generator.call 'alert', memo
@generator << '(value.className == "welcome")'
end
foo = <<-EOS.strip
var a = $$("p").inject([], function(memo, value, index) {
return (value.className == "welcome");
});
var b = $$("p").inject(null, function(memo, value, index) {
alert(memo);
return (value.className == "welcome");
});
EOS
assert_equal foo, @generator.to_s
end
def test_collection_proxy_with_pluck
@generator.select('p').pluck('a', 'className')
assert_equal %(var a = $$("p").pluck("className");), @generator.to_s
end
def test_collection_proxy_with_zip
ActionView::Helpers::JavaScriptCollectionProxy.new(@generator, '[1, 2, 3]').zip('a', [4, 5, 6], [7, 8, 9])
ActionView::Helpers::JavaScriptCollectionProxy.new(@generator, '[1, 2, 3]').zip('b', [4, 5, 6], [7, 8, 9]) do |array|
@generator.call 'array.reverse'
end
assert_equal <<-EOS.strip, @generator.to_s
var a = [1, 2, 3].zip([4,5,6], [7,8,9]);
var b = [1, 2, 3].zip([4,5,6], [7,8,9], function(array) {
return array.reverse();
});
EOS
end
def test_collection_proxy_with_find_all
@generator.select('p').find_all 'a' do |value, index|
@generator << '(value.className == "welcome")'
end
assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").findAll(function(value, index) {
return (value.className == "welcome");
});
EOS
end
def test_collection_proxy_with_in_groups_of
@generator.select('p').in_groups_of('a', 3)
@generator.select('p').in_groups_of('a', 3, 'x')
assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").inGroupsOf(3);
var a = $$("p").inGroupsOf(3, "x");
EOS
end
def test_collection_proxy_with_each_slice
@generator.select('p').each_slice('a', 3)
@generator.select('p').each_slice('a', 3) do |group, index|
group.reverse
end
assert_equal <<-EOS.strip, @generator.to_s
var a = $$("p").eachSlice(3);
var a = $$("p").eachSlice(3, function(value, index) {
return value.reverse();
});
EOS
end
def test_debug_rjs
ActionView::Base.debug_rjs = true
@generator['welcome'].replace_html 'Welcome'
assert_equal "try {\n$(\"welcome\").update(\"Welcome\");\n} catch (e) { alert('RJS error:\\n\\n' + e.toString()); alert('$(\\\"welcome\\\").update(\\\"Welcome\\\");'); throw e }", @generator.to_s
ensure
ActionView::Base.debug_rjs = false
end
def test_literal
literal = @generator.literal("function() {}")
assert_equal "\"function() {}\"", ActiveSupport::JSON.encode(literal)
assert_equal "", @generator.to_s
end
def test_class_proxy
@generator.form.focus('my_field')
assert_equal "Form.focus(\"my_field\");", @generator.to_s
end
def test_call_with_block
@generator.call(:before)
@generator.call(:my_method) do |p|
p[:one].show
p[:two].hide
end
@generator.call(:in_between)
@generator.call(:my_method_with_arguments, true, "hello") do |p|
p[:three].visual_effect(:highlight)
end
assert_equal "before();\nmy_method(function() { $(\"one\").show();\n$(\"two\").hide(); });\nin_between();\nmy_method_with_arguments(true, \"hello\", function() { $(\"three\").visualEffect(\"highlight\"); });", @generator.to_s
end
def test_class_proxy_call_with_block
@generator.my_object.my_method do |p|
p[:one].show
p[:two].hide
end
assert_equal "MyObject.myMethod(function() { $(\"one\").show();\n$(\"two\").hide(); });", @generator.to_s
end
end
| 31.554393 | 229 | 0.655572 |
ed9104889cd132c207ac667ed9a9f129519dae51 | 242 | class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :user_name
t.string :password_digest
t.timestamps
end
end
end
| 18.615385 | 48 | 0.657025 |
1d826720502b52cc2a128f9d3617a16d45ba8719 | 1,142 | cask '[email protected]' do
version '2019.3.0b3,d0377b9426dc'
sha256 :no_check
url "http://beta.unity3d.com/download/d0377b9426dc/MacEditorTargetInstaller/UnitySetup-Windows-Mono-Support-for-Editor-2019.3.0b3.pkg"
name 'Windows Build Support (Mono)'
homepage 'https://unity3d.com/unity/'
pkg 'UnitySetup-Windows-Mono-Support-for-Editor-2019.3.0b3.pkg'
depends_on cask: '[email protected]'
preflight do
if File.exist? "/Applications/Unity"
FileUtils.move "/Applications/Unity", "/Applications/Unity.temp"
end
if File.exist? "/Applications/Unity-2019.3.0b3"
FileUtils.move "/Applications/Unity-2019.3.0b3", '/Applications/Unity'
end
end
postflight do
if File.exist? '/Applications/Unity'
FileUtils.move '/Applications/Unity', "/Applications/Unity-2019.3.0b3"
end
if File.exist? '/Applications/Unity.temp'
FileUtils.move '/Applications/Unity.temp', '/Applications/Unity'
end
end
uninstall quit: 'com.unity3d.UnityEditor5.x',
delete: '/Applications/Unity-2019.3.0b3/PlaybackEngines/WindowsStandaloneSupport'
end
| 31.722222 | 136 | 0.717163 |
b952c9fa3aefdf6e47e482dd62b4681b06a84dfe | 1,248 | module ActiveAdmin
module Axlsx
module ResourceControllerExtension
def self.included(base)
# base.send :alias_method_chain, :per_page, :xlsx
# base.send :alias_method_chain, :index, :xlsx
base.prepend(ResourceControllerExtension)
base.send :respond_to, :xlsx
end
# patching the index method to allow the xlsx format.
def index(&block)
super do |format|
format.xlsx do
xlsx = active_admin_config.xlsx_builder.serialize(collection)
send_data xlsx, :filename => "#{xlsx_filename}", :type => Mime::Type.lookup_by_extension(:xlsx)
end
end
end
# patching per_page to use the CSV record max for pagination when the format is xlsx
def per_page
max_csv_records = 2000
if request.format == Mime::Type.lookup_by_extension(:xlsx)
return max_csv_records
end
per_page_without_xlsx
end
# Returns a filename for the xlsx file using the collection_name
# and current date such as 'my-articles-2011-06-24.xlsx'.
def xlsx_filename
"#{resource_collection_name.to_s.gsub('_', '-')}-#{Time.now.strftime("%Y-%m-%d")}.xlsx"
end
end
end
end
| 32 | 107 | 0.639423 |
4a8fec8454b28c62703c6e29462cac0249aa73e2 | 3,463 | require 'spec_helper'
describe 'Stock Transfers', :type => :feature, :js => true do
stub_authorization!
let(:admin_user) { create(:admin_user) }
let(:description) { 'Test stock transfer' }
before do
allow_any_instance_of(Spree::Admin::BaseController).to receive(:spree_current_user).and_return(admin_user)
end
describe 'create stock transfer' do
it 'can create a stock transfer' do
source_location = create(:stock_location_with_items, :name => 'NY')
destination_location = create(:stock_location, :name => 'SF')
visit spree.new_admin_stock_transfer_path
select "SF", from: 'stock_transfer[source_location_id]'
fill_in 'stock_transfer_description', with: description
click_button 'Continue'
expect(page).to have_field('stock_transfer_description', with: description)
select "NY", from: 'stock_transfer[destination_location_id]'
within "form.edit_stock_transfer" do
page.find('button').trigger('click')
end
expect(page).to have_content('Stock Transfer has been successfully updated')
expect(page).to have_css(:div, '#finalize-stock-transfer-warning')
expect(page).to have_content("NY")
end
end
describe 'view a stock transfer' do
let(:stock_transfer) do
create(:stock_transfer_with_items,
source_location: source_location,
destination_location: nil,
description: "Test stock transfer")
end
let(:source_location) { create(:stock_location, name: 'SF') }
context "stock transfer does not have a destination" do
it 'displays the stock transfer details' do
visit spree.admin_stock_transfer_path(stock_transfer)
expect(page).to have_content("SF")
expect(page).to have_content("Test stock transfer")
end
end
end
describe 'ship stock transfer' do
let(:stock_transfer) { create(:stock_transfer_with_items) }
before do
stock_transfer.transfer_items do |item|
item.update_attributes(expected_quantity: 1)
end
end
describe "tracking info" do
it 'adds tracking number' do
visit spree.tracking_info_admin_stock_transfer_path(stock_transfer)
fill_in 'stock_transfer_tracking_number', :with => "12345"
click_button 'Save'
expect(page).to have_content('Stock Transfer has been successfully updated')
expect(stock_transfer.reload.tracking_number).to eq '12345'
end
end
describe 'with enough stock' do
it 'ships stock transfer' do
visit spree.tracking_info_admin_stock_transfer_path(stock_transfer)
click_link 'ship'
find('#confirm-ship-link', visible: false).click
expect(current_path).to eq spree.admin_stock_transfers_path
expect(stock_transfer.reload.shipped_at).to_not be_nil
end
end
describe 'without enough stock' do
before do
stock_transfer.transfer_items.each do |item|
stock_transfer.source_location.stock_item(item.variant).set_count_on_hand(0)
end
end
it 'does not ship stock transfer' do
visit spree.tracking_info_admin_stock_transfer_path(stock_transfer)
click_link 'ship'
find('#confirm-ship-link', visible: false).click
expect(current_path).to eq spree.tracking_info_admin_stock_transfer_path(stock_transfer)
expect(stock_transfer.reload.shipped_at).to be_nil
end
end
end
end
| 32.980952 | 110 | 0.697661 |
1a40fd61db21c9e6a382b3c17b497c7528670fda | 278 | require_relative './app'
require 'test/unit'
require 'rack/test'
set :environment, :test
class MyAppTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
Sinatra::Application
end
def test_get_request
get '/'
assert last_response.ok?
end
end
| 13.9 | 38 | 0.701439 |
f7bc9f081d1967ca1adb50ddc63da82a16d5affc | 863 | Pod::Spec.new do |s|
s.name = "AsyncOperation"
s.version = "1.1.0"
s.summary = "A hassle-free implementation of asynchronous NSOperations/NSBlockOperations."
s.description = <<-DESC
AsyncOperation aims to ease the pain commonly encountered when having to subclass NSOperation for async tasks.
DESC
s.homepage = "https://github.com/regexident/AsyncOperation"
s.license = { :type => 'BSD-3', :file => 'LICENSE' }
s.author = { "Vincent Esche" => "[email protected]" }
s.source = { :git => "https://github.com/regexident/AsyncOperation.git", :tag => '1.1.0' }
s.source_files = "AsyncOperation/Classes/*.{swift,h,m}"
# s.public_header_files = "AsyncOperation/*.h"
s.requires_arc = true
s.osx.deployment_target = "10.9"
s.ios.deployment_target = "8.0"
end
| 39.227273 | 129 | 0.630359 |
e24a4c8968da2af59ec8a18385dddfd6f8ff5dd5 | 175 | module Watchtower
module Views
class Poll < Mustache
include Watchtower::Helpers
def beams
format_beams(@results || [])
end
end
end
end | 14.583333 | 36 | 0.611429 |
f736361dfd1a634096379ce0c54d9b8381b628b2 | 1,671 | require 'spec_helper'
describe ArcFurnace::MultiCSVSource do
let(:filenames) do
[
"#{ArcFurnace.test_root}/resources/source1.csv",
"#{ArcFurnace.test_root}/resources/empty_source.csv",
"#{ArcFurnace.test_root}/resources/source2.csv"
]
end
let(:source) { ArcFurnace::MultiCSVSource.new(filenames: filenames) }
let(:rows) do
[
{ "id" => "111", "Field 1" => "boo bar", "Field 2" => "baz, bar" },
{ "id" => "222", "Field 1" => "baz", "Field 2" => "boo bar" },
{ "id" => "111", "Field 3" => "boo bar", "Field 4" => "baz, bar" },
{ "id" => "222", "Field 3" => "baz", "Field 4" => "boo bar" },
{ "id" => "333", "Field 3" => "black", "Field 4" => "brown" }
]
end
describe '#row' do
it 'feeds all rows' do
expect(source.row).to eq rows[0]
expect(source.row).to eq rows[1]
expect(source.row).to eq rows[2]
expect(source.row).to eq rows[3]
expect(source.row).to eq rows[4]
expect(source.row).to be_nil
end
end
describe '#value' do
it 'feeds all rows' do
expect(source.value).to eq rows[0]
source.advance
expect(source.value).to eq rows[1]
expect(source.value).to eq rows[1]
expect(source.row).to eq rows[1]
expect(source.row).to eq rows[2]
expect(source.value).to eq rows[3]
expect(source.value).to eq rows[3]
expect(source.advance).to eq rows[4]
expect(source.value).to eq rows[4]
expect(source.empty?).to eq false
expect(source.row).to eq rows[4]
expect(source.value).to eq nil
expect(source.empty?).to eq true
expect(source.row).to eq nil
end
end
end
| 30.944444 | 73 | 0.583483 |
010dd2d5e244893d5dfb6e31e99a274c3cf3a1ed | 910 | # frozen_string_literal: true
module HttpSignatures
class HeaderList
# Cannot sign the signature headers
ILLEGAL = %w[authorization signature].freeze
def self.from_string(string)
new(string.split(' '))
end
def initialize(names)
@names = names.map(&:downcase)
validate_names!
end
def to_a
@names.dup
end
def to_str
@names.join(' ')
end
private
def validate_names!
raise EmptyHeaderList if @names.empty?
raise IllegalHeader, illegal_headers_present if illegal_headers_present.any?
end
def illegal_headers_present
ILLEGAL & @names
end
class IllegalHeader < StandardError
def initialize(names)
names_string = names.map { |n| "'#{n}'" }.join(', ')
super("Header #{names_string} not permitted")
end
end
class EmptyHeaderList < StandardError; end
end
end
| 19.782609 | 82 | 0.646154 |
79365b7642e38f77d2d7cd488f89ba43774454f4 | 14,947 | require 'test_helper'
class HyperGraphTest < Test::Unit::TestCase
def setup
@mock_connection = mock('api-connection')
@mock_connection.stubs(:verify_mode=)
Net::HTTP.stubs(:new).returns(@mock_connection)
end
def test_get_object_info_while_unauthenticated
json_api_response = '{"id":"518018845","name":"Chris Dinn","first_name":"Chris","last_name":"Dinn","link":"http://www.facebook.com/chrisdinn"}'
expected_parsed_response = { :id => 518018845,
:name => "Chris Dinn",
:first_name => "Chris",
:last_name => "Dinn",
:link => "http://www.facebook.com/chrisdinn"}
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/518018845").returns(mock_response)
assert_equal expected_parsed_response, HyperGraph.get('518018845')
end
def test_get_object_info_when_authenticated
json_api_response = '{"id":"518018845","name":"Chris Dinn","first_name":"Chris","last_name":"Dinn","link":"http://www.facebook.com/chrisdinn","birthday":"05/28/1983","email":"[email protected]","timezone":-4,"verified":true,"updated_time":"2010-03-17T20:19:03+0000"}'
expected_parsed_response = { :id => 518018845,
:name => "Chris Dinn",
:first_name => "Chris",
:last_name => "Dinn",
:link => "http://www.facebook.com/chrisdinn",
:birthday => "05/28/1983",
:email => "[email protected]",
:timezone => -4,
:verified => true,
:updated_time => Time.parse("2010-03-17T20:19:03+0000")}
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/518018845?access_token=#{access_token}").returns(mock_response)
assert_equal expected_parsed_response, HyperGraph.get('518018845', :access_token => access_token)
end
def test_get_object_connection_when_authenticated
json_api_response = '{ "data":[{"name": "Andrew Louis", "id": "28103622"},{"name": "Joey Coleman","id": "72600429"},{"name": "Kathryn Kinley","id": "28125421"},{"name": "Vanessa Larkey", "id": "28112600"}] }'
expected_sorted_array = [{:name => "Andrew Louis", :id => 28103622},{:name => "Vanessa Larkey", :id => 28112600},{:name => "Kathryn Kinley", :id => 28125421}, {:name => "Joey Coleman", :id => 72600429}]
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/518018845/friends?access_token=#{access_token}").returns(mock_response)
friends = HyperGraph.get('518018845/friends', :access_token => access_token)
expected_sorted_array.each do |friend|
assert friends.include?(friend)
end
end
def test_object_pagination
json_api_response = '{ "data": [ { "id": "248026512444",
"from": { "name": "Jennifer Byrne", "id": "511872444" },
"tags": { "data": [ { "id": "518018845", "name": "Chris Dinn", "x": 83.8889, "y": 15.3846, "created_time": "2010-01-10T23:06:41+0000" } ] },
"name": "Finally a day off....xmas dinner, a few days late", "picture": "http://photos-b.ak.fbcdn.net/hphotos-ak-snc3/hs239.snc3/22675_248026512444_511872444_3217612_4249159_s.jpg", "source": "http://sphotos.ak.fbcdn.net/hphotos-ak-snc3/hs239.snc3/22675_248026512444_511872444_3217612_4249159_n.jpg",
"height": 483, "width": 604, "link": "http://www.facebook.com/photo.php?pid=3217612&id=511872444", "icon": "http://static.ak.fbcdn.net/rsrc.php/z2E5Y/hash/8as8iqdm.gif",
"created_time": "2010-01-10T23:00:10+0000", "updated_time": "2010-01-10T23:06:36+0000" },
{ "id": "248026522444",
"from": { "name": "Jennifer Byrne", "id": "511872444" },
"tags": { "data": [ { "id": "518018845", "name": "Chris Dinn","x": 92.2222, "y": 29.6296, "created_time": "2010-01-10T23:06:42+0000"}, { "id": "691356318", "name": "Steve Durant","x": 34.4444,"y": 19.2593,"created_time": "2010-01-10T23:06:42+0000" } ] },
"name": "Steve cooking dinner", "picture": "http://photos-e.ak.fbcdn.net/hphotos-ak-snc3/hs219.snc3/22675_248026522444_511872444_3217614_8129653_s.jpg","source": "http://sphotos.ak.fbcdn.net/hphotos-ak-snc3/hs219.snc3/22675_248026522444_511872444_3217614_8129653_n.jpg",
"height": 604, "width": 402, "link": "http://www.facebook.com/photo.php?pid=3217614&id=511872444", "icon": "http://static.ak.fbcdn.net/rsrc.php/z2E5Y/hash/8as8iqdm.gif",
"created_time": "2010-01-10T23:00:10+0000", "updated_time": "2010-01-10T23:06:36+0000" } ]}'
expected_sorted_array = [ {:id => 248026512444, :from => { :name => "Jennifer Byrne", :id => 511872444}, :tags => [ { :id => 518018845, :name => "Chris Dinn", :x => 83.8889, :y => 15.3846, :created_time => Time.parse("2010-01-10T23:06:41+0000") } ],
:name => "Finally a day off....xmas dinner, a few days late",
:picture => "http://photos-b.ak.fbcdn.net/hphotos-ak-snc3/hs239.snc3/22675_248026512444_511872444_3217612_4249159_s.jpg",
:source => "http://sphotos.ak.fbcdn.net/hphotos-ak-snc3/hs239.snc3/22675_248026512444_511872444_3217612_4249159_n.jpg",
:height => 483, :width => 604, :link => "http://www.facebook.com/photo.php?pid=3217612&id=511872444",
:icon => "http://static.ak.fbcdn.net/rsrc.php/z2E5Y/hash/8as8iqdm.gif",
:created_time => Time.parse("2010-01-10T23:00:10+0000"),
:updated_time => Time.parse("2010-01-10T23:06:36+0000") },
{:id => 248026522444, :from => { :name => "Jennifer Byrne", :id => 511872444}, :tags => [ { :id => 518018845, :name => "Chris Dinn", :x => 92.2222, :y => 29.6296, :created_time => Time.parse("2010-01-10T23:06:42+0000") }, { :id => 691356318, :name => "Steve Durant", :x => 34.4444, :y => 19.2593, :created_time => Time.parse("2010-01-10T23:06:42+0000") } ],
:name => "Steve cooking dinner",
:picture => "http://photos-e.ak.fbcdn.net/hphotos-ak-snc3/hs219.snc3/22675_248026522444_511872444_3217614_8129653_s.jpg",
:source => "http://sphotos.ak.fbcdn.net/hphotos-ak-snc3/hs219.snc3/22675_248026522444_511872444_3217614_8129653_n.jpg",
:height => 604, :width => 402, :link => "http://www.facebook.com/photo.php?pid=3217614&id=511872444",
:icon => "http://static.ak.fbcdn.net/rsrc.php/z2E5Y/hash/8as8iqdm.gif",
:created_time => Time.parse("2010-01-10T23:00:10+0000"), :updated_time => Time.parse("2010-01-10T23:06:36+0000")}]
access_token = "test-access-token"
limit = 2
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/me/photos?access_token=#{access_token}&limit=#{limit}").returns(mock_response)
assert_equal expected_sorted_array, HyperGraph.get('me/photos', :access_token => access_token, :limit => limit)
end
def test_instance_with_stored_access_token
json_api_response = '{"id":"518018845","name":"Chris Dinn","first_name":"Chris","last_name":"Dinn","link":"http://www.facebook.com/chrisdinn","birthday":"05/28/1983","email":"[email protected]","timezone":-4,"verified":true,"updated_time":"2010-03-17T20:19:03+0000"}'
expected_parsed_response = { :id => 518018845,
:name => "Chris Dinn",
:first_name => "Chris",
:last_name => "Dinn",
:link => "http://www.facebook.com/chrisdinn",
:birthday => "05/28/1983",
:email => "[email protected]",
:timezone => -4,
:verified => true,
:updated_time => Time.parse("2010-03-17T20:19:03+0000")}
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/me?access_token=#{access_token}").returns(mock_response)
graph = HyperGraph.new(access_token)
assert_equal expected_parsed_response, graph.get('me')
end
def test_post_request_returning_true
json_api_response = 'true'
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:post).with("/115934485101003/maybe", "access_token=#{access_token}").returns(mock_response)
graph = HyperGraph.new(access_token)
assert_equal true, graph.post('115934485101003/maybe')
end
def test_post_request_raising_error
json_api_response = '{"error":{"type":"Exception","message":"(#210) User not visible"}}'
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:post).with('/514569082_115714061789461/comments', "access_token=#{access_token}").returns(mock_response)
graph = HyperGraph.new(access_token)
assert_raise FacebookError do
graph.post('514569082_115714061789461/comments')
end
end
def test_get_request_raising_error
json_api_response = '{"error":{"type":"QueryParseException", "message":"An active access token must be used to query information about the current user."}}'
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:get).with('/me/home').returns(mock_response)
assert_raise FacebookError do
HyperGraph.get('me/home')
end
end
def test_delete_request
json_api_response = 'true'
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.stubs(:post).with("/514569082_115714061789461/likes", "access_token=#{access_token}&method=delete").returns(mock_response)
graph = HyperGraph.new(access_token)
assert_equal true, graph.delete('514569082_115714061789461/likes')
end
def test_graph_search
json_api_response = %'{"data": [
{"id": "113412341299949562_134212343177", "from": {"name": "Big Band Ballroom", "category": "Local_business", "id": "1334523899949562"}, "message": "Big band at our ballroom", "link": "http://www.facebook.com/", "type": "link" },
{"id": "100123706392497_142067305819279", "from": {"name": "Big Band Guy", "id": "100000706392497"},"message": "What a band", "type": "status" }
]}'
expected_parsed_response = [ { :id => '113412341299949562_134212343177',
:from => { :name => "Big Band Ballroom", :category=> "Local_business", :id => 1334523899949562 },
:message => "Big band at our ballroom",
:link => "http://www.facebook.com/",
:type => "link"},
{ :id => "100123706392497_142067305819279",
:from => { :name => "Big Band Guy", :id => 100000706392497 },
:message => "What a band",
:type => "status" }
]
access_token = "test-access-token"
mock_response = stub(:body => json_api_response)
@mock_connection.stubs(:use_ssl=).with(true)
@mock_connection.stubs(:get).with("/search?access_token=#{access_token}&q=big%20band").returns(mock_response)
assert_equal expected_parsed_response, HyperGraph.search('big band', :access_token => access_token)
graph = HyperGraph.new('test-access-token')
assert_equal expected_parsed_response, graph.search('big band', :access_token => access_token)
end
def test_authorize_url
client_id = "your-client-id"
callback_url = "http://yoursite.com/callback"
expected_authorize_url = "https://graph.facebook.com/oauth/authorize?client_id=#{client_id}&redirect_uri=#{callback_url}"
assert_equal expected_authorize_url, HyperGraph.authorize_url(client_id, callback_url)
end
def test_authorize_url_with_scope_and_display
client_id = "your-client-id"
callback_url = "http://yoursite.com/callback"
scope = "user_photos,user_videos,stream_publish"
display = 'popup'
expected_authorize_url = "https://graph.facebook.com/oauth/authorize?client_id=#{client_id}&display=#{display}&redirect_uri=#{callback_url}&scope=#{scope}"
assert_equal expected_authorize_url, HyperGraph.authorize_url(client_id, callback_url, :scope => scope, :display => display)
end
def test_get_access_token
access_token = "your-token-here"
client_id = "your-client-id"
client_secret = "your-client-secret"
code = "facebook-oauth-code"
callback_url = "http://yoursite.com/callback?param1=somevalue¶m2=unencoded string value"
api_response = "access_token=#{access_token}&expires=5008"
mock_response = stub(:body => api_response)
@mock_connection.expects(:use_ssl=).with(true)
@mock_connection.expects(:get).with("/oauth/access_token?client_id=#{client_id}&client_secret=#{client_secret}&code=#{code}&redirect_uri=#{URI.encode(callback_url)}").returns(mock_response)
assert_equal access_token, HyperGraph.get_access_token(client_id, client_secret, callback_url, code)
end
end | 67.026906 | 388 | 0.599184 |
b935cbd195c323d10971639bfd40611883b5f1df | 708 | cask :v1 => 'libreoffice' do
version '4.3.4'
if Hardware::CPU.is_32_bit? or MacOS.version < :mountain_lion
sha256 '9e466cdd41ab29e0845267f6e46ed7c6edb79b36b4bcb121edd0df55aee4e53c'
url "https://download.documentfoundation.org/libreoffice/stable/#{version}/mac/x86/LibreOffice_#{version}_MacOS_x86.dmg"
else
sha256 '5389a93a32c7f9c6a410bee1f7ee0fa4cf0802becb6f896b663799f275b05f2e'
url "https://download.documentfoundation.org/libreoffice/stable/#{version}/mac/x86_64/LibreOffice_#{version}_MacOS_x86-64.dmg"
end
gpg "#{url}.asc",
:key_id => 'c2839ecad9408fbe9531c3e9f434a1efafeeaea3'
homepage 'https://www.libreoffice.org/'
license :unknown
app 'LibreOffice.app'
end
| 37.263158 | 130 | 0.772599 |
33f1021ec0f0ff68f62f2536c76fc1a3684b9c6b | 1,048 | require './test/test_helper'
class AccountTest < TestHelper
def test_it_reads_all_usernames_of_an_account
file_io_test
generate_test_account(2)
account = Account.new(account: 'test', destination: '~/Library/RyPass/test')
clean_test_csvs
assert_equal account.usernames, ['Username','[email protected]', '[email protected]'].join("\n")
end
def test_it_finds_password_belonging_to_specific_user
file_io_test
generate_test_account(2)
test0_account = Account.new(account: 'test',
destination: '~/Library/RyPass/test',
username: '[email protected]')
clean_test_csvs
assert_equal test0_account.get_password, "Password: password0"
end
def test_it_returns_array_of_all_info_stored
file_io_test
generate_test_account(2)
account = Account.new(account: 'test', destination: '~/Library/RyPass/test')
clean_test_csvs
assert_equal account.all, "Username | Password\[email protected] | password0\[email protected] | password1"
end
end
| 31.757576 | 107 | 0.707061 |
1adf31176a13280f6574fc6a502cbba7ce184b02 | 33,956 | # frozen_string_literal: true
require "action_view/helpers/javascript_helper"
require "active_support/core_ext/array/access"
require "active_support/core_ext/hash/keys"
require "active_support/core_ext/string/output_safety"
module ActionView
# = Action View URL Helpers
module Helpers #:nodoc:
# Provides a set of methods for making links and getting URLs that
# depend on the routing subsystem (see ActionDispatch::Routing).
# This allows you to use the same format for links in views
# and controllers.
module UrlHelper
# This helper may be included in any class that includes the
# URL helpers of a routes (routes.url_helpers). Some methods
# provided here will only work in the context of a request
# (link_to_unless_current, for instance), which must be provided
# as a method called #request on the context.
BUTTON_TAG_METHOD_VERBS = %w{patch put delete}
extend ActiveSupport::Concern
include TagHelper
module ClassMethods
def _url_for_modules
ActionView::RoutingUrlFor
end
end
# Basic implementation of url_for to allow use helpers without routes existence
def url_for(options = nil) # :nodoc:
case options
when String
options
when :back
_back_url
else
raise ArgumentError, "arguments passed to url_for can't be handled. Please require " \
"routes or provide your own implementation"
end
end
def _back_url # :nodoc:
_filtered_referrer || "javascript:history.back()"
end
private :_back_url
def _filtered_referrer # :nodoc:
if controller.respond_to?(:request)
referrer = controller.request.env["HTTP_REFERER"]
if referrer && URI(referrer).scheme != "javascript"
referrer
end
end
rescue URI::InvalidURIError
end
private :_filtered_referrer
# Creates an anchor element of the given +name+ using a URL created by the set of +options+.
# See the valid options in the documentation for +url_for+. It's also possible to
# pass a \String instead of an options hash, which generates an anchor element that uses the
# value of the \String as the href for the link. Using a <tt>:back</tt> \Symbol instead
# of an options hash will generate a link to the referrer (a JavaScript back link
# will be used in place of a referrer if none exists). If +nil+ is passed as the name
# the value of the link itself will become the name.
#
# ==== Signatures
#
# link_to(body, url, html_options = {})
# # url is a String; you can use URL helpers like
# # posts_path
#
# link_to(body, url_options = {}, html_options = {})
# # url_options, except :method, is passed to url_for
#
# link_to(options = {}, html_options = {}) do
# # name
# end
#
# link_to(url, html_options = {}) do
# # name
# end
#
# ==== Options
# * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>method: symbol of HTTP verb</tt> - This modifier will dynamically
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
# in dangerous actions like deleting a record (which search bots can follow
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>.
# Note that if the user has JavaScript disabled, the request will fall back
# to using GET. If <tt>href: '#'</tt> is used and the user has JavaScript
# disabled clicking the link will have no effect. If you are relying on the
# POST behavior, you should check for it in your controller's action by using
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>patch?</tt>, or <tt>put?</tt>.
# * <tt>remote: true</tt> - This will allow the unobtrusive JavaScript
# driver to make an Ajax request to the URL in question instead of following
# the link. The drivers each provide mechanisms for listening for the
# completion of the Ajax request and performing JavaScript operations once
# they're complete
#
# ==== Data attributes
#
# * <tt>confirm: 'question?'</tt> - This will allow the unobtrusive JavaScript
# driver to prompt with the question specified (in this case, the
# resulting text would be <tt>question?</tt>. If the user accepts, the
# link is processed normally, otherwise no action is taken.
# * <tt>:disable_with</tt> - Value of this parameter will be used as the
# name for a disabled version of the link. This feature is provided by
# the unobtrusive JavaScript driver.
#
# ==== Examples
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
# your application on resources and use
#
# link_to "Profile", profile_path(@profile)
# # => <a href="/profiles/1">Profile</a>
#
# or the even pithier
#
# link_to "Profile", @profile
# # => <a href="/profiles/1">Profile</a>
#
# in place of the older more verbose, non-resource-oriented
#
# link_to "Profile", controller: "profiles", action: "show", id: @profile
# # => <a href="/profiles/show/1">Profile</a>
#
# Similarly,
#
# link_to "Profiles", profiles_path
# # => <a href="/profiles">Profiles</a>
#
# is better than
#
# link_to "Profiles", controller: "profiles"
# # => <a href="/profiles">Profiles</a>
#
# When name is +nil+ the href is presented instead
#
# link_to nil, "http://example.com"
# # => <a href="http://www.example.com">http://www.example.com</a>
#
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
#
# <%= link_to(@profile) do %>
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
# <% end %>
# # => <a href="/profiles/1">
# <strong>David</strong> -- <span>Check it out!</span>
# </a>
#
# Classes and ids for CSS are easy to produce:
#
# link_to "Articles", articles_path, id: "news", class: "article"
# # => <a href="/articles" class="article" id="news">Articles</a>
#
# Be careful when using the older argument style, as an extra literal hash is needed:
#
# link_to "Articles", { controller: "articles" }, id: "news", class: "article"
# # => <a href="/articles" class="article" id="news">Articles</a>
#
# Leaving the hash off gives the wrong link:
#
# link_to "WRONG!", controller: "articles", id: "news", class: "article"
# # => <a href="/articles/index/news?class=article">WRONG!</a>
#
# +link_to+ can also produce links with anchors or query strings:
#
# link_to "Comment wall", profile_path(@profile, anchor: "wall")
# # => <a href="/profiles/1#wall">Comment wall</a>
#
# link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
#
# link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
#
# The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
#
# link_to("Destroy", "http://www.example.com", method: :delete)
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
#
# You can also use custom data attributes using the <tt>:data</tt> option:
#
# link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
#
# Also you can set any link attributes such as <tt>target</tt>, <tt>rel</tt>, <tt>type</tt>:
#
# link_to "External link", "http://www.rubyonrails.org/", target: "_blank", rel: "nofollow"
# # => <a href="http://www.rubyonrails.org/" target="_blank" rel="nofollow">External link</a>
def link_to(name = nil, options = nil, html_options = nil, &block)
html_options, options, name = options, name, block if block_given?
options ||= {}
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
html_options["href"] ||= url
content_tag("a", name || url, html_options, &block)
end
# Generates a form containing a single button that submits to the URL created
# by the set of +options+. This is the safest method to ensure links that
# cause changes to your data are not triggered by search bots or accelerators.
# If the HTML button does not work with your layout, you can also consider
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
# the +link_to+ documentation.
#
# By default, the generated form element has a class name of <tt>button_to</tt>
# to allow styling of the form itself and its children. This can be changed
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
# the form submission and input element behavior using +html_options+.
# This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
# If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
# You can also disable the button by passing <tt>disabled: true</tt> in +html_options+.
# If you are using RESTful routes, you can pass the <tt>:method</tt>
# to change the HTTP verb used to submit the form.
#
# ==== Options
# The +options+ hash accepts the same options as +url_for+.
#
# There are a few special +html_options+:
# * <tt>:method</tt> - \Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
# * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behavior. By default this behavior is an ajax submit.
# * <tt>:form</tt> - This hash will be form attributes
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
# be placed
# * <tt>:params</tt> - \Hash of parameters to be rendered as hidden fields within the form.
#
# ==== Data attributes
#
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
# prompt with the question specified. If the user accepts, the link is
# processed normally, otherwise no action is taken.
# * <tt>:disable_with</tt> - Value of this parameter will be
# used as the value for a disabled version of the submit
# button when the form is submitted. This feature is provided
# by the unobtrusive JavaScript driver.
#
# ==== Examples
# <%= button_to "New", action: "new" %>
# # => "<form method="post" action="/controller/new" class="button_to">
# # <input value="New" type="submit" />
# # </form>"
#
# <%= button_to "New", new_article_path %>
# # => "<form method="post" action="/articles/new" class="button_to">
# # <input value="New" type="submit" />
# # </form>"
#
# <%= button_to [:make_happy, @user] do %>
# Make happy <strong><%= @user.name %></strong>
# <% end %>
# # => "<form method="post" action="/users/1/make_happy" class="button_to">
# # <button type="submit">
# # Make happy <strong><%= @user.name %></strong>
# # </button>
# # </form>"
#
# <%= button_to "New", { action: "new" }, form_class: "new-thing" %>
# # => "<form method="post" action="/controller/new" class="new-thing">
# # <input value="New" type="submit" />
# # </form>"
#
#
# <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %>
# # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
# # <input value="Create" type="submit" />
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
# # </form>"
#
#
# <%= button_to "Delete Image", { action: "delete", id: @image.id },
# method: :delete, data: { confirm: "Are you sure?" } %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
# # <input type="hidden" name="_method" value="delete" />
# # <input data-confirm='Are you sure?' value="Delete Image" type="submit" />
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
# # </form>"
#
#
# <%= button_to('Destroy', 'http://www.example.com',
# method: :delete, remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %>
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
# # <input name='_method' value='delete' type='hidden' />
# # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
# # </form>"
# #
def button_to(name = nil, options = nil, html_options = nil, &block)
html_options, options = options, name if block_given?
options ||= {}
html_options ||= {}
html_options = html_options.stringify_keys
url = options.is_a?(String) ? options : url_for(options)
remote = html_options.delete("remote")
params = html_options.delete("params")
method = html_options.delete("method").to_s
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : "".html_safe
form_method = method == "get" ? "get" : "post"
form_options = html_options.delete("form") || {}
form_options[:class] ||= html_options.delete("form_class") || "button_to"
form_options[:method] = form_method
form_options[:action] = url
form_options[:'data-remote'] = true if remote
request_token_tag = if form_method == "post"
request_method = method.empty? ? "post" : method
token_tag(nil, form_options: { action: url, method: request_method })
else
""
end
html_options = convert_options_to_data_attributes(options, html_options)
html_options["type"] = "submit"
button = if block_given?
content_tag("button", html_options, &block)
else
html_options["value"] = name || url
tag("input", html_options)
end
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
if params
to_form_params(params).each do |param|
inner_tags.safe_concat tag(:input, type: "hidden", name: param[:name], value: param[:value])
end
end
content_tag("form", inner_tags, form_options)
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ unless the current request URI is the same as the links, in
# which case only the name is returned (or the given block is yielded, if
# one exists). You can give +link_to_unless_current+ a block which will
# specialize the default behavior (e.g., show a "Start Here" link rather
# than the link's text).
#
# ==== Examples
# Let's say you have a navigation menu...
#
# <ul id="navbar">
# <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
# <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
# </ul>
#
# If in the "about" action, it will render...
#
# <ul id="navbar">
# <li><a href="/controller/index">Home</a></li>
# <li>About Us</li>
# </ul>
#
# ...but if in the "index" action, it will render:
#
# <ul id="navbar">
# <li>Home</li>
# <li><a href="/controller/about">About Us</a></li>
# </ul>
#
# The implicit block given to +link_to_unless_current+ is evaluated if the current
# action is the action given. So, if we had a comments page and wanted to render a
# "Go Back" link instead of a link to the comments page, we could do something like this...
#
# <%=
# link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
# link_to("Go back", { controller: "posts", action: "index" })
# end
# %>
def link_to_unless_current(name, options = {}, html_options = {}, &block)
link_to_unless current_page?(options), name, options, html_options, &block
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ unless +condition+ is true, in which case only the name is
# returned. To specialize the default behavior (i.e., show a login link rather
# than just the plaintext link text), you can pass a block that
# accepts the name or the full argument list for +link_to_unless+.
#
# ==== Examples
# <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
# # If the user is logged in...
# # => <a href="/controller/reply/">Reply</a>
#
# <%=
# link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
# link_to(name, { controller: "accounts", action: "signup" })
# end
# %>
# # If the user is logged in...
# # => <a href="/controller/reply/">Reply</a>
# # If not...
# # => <a href="/accounts/signup">Reply</a>
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
link_to_if !condition, name, options, html_options, &block
end
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ if +condition+ is true, otherwise only the name is
# returned. To specialize the default behavior, you can pass a block that
# accepts the name or the full argument list for +link_to_if+.
#
# ==== Examples
# <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
# # If the user isn't logged in...
# # => <a href="/sessions/new/">Login</a>
#
# <%=
# link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
# link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
# end
# %>
# # If the user isn't logged in...
# # => <a href="/sessions/new/">Login</a>
# # If they are logged in...
# # => <a href="/accounts/show/3">my_username</a>
def link_to_if(condition, name, options = {}, html_options = {}, &block)
if condition
link_to(name, options, html_options)
else
if block_given?
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
else
ERB::Util.html_escape(name)
end
end
end
# Creates a mailto link tag to the specified +email_address+, which is
# also used as the name of the link unless +name+ is specified. Additional
# HTML attributes for the link can be passed in +html_options+.
#
# +mail_to+ has several methods for customizing the email itself by
# passing special keys to +html_options+.
#
# ==== Options
# * <tt>:subject</tt> - Preset the subject line of the email.
# * <tt>:body</tt> - Preset the body of the email.
# * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
# * <tt>:reply_to</tt> - Preset the Reply-To field of the email.
#
# ==== Obfuscation
# Prior to Rails 4.0, +mail_to+ provided options for encoding the address
# in order to hinder email harvesters. To take advantage of these options,
# install the +actionview-encoded_mail_to+ gem.
#
# ==== Examples
# mail_to "[email protected]"
# # => <a href="mailto:[email protected]">[email protected]</a>
#
# mail_to "[email protected]", "My email"
# # => <a href="mailto:[email protected]">My email</a>
#
# mail_to "[email protected]", "My email", cc: "[email protected]",
# subject: "This is an example email"
# # => <a href="mailto:[email protected][email protected]&subject=This%20is%20an%20example%20email">My email</a>
#
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
#
# <%= mail_to "[email protected]" do %>
# <strong>Email me:</strong> <span>[email protected]</span>
# <% end %>
# # => <a href="mailto:[email protected]">
# <strong>Email me:</strong> <span>[email protected]</span>
# </a>
def mail_to(email_address, name = nil, html_options = {}, &block)
html_options, name = name, nil if block_given?
html_options = (html_options || {}).stringify_keys
extras = %w{ cc bcc body subject reply_to }.map! { |item|
option = html_options.delete(item).presence || next
"#{item.dasherize}=#{ERB::Util.url_encode(option)}"
}.compact
extras = extras.empty? ? "" : "?" + extras.join("&")
encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@")
html_options["href"] = "mailto:#{encoded_email_address}#{extras}"
content_tag("a", name || email_address, html_options, &block)
end
# True if the current request URI was generated by the given +options+.
#
# ==== Examples
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
#
# current_page?(action: 'process')
# # => false
#
# current_page?(action: 'checkout')
# # => true
#
# current_page?(controller: 'library', action: 'checkout')
# # => false
#
# current_page?(controller: 'shop', action: 'checkout')
# # => true
#
# current_page?(controller: 'shop', action: 'checkout', order: 'asc')
# # => false
#
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
# # => true
#
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
# # => false
#
# current_page?('http://www.example.com/shop/checkout')
# # => true
#
# current_page?('http://www.example.com/shop/checkout', check_parameters: true)
# # => false
#
# current_page?('/shop/checkout')
# # => true
#
# current_page?('http://www.example.com/shop/checkout?order=desc&page=1')
# # => true
#
# Let's say we're in the <tt>http://www.example.com/products</tt> action with method POST in case of invalid product.
#
# current_page?(controller: 'product', action: 'index')
# # => false
#
# We can also pass in the symbol arguments instead of strings.
#
def current_page?(options, check_parameters: false)
unless request
raise "You cannot use helpers that need to determine the current " \
"page unless your view context provides a Request object " \
"in a #request method"
end
return false unless request.get? || request.head?
check_parameters ||= options.is_a?(Hash) && options.delete(:check_parameters)
url_string = URI::DEFAULT_PARSER.unescape(url_for(options)).force_encoding(Encoding::BINARY)
# We ignore any extra parameters in the request_uri if the
# submitted URL doesn't have any either. This lets the function
# work with things like ?order=asc
# the behaviour can be disabled with check_parameters: true
request_uri = url_string.index("?") || check_parameters ? request.fullpath : request.path
request_uri = URI::DEFAULT_PARSER.unescape(request_uri).force_encoding(Encoding::BINARY)
if url_string.start_with?("/") && url_string != "/"
url_string.chomp!("/")
request_uri.chomp!("/")
end
if %r{^\w+://}.match?(url_string)
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
else
url_string == request_uri
end
end
# Creates an SMS anchor link tag to the specified +phone_number+, which is
# also used as the name of the link unless +name+ is specified. Additional
# HTML attributes for the link can be passed in +html_options+.
#
# When clicked, an SMS message is prepopulated with the passed phone number
# and optional +body+ value.
#
# +sms_to+ has a +body+ option for customizing the SMS message itself by
# passing special keys to +html_options+.
#
# ==== Options
# * <tt>:body</tt> - Preset the body of the message.
#
# ==== Examples
# sms_to "5155555785"
# # => <a href="sms:5155555785;">5155555785</a>
#
# sms_to "5155555785", "Text me"
# # => <a href="sms:5155555785;">Text me</a>
#
# sms_to "5155555785", "Text me",
# body: "Hello Jim I have a question about your product."
# # => <a href="sms:5155555785;?body=Hello%20Jim%20I%20have%20a%20question%20about%20your%20product">Text me</a>
#
# You can use a block as well if your link target is hard to fit into the name parameter. \ERB example:
#
# <%= sms_to "5155555785" do %>
# <strong>Text me:</strong>
# <% end %>
# # => <a href="sms:5155555785;">
# <strong>Text me:</strong>
# </a>
def sms_to(phone_number, name = nil, html_options = {}, &block)
html_options, name = name, nil if block_given?
html_options = (html_options || {}).stringify_keys
extras = %w{ body }.map! { |item|
option = html_options.delete(item).presence || next
"#{item.dasherize}=#{ERB::Util.url_encode(option)}"
}.compact
extras = extras.empty? ? "" : "?&" + extras.join("&")
encoded_phone_number = ERB::Util.url_encode(phone_number)
html_options["href"] = "sms:#{encoded_phone_number};#{extras}"
content_tag("a", name || phone_number, html_options, &block)
end
# Creates a TEL anchor link tag to the specified +phone_number+, which is
# also used as the name of the link unless +name+ is specified. Additional
# HTML attributes for the link can be passed in +html_options+.
#
# When clicked, the default app to make calls is opened, and it
# is prepopulated with the passed phone number and optional
# +country_code+ value.
#
# +phone_to+ has an optional +country_code+ option which automatically adds the country
# code as well as the + sign in the phone numer that gets prepopulated,
# for example if +country_code: "01"+ +\+01+ will be prepended to the
# phone numer, by passing special keys to +html_options+.
#
# ==== Options
# * <tt>:country_code</tt> - Prepends the country code to the number
#
# ==== Examples
# phone_to "1234567890"
# # => <a href="tel:1234567890">1234567890</a>
#
# phone_to "1234567890", "Phone me"
# # => <a href="tel:134567890">Phone me</a>
#
# phone_to "1234567890", "Phone me", country_code: "01"
# # => <a href="tel:+015155555785">Phone me</a>
#
# You can use a block as well if your link target is hard to fit into the name parameter. \ERB example:
#
# <%= phone_to "1234567890" do %>
# <strong>Phone me:</strong>
# <% end %>
# # => <a href="tel:1234567890">
# <strong>Phone me:</strong>
# </a>
def phone_to(phone_number, name = nil, html_options = {}, &block)
html_options, name = name, nil if block_given?
html_options = (html_options || {}).stringify_keys
country_code = html_options.delete("country_code").presence
country_code = country_code.nil? ? "" : "+#{ERB::Util.url_encode(country_code)}"
encoded_phone_number = ERB::Util.url_encode(phone_number)
html_options["href"] = "tel:#{country_code}#{encoded_phone_number}"
content_tag("a", name || phone_number, html_options, &block)
end
private
def convert_options_to_data_attributes(options, html_options)
if html_options
html_options = html_options.stringify_keys
html_options["data-remote"] = "true" if link_to_remote_options?(options) || link_to_remote_options?(html_options)
method = html_options.delete("method")
add_method_to_attributes!(html_options, method) if method
html_options
else
link_to_remote_options?(options) ? { "data-remote" => "true" } : {}
end
end
def link_to_remote_options?(options)
if options.is_a?(Hash)
options.delete("remote") || options.delete(:remote)
end
end
def add_method_to_attributes!(html_options, method)
if method_not_get_method?(method) && !html_options["rel"]&.match?(/nofollow/)
if html_options["rel"].blank?
html_options["rel"] = "nofollow"
else
html_options["rel"] = "#{html_options["rel"]} nofollow"
end
end
html_options["data-method"] = method
end
STRINGIFIED_COMMON_METHODS = {
get: "get",
delete: "delete",
patch: "patch",
post: "post",
put: "put",
}.freeze
def method_not_get_method?(method)
return false unless method
(STRINGIFIED_COMMON_METHODS[method] || method.to_s.downcase) != "get"
end
def token_tag(token = nil, form_options: {})
if token != false && defined?(protect_against_forgery?) && protect_against_forgery?
token ||= form_authenticity_token(form_options: form_options)
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
else
""
end
end
def method_tag(method)
tag("input", type: "hidden", name: "_method", value: method.to_s)
end
# Returns an array of hashes each containing :name and :value keys
# suitable for use as the names and values of form input fields:
#
# to_form_params(name: 'David', nationality: 'Danish')
# # => [{name: 'name', value: 'David'}, {name: 'nationality', value: 'Danish'}]
#
# to_form_params(country: { name: 'Denmark' })
# # => [{name: 'country[name]', value: 'Denmark'}]
#
# to_form_params(countries: ['Denmark', 'Sweden']})
# # => [{name: 'countries[]', value: 'Denmark'}, {name: 'countries[]', value: 'Sweden'}]
#
# An optional namespace can be passed to enclose key names:
#
# to_form_params({ name: 'Denmark' }, 'country')
# # => [{name: 'country[name]', value: 'Denmark'}]
def to_form_params(attribute, namespace = nil)
attribute = if attribute.respond_to?(:permitted?)
attribute.to_h
else
attribute
end
params = []
case attribute
when Hash
attribute.each do |key, value|
prefix = namespace ? "#{namespace}[#{key}]" : key
params.push(*to_form_params(value, prefix))
end
when Array
array_prefix = "#{namespace}[]"
attribute.each do |value|
params.push(*to_form_params(value, array_prefix))
end
else
params << { name: namespace.to_s, value: attribute.to_param }
end
params.sort_by { |pair| pair[:name] }
end
end
end
end
| 44.041505 | 139 | 0.585493 |
d5f3c679213ac045491ad42e4f2516c9e5fb7b7b | 409 | class CreateSearchableBoards < ActiveRecord::Migration
def change
create_table :searchable_boards, id: false do |t|
t.primary_key :searchable_id
t.string :searchable_type, null: false
t.tsvector :content, null: false, default: ''
t.string :section, null: false
end
add_index :searchable_boards, :content, using: :gin
add_index :searchable_boards, :section
end
end
| 29.214286 | 55 | 0.709046 |
62d41fcdab3ab401193f4819761c3e43915fc7e9 | 825 | class AssetBaseAuditResultsListReport < Report
def get_data(conditions)
if conditions[:audit_result_type_id].to_i == AuditResultType::AUDIT_RESULT_UNKNOWN.to_i
audit_results = []
not_tested = TransitAsset.operational.where(organization_id: conditions[:organization_id], (conditions[:filterable_type].foreign_key.to_sym) => conditions[:filterable_id]).where.not(id: AuditResult.where(conditions.except(:audit_result_type_id)).pluck(:auditable_id))
not_tested.each do |no_audit_obj|
audit_results << AuditResult.new(auditable: no_audit_obj, organization_id: no_audit_obj.organization_id)
end
else
audit_results = AuditResult.search_auditable(conditions, Rails.application.config.asset_base_class_name, {disposition_date: nil})
end
return audit_results
end
end | 45.833333 | 273 | 0.773333 |
aca53d702eba3b6260ad294985a1998554b77029 | 2,047 | require "spec_helper"
module Refinery
describe "the Admin Images Tab" do
refinery_login_with :refinery_user
include_context 'admin images tab'
context 'When there are no images' do
include_context 'no existing images'
it 'says there are no images'do
visit refinery.admin_images_path
expect(page).to have_content(::I18n.t('no_images_yet', scope: 'refinery.admin.images.records'))
end
it_has_behaviour 'uploads images'
end
context 'When there is one image' do
include_context 'one image'
it_has_behaviour 'indexes images'
it_has_behaviour 'shows list and grid views'
it_has_behaviour 'shows an image preview'
it_has_behaviour 'deletes an image'
it_has_behaviour 'edits an image'
it_has_behaviour 'uploads images'
end
context 'When there are many images' do
include_context 'many images'
it_has_behaviour 'indexes images'
it_has_behaviour 'shows list and grid views'
it_has_behaviour 'paginates the list of images'
it_has_behaviour 'shows an image preview'
it_has_behaviour 'deletes an image'
it_has_behaviour 'uploads images'
it_has_behaviour 'edits an image'
end
end
describe 'Page Visual Editor - Add Image' do
refinery_login_with :refinery_user
include_context 'Visual Editor - add image'
context 'When there are no images' do
include_context 'no existing images'
it_has_behaviour 'uploads images'
end
context 'When there is one image' do
include_context 'one image'
it_has_behaviour 'indexes images'
it_has_behaviour 'paginates the list of images'
it_has_behaviour 'uploads images'
it_has_behaviour 'inserts images'
end
context 'When there are many images' do
include_context 'many images'
it_has_behaviour 'indexes images'
it_has_behaviour 'paginates the list of images'
it_has_behaviour 'uploads images'
it_has_behaviour 'inserts images'
end
end
end
| 26.934211 | 103 | 0.703468 |
9142aaf99fa89bbf924465c667c68d95a360350c | 314 | CoDy::LogBook.new do
r = repo '.'
log do
position 'b56ab8e15a865918acfaccad0b486544a78b37a2'
entry '''
This is an empty repository ...
'''
position '6fe8def3e2719f53c7ad929e491d8fc201815c38'
end
final do
position r.current_branch
end
end | 14.272727 | 59 | 0.601911 |
ac30b3b7a14c58e773357a883f67fa124afe6b7b | 5,027 | # Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
module AWS
class EC2
# Represents the collection of permissions for an EC2 resource.
# Each permission is a string containing the AWS account ID of a
# user who has permission to use the resource in question. The
# {Image} and {Snapshot} classes are currently the only ones
# that use this interface.
class PermissionCollection
include Core::Model
include Enumerable
# @private
def initialize(resource, opts = {})
@resource = resource
super(opts)
end
# @yield [user_id] Each user ID that has explicit
# permissions to launch this AMI.
def each(&block)
resp = client.send(describe_call, describe_params)
resp.send(inflected_permissions_attribute).each do |permission|
if permission[:user_id]
user_id = permission[:user_id]
yield(user_id)
end
end
end
# @return [Integer] The number of users that have explicit
# permissions to launch this AMI.
def size
inject(0) { |sum, i| sum + 1 }
end
# @return [Boolean] True if the collection is empty.
def empty?
size == 0
end
# @return [Boolean] True if the resource is public.
def public?
resp = client.send(describe_call, describe_params)
resp.send(inflected_permissions_attribute).any? do |permission|
permission[:group] and permission[:group] == "all"
end
end
# @return [Boolean] True if the resource is private (i.e. not
# public).
def private?
!public?
end
# Sets whether the resource is public or not. This has no
# effect on the explicit AWS account IDs that may already have
# permissions to use the resource.
#
# @param [Boolean] value If true, the resource is made public,
# otherwise the resource is made private.
# @return [nil]
def public= value
params = value ?
{ :add => [{ :group => "all" }] } :
{ :remove => [{ :group => "all" }] }
client.send(modify_call, modify_params(params))
nil
end
# Adds permissions for specific users to launch this AMI.
#
# @param [Array of Strings] users The AWS account IDs of the
# users that should be able to launch this AMI.
# @return [nil]
def add(*users)
modify(:add, *users)
end
# Removes permissions for specific users to launch this AMI.
# @param [Array of Strings] users The AWS account IDs of the
# users that should no longer be able to launch this AMI.
# @return [nil]
def remove(*users)
modify(:remove, *users)
end
# Resets the launch permissions to their default state.
# @return [nil]
def reset
client.send(reset_call, reset_params)
end
# @private
private
def describe_call
"describe_#{resource_name}_attribute"
end
# @private
private
def modify_call
"modify_#{resource_name}_attribute"
end
# @private
private
def reset_call
"reset_#{resource_name}_attribute"
end
# @private
private
def describe_params
Hash[[["#{resource_name}_id".to_sym, @resource.send(:__resource_id__)],
[:attribute, permissions_attribute]]]
end
alias_method :reset_params, :describe_params
# @private
private
def inflected_permissions_attribute
Core::Inflection.ruby_name(permissions_attribute).to_sym
end
# @private
private
def permissions_attribute
@resource.__permissions_attribute__
end
# @private
private
def resource_name
@resource.send(:inflected_name)
end
# @private
private
def modify(action, *users)
return if users.empty?
opts = modify_params(Hash[[[action,
users.map do |user_id|
{ :user_id => user_id }
end]]])
client.send(modify_call, opts)
nil
end
# @private
private
def modify_params(modifications)
Hash[[["#{resource_name}_id".to_sym, @resource.send(:__resource_id__)],
[inflected_permissions_attribute, modifications]]]
end
end
end
end
| 28.725714 | 79 | 0.605132 |
b9e74f5b31f72ac174dd6ddf889b0a308d877ca9 | 83 | module Docker
# The version of the docker-api gem.
VERSION = '2.0.0.pre.1'
end
| 16.6 | 38 | 0.674699 |
28985cc4d942125e94568b0a0320dcd6526da678 | 3,924 | class Remarshal < Formula
include Language::Python::Virtualenv
desc "Convert between TOML, YAML and JSON"
homepage "https://github.com/dbohdan/remarshal"
url "https://files.pythonhosted.org/packages/24/37/1f167687b2d9f3bac3e7e73508f86c7e6c1bf26a37ca5443182c8f596625/remarshal-0.14.0.tar.gz"
sha256 "16425aa1575a271dd3705d812b06276eeedc3ac557e7fd28e06822ad14cd0667"
license "MIT"
revision 3
head "https://github.com/dbohdan/remarshal.git", branch: "master"
bottle do
sha256 cellar: :any, arm64_monterey: "f6bd3e96392bcfa62be9d9c67d6aef33b9d18da54e657d4c26a37f38ca20b2f8"
sha256 cellar: :any, arm64_big_sur: "17886e23ddb3e6dc1824e195a5bbe2e6f65b08f750c61fe149f0cad9b95d3e40"
sha256 cellar: :any, monterey: "dcb1b2b8cc49e3a2a7091531f1c37df9fb47852035d56c659a90bab72c552173"
sha256 cellar: :any, big_sur: "35e9b3686329a3a49410078a62efa4a1a47d247c61b4806a2baebb4cca2f6285"
sha256 cellar: :any, catalina: "d3556c7f66d0e0e293a27a249a5096cbcf5036656afabb9e7b80d95b8470e28b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "6b23018ebe711328bfe03cb664f4ce1f143ea136546807565bb1c100cbaf5e7d"
end
depends_on "poetry" => :build
depends_on "libyaml" # for faster PyYAML
depends_on "[email protected]"
depends_on "six"
conflicts_with "msgpack-tools", because: "both install 'json2msgpack' binary"
resource "cbor2" do
url "https://files.pythonhosted.org/packages/9e/25/9dd432c051010faea6a702cb85d0b53dc9d5414513866b6a73b3ac954092/cbor2-5.4.1.tar.gz"
sha256 "a8bf432f6cb595f50aeb8fed2a4aa3b3f7caa7f135fb57e4378eaa39242feac9"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/4c/c4/13b4776ea2d76c115c1d1b84579f3764ee6d57204f6be27119f13a61d0a9/python-dateutil-2.8.2.tar.gz"
sha256 "0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"
end
resource "PyYAML" do
url "https://files.pythonhosted.org/packages/a0/a4/d63f2d7597e1a4b55aa3b4d6c5b029991d3b824b5bd331af8d4ab1ed687d/PyYAML-5.4.1.tar.gz"
sha256 "607774cbba28732bfa802b54baa7484215f530991055bb562efbed5b2f20a45e"
end
resource "tomlkit" do
url "https://files.pythonhosted.org/packages/65/ed/7b7216101bc48627b630693b03392f33827901b81d4e1360a76515e3abc4/tomlkit-0.7.2.tar.gz"
sha256 "d7a454f319a7e9bd2e249f239168729327e4dd2d27b17dc68be264ad1ce36754"
end
resource "u-msgpack-python" do
url "https://files.pythonhosted.org/packages/62/94/a4f485b628310534d377b3e7cb6f85b8066dc823dbff0e4421fb4227fb7e/u-msgpack-python-2.7.1.tar.gz"
sha256 "b7e7d433cab77171a4c752875d91836f3040306bab5063fb6dbe11f64ea69551"
end
def install
venv = virtualenv_create(libexec, "python3")
venv.pip_install resources
system Formula["poetry"].opt_bin/"poetry", "build", "--format", "wheel", "--verbose", "--no-interaction"
venv.pip_install_and_link Dir["dist/remarshal-*.whl"].first
%w[toml yaml json msgpack].permutation(2).each do |informat, outformat|
bin.install_symlink "remarshal" => "#{informat}2#{outformat}"
end
end
test do
json = <<~EOS.chomp
{"foo.bar":"baz","qux":1}
EOS
yaml = <<~EOS.chomp
foo.bar: baz
qux: 1
EOS
toml = <<~EOS.chomp
"foo.bar" = "baz"
qux = 1
EOS
assert_equal yaml, pipe_output("#{bin}/remarshal -if=json -of=yaml", json)
assert_equal yaml, pipe_output("#{bin}/json2yaml", json)
assert_equal toml, pipe_output("#{bin}/remarshal -if=yaml -of=toml", yaml)
assert_equal toml, pipe_output("#{bin}/yaml2toml", yaml)
assert_equal json, pipe_output("#{bin}/remarshal -if=toml -of=json", toml).chomp
assert_equal json, pipe_output("#{bin}/toml2json", toml).chomp
assert_equal pipe_output("#{bin}/remarshal -if=yaml -of=msgpack", yaml),
pipe_output("#{bin}/remarshal -if=json -of=msgpack", json)
end
end
| 44.590909 | 146 | 0.744903 |
7a8f5c74b1f3a7c3724dcb0070cd41e9b83b5daa | 526 | unless String.method_defined? :rpartition
require 'backports/tools/arguments'
class String
def rpartition(pattern)
pattern = Backports.coerce_to(pattern, String, :to_str) unless pattern.is_a? Regexp
i = rindex(pattern)
return ["", "", self] unless i
if pattern.is_a? Regexp
match = Regexp.last_match
[match.pre_match, match[0], match.post_match]
else
last = i+pattern.length
[self[0...i], self[i...last], self[last...length]]
end
end
end
end
| 26.3 | 89 | 0.63308 |
1ac652a282d99325f3c976d4ab9e5e351a61ca9c | 68 | require_relative './base_views'
class HistoryViews < BaseViews; end | 22.666667 | 35 | 0.808824 |
ff0a43c7baf53ebc9b94013f3e37df3c73024aa2 | 3,254 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require
require "ornament"
module Dummy
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 escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Setting boolean as integer to true to fix deprecation warnings
Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
# 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'
# FOR DEVELOPMENT PURPOSES ONLY
# Add the generator's assets directory to dummy app's assets path.
config.paths["app/assets"] << Rails.root.join("../../lib/generators/ornament/templates/app/assets")
config.paths["app/controllers"] << Rails.root.join("../../lib/generators/ornament/templates/app/controllers")
config.paths["app/views"] << Rails.root.join("../../lib/generators/ornament/templates/app/views")
config.paths["vendor/assets"] << Rails.root.join("../../lib/generators/ornament/templates/vendor/assets")
end
end
| 46.485714 | 113 | 0.732329 |
21e3870153b292b9928f2d37e3573b3945653052 | 179 | class AddStatusFeedback < ActiveRecord::Migration
def self.up
add_column :statuses, :feedback, :text
end
def self.down
remove_column :statuses, :feedback
end
end
| 17.9 | 49 | 0.731844 |
0381cba24b53769a4e925fb267eea3680617867b | 4,062 | require 'sinatra/base'
require 'slack-ruby-client'
require 'uri'
require 'incident'
def get_random_string(length=7)
source=("a".."z").to_a + (0..9).to_a
key=""
length.times{ key += source[rand(source.size)].to_s }
return key
end
# Load Slack app info into a hash called `config` from the environment variables assigned during setup
SLACK_CONFIG = {
slack_client_id: ENV['SLACK_CLIENT_ID'],
slack_api_secret: ENV['SLACK_API_SECRET'],
slack_redirect_uri: ENV['SLACK_REDIRECT_URI'],
}
# Check to see if the required variables listed above were provided, and raise an exception if any are missing.
missing_params = SLACK_CONFIG.select { |key, value| value.nil? }
if missing_params.any?
error_msg = missing_params.keys.join(", ").upcase
raise "Missing Slack config variables: #{error_msg}"
end
# Set the scope, all the things we'll need to access. See: https://api.slack.com/docs/oauth-scopes for more info.
BOT_SCOPE = 'bot,channels:write,chat:write:bot,channels:read,channels:history,users:read'
# This hash will contain all the info for each authed team, as well as each team's Slack client object.
# In a production environment, you may want to move some of this into a real data store.
$teams = {}
# Since we're going to create a Slack client object for each team, this helper keeps all of that logic in one place.
def create_slack_client(slack_api_secret)
Slack.configure do |config|
config.token = slack_api_secret
fail 'Missing API token' unless config.token
end
Slack::Web::Client.new
end
# Slack uses OAuth for user authentication. This auth process is performed by exchanging a set of
# keys and tokens between Slack's servers and yours. This process allows the authorizing user to confirm
# that they want to grant our bot access to their team.
# See https://api.slack.com/docs/oauth for more information.
class Auth < Sinatra::Base
configure do
enable :logging
set :logging, Logger::INFO
end
# If a user tries to access the index page, redirect them to the auth start page
get '/' do
redirect '/begin_auth'
end
# This page shows the user what our app would like to access and what bot user we'd like to create for their team.
get '/begin_auth' do
redirect_uri = URI.parse(SLACK_CONFIG[:slack_redirect_uri])
if params[:a]
redirect_uri.query = "a=#{params[:a]}"
end
redirect "https://slack.com/oauth/authorize?scope=#{BOT_SCOPE}&client_id=#{SLACK_CONFIG[:slack_client_id]}&redirect_uri=#{redirect_uri}"
end
# OAuth Step 2: The user has told Slack that they want to authorize our app to use their account, so
# Slack sends us a code which we can use to request a token for the user's account.
get '/finish_auth' do
main_channel_id = ENV['SLACK_CHANNEL_ID']
redirect_uri = URI.parse(SLACK_CONFIG[:slack_redirect_uri])
if params[:a]
redirect_uri.query = "a=#{params[:a]}"
end
client = Slack::Web::Client.new
# OAuth Step 3: Success or failure
begin
response = client.oauth_access(
{
client_id: SLACK_CONFIG[:slack_client_id],
client_secret: SLACK_CONFIG[:slack_api_secret],
redirect_uri: redirect_uri,
code: params[:code] # (This is the OAuth code mentioned above)
}
)
# authorizes the app to access slack.
team_id = response['user_id']
client = create_slack_client(response['access_token'])
user_id = response[:user_id]
$teams[user_id] = {
user_access_token: response['access_token'],
bot_user_id: response['bot']['bot_user_id'],
bot_access_token: response['bot']['bot_access_token']
}
$teams[user_id]['client'] = client
# Be sure to let the user know that auth succeeded.
status 200
body 'Yay! Auth succeeded!'
if params[:a] == 'start'
incident = Incident.new(logger)
incident.start(user_id, main_channel_id)
end
rescue Slack::Web::Api::Error => e
# Failure:
status 403
body "status 403<br/>"
end
end
end
| 33.295082 | 140 | 0.698178 |
61c84c6a32ceff9cb8865e9de36dd0c6b7e30bd4 | 1,825 | # -*- encoding: utf-8 -*-
# stub: redcarpet 3.4.0 ruby lib
# stub: ext/redcarpet/extconf.rb
Gem::Specification.new do |s|
s.name = "redcarpet".freeze
s.version = "3.4.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Natacha Port\u00E9".freeze, "Vicent Mart\u00ED".freeze]
s.date = "2016-12-25"
s.description = "A fast, safe and extensible Markdown to (X)HTML parser".freeze
s.email = "[email protected]".freeze
s.executables = ["redcarpet".freeze]
s.extensions = ["ext/redcarpet/extconf.rb".freeze]
s.extra_rdoc_files = ["COPYING".freeze]
s.files = ["COPYING".freeze, "bin/redcarpet".freeze, "ext/redcarpet/extconf.rb".freeze]
s.homepage = "http://github.com/vmg/redcarpet".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 1.9.2".freeze)
s.rubygems_version = "2.6.11".freeze
s.summary = "Markdown that smells nice".freeze
s.installed_by_version = "2.6.11" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_development_dependency(%q<rake-compiler>.freeze, ["~> 0.9.5"])
s.add_development_dependency(%q<test-unit>.freeze, ["~> 3.1.3"])
else
s.add_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_dependency(%q<rake-compiler>.freeze, ["~> 0.9.5"])
s.add_dependency(%q<test-unit>.freeze, ["~> 3.1.3"])
end
else
s.add_dependency(%q<rake>.freeze, ["~> 10.5"])
s.add_dependency(%q<rake-compiler>.freeze, ["~> 0.9.5"])
s.add_dependency(%q<test-unit>.freeze, ["~> 3.1.3"])
end
end
| 40.555556 | 112 | 0.667397 |
d5eaba9033010cc63fa3d8ef652f06793e9f41cc | 1,662 | class Topgrade < Formula
desc "Upgrade all the things"
homepage "https://github.com/r-darwish/topgrade"
url "https://github.com/r-darwish/topgrade/archive/v6.9.1.tar.gz"
sha256 "4cd2a24fcb5f3b9c709b8ff85ff9bdc52afe87735d39f0096e46c57931b5680c"
license "GPL-3.0-or-later"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "4e0c11970d1aa7074249ba22055ad46cf8a1e438e15cd86dd49c2cb222280477"
sha256 cellar: :any_skip_relocation, big_sur: "908af0d54fd7c7948d8b987ae8dc7d74c1eb63e0d4df193705b95289bfc2d274"
sha256 cellar: :any_skip_relocation, catalina: "9790c78bcc07419629bae49f9658248673814247ef187b531fadee0bae28a077"
sha256 cellar: :any_skip_relocation, mojave: "3f41637cc41cdb9867b49a9b17070bc504c54e3be8b97224857fb504bdeb403c"
end
depends_on "rust" => :build
depends_on xcode: :build if MacOS::CLT.version >= "11.4" # libxml2 module bug
def install
system "cargo", "install", *std_cargo_args
end
test do
# Configuration path details: https://github.com/r-darwish/topgrade/blob/HEAD/README.md#configuration-path
# Sample config file: https://github.com/r-darwish/topgrade/blob/HEAD/config.example.toml
(testpath/"Library/Preferences/topgrade.toml").write <<~EOS
# Additional git repositories to pull
#git_repos = [
# "~/src/*/",
# "~/.config/something"
#]
EOS
assert_match version.to_s, shell_output("#{bin}/topgrade --version")
output = shell_output("#{bin}/topgrade -n --only brew_formula")
assert_match "Dry running: #{HOMEBREW_PREFIX}/bin/brew upgrade", output
refute_match(/\sSelf update\s/, output)
end
end
| 41.55 | 122 | 0.738267 |
91c5ea265a17daf19b9d6d0af36e26226c9d9be4 | 300 | class PolychromeShow < ActiveRecord::Base
attr_accessible :show_data, :slug
before_create :create_unique_slug
def to_param
slug
end
def create_unique_slug
begin
self[:slug] = SecureRandom.urlsafe_base64(8)
end while OpenNoteNote.exists?(:slug => self[:slug])
end
end
| 18.75 | 56 | 0.723333 |
d588ba50e50f5627cf3c61759629f44ba202508a | 4,811 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::BrowserExploitServer
def initialize(info={})
super(update_info(info,
'Name' => "Adobe Flash Player Integer Underflow Remote Code Execution",
'Description' => %q{
This module exploits a vulnerability found in the ActiveX component of Adobe Flash Player
before 12.0.0.43. By supplying a specially crafted swf file it is possible to trigger an
integer underflow in several avm2 instructions, which can be turned into remote code
execution under the context of the user, as exploited in the wild in February 2014. This
module has been tested successfully with Adobe Flash Player 11.7.700.202 on Windows XP
SP3, Windows 7 SP1 and Adobe Flash Player 11.3.372.94 on Windows 8 even when it includes
rop chains for several Flash 11 versions, as exploited in the wild.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Unknown', # vulnerability discovery and exploit in the wild
'juan vazquez' # msf module
],
'References' =>
[
[ 'CVE', '2014-0497' ],
[ 'OSVDB', '102849' ],
[ 'BID', '65327' ],
[ 'URL', 'http://helpx.adobe.com/security/products/flash-player/apsb14-04.html' ],
[ 'URL', 'http://blogs.technet.com/b/mmpc/archive/2014/02/17/a-journey-to-cve-2014-0497-exploit.aspx' ],
[ 'URL', 'http://blog.vulnhunt.com/index.php/2014/02/20/cve-2014-0497_analysis/' ]
],
'Payload' =>
{
'Space' => 1024,
'DisableNops' => true
},
'DefaultOptions' =>
{
'InitialAutoRunScript' => 'migrate -f',
'Retries' => false
},
'Platform' => 'win',
# Versions targeted in the wild:
# [*] Windows 8:
# 11,3,372,94, 11,3,375,10, 11,3,376,12, 11,3,377,15, 11,3,378,5, 11,3,379,14
# 11,6,602,167, 11,6,602,171 ,11,6,602,180
# 11,7,700,169, 11,7,700,202, 11,7,700,224
# [*] Before windows 8:
# 11,0,1,152,
# 11,1,102,55, 11,1,102,62, 11,1,102,63
# 11,2,202,228, 11,2,202,233, 11,2,202,235
# 11,3,300,257, 11,3,300,273
# 11,4,402,278
# 11,5,502,110, 11,5,502,135, 11,5,502,146, 11,5,502,149
# 11,6,602,168, 11,6,602,171, 11,6,602,180
# 11,7,700,169, 11,7,700,202
# 11,8,800,97, 11,8,800,50
'BrowserRequirements' =>
{
:source => /script|headers/i,
:clsid => "{D27CDB6E-AE6D-11cf-96B8-444553540000}",
:method => "LoadMovie",
:os_name => Msf::OperatingSystems::WINDOWS,
:ua_name => Msf::HttpClients::IE,
:flash => lambda { |ver| ver =~ /^11\./ }
},
'Targets' =>
[
[ 'Automatic', {} ]
],
'Privileged' => false,
'DisclosureDate' => "Feb 5 2014",
'DefaultTarget' => 0))
end
def exploit
@swf = create_swf
super
end
def on_request_exploit(cli, request, target_info)
print_status("Request: #{request.uri}")
if request.uri =~ /\.swf$/
print_status("Sending SWF...")
send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Pragma' => 'no-cache'})
return
end
print_status("Sending HTML...")
tag = retrieve_tag(cli, request)
profile = get_profile(tag)
profile[:tried] = false unless profile.nil? # to allow request the swf
send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
end
def exploit_template(cli, target_info)
swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
shellcode = get_payload(cli, target_info).unpack("H*")[0]
html_template = %Q|<html>
<body>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
<param name="movie" value="<%=swf_random%>" />
<param name="allowScriptAccess" value="always" />
<param name="FlashVars" value="id=<%=shellcode%>" />
<param name="Play" value="true" />
</object>
</body>
</html>
|
return html_template, binding()
end
def create_swf
path = ::File.join( Msf::Config.data_directory, "exploits", "CVE-2014-0497", "Vickers.swf" )
swf = ::File.open(path, 'rb') { |f| swf = f.read }
swf
end
end | 36.44697 | 168 | 0.565787 |
038f29c10098691079d5d2e16010884206d4f4ce | 2,845 | require 'trashed/test_helper'
require 'trashed/reporter'
require 'logger'
require 'stringio'
class ReporterTest < Minitest::Test
def setup
@reporter = Trashed::Reporter.new
@reporter.timing_sample_rate = 1
@reporter.gauge_sample_rate = 1
end
def test_sample_rate_defaults
assert_equal 0.1, Trashed::Reporter.new.timing_sample_rate
assert_equal 0.05, Trashed::Reporter.new.gauge_sample_rate
end
def test_report_logger
assert_report_logs 'Rack handled in 1.00ms.'
assert_report_logs 'Rack handled in 1.00ms (9.9% cpu, 90.1% idle).', :'Time.pct.cpu' => 9.9, :'Time.pct.idle' => 90.1
assert_report_logs 'Rack handled in 1.00ms.', :'GC.allocated_objects' => 0
assert_report_logs 'Rack handled in 1.00ms. 10 objects.', :'GC.allocated_objects' => 10
assert_report_logs 'Rack handled in 1.00ms. 0 GCs.', :'GC.count' => 0
assert_report_logs 'Rack handled in 1.00ms. 2 GCs.', :'GC.count' => 2
assert_report_logs 'Rack handled in 1.00ms. 2 GCs (3 major, 4 minor).', :'GC.count' => 2, :'GC.major_count' => 3, :'GC.minor_count' => 4
assert_report_logs 'Rack handled in 1.00ms. 2 GCs took 10.00ms.', :'GC.count' => 2, :'GC.time' => 10
assert_report_logs 'Rack handled in 1.00ms.', :'OOBGC.count' => 0
assert_report_logs 'Rack handled in 1.00ms. 0 GCs. Avoided 3 OOB GCs.', :'OOBGC.count' => 3
assert_report_logs 'Rack handled in 1.00ms. 0 GCs. Avoided 3 OOB GCs (4 major, 5 minor, 6 sweep).', :'OOBGC.count' => 3, :'OOBGC.major_count' => 4, :'OOBGC.minor_count' => 5, :'OOBGC.sweep_count' => 6
assert_report_logs 'Rack handled in 1.00ms. 0 GCs. Avoided 3 OOB GCs saving 10.00ms.', :'OOBGC.count' => 3, :'OOBGC.time' => 10
assert_report_logs 'Rack handled in 1.00ms (9.1% cpu, 90.1% idle). 10 objects. 2 GCs (3 major, 4 minor) took 10.00ms. Avoided 3 OOB GCs (4 major, 5 minor, 6 sweep) saving 10.00ms.',
:'Time.pct.cpu' => 9.1, :'Time.pct.idle' => 90.1,
:'GC.allocated_objects' => 10,
:'GC.count' => 2, :'GC.time' => 10,
:'GC.major_count' => 3, :'GC.minor_count' => 4,
:'OOBGC.count' => 3, :'OOBGC.time' => 10,
:'OOBGC.major_count' => 4, :'OOBGC.minor_count' => 5, :'OOBGC.sweep_count' => 6
end
def test_tagged_logger
@reporter.logger = logger = Logger.new(out = StringIO.new)
class << logger
attr_reader :tags
def tagged(tags) @tags = tags; yield end
end
@reporter.report_logger 'trashed.logger.tags' => %w(a b c), 'trashed.timings' => { :'Time.wall' => 1 }
assert_match 'Rack handled in 1.00ms.', out.string
assert_equal %w(a b c), logger.tags
end
private
def assert_report_logs(string, timings = {})
@reporter.logger = Logger.new(out = StringIO.new)
@reporter.report_logger 'trashed.timings' => timings.merge(:'Time.wall' => 1)
assert_match string, out.string
end
end
| 45.15873 | 204 | 0.660105 |
ed9f4fa1428942b5730a059df8611a35d7860430 | 203 | component "rubygem-aws-sdk-ec2" do |pkg, settings, platform|
pkg.version "1.259.0"
pkg.md5sum "e93081b9c457f7efda1299e19602d794"
instance_eval File.read('configs/components/_base-rubygem.rb')
end
| 29 | 64 | 0.773399 |
bb813d34486887daa074a1c9018fefc696b78055 | 253 | module Api
class BaseController < ApplicationController
before_action :doorkeeper_authorize!
respond_to :json
def render_json(results)
render json: results
.map(&:attributes)
.map(&:to_snake_keys)
end
end
end
| 18.071429 | 46 | 0.679842 |
260d11d1b34697b5eb8bbc63014e4e3edd9465a7 | 419 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_06_01
module Models
#
# Defines values for PcStatus
#
module PcStatus
NotStarted = "NotStarted"
Running = "Running"
Stopped = "Stopped"
Error = "Error"
Unknown = "Unknown"
end
end
end
| 22.052632 | 70 | 0.661098 |
ac0e01f83f8a2b37ff7a478ee5614f2fa1c81fdb | 3,334 | #
# Cookbook Name:: f5-bigip
# Library:: loader
#
# Copyright 2014, Target Corporation
#
# 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.
#
module F5
# rubocop:disable ClassVars, MethodLength
# Loader function to load data from f5 to compare resources to
module Loader
include F5::Helpers
#
# Convert to Array
#
# @param [Object] item to make sure is an Array
#
# @return [Array] if obj was already an Array it returns the obj. Otherwise
# returns a single element Array of the obj
#
def convert_to_array(obj)
obj = [obj] unless obj.is_a? Array
obj
end
# Method call to require f5-icontrol
# after chef_gem has had a chance to run
def load_dependencies
require 'f5-icontrol'
end
#
# Interfaces to load from F5 icontrol
#
# @return [Array<String>] list of interfaces to load from F5 icontrol
#
def interfaces
[
'LocalLB.Monitor',
'LocalLB.NodeAddressV2',
'LocalLB.Pool',
'LocalLB.VirtualServer',
'Management.DeviceGroup',
'System.ConfigSync',
'System.Failover',
'System.Inet'
]
end
#
# Retrieve/Create load balancer from list of load balancers for a resource
#
# @return [F5::LoadBalancer] instance of F5::LoadBalancer matching the resource
#
def load_balancer # rubocop:disable AbcSize
raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?
@@load_balancers ||= []
add_lb(@new_resource.f5) if @@load_balancers.empty?
add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?
@@load_balancers.find { |lb| lb.name == @new_resource.f5 }
end
#
# Add new load balancer to list of load balancers
#
# @param hostname [String] hostname of load balancer to add
#
def add_lb(hostname)
@@load_balancers << LoadBalancer.new(hostname, create_icontrol(hostname))
end
#
# Create icontrol binding for load balancer
#
# @param hostname [String] hostname of load balancer to create binding for
#
# @return [Hash] Hash of interfaces from F5::IControl
#
def create_icontrol(hostname) # rubocop:disable AbcSize
load_dependencies
f5_creds = chef_vault_item(node['f5-bigip']['credentials']['databag'], node['f5-bigip']['credentials']['item'])
if node['f5-bigip']['credentials']['host_is_key']
f5_creds = f5_creds[hostname]
else
f5_creds = f5_creds[node['f5-bigip']['credentials']['key']] unless node['f5-bigip']['credentials']['key'].empty?
end
F5::IControl.new(hostname,
f5_creds['username'],
f5_creds['password'],
interfaces).get_interfaces
end
end
end
| 31.158879 | 120 | 0.65147 |
268452f422637448e1ca20f979633662a10519bb | 5,381 | require 'set'
module ActiveRecord
module Associations
class AssociationCollection < AssociationProxy #:nodoc:
def to_ary
load_target
@target.to_ary
end
def reset
@target = []
@loaded = false
end
# Add +records+ to this association. Returns +self+ so method calls may be chained.
# Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
def <<(*records)
result = true
load_target
@owner.transaction do
flatten_deeper(records).each do |record|
raise_on_type_mismatch(record)
callback(:before_add, record)
result &&= insert_record(record) unless @owner.new_record?
@target << record
callback(:after_add, record)
end
end
result && self
end
alias_method :push, :<<
alias_method :concat, :<<
# Remove all records from this association
def delete_all
load_target
delete(@target)
@target = []
end
# Remove +records+ from this association. Does not destroy +records+.
def delete(*records)
records = flatten_deeper(records)
records.each { |record| raise_on_type_mismatch(record) }
records.reject! { |record| @target.delete(record) if record.new_record? }
return if records.empty?
@owner.transaction do
records.each { |record| callback(:before_remove, record) }
delete_records(records)
records.each do |record|
@target.delete(record)
callback(:after_remove, record)
end
end
end
# Removes all records from this association. Returns +self+ so method calls may be chained.
def clear
return self if length.zero? # forces load_target if hasn't happened already
if @reflection.options[:dependent] && @reflection.options[:dependent] == :delete_all
destroy_all
else
delete_all
end
self
end
def destroy_all
@owner.transaction do
each { |record| record.destroy }
end
@target = []
end
def create(attributes = {})
# Can't use Base.create since the foreign key may be a protected attribute.
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr) }
else
record = build(attributes)
record.save unless @owner.new_record?
record
end
end
# Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
# calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero
# and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length.
def size
if loaded? then @target.size else count_records end
end
# Returns the size of the collection by loading it and calling size on the array. If you want to use this method to check
# whether the collection is empty, use collection.length.zero? instead of collection.empty?
def length
load_target.size
end
def empty?
size.zero?
end
def uniq(collection = self)
collection.inject([]) { |uniq_records, record| uniq_records << record unless uniq_records.include?(record); uniq_records }
end
# Replace this collection with +other_array+
# This will perform a diff and delete/add only records that have changed.
def replace(other_array)
other_array.each { |val| raise_on_type_mismatch(val) }
load_target
other = other_array.size < 100 ? other_array : other_array.to_set
current = @target.size < 100 ? @target : @target.to_set
@owner.transaction do
delete(@target.select { |v| !other.include?(v) })
concat(other_array.select { |v| !current.include?(v) })
end
end
private
# Array#flatten has problems with recursive arrays. Going one level deeper solves the majority of the problems.
def flatten_deeper(array)
array.collect { |element| element.respond_to?(:flatten) ? element.flatten : element }.flatten
end
def callback(method, record)
callbacks_for(method).each do |callback|
case callback
when Symbol
@owner.send(callback, record)
when Proc, Method
callback.call(@owner, record)
else
if callback.respond_to?(method)
callback.send(method, @owner, record)
else
raise ActiveRecordError, "Callbacks must be a symbol denoting the method to call, a string to be evaluated, a block to be invoked, or an object responding to the callback method."
end
end
end
end
def callbacks_for(callback_name)
full_callback_name = "#{callback_name}_for_#{@reflection.name}"
@owner.class.read_inheritable_attribute(full_callback_name.to_sym) || []
end
end
end
end
| 33.42236 | 197 | 0.599703 |
f7f328058449aa3e32585743350d4481071d4de1 | 3,740 | require File.dirname(__FILE__) + '/../test_helper'
class DependencyTest < ActiveSupport::TestCase
should belong_to :rubygem
should belong_to :version
context "with dependency" do
setup do
@version = Factory(:version)
@dependency = FactoryGirl.build(:dependency, :version => @version)
end
should "be valid with factory" do
assert_valid @dependency
end
should "return JSON" do
@dependency.save
json = JSON.parse(@dependency.to_json)
assert_equal %w[name requirements], json.keys
assert_equal @dependency.rubygem.name, json["name"]
assert_equal @dependency.requirements, json["requirements"]
end
should "return XML" do
@dependency.save
xml = Nokogiri.parse(@dependency.to_xml)
assert_equal "dependency", xml.root.name
assert_equal %w[name requirements], xml.root.children.select(&:element?).map(&:name)
assert_equal @dependency.rubygem.name, xml.at_css("name").content
assert_equal @dependency.requirements, xml.at_css("requirements").content
end
should "return YAML" do
@dependency.save
yaml = YAML.load(@dependency.to_yaml)
assert_equal %w[name requirements], yaml.keys
assert_equal @dependency.rubygem.name, yaml["name"]
assert_equal @dependency.requirements, yaml["requirements"]
end
should "be pushed onto a redis list if a runtime dependency" do
@dependency.save
assert_equal "#{@dependency.name} #{@dependency.requirements}", $redis.lindex(Dependency.runtime_key(@version.full_name), 0)
end
should "not push development dependency onto the redis list" do
@dependency = Factory(:development_dependency)
assert !$redis.exists(Dependency.runtime_key(@dependency.version.full_name))
end
end
context "with a Gem::Dependency" do
context "that refers to a Rubygem that exists" do
setup do
@rubygem = Factory(:rubygem)
@requirements = ['>= 0.0.0']
@gem_dependency = Gem::Dependency.new(@rubygem.name, @requirements)
@dependency = Factory(:dependency, :rubygem => @rubygem, :gem_dependency => @gem_dependency)
end
should "create a Dependency referring to the existing Rubygem" do
assert_equal @rubygem, @dependency.rubygem
assert_equal @requirements[0].to_s, @dependency.requirements
end
end
context "that refers to a Rubygem that exists and has multiple requirements" do
setup do
@rubygem = Factory(:rubygem)
@requirements = ['< 1.0.0', '>= 0.0.0']
@gem_dependency = Gem::Dependency.new(@rubygem.name, @requirements)
@dependency = Factory(:dependency, :rubygem => @rubygem, :gem_dependency => @gem_dependency)
end
should "create a Dependency referring to the existing Rubygem" do
assert_equal @rubygem, @dependency.rubygem
assert_equal @requirements.join(', '), @dependency.requirements
end
end
context "that refers to a Rubygem that does not exist" do
setup do
@rubygem_name = 'other-name'
@gem_dependency = Gem::Dependency.new(@rubygem_name, "= 1.0.0")
end
should "not create rubygem" do
dependency = Dependency.create(:gem_dependency => @gem_dependency)
assert dependency.new_record?
assert dependency.errors[:base].present?
assert_nil Rubygem.find_by_name(@rubygem_name)
end
end
end
context "without using Gem::Dependency" do
should "be invalid" do
dependency = Dependency.create(:gem_dependency => ["ruby-ajp", ">= 0.2.0"])
assert dependency.new_record?
assert dependency.errors[:rubygem].present?
end
end
end
| 34 | 130 | 0.670321 |
1dad8d5118318eee115360193a9b1bd2878e8047 | 856 | Pod::Spec.new do |s|
s.name = "SwiftMandrill"
s.version = "1.0.4"
s.summary = "A simple iOS client for the Mandrill Mail API"
s.description = <<-DESC
SwiftMandrill provides simple alternative when you need to send an email with your iOS app.
DESC
s.homepage = "https://github.com/PiXeL16/SwiftMandrill"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Chris Jimenez" => "[email protected]" }
s.social_media_url = "http://twitter.com/chrisjimeneznat"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/Adrage/SwiftMandrill.git", :tag => s.version }
s.source_files = "SwiftMandrill/", "SwiftMandrill/**/*.{h,m,swift}"
s.requires_arc = true
s.dependency 'ObjectMapper', '~> 2.2'
s.dependency 'Alamofire', '~> 4.3'
end
| 32.923077 | 106 | 0.606308 |
d5d59943bdf85532421233537ecbee72ea72ec9f | 497 | # frozen_string_literal: true
class CreateOutboundWebhooks < ActiveRecord::Migration[4.2]
def change
create_table :outbound_webhooks do |t|
t.timestamps null: false
t.timestamp :deleted_at, default: nil
t.integer :project_id, null: false
t.integer :stage_id, null: false
t.string :url, null: false
t.string :username
t.string :password
end
add_index :outbound_webhooks, :deleted_at
add_index :outbound_webhooks, :project_id
end
end
| 24.85 | 59 | 0.700201 |
f8afb9d9dd484b66be9af026a80b762fbde4718b | 1,484 | require 'thread'
# used to run concurrent sneaql transforms
# from a threadsafe queue.
class ParallelizeSneaqlTransforms
# initialize object and run concurrent transforms.
# @param [Queue] queue_to_process queue of hashes with all params needed for transform
# @param [Fixnum] concurrency number of threads
# @param [Logger] logger optional logger object
def initialize(queue_to_process, concurrency, logger = nil)
@logger = logger ? logger : Logger.new(STDOUT)
@queue_to_process = queue_to_process
@concurrency = concurrency
parallelize
end
# performs the actual parallel execution
def parallelize
@logger.info(
"processing #{@queue_to_process} with a concurrency of #{@concurrency}..."
)
threads = []
@concurrency.times do
threads << Thread.new do
# loop until there are no more things to do
until @queue_to_process.empty?
begin
object_to_process = @queue_to_process.pop(true) rescue nil
# logger.debug(object_to_process)
t = Sneaql::Transform.new(
object_to_process,
@logger
)
t.run
rescue => e
@logger.error(e.message)
e.backtrace.each { |b| @logger.error(b) }
ensure
@logger.info("finished processing #{object_to_process['transform_name']}")
end
end
end
end
threads.each { |t| t.join }
threads = nil
end
end
| 30.285714 | 88 | 0.634771 |
38020030114915e87c8d4269770e9e56462d7902 | 9,640 | require 'xsd/qname'
module AdwordsApi; module V13; module AccountService
# AccountInfo
# - billingAddress - AdwordsApi::V13::AccountService::Address
# - currencyCode - SOAP::SOAPString
# - customerId - SOAP::SOAPLong
# - defaultNetworkTargeting - AdwordsApi::V13::AccountService::NetworkTarget
# - descriptiveName - SOAP::SOAPString
# - emailPromotionsPreferences - AdwordsApi::V13::AccountService::EmailPromotionsPreferences
# - languagePreference - SOAP::SOAPString
# - primaryAddress - AdwordsApi::V13::AccountService::Address
# - primaryBusinessCategory - SOAP::SOAPString
# - timeZoneEffectiveDate - SOAP::SOAPLong
# - timeZoneId - SOAP::SOAPString
class AccountInfo
attr_accessor :billingAddress
attr_accessor :currencyCode
attr_accessor :customerId
attr_accessor :defaultNetworkTargeting
attr_accessor :descriptiveName
attr_accessor :emailPromotionsPreferences
attr_accessor :languagePreference
attr_accessor :primaryAddress
attr_accessor :primaryBusinessCategory
attr_accessor :timeZoneEffectiveDate
attr_accessor :timeZoneId
def initialize(billingAddress = nil, currencyCode = nil, customerId = nil, defaultNetworkTargeting = nil, descriptiveName = nil, emailPromotionsPreferences = nil, languagePreference = nil, primaryAddress = nil, primaryBusinessCategory = nil, timeZoneEffectiveDate = nil, timeZoneId = nil)
@billingAddress = billingAddress
@currencyCode = currencyCode
@customerId = customerId
@defaultNetworkTargeting = defaultNetworkTargeting
@descriptiveName = descriptiveName
@emailPromotionsPreferences = emailPromotionsPreferences
@languagePreference = languagePreference
@primaryAddress = primaryAddress
@primaryBusinessCategory = primaryBusinessCategory
@timeZoneEffectiveDate = timeZoneEffectiveDate
@timeZoneId = timeZoneId
end
end
# Address
# - addressLine1 - SOAP::SOAPString
# - addressLine2 - SOAP::SOAPString
# - city - SOAP::SOAPString
# - companyName - SOAP::SOAPString
# - countryCode - SOAP::SOAPString
# - emailAddress - SOAP::SOAPString
# - faxNumber - SOAP::SOAPString
# - name - SOAP::SOAPString
# - phoneNumber - SOAP::SOAPString
# - postalCode - SOAP::SOAPString
# - state - SOAP::SOAPString
class Address
attr_accessor :addressLine1
attr_accessor :addressLine2
attr_accessor :city
attr_accessor :companyName
attr_accessor :countryCode
attr_accessor :emailAddress
attr_accessor :faxNumber
attr_accessor :name
attr_accessor :phoneNumber
attr_accessor :postalCode
attr_accessor :state
def initialize(addressLine1 = nil, addressLine2 = nil, city = nil, companyName = nil, countryCode = nil, emailAddress = nil, faxNumber = nil, name = nil, phoneNumber = nil, postalCode = nil, state = nil)
@addressLine1 = addressLine1
@addressLine2 = addressLine2
@city = city
@companyName = companyName
@countryCode = countryCode
@emailAddress = emailAddress
@faxNumber = faxNumber
@name = name
@phoneNumber = phoneNumber
@postalCode = postalCode
@state = state
end
end
# ApiError
# - code - SOAP::SOAPInt
# - detail - SOAP::SOAPString
# - field - SOAP::SOAPString
# - index - SOAP::SOAPInt
# - isExemptable - SOAP::SOAPBoolean
# - textIndex - SOAP::SOAPInt
# - textLength - SOAP::SOAPInt
# - trigger - SOAP::SOAPString
class ApiError
attr_accessor :code
attr_accessor :detail
attr_accessor :field
attr_accessor :index
attr_accessor :isExemptable
attr_accessor :textIndex
attr_accessor :textLength
attr_accessor :trigger
def initialize(code = nil, detail = nil, field = nil, index = nil, isExemptable = nil, textIndex = nil, textLength = nil, trigger = nil)
@code = code
@detail = detail
@field = field
@index = index
@isExemptable = isExemptable
@textIndex = textIndex
@textLength = textLength
@trigger = trigger
end
end
# ApiException
# - code - SOAP::SOAPInt
# - errors - AdwordsApi::V13::AccountService::ApiError
# - internal - SOAP::SOAPBoolean
# - message - SOAP::SOAPString
# - trigger - SOAP::SOAPString
class ApiException
attr_accessor :code
attr_accessor :errors
attr_accessor :internal
attr_accessor :message
attr_accessor :trigger
def initialize(code = nil, errors = [], internal = nil, message = nil, trigger = nil)
@code = code
@errors = errors
@internal = internal
@message = message
@trigger = trigger
end
end
# ClientAccountInfo
# - emailAddress - SOAP::SOAPString
# - isCustomerManager - SOAP::SOAPBoolean
class ClientAccountInfo
attr_accessor :emailAddress
attr_accessor :isCustomerManager
def initialize(emailAddress = nil, isCustomerManager = nil)
@emailAddress = emailAddress
@isCustomerManager = isCustomerManager
end
end
# EmailPromotionsPreferences
# - accountPerformanceEnabled - SOAP::SOAPBoolean
# - disapprovedAdsEnabled - SOAP::SOAPBoolean
# - marketResearchEnabled - SOAP::SOAPBoolean
# - newsletterEnabled - SOAP::SOAPBoolean
# - promotionsEnabled - SOAP::SOAPBoolean
class EmailPromotionsPreferences
attr_accessor :accountPerformanceEnabled
attr_accessor :disapprovedAdsEnabled
attr_accessor :marketResearchEnabled
attr_accessor :newsletterEnabled
attr_accessor :promotionsEnabled
def initialize(accountPerformanceEnabled = nil, disapprovedAdsEnabled = nil, marketResearchEnabled = nil, newsletterEnabled = nil, promotionsEnabled = nil)
@accountPerformanceEnabled = accountPerformanceEnabled
@disapprovedAdsEnabled = disapprovedAdsEnabled
@marketResearchEnabled = marketResearchEnabled
@newsletterEnabled = newsletterEnabled
@promotionsEnabled = promotionsEnabled
end
end
# MccAlert
# - clientCompanyName - SOAP::SOAPString
# - clientCustomerId - SOAP::SOAPLong
# - clientLogin - SOAP::SOAPString
# - clientName - SOAP::SOAPString
# - priority - AdwordsApi::V13::AccountService::MccAlertPriority
# - triggerTime - SOAP::SOAPDateTime
# - type - AdwordsApi::V13::AccountService::MccAlertType
class MccAlert
attr_accessor :clientCompanyName
attr_accessor :clientCustomerId
attr_accessor :clientLogin
attr_accessor :clientName
attr_accessor :priority
attr_accessor :triggerTime
attr_accessor :type
def initialize(clientCompanyName = nil, clientCustomerId = nil, clientLogin = nil, clientName = nil, priority = nil, triggerTime = nil, type = nil)
@clientCompanyName = clientCompanyName
@clientCustomerId = clientCustomerId
@clientLogin = clientLogin
@clientName = clientName
@priority = priority
@triggerTime = triggerTime
@type = type
end
end
# NetworkTarget
# - networkTypes - AdwordsApi::V13::AccountService::NetworkType
class NetworkTarget
attr_accessor :networkTypes
def initialize(networkTypes = [])
@networkTypes = networkTypes
end
end
# MccAlertPriority
class MccAlertPriority < ::String
High = MccAlertPriority.new("High")
Low = MccAlertPriority.new("Low")
end
# MccAlertType
class MccAlertType < ::String
AccountBudgetBurnRate = MccAlertType.new("AccountBudgetBurnRate")
AccountBudgetEnding = MccAlertType.new("AccountBudgetEnding")
AccountOnTarget = MccAlertType.new("AccountOnTarget")
CampaignEnded = MccAlertType.new("CampaignEnded")
CampaignEnding = MccAlertType.new("CampaignEnding")
CreativeDisapproved = MccAlertType.new("CreativeDisapproved")
CreditCardExpiring = MccAlertType.new("CreditCardExpiring")
DeclinedPayment = MccAlertType.new("DeclinedPayment")
KeywordBelowMinCpc = MccAlertType.new("KeywordBelowMinCpc")
MissingBankReferenceNumber = MccAlertType.new("MissingBankReferenceNumber")
PaymentNotEntered = MccAlertType.new("PaymentNotEntered")
end
# NetworkType
class NetworkType < ::String
ContentNetwork = NetworkType.new("ContentNetwork")
GoogleSearch = NetworkType.new("GoogleSearch")
SearchNetwork = NetworkType.new("SearchNetwork")
end
# getAccountInfo
class GetAccountInfo #:nodoc: all
def initialize
end
end
# getAccountInfoResponse
# - getAccountInfoReturn - AdwordsApi::V13::AccountService::AccountInfo
class GetAccountInfoResponse #:nodoc: all
attr_accessor :getAccountInfoReturn
def initialize(getAccountInfoReturn = nil)
@getAccountInfoReturn = getAccountInfoReturn
end
end
# getClientAccountInfos
class GetClientAccountInfos #:nodoc: all
def initialize
end
end
# getClientAccountInfosResponse
# - getClientAccountInfosReturn - AdwordsApi::V13::AccountService::ClientAccountInfo
class GetClientAccountInfosResponse #:nodoc: all
attr_accessor :getClientAccountInfosReturn
def initialize(getClientAccountInfosReturn = [])
@getClientAccountInfosReturn = getClientAccountInfosReturn
end
end
# getClientAccounts
class GetClientAccounts #:nodoc: all
def initialize
end
end
# getClientAccountsResponse
# - getClientAccountsReturn - SOAP::SOAPString
class GetClientAccountsResponse #:nodoc: all
attr_accessor :getClientAccountsReturn
def initialize(getClientAccountsReturn = [])
@getClientAccountsReturn = getClientAccountsReturn
end
end
# getMccAlerts
class GetMccAlerts #:nodoc: all
def initialize
end
end
# getMccAlertsResponse
# - getMccAlertsReturn - AdwordsApi::V13::AccountService::MccAlert
class GetMccAlertsResponse #:nodoc: all
attr_accessor :getMccAlertsReturn
def initialize(getMccAlertsReturn = [])
@getMccAlertsReturn = getMccAlertsReturn
end
end
# updateAccountInfo
# - accountInfo - AdwordsApi::V13::AccountService::AccountInfo
class UpdateAccountInfo #:nodoc: all
attr_accessor :accountInfo
def initialize(accountInfo = nil)
@accountInfo = accountInfo
end
end
# updateAccountInfoResponse
class UpdateAccountInfoResponse #:nodoc: all
def initialize
end
end
end; end; end
| 29.937888 | 290 | 0.771577 |
21392f1780826589ecc87e98358ef11c1fb49f53 | 282 | #!/usr/bin/env ruby
require 'dcell/explorer'
require_relative 'options'
explorer_host = 'localhost'
explorer_port = 7778
DCell.start registry: registry
DCell::Explorer.new explorer_host, explorer_port
puts "Visit explorer page at http://#{explorer_host}:#{explorer_port}"
sleep
| 20.142857 | 70 | 0.783688 |
1d180734adb63cf89edfcd65fc4a8f1cedc55384 | 1,551 | require_relative 'helper'
require 'zendesk/deployment/restart'
describe Zendesk::Deployment::Restart do
let(:exclude_services) { [] }
let(:allow_check_services_failure) { false }
before do
cap.extend(Zendesk::Deployment::Restart)
cap.set :application, 'test_app'
cap.set :exclude_services, exclude_services if exclude_services.any?
cap.set :allow_check_services_failure, allow_check_services_failure if allow_check_services_failure
end
describe 'deploy:restart' do
before { cap.find_and_execute_task('deploy:restart') }
it 'must use reload_services and check_services' do
cap.must_have_run('sudo /usr/local/bin/reload_services test_app')
cap.must_have_run('sudo /usr/local/bin/check_services test_app')
end
describe 'with excluded services' do
let(:exclude_services) { ['test_service', 'test_service1'] }
it 'must use reload_services and exclude the specified services' do
cap.must_have_run('sudo /usr/local/bin/reload_services -s test_service -s test_service1 test_app')
end
it 'must use check all services' do
cap.must_have_run('sudo /usr/local/bin/check_services test_app')
end
end
describe "with allow_check_services_failure" do
let(:allow_check_services_failure) { true }
it 'must ignore check_services failure' do
cap.must_have_run('sudo /usr/local/bin/reload_services test_app')
cap.must_have_run("sudo /usr/local/bin/check_services test_app || echo 'Failure ignored'")
end
end
end
end
| 33.717391 | 106 | 0.728562 |
ac5b664697f42986b2cb875b2ff4bb0a0a9a42a6 | 172 | # -*- coding: binary -*-
module Rex
module Java
module Serialization
module Model
class NullReference < Element
end
end
end
end
end | 14.333333 | 37 | 0.587209 |
28da2f31b3cb4b16f46495bac1dfae91c04d8faa | 134 | # frozen_string_literal: true
FactoryGirl.define do
factory :comment do
content 'MyText'
post_id 1
user_id 1
end
end
| 13.4 | 29 | 0.708955 |
79a9488c539aa6fb7ea683da22d30624bd3adcb8 | 7,909 | require File.dirname(__FILE__) + '/spec_helper'
describe "Pages" do
in_contexts do
before(:each) do
@pages = @articles.pages
@per_page = 2
@articles.stub!(:per_page).and_return(@per_page)
@articles.stub!(:page_name).and_return("Page")
end
it "should raise an error if per_page is not specified" do
@articles.stub!(:per_page).and_return(nil)
lambda { @pages.per_page }.should raise_error(RuntimeError)
end
it "should paginate using per_page from its proxy if available" do
@articles.stub!(:per_page).and_return(@per_page)
@pages.per_page.should == @per_page
end
it "should be a class" do
@pages.should be_a_kind_of(Class)
end
it "should be a class with name of the proxy's page name" do
@pages.name.should == "Page"
end
it "should know the page count" do
@pages.count.should == (@articles.all.length - 1)/@per_page + 1
end
it "should cache the page count" do
@articles.should_receive(:count).and_return(1)
2.times { @pages.count }
end
it "should clear the count cache when reloaded" do
@articles.should_receive(:count).twice.and_return(1)
@pages.count
@pages.reload!
@pages.count
end
it "should find pages with valid numbers" do
1.upto(@pages.count) do |number|
lambda { @pages.find(number) }.should_not raise_error
end
end
it "should cache the results of find" do
@pages.should_receive(:new).once
2.times { @pages.find(1) }
end
it "should clear the find cache when reloaded" do
@pages.should_receive(:new).twice
@pages.find(1)
@pages.reload!
@pages.find(1)
end
it "should raise an error containing the nearest substitute page for invalid page numbers" do
[ [ -1, @pages.first], [ 0, @pages.first ], [ @pages.count + 1, @pages.last ] ].each do |number, substitute_page|
lambda { @pages.find(number) }.should raise_error do |error|
error.substitute.should == substitute_page
end
end
end
it "should be enumerable" do
@pages.metaclass.included_modules.should include(Enumerable)
@pages.should respond_to(:each)
args_for_each = []
@pages.each { |page| args_for_each << page }
args_for_each.should == ([email protected]).map { |number| @pages.find(number) }
end
it "should find the first page" do
@pages.first.number.should == 1
end
it "should find the last page" do
@pages.last.number.should == @pages.count
end
it "should find all pages" do
@pages.all.should == ([email protected]).map { |number| @pages.find(number) }
end
it "should find a page closest to a given number" do
@pages.closest_to(0 ).should == @pages.first
@pages.closest_to(@pages.count ).should == @pages.last
@pages.closest_to(@pages.count + 1).should == @pages.last
end
it "should find the page of an object in the collection" do
@articles.all.each_with_index do |article, index|
@pages.find_by_article(article).number.should == 1 + index/@pages.per_page
end
end
it "should not find the page of an object not in the collection" do
(Article.all - @articles.all).each do |article|
@pages.find_by_article(article).should be_nil
lambda { @pages.find_by_article!(article) }.should raise_error(PagedScopes::PageNotFound)
end
end
it "should not find the page of an object if the object is a new record" do
lambda { @pages.find_by_article!(Article.new) }.should raise_error(PagedScopes::PageNotFound)
end
it "should not find the page of an object if the object is not an ActiveRecord::Base instance" do
lambda { @pages.find_by_article!(Object.new) }.should raise_error(PagedScopes::PageNotFound)
end
it "should find a page from a params hash with a pages name as an id in the key" do
@pages.stub!(:name).and_return("Page")
@pages.from_params!(:page_id => "1").should == @pages.first
end
it "should find a nil page from a params hash without a pages name as an id in the key" do
@pages.stub!(:name).and_return("Page")
@pages.from_params!({}).should be_nil
end
it "should raise an error from a params hash containing an out-of-range page id in the key" do
@pages.stub!(:name).and_return("Page")
lambda { @pages.from_params!(:page_id => @pages.count + 1) }.should raise_error(PagedScopes::PageNotFound)
end
end
context "for an empty collection" do
before(:each) do
@articles = Article.scoped(:conditions => { :title => "Supercalifragilisticexpialidocious" })
@articles.all.should be_empty
@articles.per_page = 2
end
it "should have one page" do
@articles.pages.count.should == 1
end
it "should have a page numbered one" do
@articles.pages.first.number.should == 1
end
it "should have an empty page" do
@articles.pages.first.articles.all.should be_empty
end
end
end
describe "Page instance" do
in_contexts do
before(:each) do
@pages = @articles.pages
@per_page = 2
@articles.stub!(:per_page).and_return(@per_page)
end
it "should have a scope representing the objects in the page" do
@pages.each { |page| page.articles.class.should == ActiveRecord::NamedScope::Scope }
end
it "should know its number" do
@pages.find(1).number.should == 1
end
it "should parameterise to the page number" do
@pages.map(&:to_param).should == @pages.map(&:number).map(&:to_s)
end
it "should have the page number as id" do
@pages.map(&:id).should == @pages.map(&:number)
end
it "should clear the page class cache when reloaded" do
@pages.should_receive(:reload!)
@pages.first.reload!
end
it "should be found again by the page class when reloaded" do
@page = @pages.first
@pages.should_receive(:find).with(@page.number)
@page.reload!
end
it "should know whether it's first" do
pages = @pages.all
pages.shift.should be_first
pages.each { |page| page.should_not be_first }
end
it "should know whether it's last" do
pages = @pages.all
pages.pop.should be_last
pages.each { |page| page.should_not be_last }
end
it "should know the next page" do
pages = @pages.all
until pages.empty? do
pages.shift.next.should == pages.first
end
end
it "should know the previous page" do
pages = @pages.all
until pages.empty? do
pages.pop.previous.should == pages.last
end
end
it "should know the page which is offset by a specified amount" do
[ -2, 0, +2 ].each do |offset|
pages = @pages.all
pages.each_with_index do |page, index|
page.offset(offset).should == (index + offset < 0 ? nil : pages[index + offset])
end
end
end
it "should be equal based on its page number" do
@pages.find(1).should == @pages.find(1)
@pages.find(1).should_not == @pages.find(2)
end
it "should know the page count" do
@pages.first.page_count.should == @pages.count
end
it "should be sortable by page number" do
@pages.all.reverse.sort.should == @pages.all
end
it "should know whether it's full" do
@pages.each do |page|
page.articles.all.length == @per_page ? page.should(be_full) : page.should_not(be_full)
end
end
it "should be correctly paginated and ordered" do
@pages.map(&:articles).should == @articles.all.in_groups_of(@per_page, false)
end
end
end
| 31.636 | 119 | 0.626754 |
ac45b53ada8f0a78dc84f103dfc7017cde915cf9 | 127 | class AddDummyBlobToQuestions < ActiveRecord::Migration
def change
add_column :questions, :dummy_blob, :string
end
end
| 21.166667 | 55 | 0.779528 |
7a4a25655e3ccd2615b8cd1db1ebe5c249e7b50a | 1,254 | # 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-shield'
spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip
spec.summary = 'AWS SDK for Ruby - AWS Shield'
spec.description = 'Official AWS Ruby gem for AWS Shield. 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/version-3/gems/aws-sdk-shield',
'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-shield/CHANGELOG.md'
}
spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.120.0')
spec.add_dependency('aws-sigv4', '~> 1.1')
spec.required_ruby_version = '>= 2.3'
end
| 38 | 110 | 0.661882 |
bb58c62f708285fd5e6f7de33a5a8aaf870c0bf5 | 2,353 | module Jets::Job::Dsl
module DynamodbEvent
def dynamodb_event(table_name, options={})
return if ENV['JETS_BUILD_NO_INTERNET'] # Disable during build since jets build tries to init this
stream_arn = full_dynamodb_stream_arn(table_name)
default_iam_policy = default_dynamodb_stream_policy(stream_arn)
# Create iam policy allows access to queue
# Allow disabling in case use wants to add permission application-wide and not have extra IAM policy
iam_policy_props = options.delete(:iam_policy) || @iam_policy || default_iam_policy
iam_policy(iam_policy_props) unless iam_policy_props == :disable
props = options # by this time options only has EventSourceMapping properties
default = {
event_source_arn: stream_arn,
starting_position: "TRIM_HORIZON",
}
props = default.merge(props)
event_source_mapping(props)
end
# Expands table name to the full stream arn. Example:
#
# test-table
# To:
# arn:aws:dynamodb:us-west-2:112233445566:table/test-table/stream/2019-02-15T21:41:15.217
#
# Note, this does not check if the stream has been disabled.
def full_dynamodb_stream_arn(table_name)
return table_name if table_name.include?("arn:aws:dynamodb") # assume full stream arn
begin
resp = dynamodb.describe_table(table_name: table_name)
rescue Aws::DynamoDB::Errors::ResourceNotFoundException => e
puts e.message
puts "ERROR: Was not able to find the DynamoDB table: #{table_name}.".color(:red)
code_line = caller.grep(%r{/app/jobs}).first
puts "Please check: #{code_line}"
puts "Exiting"
exit 1
end
stream_arn = resp.table.latest_stream_arn
return stream_arn if stream_arn
end
def default_dynamodb_stream_policy(stream_name_arn='*')
stream = {
action: ["dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:DescribeStream",
"dynamodb:ListStreams"],
effect: "Allow",
resource: stream_name_arn,
}
table_name_arn = stream_name_arn.gsub(%r{/stream/20.*},'')
table = {
action: ["dynamodb:DescribeTable"],
effect: "Allow",
resource: table_name_arn,
}
[stream, table]
end
end
end | 35.119403 | 106 | 0.661283 |
33cfca732cab380edf8b80db3cf5859323e77ab3 | 120 | class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true, email: true
end
| 17.142857 | 47 | 0.741667 |
18a41b1c95b196989f5150aa2cdd306add7b55a4 | 12,029 | #! /usr/bin/env ruby
require 'webrick'
require 'optparse'
require 'ostruct'
include WEBrick
# We are a servlet for the WEBRick server that we are creating.
class DoppioServer
attr_accessor :server, :serverpid, :expIndex, :experiments
module Mode
DEV = 0
BMK = 1
REL = 2
end
module Browser
CHROME = "chrome"
FIREFOX = "firefox"
SAFARI = "safari"
OPERA = "opera"
end
##############################################################################
# Attributes
##############################################################################
# Contains all of the command line options.
def options
@options
end
# While long, this performs all of the needed sanity checks for command line
# options.
def options=(args)
options = OpenStruct.new
# Defaults.
options.verbosity = 1
options.mode = Mode::REL
options.logdir = "./logs"
opts = OptionParser.new do |opts|
opts.banner = "Usage: webrick.rb -[r|d|b [scripts] -w [browsers] -e " +
"[experiment]] [options]"
opts.on("-r", "--release", "Host Doppio in release mode") do |r|
options.mode = Mode::REL
end
opts.on("-d", "--dev", "Host Doppio in development mode") do |d|
options.mode = Mode::DEV
end
opts.on("-b", "--benchmark script1,script2,...", Array, "Host Doppio " +
"in benchmark mode with the specified benchmark scripts") do |scripts|
if scripts.empty?
opts.abort "You must specify at least one benchmark script."
end
scripts.each do |script|
if !File::readable? script
opts.abort "Unable to read benchmark script " + script + "."
elsif !File::file? script
opts.abort "Not a file: " + script
end
end
options.mode = Mode::BMK
options.scripts = scripts
end
opts.on("-w", "--browser browsername:browser1,browsername:browser2,...",
Array, "Run benchmarking scripts in the given browsers. Recognized " +
"browsers are [firefox|chrome|opera|safari].") do |browsers|
if browsers.empty?
opts.abort "You must specify at least one browser."
end
# Map return value of loop back into browsers array.
browsers.collect! do |browser|
spBrowser = browser.split(':')
browserName = spBrowser[0]
# Gross
case browserName
when Browser::FIREFOX
when Browser::OPERA
when Browser::CHROME
when Browser::SAFARI
else
opts.abort "ERROR: Invalid browser type: " + browserName
end
browserFilename = spBrowser[1]
# See if we can find it on the path.
errorMsg = ''
error = false
paths = ENV['PATH'].split(':')
# For Mac users.
paths.unshift('/Applications')
# Current directory takes second priority.
paths.unshift('.')
# Absolute path takes first priority.
paths.unshift('')
browserPath = ""
# Finds the true browserPath, or sets error to 'true' with an optional
# error message.
# Ugly, but it works! 8D
paths.each do |path|
if path != ''
browserPath = path + "/" + browserFilename
else
browserPath = browserFilename
end
# Bad if File exists.
if !File::exists? browserPath
# NOP
# Bad if not a file and not a directory that is a Mac application.
elsif !File::file? browserPath and (!File::directory? browserPath or
!browserPath.split('.').last == 'app')
errorMsg = "Not a file or Mac application: " + browserPath
# Bad if it's not executable, whether a file or a Mac app directory.
elsif !File::executable? browserPath
errorMsg = "The following browser is not executable: " +
browserPath
else
# It's either a Mac application or an executable file, which is
# what we want.
error = false
break
end
# Last ditch effort: Is it a .app w/o the extension?
newBp = browserPath + ".app"
if File::directory? newBp and File::executable? newBp
browserPath = newBp
error = false
break
end
# Loop didn't terminate yet. We encountered an error.
error = true
end
if error
if errorMsg != ""
opts.abort errorMsg
else
opts.abort "Unable to find browser: " + browserFilename
end
end
browserName + ":" + browserPath
end
options.browsers = browsers
end
opts.on("-e", "--experiment name", "Specifies the name of the " +
"experiment. Used for log file naming.") do |e|
options.exp = e
end
opts.separator ""
opts.separator "Common options:"
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on_tail("-v", "--verbosity N", OptionParser::DecimalInteger,
"Specify the level of verbosity [0-3]") do |v|
if v > 3 || v < 0
opts.abort "Invalid verbosity option (verbosity should be in the "+
"range [0-3])."
end
options.verbosity = v
end
end
opts.parse!(ARGV)
# Sanity checks. Need to specify *browsers* and *scripts* for benchmark
# mode.
if options.mode == Mode::BMK and (options.browsers == nil or
options.scripts == nil or options.exp == nil)
abort "In benchmark mode, you must specify at least one browser, at " +
"least one script, and an experiment name."
end
# Create needed Experiment objects.
if options.mode == Mode::BMK
# Create log directory if needed.
fullLogDir = options.logdir + "/" + options.exp
Dir::mkdir(options.logdir) unless File::exists? options.logdir
Dir::mkdir(fullLogDir) unless File::exists? fullLogDir
logNum = 0
options.browsers.each do |browser|
options.scripts.each do |script|
logFile = fullLogDir + "/log" + logNum.to_s +
".log"
if File::exists? logFile
puts "ERROR: Log file exists: " + logFile
exit()
end
@experiments.push(Experiment.new(self, browser, script, logFile))
logNum += 1
end
end
end
@options = options
p3 "Input options: "
p3 options
end
##############################################################################
# Experiment Class + Experiment Helper Methods
##############################################################################
def addExperiment(exp)
@experiments.push(exp)
end
def getCurrentExperiment()
@experiments[@expIndex]
end
def nextExperiment()
# Stop the current experiment.
getCurrentExperiment().stop()
# Advance to the next experiment.
@expIndex += 1
# Check if we are done experimenting.
if @expIndex >= @experiments.length
@server.stop()
return
end
# Start the next experiment.
getCurrentExperiment().start()
end
class Experiment
attr_accessor :outer, :browserPath, :browserName, :browserPid, :script, :logfile
def getMainExecutableName()
case @browserName
when Browser::FIREFOX then 'firefox'
when Browser::CHROME then 'Google Chrome'
when Browser::SAFARI then 'Safari'
when Browser::OPERA then 'Opera'
end
end
def initialize(outer, browser, script, logfile)
@outer = outer
spBrowser = browser.split(':')
@browserName = spBrowser[0]
@browserPath = spBrowser[1]
@browserPid = nil
@script = File.read(script)
@logfile = File.new(logfile, "w")
end
def start()
# Print starting line.
writeMessage("EXPERIMENT BEGIN: " + Time.now.to_s + "\n")
writeMessage("BROWSER: " + @browserName + ":" + @browserPath + "\n")
writeMessage("SCRIPT: " + @script + "\n")
# Launch the browser.
@browserPid = spawn('open', '-a', @browserPath, 'http://localhost:8000/')
end
def stop()
# Print ending line.
writeMessage("\nEXPERIMENT END: " + Time.now.to_s + "\n")
# Close the logfile.
@logfile.close()
# Kill the browser.
system('killall', getMainExecutableName())
end
def writeMessage(txt)
@outer.p3 "MESSAGE: " + txt
@logfile.write(txt)
@logfile.flush()
end
def writeError(error)
@outer.p3 "ERROR: " + error
@logfile.write("DOPPIO EXPERIMENT ERROR: " + error + "\n")
@logfile.flush()
end
end
##############################################################################
# WEBRick Request Handlers
##############################################################################
class DoppioServlet < HTTPServlet::AbstractServlet
attr_accessor :path, :outer
# Initialize with reference to outer class.
def initialize(server, path, outer)
@path = path
@outer = outer
end
def do_GET(request, response)
response.status = 200
response['Content-Type'] = 'text/html'
response.body = @outer.getCurrentExperiment().script
end
def do_POST(request, response)
body = request.body()
response.status = 200
response['Content-Type'] = "text/html"
response.body = "Success."
exp = @outer.getCurrentExperiment()
case @path
when "/complete"
@outer.nextExperiment()
when "/message"
exp.writeMessage(body)
when "/error"
exp.writeError(body)
end
end
end
##############################################################################
# Other Methods
##############################################################################
def initialize(args)
@expIndex = 0
@experiments = []
self.options = args
end
def Mode2String(mode)
case mode
when Mode::DEV
return 'development'
when Mode::BMK
return 'benchmark'
else
return 'release'
end
end
# Handles printing at various verbosities.
def p1(message)
pn(1, message)
end
def p2(message)
pn(2, message)
end
def p3(message)
pn(3, message)
end
def pn(n, message)
if n <= options.verbosity
puts message
end
end
def start()
doppioRoot = "#{File.dirname __FILE__}/.."
documentRoot = doppioRoot
case @options.mode
when Mode::REL
documentRoot = doppioRoot + "/build/release"
when Mode::BMK
documentRoot = doppioRoot + "/build/benchmark"
when Mode::DEV
documentRoot = doppioRoot + "/build/dev"
end
p1 "Creating server in " + Mode2String(@options.mode) + " mode."
mime_types = WEBrick::HTTPUtils::DefaultMimeTypes
mime_types.store 'svg', 'image/svg+xml'
@server = HTTPServer.new({:DocumentRoot => documentRoot,
:Port => 8000,
:MimeTypes => mime_types})
['INT', 'TERM'].each {|signal|
trap(signal) {@server.shutdown}
}
# Benchmark mount points for communicating with the mock console.
if @options.mode == Mode::BMK
@server.mount "/message", DoppioServlet, "/message", self
@server.mount "/error", DoppioServlet, "/error", self
@server.mount "/complete", DoppioServlet, "/complete", self
@server.mount "/commands", DoppioServlet, "/commands", self
end
p1 "Starting server."
@serverpid = fork do
@server.start
end
sleep 1
if @options::mode == Mode::BMK
getCurrentExperiment().start()
end
Process.wait(@serverpid)
end
end
doppio = DoppioServer.new(ARGV)
doppio.start()
| 28.985542 | 84 | 0.549755 |
332bd0cc72a6a04830b09b53f2e014c66a51a76b | 633 | # frozen_string_literal: true
module Nomis
module Elite2
class UserApi
extend Elite2Api
def self.user_details(username)
route = "/elite2api/api/users/#{username}"
response = e2_client.get(route)
user = api_deserialiser.deserialise(Nomis::UserDetails, response)
user.email_address =
Nomis::Elite2::PrisonOffenderManagerApi.fetch_email_addresses(user.staff_id)
user
end
def self.user_caseloads(staff_id)
route = "/elite2api/api/staff/#{staff_id}/caseloads"
response = e2_client.get(route)
response
end
end
end
end
| 23.444444 | 86 | 0.658768 |
79ff72984e5bac3d81733ae308df68f5593ab71e | 3,212 | # 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::SQL::Mgmt::V2014_04_01
module Models
#
# A database geo backup policy.
#
class GeoBackupPolicy < ProxyResource
include MsRestAzure
# @return [GeoBackupPolicyState] The state of the geo backup policy.
# Possible values include: 'Disabled', 'Enabled'
attr_accessor :state
# @return [String] The storage type of the geo backup policy.
attr_accessor :storage_type
# @return [String] Kind of geo backup policy. This is metadata used for
# the Azure portal experience.
attr_accessor :kind
# @return [String] Backup policy location.
attr_accessor :location
#
# Mapper for GeoBackupPolicy class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'GeoBackupPolicy',
type: {
name: 'Composite',
class_name: 'GeoBackupPolicy',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
state: {
client_side_validation: true,
required: true,
serialized_name: 'properties.state',
type: {
name: 'Enum',
module: 'GeoBackupPolicyState'
}
},
storage_type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.storageType',
type: {
name: 'String'
}
},
kind: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'kind',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'location',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.424779 | 78 | 0.460149 |
d560ebcc6e620fd3a5a3ce97efec9493ffde002e | 2,021 | # frozen_string_literal: true
class BulkImportWorker # rubocop:disable Scalability/IdempotentWorker
include ApplicationWorker
data_consistency :always
feature_category :importers
sidekiq_options retry: false, dead: false
PERFORM_DELAY = 5.seconds
DEFAULT_BATCH_SIZE = 5
def perform(bulk_import_id)
@bulk_import = BulkImport.find_by_id(bulk_import_id)
return unless @bulk_import
return if @bulk_import.finished? || @bulk_import.failed?
return @bulk_import.fail_op! if all_entities_failed?
return @bulk_import.finish! if all_entities_processed? && @bulk_import.started?
return re_enqueue if max_batch_size_exceeded? # Do not start more jobs if max allowed are already running
@bulk_import.start! if @bulk_import.created?
created_entities.first(next_batch_size).each do |entity|
entity.create_pipeline_trackers!
BulkImports::ExportRequestWorker.perform_async(entity.id)
BulkImports::EntityWorker.perform_async(entity.id)
entity.start!
end
re_enqueue
rescue StandardError => e
Gitlab::ErrorTracking.track_exception(e, bulk_import_id: @bulk_import&.id)
@bulk_import&.fail_op
end
private
def entities
@entities ||= @bulk_import.entities
end
def started_entities
entities.with_status(:started)
end
def created_entities
entities.with_status(:created)
end
def all_entities_processed?
entities.all? { |entity| entity.finished? || entity.failed? }
end
def all_entities_failed?
entities.all? { |entity| entity.failed? }
end
def max_batch_size_exceeded?
started_entities.count >= DEFAULT_BATCH_SIZE
end
def next_batch_size
[DEFAULT_BATCH_SIZE - started_entities.count, 0].max
end
# A new BulkImportWorker job is enqueued to either
# - Process the new BulkImports::Entity created during import (e.g. for the subgroups)
# - Or to mark the `bulk_import` as finished
def re_enqueue
BulkImportWorker.perform_in(PERFORM_DELAY, @bulk_import.id)
end
end
| 25.582278 | 109 | 0.748639 |
7adaee4d8b279af8282828f464b6bcffda448c55 | 167 | class AddNameToIssues < ActiveRecord::Migration
def self.up
add_column :issues, :name, :string
end
def self.down
remove_column :issues, :name
end
end
| 16.7 | 47 | 0.712575 |
1a9258fda052a710065dee96d7644f9093fa3be6 | 5,269 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Getting issues for an epic' do
include GraphqlHelpers
let_it_be(:current_user) { create(:user) }
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group, :public) }
let_it_be(:epic) { create(:epic, group: group) }
let_it_be(:project) { create(:project, :private, group: group) }
let_it_be(:issue) { create(:issue, project: project) }
let_it_be(:confidential_issue) { create(:issue, :confidential, project: project) }
let_it_be(:epic_issue) { create(:epic_issue, epic: epic, issue: issue, relative_position: 3) }
let_it_be(:epic_issue2) { create(:epic_issue, epic: epic, issue: confidential_issue, relative_position: 5) }
let(:epics_data) { graphql_data['group']['epics']['edges'] }
let(:epic_node) do
<<~NODE
edges {
node {
iid
issues {
edges {
node {
id
}
}
}
}
}
NODE
end
def epic_query(params = {}, epic_fields = epic_node)
graphql_query_for("group", { "fullPath" => group.full_path },
query_graphql_field("epics", params, epic_fields)
)
end
def issue_ids(epics = epics_data)
node_array(epics).to_h do |node|
[node['iid'].to_i, node_array(node['issues']['edges'], 'id')]
end
end
def first_epic_issues_page_info
epics_data.first['node']['issues']['pageInfo']
end
context 'when epics are enabled' do
before do
stub_licensed_features(epics: true)
end
it 'does not return inaccessible issues' do
post_graphql(epic_query(iid: epic.iid), current_user: user)
expect(response).to have_gitlab_http_status(:success)
expect(issue_ids[epic.iid]).to be_empty
end
context 'when user has access to the issue project' do
before do
project.add_developer(user)
end
it 'returns issues in this project' do
post_graphql(epic_query(iid: epic.iid), current_user: user)
expect(response).to have_gitlab_http_status(:success)
expect(issue_ids[epic.iid]).to match_array [issue.to_global_id.to_s, confidential_issue.to_global_id.to_s]
end
context 'pagination' do
let(:data_path) { %i[group epics nodes] + [0] + %i[issues] }
def pagination_query(args)
epic_query({ iid: epic.iid }, epic_fields(args))
end
def epic_fields(args)
query_graphql_field(:nodes, query_nodes(:issues, :id, args: args, include_pagination_info: true))
end
it_behaves_like 'sorted paginated query' do
let(:current_user) { user }
let(:sort_param) { }
let(:first_param) { 1 }
let(:all_records) { [issue, confidential_issue].map { |i| global_id_of(i) } }
end
end
end
context 'when user is guest' do
before do
project.add_guest(user)
end
it 'filters out confidential issues' do
post_graphql(epic_query(iid: epic.iid), current_user: user)
expect(response).to have_gitlab_http_status(:success)
expect(issue_ids[epic.iid]).to eq [issue.to_global_id.to_s]
end
end
context 'when issues from multiple epics are queried' do
let_it_be(:epic2) { create(:epic, group: group) }
let_it_be(:issue2) { create(:issue, project: project) }
let_it_be(:epic_issue3) { create(:epic_issue, epic: epic2, issue: issue2, relative_position: 3) }
let(:params) { { iids: [epic.iid, epic2.iid] } }
it 'returns issues for each epic' do
project.add_developer(user)
post_graphql(epic_query(params), current_user: user)
expect(response).to have_gitlab_http_status(:success)
result = issue_ids
expect(result[epic.iid]).to match_array [issue.to_global_id.to_s, confidential_issue.to_global_id.to_s]
expect(result[epic2.iid]).to match_array [issue2.to_global_id.to_s]
end
it 'does limited number of N+1 queries' do
# extra queries:
# epic_issues - for each epic issues are loaded ordered by relatve_position
# issue_assignees - issue policy checks if user is between issue assignees
# when https://gitlab.com/gitlab-org/gitlab/-/issues/353375 is fixed, we can
# preload also issue assignees
extra_queries_count = 2
# warm-up query
post_graphql(epic_query(iid: epic.iid), current_user: user)
control_count = ActiveRecord::QueryRecorder.new(query_recorder_debug: true) do
post_graphql(epic_query(iid: epic.iid), current_user: user)
end
expect do
post_graphql(epic_query(params), current_user: user)
end.not_to exceed_query_limit(control_count).with_threshold(extra_queries_count)
expect(graphql_errors).to be_nil
end
end
end
context 'when epics are disabled' do
before do
stub_licensed_features(epics: false)
end
it 'does not find the epic' do
post_graphql(epic_query(iid: epic.iid), current_user: user)
expect(response).to have_gitlab_http_status(:success)
expect(graphql_errors).to be_nil
expect(graphql_data['group']['epic']).to be_nil
end
end
end
| 31.933333 | 114 | 0.649839 |
e90f252a3dab71d273dec5d1de3a74be46816db5 | 195 | if Gem::Specification.find_by_name('capistrano').version >= Gem::Version.new('3.0.0')
load File.expand_path('../capistrano/tasks.cap', __FILE__)
else
require_relative 'capistrano/tasks2'
end
| 32.5 | 85 | 0.753846 |
380c3a7909a33c1dda80c5420c8ce6def7c384ad | 1,900 | # Load the rails application
require File.expand_path('../application', __FILE__)
require File.expand_path('../../lib/printing/invoice_printer', __FILE__)
# Initialize the rails application
Hadean::Application.initialize!
Hadean::Application.configure do
config.after_initialize do
unless Settings.encryption_key
raise "
############################################################################################
! You need to setup the settings.yml
! copy settings.yml.example to settings.yml
!
! Make sure you personalize the passwords in this file and for security never check this file in.
############################################################################################
"
end
unless Settings.authnet.login
puts "
############################################################################################
############################################################################################
! You need to setup the settings.yml
! copy settings.yml.example to settings.yml
!
! YOUR ENV variables are not ready for checkout!
! please adjust ENV['AUTHNET_LOGIN'] && ENV['AUTHNET_PASSWORD']
! if you are not using authorize.net go to each file in /config/environments/*.rb and
! adjust the following code accordingly...
::GATEWAY = ActiveMerchant::Billing::AuthorizeNetGateway.new(
:login => Settings.authnet.login,
:password => Settings.authnet.password
)
! This is required for the checkout process to work.
!
! Remove or Adjust this warning in /config/environment.rb for developers on your team
! once you have everything working with your specific Gateway.
############################################################################################
"
end
end
end
| 42.222222 | 104 | 0.503684 |
f8deb9d5255a74c17e3869d9ec3ee2abe3e76224 | 761 | require 'upsert/connection/jdbc'
class Upsert
class Connection
# @private
class Java_ComMysqlJdbc_JDBC4Connection < Connection
include Jdbc
def quote_ident(k)
if metal.useAnsiQuotedIdentifiers
DOUBLE_QUOTE + k.to_s.gsub(DOUBLE_QUOTE, '""') + DOUBLE_QUOTE
else
# Escape backticks by doubling them. Ref http://dev.mysql.com/doc/refman/5.7/en/identifiers.html
BACKTICK + k.to_s.gsub(BACKTICK, BACKTICK + BACKTICK) + BACKTICK
end
end
def bind_value(v)
case v
when Time, DateTime
# mysql doesn't like it when you send timezone to a datetime
Upsert.utc_iso8601 v, false
else
super
end
end
end
end
end
| 25.366667 | 107 | 0.621551 |
39de2fd686d6cb529dfebca1d0aafa7c8a535d00 | 1,257 | t = PryTheme.create :name => 'pry-modern-256' do
author :name => 'Kyrylo Silin', :email => '[email protected]'
description 'Nifty version of pry-classic'
define_theme do
class_ 'fuchsia', [:bold]
class_variable 'robin_egg_blue04'
comment 'cerulean_grey01'
constant 'klein_blue', [:bold, :underline]
error 'cerulean_grey02'
float 'dark_pink01', [:bold]
global_variable 'gold'
inline_delimiter 'malachite01', [:bold]
instance_variable 'robin_egg_blue04'
integer 'robin_egg_blue01', [:bold]
keyword 'chestnut01', [:bold]
method 'grass01', [:bold]
predefined_constant 'cyan', [:bold]
symbol 'malachite02', [:bold]
regexp do
self_ 'tangerine'
char 'tangerine'
content 'violaceous03'
delimiter 'tangerine', [:bold]
modifier 'dark_pink01', [:bold]
escape 'malachite01', [:bold]
end
shell do
self_ 'grass01'
char 'grass01'
content 'grass01'
delimiter 'white'
escape 'malachite01', [:bold]
end
string do
self_ 'malachite01'
char 'malachite01'
content 'malachite01'
delimiter 'malachite01', [:bold]
escape 'malachite01', [:bold]
end
end
end
PryTheme::ThemeList.add_theme(t)
| 25.653061 | 67 | 0.641209 |
6a23c2fe164cdec89105c1a2b7046fe20335027a | 759 | module Sanction
class Permission
attr_reader :predicates
def initialize(permission_graph, *predicates)
@graph = permission_graph
@predicates = predicates
end
def path
@path ||= begin
path = @graph.root
@predicates.each do |predicate|
if predicate.is_a?(Class)
path = path[predicate.to_s.demodulize.underscore.to_sym]
else
path = path[predicate.class.to_s.demodulize.underscore.to_sym][predicate.id]
end
end
path
end
end
def persisted?
path.persisted?
end
def permitted?
path.permitted?
end
def permitted_with_scope?(scope)
permitted? && path.has_scope?(scope)
end
end
end | 19.973684 | 88 | 0.602108 |
b91301e0feebf8e1c773829fa957aa1cd3bb1a76 | 1,002 | lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "wasmer/version"
Gem::Specification.new do |spec|
spec.name = "wasmer"
spec.version = Wasmer::VERSION
spec.authors = ["Ivan Enderlin"]
spec.email = ["[email protected]"]
spec.summary = "Run WebAssembly binaries."
spec.description = "Wasmer is a Ruby extension to run WebAssembly binaries."
spec.homepage = "https://github.com/wasmerio/ruby-ext-wasm"
spec.license = "BSD-3-Clause"
spec.extensions = %w(Rakefile)
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(examples|tests)/}) }
end
spec.require_paths = %w(lib)
spec.add_dependency "rutie", "~> 0.0.3"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
end
| 33.4 | 81 | 0.650699 |
6278d199a7d495032ac1d008c5926dd93b485bc0 | 302 | module Golem
module Actions
class ListPlayers < Action
def setup
log "#{state.players.size} other players"
state.players.each do |name, entity|
pos = entity.position.map {|v| v / 32 }
log "#{name}: #{pos.inspect}"
end
end
end
end
end
| 21.571429 | 49 | 0.559603 |
33625f010fcb96d0fdaca9cc24b3f25f60e0f7ae | 922 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint kuma_player.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'kuma_player'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
end
| 38.416667 | 104 | 0.598698 |
ace7666f6721f5bfb463addd2c255da34d55c37e | 555 | module HealthSeven::V2_5_1
class Cf < ::HealthSeven::DataType
# Identifier
attribute :identifier, St, position: "CF.1"
# Formatted Text
attribute :formatted_text, Ft, position: "CF.2"
# Name of Coding System
attribute :name_of_coding_system, Id, position: "CF.3"
# Alternate Identifier
attribute :alternate_identifier, St, position: "CF.4"
# Alternate Formatted Text
attribute :alternate_formatted_text, Ft, position: "CF.5"
# Name of Alternate Coding System
attribute :name_of_alternate_coding_system, Id, position: "CF.6"
end
end | 34.6875 | 66 | 0.74955 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.