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
|
---|---|---|---|---|---|
ac81330b1e1f50f046a780b52cfb94dbe4d9b9fd | 154 | class PagesController < ApplicationController
skip_before_action :authenticate_user!
def home
redirect_to posts_path if user_signed_in?
end
end
| 22 | 45 | 0.818182 |
792ced39056079fd033028a32bb64ef01b536c34 | 2,218 | require File.expand_path('../fixtures/classes', __FILE__)
require 'matrix'
ruby_version_is "1.9" do
describe "Matrix.build" do
it "returns a Matrix object of the given size" do
m = Matrix.build(3, 4){1}
m.should be_an_instance_of(Matrix)
m.row_size.should == 3
m.column_size.should == 4
end
it "builds the Matrix using the given block" do
Matrix.build(2, 3){|col, row| 10*col - row}.should ==
Matrix[[0, -1, -2], [10, 9, 8]]
end
it "iterates through the first row, then the second, ..." do
acc = []
Matrix.build(2, 3){|*args| acc << args}
acc.should == [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
end
it "returns an Enumerator is no block is given" do
enum = Matrix.build(2, 1)
enum.should be_an_instance_of(enumerator_class)
enum.each{1}.should == Matrix[[1], [1]]
end
it "requires integers as parameters" do
lambda { Matrix.build("1", "2"){1} }.should raise_error(TypeError)
lambda { Matrix.build(nil, nil){1} }.should raise_error(TypeError)
lambda { Matrix.build(1..2){1} }.should raise_error(TypeError)
end
it "requires non-negative integers" do
lambda { Matrix.build(-1, 1){1} }.should raise_error(ArgumentError)
lambda { Matrix.build(+1,-1){1} }.should raise_error(ArgumentError)
end
it "returns empty Matrix if one argument is zero" do
m = Matrix.build(0, 3){
raise "Should not yield"
}
m.should be_empty
m.column_size.should == 3
m = Matrix.build(3, 0){
raise "Should not yield"
}
m.should be_empty
m.row_size.should == 3
end
it "tries to calls :to_int on arguments" do
int = mock('int')
int.should_receive(:to_int).twice.and_return(2)
Matrix.build(int, int){ 1 }.should == Matrix[ [1,1], [1,1] ]
end
it "builds an nxn Matrix when given only one argument" do
m = Matrix.build(3){1}
m.row_size.should == 3
m.column_size.should == 3
end
end
describe "for a subclass of Matrix" do
it "returns an instance of that subclass" do
MatrixSub.build(3){1}.should be_an_instance_of(MatrixSub)
end
end
end
| 29.184211 | 73 | 0.609107 |
111662fa4fe9055df30bf32509e1e4be214cb850 | 340 | require 'rails_helper'
RSpec.describe "contributions/show", type: :view do
before(:each) do
@contribution = assign(:contribution, Contribution.create!(
:user => nil,
:package => nil
))
end
it "renders attributes in <p>" do
render
expect(rendered).to match(//)
expect(rendered).to match(//)
end
end
| 20 | 63 | 0.638235 |
91e2c8aac84cd17d2d55c309ec1935fe5768bc4c | 32,058 | # frozen_string_literal: true
describe Appeal, :all_dbs do
include IntakeHelpers
before do
Timecop.freeze(Time.utc(2019, 1, 1, 12, 0, 0))
end
let!(:appeal) { create(:appeal) } # must be *after* Timecop.freeze
context "#create_stream" do
let(:stream_type) { "vacate" }
let!(:appeal) { create(:appeal, number_of_claimants: 1) }
subject { appeal.create_stream(stream_type) }
it "creates a new appeal stream with data from the original appeal" do
expect(subject).to have_attributes(
receipt_date: appeal.receipt_date,
veteran_file_number: appeal.veteran_file_number,
legacy_opt_in_approved: appeal.legacy_opt_in_approved,
veteran_is_not_claimant: appeal.veteran_is_not_claimant,
stream_docket_number: appeal.docket_number,
stream_type: stream_type
)
expect(subject.reload.claimant.participant_id).to eq(appeal.claimant.participant_id)
end
end
context "includes PrintsTaskTree concern" do
context "#structure" do
let!(:root_task) { create(:root_task, appeal: appeal) }
subject { appeal.structure(:id) }
it "returns the task structure" do
expect_any_instance_of(RootTask).to receive(:structure).with(:id)
expect(subject.key?(:"Appeal #{appeal.id} [id]")).to be_truthy
end
end
context "#structure_as_json" do
let!(:root_task) { create(:root_task, appeal: appeal) }
subject { appeal.structure_as_json(:id) }
it "returns the task tree as a hash" do
expect(subject).to eq(Appeal: { id: appeal.id, tasks: [{ RootTask: { id: root_task.id, tasks: [] } }] })
end
end
end
context "active appeals" do
let!(:active_appeal) { create(:appeal, :with_post_intake_tasks) }
let!(:inactive_appeal) { create(:appeal, :outcoded) }
subject { Appeal.active }
it "returns only active appeals" do
expect(subject).to include active_appeal
expect(subject).to_not include inactive_appeal
end
end
context "#create_business_line_tasks!" do
let(:request_issues) do
[
create(:request_issue, benefit_type: "education"),
create(:request_issue, benefit_type: "education"),
create(:request_issue, benefit_type: "nca")
]
end
let(:appeal) { create(:appeal, request_issues: request_issues) }
subject { appeal.create_business_line_tasks! }
it "creates one VeteranRecordRequest task per business line" do
expect(VeteranRecordRequest).to receive(:create!).twice
subject
end
context "when the appeal has no active issues" do
let(:request_issues) do
[
create(:request_issue, :ineligible, benefit_type: "education"),
create(:request_issue, :ineligible, benefit_type: "nca")
]
end
it "does not create business line tasks" do
expect(VeteranRecordRequest).to_not receive(:create!)
subject
end
end
end
context "#create_issues!" do
subject { appeal.create_issues!(issues) }
let(:issues) { [request_issue] }
let(:request_issue) do
create(
:request_issue,
ineligible_reason: ineligible_reason,
vacols_id: vacols_id,
vacols_sequence_id: vacols_sequence_id
)
end
let(:ineligible_reason) { nil }
let(:vacols_id) { nil }
let(:vacols_sequence_id) { nil }
let(:vacols_case) { create(:case, case_issues: [create(:case_issue)]) }
let(:legacy_appeal) { create(:legacy_appeal, vacols_case: vacols_case) }
context "when there is no associated legacy issue" do
it "does not create a legacy issue" do
subject
expect(request_issue.legacy_issues).to be_empty
end
end
context "when there is an associated legacy issue" do
let(:vacols_id) { legacy_appeal.vacols_id }
let(:vacols_sequence_id) { legacy_appeal.issues.first.vacols_sequence_id }
context "when the veteran did not opt in their legacy issues" do
let(:ineligible_reason) { "legacy_issue_not_withdrawn" }
it "creates a legacy issue, but no opt-in" do
subject
expect(request_issue.legacy_issues.count).to eq 1
expect(request_issue.legacy_issue_optin).to be_nil
end
end
context "when legacy opt in is approved by the veteran" do
let(:ineligible_reason) { nil }
it "creates a legacy issue and an associated opt-in" do
subject
expect(request_issue.legacy_issue_optin.legacy_issue).to eq(request_issue.legacy_issues.first)
end
end
end
end
context "#create_remand_supplemental_claims!" do
before { setup_prior_claim_with_payee_code(appeal, veteran) }
let(:veteran) { create(:veteran) }
let(:appeal) do
create(:appeal, number_of_claimants: 1, veteran_file_number: veteran.file_number)
end
subject { appeal.create_remand_supplemental_claims! }
let!(:remanded_decision_issue) do
create(
:decision_issue,
decision_review: appeal,
disposition: "remanded",
benefit_type: "compensation",
caseflow_decision_date: decision_date
)
end
let!(:remanded_decision_issue_processed_in_caseflow) do
create(
:decision_issue, decision_review: appeal, disposition: "remanded", benefit_type: "nca",
caseflow_decision_date: decision_date
)
end
let(:decision_date) { 10.days.ago }
let!(:decision_document) { create(:decision_document, decision_date: decision_date, appeal: appeal) }
let!(:not_remanded_decision_issue) { create(:decision_issue, decision_review: appeal) }
it "creates supplemental claim, request issues, and starts processing" do
subject
remanded_supplemental_claims = SupplementalClaim.where(decision_review_remanded: appeal)
expect(remanded_supplemental_claims.count).to eq(2)
vbms_remand = remanded_supplemental_claims.find_by(benefit_type: "compensation")
expect(vbms_remand).to have_attributes(
receipt_date: decision_date.to_date
)
expect(vbms_remand.request_issues.count).to eq(1)
expect(vbms_remand.request_issues.first).to have_attributes(
contested_decision_issue: remanded_decision_issue
)
expect(vbms_remand.end_product_establishments.first).to be_committed
expect(vbms_remand.tasks).to be_empty
caseflow_remand = remanded_supplemental_claims.find_by(benefit_type: "nca")
expect(caseflow_remand).to have_attributes(
receipt_date: decision_date.to_date
)
expect(caseflow_remand.request_issues.count).to eq(1)
expect(caseflow_remand.request_issues.first).to have_attributes(
contested_decision_issue: remanded_decision_issue_processed_in_caseflow
)
expect(caseflow_remand.end_product_establishments).to be_empty
expect(caseflow_remand.tasks.first).to have_attributes(assigned_to: BusinessLine.find_by(url: "nca"))
end
end
context "#document_fetcher" do
let(:veteran_file_number) { "64205050" }
let(:appeal) do
create(:appeal, veteran_file_number: veteran_file_number)
end
it "returns a DocumentFetcher" do
expect(appeal.document_fetcher.appeal).to eq(appeal)
expect(appeal.document_fetcher.use_efolder).to eq(true)
end
end
context "#latest_attorney_case_review" do
let(:appeal) { create(:appeal) }
let(:task1) { create(:ama_attorney_task, appeal: appeal) }
let(:task2) { create(:ama_attorney_task, appeal: appeal) }
let!(:attorney_case_review1) { create(:attorney_case_review, task: task1, created_at: 2.days.ago) }
let!(:attorney_case_review2) { create(:attorney_case_review, task: task2, created_at: 1.day.ago) }
subject { appeal.latest_attorney_case_review }
it "returns the latest record" do
expect(subject).to eq attorney_case_review2
end
end
context "#contestable_issues" do
subject { appeal.contestable_issues }
let(:veteran_file_number) { "64205050" }
let!(:veteran) do
Generators::Veteran.build(
file_number: veteran_file_number,
first_name: "Ed",
last_name: "Merica",
participant_id: "55443322"
)
end
let(:receipt_date) { Time.zone.today }
let(:appeal) do
create(:appeal, veteran: veteran, receipt_date: receipt_date)
end
let(:another_review) do
create(:higher_level_review, veteran_file_number: veteran_file_number, receipt_date: receipt_date)
end
let!(:past_decision_issue) do
create(:decision_issue,
decision_review: another_review,
rating_profile_date: receipt_date - 1.day,
benefit_type: another_review.benefit_type,
decision_text: "something decided in the past",
description: "past issue",
participant_id: veteran.participant_id,
end_product_last_action_date: receipt_date - 1.day)
end
let!(:future_decision_issue) do
create(:decision_issue,
decision_review: another_review,
rating_profile_date: receipt_date + 1.day,
rating_promulgation_date: receipt_date + 1.day,
benefit_type: another_review.benefit_type,
decision_text: "something was decided in the future",
description: "future issue",
participant_id: veteran.participant_id,
end_product_last_action_date: receipt_date - 1.day)
end
# it "does not return Decision Issues in the future" do
# expect(subject.count).to eq(1)
# expect(subject.first.decision_issue.id).to eq(past_decision_issue.id)
# end
end
context "async logic scopes" do
let!(:appeal_requiring_processing_newly_submitted) do
create(:appeal).tap(&:submit_for_processing!)
end
let!(:appeal_requiring_processing) do
create(:appeal).tap do |appeal|
appeal.submit_for_processing!
appeal.update!(
establishment_last_submitted_at: (Appeal.processing_retry_interval_hours + 1).hours.ago
)
end
end
let!(:appeal_processed) do
create(:appeal).tap(&:processed!)
end
let!(:appeal_recently_attempted) do
create(
:appeal,
establishment_attempted_at: (Appeal.processing_retry_interval_hours - 1).hours.ago
)
end
let!(:appeal_attempts_ended) do
create(
:appeal,
establishment_last_submitted_at: (Appeal::REQUIRES_PROCESSING_WINDOW_DAYS + 5).days.ago,
establishment_attempted_at: (Appeal::REQUIRES_PROCESSING_WINDOW_DAYS + 1).days.ago
)
end
context ".unexpired" do
it "matches appeals still inside the processing window" do
expect(Appeal.unexpired).to match_array(
[appeal_requiring_processing, appeal_requiring_processing_newly_submitted]
)
end
end
context ".processable" do
it "matches appeals eligible for processing" do
expect(Appeal.processable).to match_array(
[appeal_requiring_processing, appeal_attempts_ended, appeal_requiring_processing_newly_submitted]
)
end
end
context ".attemptable" do
it "matches appeals that could be attempted" do
expect(Appeal.attemptable).not_to include(appeal_recently_attempted)
end
end
context ".requires_processing" do
it "matches appeals that need to be reprocessed" do
expect(Appeal.requires_processing).to match_array([appeal_requiring_processing])
end
end
context ".expired_without_processing" do
it "matches appeals unfinished but outside the retry window" do
expect(Appeal.expired_without_processing).to eq([appeal_attempts_ended])
end
end
end
context "#establish!" do
it { is_expected.to_not be_nil }
end
context "#every_request_issue_has_decision" do
let(:appeal) { create(:appeal, request_issues: [request_issue]) }
let(:request_issue) { create(:request_issue, decision_issues: decision_issues) }
subject { appeal.every_request_issue_has_decision? }
context "when no decision issues" do
let(:decision_issues) { [] }
it { is_expected.to eq false }
end
context "when decision issues" do
let(:decision_issues) { [build(:decision_issue)] }
it { is_expected.to eq true }
end
end
context "#docket_number" do
context "when receipt_date is defined" do
let(:appeal) do
create(:appeal, receipt_date: Time.new("2018", "04", "05").utc)
end
it "returns a docket number if id and receipt_date are defined" do
expect(appeal.docket_number).to eq("180405-#{appeal.id}")
end
end
context "when receipt_date is nil" do
let(:appeal) do
create(:appeal, receipt_date: nil)
end
it "returns Missing Docket Number" do
expect(appeal.docket_number).to eq("Missing Docket Number")
end
end
end
context "#set_stream_docket_number_and_stream_type" do
it "persists an accurate value for stream_docket_number to the database" do
appeal = Appeal.new(veteran_file_number: "1234")
appeal.save!
expect(appeal.stream_docket_number).to be_nil
appeal.receipt_date = Time.new("2020", "01", "24").utc
expect(appeal.docket_number).to eq("200124-#{appeal.id}")
appeal.save!
expect(appeal.stream_docket_number).to eq("200124-#{appeal.id}")
appeal.stream_docket_number = "something else"
appeal.save!
expect(Appeal.where(stream_docket_number: "something else").count).to eq(1)
end
end
context "#advanced_on_docket?" do
context "when a claimant is advanced_on_docket?" do
let(:appeal) do
create(:appeal, claimants: [create(:claimant, :advanced_on_docket_due_to_age)])
end
it "returns true" do
expect(appeal.advanced_on_docket?).to eq(true)
end
end
context "when no claimant is advanced_on_docket?" do
let(:appeal) do
create(:appeal)
end
it "returns false" do
expect(appeal.advanced_on_docket?).to eq(false)
end
end
end
context "#find_appeal_by_id_or_find_or_create_legacy_appeal_by_vacols_id" do
context "with a uuid (AMA appeal id)" do
let(:veteran_file_number) { "64205050" }
let(:appeal) do
create(:appeal, veteran_file_number: veteran_file_number)
end
it "finds the appeal" do
expect(Appeal.find_appeal_by_id_or_find_or_create_legacy_appeal_by_vacols_id(appeal.uuid)).to \
eq(appeal)
end
it "returns RecordNotFound for a non-existant one" do
made_up_uuid = "11111111-aaaa-bbbb-CCCC-999999999999"
expect { Appeal.find_appeal_by_id_or_find_or_create_legacy_appeal_by_vacols_id(made_up_uuid) }.to \
raise_exception(ActiveRecord::RecordNotFound, "Couldn't find Appeal")
end
end
context "with a legacy appeal" do
let(:vacols_issue) { create(:case_issue) }
let(:vacols_case) { create(:case, case_issues: [vacols_issue]) }
let(:legacy_appeal) do
create(:legacy_appeal, vacols_case: vacols_case)
end
it "finds the appeal" do
legacy_appeal.save
expect(Appeal.find_appeal_by_id_or_find_or_create_legacy_appeal_by_vacols_id(legacy_appeal.vacols_id)).to \
eq(legacy_appeal)
end
it "returns RecordNotFound for a non-existant one" do
made_up_non_uuid = "9876543"
expect do
Appeal.find_appeal_by_id_or_find_or_create_legacy_appeal_by_vacols_id(made_up_non_uuid)
end.to raise_exception(ActiveRecord::RecordNotFound)
end
end
end
context "#appellant_first_name" do
subject { appeal.appellant_first_name }
context "when appeal has claimants" do
let(:appeal) { create(:appeal, number_of_claimants: 1) }
it "returns claimant's name" do
expect(subject).to_not eq nil
expect(subject).to eq appeal.claimant.first_name
end
end
context "when appeal doesn't have claimants" do
let(:appeal) { create(:appeal, number_of_claimants: 0) }
it { is_expected.to eq nil }
end
end
context "when claimants have different poas" do
let(:participant_id_with_pva) { "1234" }
let(:participant_id_with_aml) { "5678" }
let(:appeal) do
create(:appeal, claimants: [
create(:claimant, participant_id: participant_id_with_pva),
create(:claimant, participant_id: participant_id_with_aml)
])
end
let!(:vso) do
Vso.create(
name: "Paralyzed Veterans Of America",
role: "VSO",
url: "paralyzed-veterans-of-america",
participant_id: "9876"
)
end
before do
allow_any_instance_of(BGSService).to receive(:fetch_poas_by_participant_ids)
.with([participant_id_with_pva]).and_return(
participant_id_with_pva => {
representative_name: "PARALYZED VETERANS OF AMERICA, INC.",
representative_type: "POA National Organization",
participant_id: "9876"
}
)
allow_any_instance_of(BGSService).to receive(:fetch_poas_by_participant_ids)
.with([participant_id_with_aml]).and_return(
participant_id_with_aml => {
representative_name: "AMERICAN LEGION",
representative_type: "POA National Organization",
participant_id: "54321"
}
)
end
context "#power_of_attorney" do
it "returns the first claimant's power of attorney" do
expect(appeal.power_of_attorney.representative_name).to eq("AMERICAN LEGION")
end
end
context "#power_of_attorneys" do
it "returns all claimants power of attorneys" do
expect(appeal.power_of_attorneys[0].representative_name).to eq("PARALYZED VETERANS OF AMERICA, INC.")
expect(appeal.power_of_attorneys[1].representative_name).to eq("AMERICAN LEGION")
end
end
context "#representatives" do
it "returns all representatives this appeal has that exist in our DB" do
expect(appeal.representatives.count).to eq(1)
expect(appeal.representatives.first.name).to eq("Paralyzed Veterans Of America")
end
context "when there is no VSO" do
let(:participant_id_with_nil) { "1234" }
before do
allow_any_instance_of(BGSService).to receive(:fetch_poas_by_participant_ids)
.with([participant_id_with_nil]).and_return(
participant_id_with_pva => nil
)
end
let(:appeal) do
create(:appeal, claimants: [create(:claimant, participant_id: participant_id_with_nil)])
end
let!(:vso) do
Vso.create(
name: "Test VSO",
url: "test-vso"
)
end
it "does not return VSOs with nil participant_id" do
expect(appeal.representatives).to eq([])
end
end
end
end
context ".create_tasks_on_intake_success!" do
let!(:appeal) { create(:appeal) }
subject { appeal.create_tasks_on_intake_success! }
it "creates root and vso tasks" do
expect_any_instance_of(InitialTasksFactory).to receive(:create_root_and_sub_tasks!).once
subject
end
context "request issue has non-comp business line" do
let!(:appeal) do
create(:appeal, request_issues: [
create(:request_issue, benefit_type: :fiduciary),
create(:request_issue, benefit_type: :compensation),
create(:request_issue, :unidentified)
])
end
it "creates root task and veteran record request task" do
expect(VeteranRecordRequest).to receive(:create!).once
subject
end
end
context "request issue is missing benefit type" do
let!(:appeal) do
create(:appeal, request_issues: [
create(:request_issue, benefit_type: "unknown"),
create(:request_issue, :unidentified)
])
end
it "raises MissingBusinessLine exception" do
expect { subject }.to raise_error(Caseflow::Error::MissingBusinessLine)
end
end
context "creating translation tasks" do
let!(:mock_response) { HTTPI::Response.new(200, {}, {}.to_json) }
let(:bgs_veteran_state) { nil }
let(:bgs_veteran_record) { { state: bgs_veteran_state } }
let(:validated_veteran_state) { nil }
let(:mock_va_dot_gov_address) { { state_code: validated_veteran_state } }
let(:veteran) { create(:veteran, bgs_veteran_record: bgs_veteran_record) }
let(:appeal) { create(:appeal, veteran: veteran) }
context "VADotGovService is responsive" do
before do
valid_address_response = ExternalApi::VADotGovService::AddressValidationResponse.new(mock_response)
allow(valid_address_response).to receive(:data).and_return(mock_va_dot_gov_address)
allow(VADotGovService).to receive(:validate_address)
.and_return(valid_address_response)
end
context "the service returns a state code" do
context "the state code is PR or PI" do
let(:validated_veteran_state) { "PR" }
it "creates a translation task" do
expect(TranslationTask).to receive(:create_from_parent).once.with(kind_of(DistributionTask))
subject
end
context "the bgs veteran record has a different state code" do
let(:validated_veteran_state) { "PI" }
let(:bgs_veteran_state) { "NV" }
it "prefers the service state code and creates a translation task" do
expect(TranslationTask).to receive(:create_from_parent).once.with(kind_of(DistributionTask))
subject
end
end
end
context "the state code is not PR or PI" do
let(:validated_veteran_state) { "NV" }
it "doesn't create a translation task" do
translation_task_count = TranslationTask.all.count
subject
expect(TranslationTask.all.count).to eq(translation_task_count)
end
end
end
end
context "the VADotGovService is not responsive" do
let(:message) { { "messages" => [{ "key" => "AddressCouldNotBeFound" }] } }
let(:error) { Caseflow::Error::VaDotGovServerError.new(code: "500", message: message) }
before do
allow(VADotGovService).to receive(:send_va_dot_gov_request).and_raise(error)
end
it "fails silently" do
expect { subject }.to_not raise_error
end
context "the bgs veteran record has no state code" do
it "doesn't create a translation task" do
translation_task_count = TranslationTask.all.count
subject
expect(TranslationTask.all.count).to eq(translation_task_count)
end
end
context "the bgs veteran record has a state code" do
context "the state code is PR or PI" do
let(:bgs_veteran_state) { "PI" }
it "creates a translation task" do
expect(TranslationTask).to receive(:create_from_parent).once.with(kind_of(DistributionTask))
subject
end
end
context "the state code is not PR or PI" do
let(:bgs_veteran_state) { "NV" }
it "doesn't create a translation task" do
translation_task_count = TranslationTask.all.count
subject
expect(TranslationTask.all.count).to eq(translation_task_count)
end
end
end
end
end
end
context "#assigned_to_location" do
context "if the RootTask status is completed" do
let(:appeal) { create(:appeal) }
before do
create(:root_task, :completed, appeal: appeal)
end
it "returns Post-decision" do
expect(appeal.assigned_to_location).to eq(COPY::CASE_LIST_TABLE_POST_DECISION_LABEL)
end
end
context "if there are no active tasks" do
let(:appeal) { create(:appeal) }
it "returns 'other close'" do
expect(appeal.assigned_to_location).to eq(:other_close.to_s.titleize)
end
end
context "if the only active case is a RootTask" do
let(:appeal) { create(:appeal) }
before do
create(:root_task, :in_progress, appeal: appeal)
end
it "returns Case storage" do
expect(appeal.assigned_to_location).to eq(COPY::CASE_LIST_TABLE_CASE_STORAGE_LABEL)
end
end
context "if there are active TrackVeteranTask, TimedHoldTask, and RootTask" do
let(:appeal) { create(:appeal) }
let(:today) { Time.zone.today }
let(:root_task) { create(:root_task, :in_progress, appeal: appeal) }
before do
create(:track_veteran_task, :in_progress, appeal: appeal, parent: root_task, updated_at: today + 21)
create(:timed_hold_task, :in_progress, appeal: appeal, parent: root_task, updated_at: today + 21)
end
describe "when there are no other tasks" do
it "returns Case storage because it does not include nonactionable tasks in its determinations" do
expect(appeal.assigned_to_location).to eq(COPY::CASE_LIST_TABLE_CASE_STORAGE_LABEL)
end
end
describe "when there is an actionable task with an assignee", skip: "flake" do
let(:assignee) { create(:user) }
let!(:task) do
create(:ama_attorney_task, :in_progress, assigned_to: assignee, appeal: appeal, parent: root_task)
end
it "returns the actionable task's label and does not include nonactionable tasks in its determinations" do
expect(appeal.assigned_to_location).to(
eq(assignee.css_id), appeal.structure_render(:id, :status, :created_at, :assigned_to_id)
)
end
end
end
context "if there is an assignee" do
let(:organization) { create(:organization) }
let(:appeal_organization) { create(:appeal) }
let(:user) { create(:user) }
let(:appeal_user) { create(:appeal) }
let(:appeal_on_hold) { create(:appeal) }
let(:today) { Time.zone.today }
before do
organization_root_task = create(:root_task, appeal: appeal_organization)
create(:ama_task, assigned_to: organization, appeal: appeal_organization, parent: organization_root_task)
user_root_task = create(:root_task, appeal: appeal_user)
create(:ama_task, assigned_to: user, appeal: appeal_user, parent: user_root_task)
on_hold_root = create(:root_task, appeal: appeal_on_hold, updated_at: today - 1)
create(:ama_task, :on_hold, appeal: appeal_on_hold, parent: on_hold_root, updated_at: today + 1)
# These tasks are the most recently updated but should be ignored in the determination
create(:track_veteran_task, :in_progress, appeal: appeal, updated_at: today + 20)
create(:timed_hold_task, :in_progress, appeal: appeal, updated_at: today + 20)
end
it "if the most recent assignee is an organization it returns the organization name" do
expect(appeal_organization.assigned_to_location).to eq(organization.name)
end
it "if the most recent assignee is not an organization it returns the id" do
expect(appeal_user.assigned_to_location).to eq(user.css_id)
end
it "if the task is on hold but there isn't an assignee it returns something" do
expect(appeal_on_hold.assigned_to_location).not_to eq(nil)
end
end
end
context "is taskable" do
context ".assigned_attorney" do
let!(:attorney) { create(:user) }
let!(:attorney2) { create(:user) }
let!(:appeal) { create(:appeal) }
let!(:task) { create(:ama_attorney_task, assigned_to: attorney, appeal: appeal, created_at: 1.day.ago) }
let!(:task2) { create(:ama_attorney_task, assigned_to: attorney2, appeal: appeal) }
subject { appeal.assigned_attorney }
it "returns the assigned attorney for the most recent non-cancelled AttorneyTask" do
expect(subject).to eq attorney2
end
it "should know the right assigned attorney with a cancelled task" do
task2.update(status: "cancelled")
expect(subject).to eq attorney
end
end
context ".assigned_judge" do
let!(:judge) { create(:user) }
let!(:judge2) { create(:user) }
let!(:appeal) { create(:appeal) }
let!(:task) { create(:ama_judge_task, assigned_to: judge, appeal: appeal, created_at: 1.day.ago) }
let!(:task2) { create(:ama_judge_task, assigned_to: judge2, appeal: appeal) }
subject { appeal.assigned_judge }
it "returns the assigned judge for the most recent non-cancelled JudgeTask" do
expect(subject).to eq judge2
end
it "should know the right assigned judge with a cancelled tasks" do
task2.update(status: "cancelled")
expect(subject).to eq judge
end
end
end
context ".active?" do
subject { appeal.active? }
context "when there are no tasks for an appeal" do
let(:appeal) { create(:appeal) }
it "should indicate the appeal is not active" do
expect(subject).to eq(false)
end
end
context "when there are only completed tasks for an appeal" do
let(:appeal) { create(:appeal) }
before do
create_list(:task, 6, :completed, appeal: appeal)
end
it "should indicate the appeal is not active" do
expect(subject).to eq(false)
end
end
context "when there are incomplete tasks for an appeal" do
let(:appeal) { create(:appeal) }
before do
create_list(:task, 3, :in_progress, appeal: appeal)
end
it "should indicate the appeal is active" do
expect(subject).to eq(false)
end
end
end
describe "#status" do
it "returns BVAAppealStatus object" do
expect(appeal.status).to be_a(BVAAppealStatus)
expect(appeal.status.to_s).to eq("UNKNOWN") # zero tasks
end
end
context "#set_target_decision_date!" do
let(:direct_review_appeal) do
create(:appeal,
docket_type: Constants.AMA_DOCKETS.direct_review)
end
let(:evidence_submission_appeal) do
create(:appeal,
docket_type: Constants.AMA_DOCKETS.evidence_submission)
end
context "with direct review appeal" do
subject { direct_review_appeal }
it "sets target decision date" do
subject.set_target_decision_date!
expect(subject.target_decision_date).to eq(
subject.receipt_date + DirectReviewDocket::DAYS_TO_DECISION_GOAL.days
)
end
end
context "with not direct review appeal" do
subject { evidence_submission_appeal }
it "does not set target date" do
subject.set_target_decision_date!
expect(subject.target_decision_date).to eq(nil)
end
end
end
describe "#stuck?" do
context "Appeal has BvaDispatchTask completed but still on hold" do
let(:appeal) do
appeal = create(:appeal, :with_post_intake_tasks)
create(:bva_dispatch_task, :completed, appeal: appeal)
appeal
end
it "returns true" do
expect(appeal.stuck?).to eq(true)
end
end
end
describe "#vacate_type" do
subject { appeal.vacate_type }
context "Appeal is a vacatur and has a post-decision motion" do
let(:original) { create(:appeal, :with_straight_vacate_stream) }
let(:appeal) { Appeal.vacate.find_by(stream_docket_number: original.docket_number) }
it "returns the post-decision motion's vacate type" do
expect(subject).to eq "straight_vacate"
end
end
context "Appeal is not a vacatur" do
let(:appeal) { create(:appeal) }
it "returns nil" do
expect(subject).to be_nil
end
end
end
end
| 33.083591 | 115 | 0.66205 |
ac3ca7a571dca871c8ff23ab16c0bfa7e7346403 | 7,789 | # frozen_string_literal: true
require 'spec_helper'
module Spree
describe Api::TaxonsController, type: :request do
let!(:taxonomy) { create(:taxonomy) }
let!(:taxon) { create(:taxon, name: "Ruby", parent: taxonomy.root, taxonomy: taxonomy) }
let!(:taxon2) { create(:taxon, name: "Rails", parent: taxon, taxonomy: taxonomy) }
let!(:rails_v3_2_2) { create(:taxon, name: "3.2.2", parent: taxon2, taxonomy: taxonomy) }
let(:attributes) { ["id", "name", "pretty_name", "permalink", "parent_id", "taxonomy_id"] }
before do
stub_authentication!
end
context "as a normal user" do
it "gets all taxons for a taxonomy" do
get spree.api_taxonomy_taxons_path(taxonomy)
expect(json_response['taxons'].first['name']).to eq taxon.name
children = json_response['taxons'].first['taxons']
expect(children.count).to eq 1
expect(children.first['name']).to eq taxon2.name
expect(children.first['taxons'].count).to eq 1
end
# Regression test for https://github.com/spree/spree/issues/4112
it "does not include children when asked not to" do
get spree.api_taxonomy_taxons_path(taxonomy), params: { without_children: 1 }
expect(json_response['taxons'].first['name']).to eq(taxon.name)
expect(json_response['taxons'].first['taxons']).to be_nil
end
it "paginates through taxons" do
new_taxon = create(:taxon, name: "Go", taxonomy: taxonomy)
taxonomy.root.children << new_taxon
expect(taxonomy.root.children.count).to eql(2)
get spree.api_taxonomy_taxons_path(taxonomy), params: { page: 1, per_page: 1 }
expect(json_response["count"]).to eql(1)
expect(json_response["total_count"]).to eql(2)
expect(json_response["current_page"]).to eql(1)
expect(json_response["per_page"]).to eql(1)
expect(json_response["pages"]).to eql(2)
end
describe 'searching' do
context 'with a name' do
before do
get spree.api_taxons_path, params: { q: { name_cont: name } }
end
context 'with one result' do
let(:name) { "Ruby" }
it "returns an array including the matching taxon" do
expect(json_response['taxons'].count).to eq(1)
expect(json_response['taxons'].first['name']).to eq "Ruby"
end
end
context 'with no results' do
let(:name) { "Imaginary" }
it 'returns an empty array of taxons' do
expect(json_response.keys).to include('taxons')
expect(json_response['taxons'].count).to eq(0)
end
end
end
context 'with no filters' do
it "gets all taxons" do
get spree.api_taxons_path
expect(json_response['taxons'].first['name']).to eq taxonomy.root.name
children = json_response['taxons'].first['taxons']
expect(children.count).to eq 1
expect(children.first['name']).to eq taxon.name
expect(children.first['taxons'].count).to eq 1
end
end
end
context 'filtering by taxon ids' do
it 'returns only requested id' do
get spree.api_taxons_path, params: { ids: [rails_v3_2_2.id] }
expect(json_response['taxons'].size).to eq 1
end
it 'returns only requested ids' do
# We need a completly new branch to avoid having parent that can be preloaded from the rails ancestors
python = create(:taxon, name: "Python", parent: taxonomy.root, taxonomy: taxonomy)
python_three = create(:taxon, name: "3.0", parent: python, taxonomy: taxonomy)
get spree.api_taxons_path, params: { ids: [rails_v3_2_2.id, python_three.id] }
expect(json_response['taxons'].size).to eq 2
end
end
it "gets a single taxon" do
get spree.api_taxonomy_taxon_path(taxonomy, taxon.id)
expect(json_response['name']).to eq taxon.name
expect(json_response['taxons'].count).to eq 1
end
it "can learn how to create a new taxon" do
get spree.new_api_taxonomy_taxon_path(taxonomy)
expect(json_response["attributes"]).to eq(attributes.map(&:to_s))
required_attributes = json_response["required_attributes"]
expect(required_attributes).to include("name")
end
it "cannot create a new taxon if not an admin" do
post spree.api_taxonomy_taxons_path(taxonomy), params: { taxon: { name: "Location" } }
assert_unauthorized!
end
it "cannot update a taxon if not an admin" do
put spree.api_taxonomy_taxon_path(taxonomy, taxon.id), params: { taxon: { name: "I hacked your store!" } }
assert_unauthorized!
end
it "cannot delete a taxon if not an admin" do
delete spree.api_taxonomy_taxon_path(taxonomy, taxon.id)
assert_unauthorized!
end
context "with caching enabled" do
let!(:product) { create(:product, taxons: [taxon]) }
before do
ActionController::Base.perform_caching = true
end
it "handles exclude_data correctly" do
get spree.api_taxon_products_path, params: { id: taxon.id, simple: true }
expect(response).to be_successful
simple_response = json_response
get spree.api_taxon_products_path, params: { id: taxon.id }
expect(response).to be_successful
full_response = json_response
expect(simple_response["products"][0]["description"]).to be_nil
expect(full_response["products"][0]["description"]).not_to be_nil
end
after do
ActionController::Base.perform_caching = false
end
end
end
context "as an admin" do
sign_in_as_admin!
it "can create" do
post spree.api_taxonomy_taxons_path(taxonomy), params: { taxon: { name: "Colors" } }
expect(json_response).to have_attributes(attributes)
expect(response.status).to eq(201)
expect(taxonomy.reload.root.children.count).to eq 2
taxon = Spree::Taxon.where(name: 'Colors').first
expect(taxon.parent_id).to eq taxonomy.root.id
expect(taxon.taxonomy_id).to eq taxonomy.id
end
it "can update the position in the list" do
taxonomy.root.children << taxon2
put spree.api_taxonomy_taxon_path(taxonomy, taxon.id), params: { taxon: { parent_id: taxon.parent_id, child_index: 2 } }
expect(response.status).to eq(200)
expect(taxonomy.reload.root.children[0]).to eql taxon2
expect(taxonomy.reload.root.children[1]).to eql taxon
end
it "cannot create a new taxon with invalid attributes" do
post spree.api_taxonomy_taxons_path(taxonomy), params: { taxon: { name: '' } }
expect(response.status).to eq(422)
expect(json_response["error"]).to eq("Invalid resource. Please fix errors and try again.")
expect(taxonomy.reload.root.children.count).to eq 1
end
it "cannot create a new taxon with invalid taxonomy_id" do
post spree.api_taxonomy_taxons_path(1000), params: { taxon: { name: "Colors" } }
expect(response.status).to eq(422)
expect(json_response["error"]).to eq("Invalid resource. Please fix errors and try again.")
errors = json_response["errors"]
expect(errors["taxonomy_id"]).not_to be_nil
expect(errors["taxonomy_id"].first).to eq "Invalid taxonomy id."
expect(taxonomy.reload.root.children.count).to eq 1
end
it "can destroy" do
delete spree.api_taxonomy_taxon_path(taxonomy, taxon.id)
expect(response.status).to eq(204)
end
end
end
end
| 37.267943 | 128 | 0.633457 |
bf9361d4b5bb7e9d44e3aeb4665f8e19cd6aaca7 | 452 | require('spec_helper')
describe(Venue) do
it { should have_and_belong_to_many(:bands)}
it("validates the presence of a venue") do
venue = Venue.new({:name => ''})
expect(venue.save()).to(eq(false))
end
describe("upcase") do
it("should capitalize the first letter of each word") do
venue_test = Venue.create({:name => "the crystal ballroom"})
expect(venue_test.upcase().to(eq(The Crystal Ballroom)))
end
end
end
| 25.111111 | 66 | 0.665929 |
7a9e7d8afba4b8566f7ce59b9d90d69978456bcc | 4,905 | # frozen_string_literal: true
require 'spec_helper'
# We want to test Import on "complete" data set,
# which means that every relation (as in our Import/Export definition) is covered.
# Fixture JSONs we use for testing Import such as
# `spec/fixtures/lib/gitlab/import_export/complex/project.json`
# should include these relations being non-empty.
RSpec.describe 'Test coverage of the Project Import' do
include ConfigurationHelper
# `muted_relations` is a technical debt.
# This list expected to be empty or used as a workround
# in case this spec blocks an important urgent MR.
# It is also expected that adding a relation in the list should lead to
# opening a follow-up issue to fix this.
let(:muted_relations) do
%w[
project.milestones.events.push_event_payload
project.issues.events
project.issues.events.push_event_payload
project.issues.notes.events
project.issues.notes.events.push_event_payload
project.issues.milestone.events.push_event_payload
project.issues.issuable_sla
project.issues.issue_milestones
project.issues.issue_milestones.milestone
project.issues.resource_label_events.label.priorities
project.issues.designs.notes
project.issues.designs.notes.author
project.issues.designs.notes.events
project.issues.designs.notes.events.push_event_payload
project.merge_requests.metrics
project.merge_requests.notes.events.push_event_payload
project.merge_requests.events.push_event_payload
project.merge_requests.timelogs
project.merge_requests.label_links
project.merge_requests.label_links.label
project.merge_requests.label_links.label.priorities
project.merge_requests.milestone
project.merge_requests.milestone.events
project.merge_requests.milestone.events.push_event_payload
project.merge_requests.merge_request_milestones
project.merge_requests.merge_request_milestones.milestone
project.merge_requests.resource_label_events.label
project.merge_requests.resource_label_events.label.priorities
project.ci_pipelines.notes.events
project.ci_pipelines.notes.events.push_event_payload
project.protected_branches.unprotect_access_levels
project.prometheus_metrics
project.metrics_setting
project.boards.lists.label.priorities
project.service_desk_setting
project.security_setting
].freeze
end
# A list of JSON fixture files we use to test Import.
# Most of the relations are present in `complex/project.json`
# which is our main fixture.
let(:project_json_fixtures) do
[
'spec/fixtures/lib/gitlab/import_export/complex/project.json',
'spec/fixtures/lib/gitlab/import_export/group/project.json',
'spec/fixtures/lib/gitlab/import_export/light/project.json',
'spec/fixtures/lib/gitlab/import_export/milestone-iid/project.json',
'spec/fixtures/lib/gitlab/import_export/designs/project.json'
].freeze
end
it 'ensures that all imported/exported relations are present in test JSONs' do
not_tested_relations = (relations_from_config - tested_relations) - muted_relations
expect(not_tested_relations).to be_empty, failure_message(not_tested_relations)
end
def relations_from_config
relation_paths_for(:project)
.map { |relation_names| relation_names.join(".") }
.to_set
end
def tested_relations
project_json_fixtures.flat_map(&method(:relations_from_json)).to_set
end
def relations_from_json(json_file)
json = ActiveSupport::JSON.decode(IO.read(json_file))
[].tap {|res| gather_relations({ project: json }, res, [])}
.map {|relation_names| relation_names.join('.')}
end
def gather_relations(item, res, path)
case item
when Hash
item.each do |k, v|
if (v.is_a?(Array) || v.is_a?(Hash)) && v.present?
new_path = path + [k]
res << new_path
gather_relations(v, res, new_path)
end
end
when Array
item.each {|i| gather_relations(i, res, path)}
end
end
def failure_message(not_tested_relations)
<<~MSG
These relations seem to be added recenty and
they expected to be covered in our Import specs: #{not_tested_relations}.
To do that, expand one of the files listed in `project_json_fixtures`
(or expand the list if you consider adding a new fixture file).
After that, add a new spec into
`spec/lib/gitlab/import_export/project_tree_restorer_spec.rb`
to check that the relation is being imported correctly.
In case the spec breaks the master or there is a sense of urgency,
you could include the relations into the `muted_relations` list.
Muting relations is considered to be a temporary solution, so please
open a follow-up issue and try to fix that when it is possible.
MSG
end
end
| 37.730769 | 87 | 0.738634 |
28a9d838e63ef008915e78535fa1ac7f4048b781 | 3,004 | require 'spec_helper'
module VCAP::CloudController
module Repositories
RSpec.describe OrganizationEventRepository do
let(:request_attrs) { { 'name' => 'new-space' } }
let(:user) { User.make }
let(:organization) { Organization.make }
let(:user_email) { 'email address' }
let(:user_name) { 'user name' }
let(:user_audit_info) { UserAuditInfo.new(user_email: user_email, user_guid: user.guid, user_name: user_name) }
subject(:organization_event_repository) { OrganizationEventRepository.new }
describe '#record_organization_create' do
it 'records event correctly' do
event = organization_event_repository.record_organization_create(organization, user_audit_info, request_attrs)
event.reload
expect(event.organization_guid).to eq(organization.guid)
expect(event.type).to eq('audit.organization.create')
expect(event.actee).to eq(organization.guid)
expect(event.actee_type).to eq('organization')
expect(event.actee_name).to eq(organization.name)
expect(event.actor).to eq(user.guid)
expect(event.actor_type).to eq('user')
expect(event.actor_name).to eq(user_email)
expect(event.metadata).to eq({ 'request' => request_attrs })
end
end
describe '#record_organization_update' do
it 'records event correctly' do
event = organization_event_repository.record_organization_update(organization, user_audit_info, request_attrs)
event.reload
expect(event.organization_guid).to eq(organization.guid)
expect(event.type).to eq('audit.organization.update')
expect(event.actee).to eq(organization.guid)
expect(event.actee_type).to eq('organization')
expect(event.actee_name).to eq(organization.name)
expect(event.actor).to eq(user.guid)
expect(event.actor_type).to eq('user')
expect(event.actor_name).to eq(user_email)
expect(event.metadata).to eq({ 'request' => request_attrs })
end
end
describe '#record_organization_delete' do
let(:recursive) { true }
before do
organization.destroy
end
it 'records event correctly' do
event = organization_event_repository.record_organization_delete_request(organization, user_audit_info, request_attrs)
event.reload
expect(event.organization_guid).to eq(organization.guid)
expect(event.type).to eq('audit.organization.delete-request')
expect(event.actee).to eq(organization.guid)
expect(event.actee_type).to eq('organization')
expect(event.actee_name).to eq(organization.name)
expect(event.actor).to eq(user.guid)
expect(event.actor_type).to eq('user')
expect(event.actor_name).to eq(user_email)
expect(event.metadata).to eq({ 'request' => request_attrs })
end
end
end
end
end
| 42.309859 | 128 | 0.665113 |
1850ae5277e4d774ccffa465422e511a33387729 | 8,874 | # frozen_string_literal: true
module Parser
module Source
##
# A range of characters in a particular source buffer.
#
# The range is always exclusive, i.e. a range with `begin_pos` of 3 and
# `end_pos` of 5 will contain the following characters:
#
# example
# ^^
#
# @!attribute [r] source_buffer
# @return [Parser::Source::Buffer]
#
# @!attribute [r] begin_pos
# @return [Integer] index of the first character in the range
#
# @!attribute [r] end_pos
# @return [Integer] index of the character after the last character in the range
#
# @api public
#
class Range
include Comparable
attr_reader :source_buffer
attr_reader :begin_pos, :end_pos
##
# @param [Buffer] source_buffer
# @param [Integer] begin_pos
# @param [Integer] end_pos
#
def initialize(source_buffer, begin_pos, end_pos)
if end_pos < begin_pos
raise ArgumentError, 'Parser::Source::Range: end_pos must not be less than begin_pos'
end
if source_buffer.nil?
raise ArgumentError, 'Parser::Source::Range: source_buffer must not be nil'
end
@source_buffer = source_buffer
@begin_pos, @end_pos = begin_pos, end_pos
freeze
end
##
# @return [Range] a zero-length range located just before the beginning
# of this range.
#
def begin
with(end_pos: @begin_pos)
end
##
# @return [Range] a zero-length range located just after the end
# of this range.
#
def end
with(begin_pos: @end_pos)
end
##
# @return [Integer] amount of characters included in this range.
#
def size
@end_pos - @begin_pos
end
alias length size
##
# Line number of the beginning of this range. By default, the first line
# of a buffer is 1; as such, line numbers are most commonly one-based.
#
# @see Buffer
# @return [Integer] line number of the beginning of this range.
#
def line
@source_buffer.line_for_position(@begin_pos)
end
alias_method :first_line, :line
##
# @return [Integer] zero-based column number of the beginning of this range.
#
def column
@source_buffer.column_for_position(@begin_pos)
end
##
# @return [Integer] line number of the end of this range.
#
def last_line
@source_buffer.line_for_position(@end_pos)
end
##
# @return [Integer] zero-based column number of the end of this range.
#
def last_column
@source_buffer.column_for_position(@end_pos)
end
##
# @return [::Range] a range of columns spanned by this range.
# @raise RangeError
#
def column_range
if self.begin.line != self.end.line
raise RangeError, "#{self.inspect} spans more than one line"
end
self.begin.column...self.end.column
end
##
# @return [String] a line of source code containing the beginning of this range.
#
def source_line
@source_buffer.source_line(line)
end
##
# @return [String] all source code covered by this range.
#
def source
@source_buffer.slice(self.begin_pos...self.end_pos)
end
##
# `is?` provides a concise way to compare the source corresponding to this range.
# For example, `r.source == '(' || r.source == 'begin'` is equivalent to
# `r.is?('(', 'begin')`.
#
def is?(*what)
what.include?(source)
end
##
# @return [Array<Integer>] a set of character indexes contained in this range.
#
def to_a
(@begin_pos...@end_pos).to_a
end
##
# @return [Range] a Ruby range with the same `begin_pos` and `end_pos`
#
def to_range
self.begin_pos...self.end_pos
end
##
# Composes a GNU/Clang-style string representation of the beginning of this
# range.
#
# For example, for the following range in file `foo.rb`,
#
# def foo
# ^^^
#
# `to_s` will return `foo.rb:1:5`.
# Note that the column index is one-based.
#
# @return [String]
#
def to_s
line, column = @source_buffer.decompose_position(@begin_pos)
[@source_buffer.name, line, column + 1].join(':')
end
##
# @param [Hash] Endpoint(s) to change, any combination of :begin_pos or :end_pos
# @return [Range] the same range as this range but with the given end point(s) changed
# to the given value(s).
#
def with(begin_pos: @begin_pos, end_pos: @end_pos)
Range.new(@source_buffer, begin_pos, end_pos)
end
##
# @param [Hash] Endpoint(s) to change, any combination of :begin_pos or :end_pos
# @return [Range] the same range as this range but with the given end point(s) adjusted
# by the given amount(s)
#
def adjust(begin_pos: 0, end_pos: 0)
Range.new(@source_buffer, @begin_pos + begin_pos, @end_pos + end_pos)
end
##
# @param [Integer] new_size
# @return [Range] a range beginning at the same point as this range and length `new_size`.
#
def resize(new_size)
with(end_pos: @begin_pos + new_size)
end
##
# @param [Range] other
# @return [Range] smallest possible range spanning both this range and `other`.
#
def join(other)
Range.new(@source_buffer,
[@begin_pos, other.begin_pos].min,
[@end_pos, other.end_pos].max)
end
##
# @param [Range] other
# @return [Range] overlapping region of this range and `other`, or `nil`
# if they do not overlap
#
def intersect(other)
unless disjoint?(other)
Range.new(@source_buffer,
[@begin_pos, other.begin_pos].max,
[@end_pos, other.end_pos].min)
end
end
##
# Return `true` iff this range and `other` are disjoint.
#
# Two ranges must be one and only one of ==, disjoint?, contains?, contained? or crossing?
#
# @param [Range] other
# @return [Boolean]
#
def disjoint?(other)
if empty? && other.empty?
@begin_pos != other.begin_pos
else
@begin_pos >= other.end_pos || other.begin_pos >= @end_pos
end
end
##
# Return `true` iff this range is not disjoint from `other`.
#
# @param [Range] other
# @return [Boolean] `true` if this range and `other` overlap
#
def overlaps?(other)
!disjoint?(other)
end
##
# Returns true iff this range contains (strictly) `other`.
#
# Two ranges must be one and only one of ==, disjoint?, contains?, contained? or crossing?
#
# @param [Range] other
# @return [Boolean]
#
def contains?(other)
(other.begin_pos <=> @begin_pos) + (@end_pos <=> other.end_pos) >= (other.empty? ? 2 : 1)
end
##
# Return `other.contains?(self)`
#
# Two ranges must be one and only one of ==, disjoint?, contains?, contained? or crossing?
#
# @param [Range] other
# @return [Boolean]
#
def contained?(other)
other.contains?(self)
end
##
# Returns true iff both ranges intersect and also have different elements from one another.
#
# Two ranges must be one and only one of ==, disjoint?, contains?, contained? or crossing?
#
# @param [Range] other
# @return [Boolean]
#
def crossing?(other)
return false unless overlaps?(other)
(@begin_pos <=> other.begin_pos) * (@end_pos <=> other.end_pos) == 1
end
##
# Checks if a range is empty; if it contains no characters
# @return [Boolean]
def empty?
@begin_pos == @end_pos
end
##
# Compare ranges, first by begin_pos, then by end_pos.
#
def <=>(other)
return nil unless other.is_a?(::Parser::Source::Range) &&
@source_buffer == other.source_buffer
(@begin_pos <=> other.begin_pos).nonzero? ||
(@end_pos <=> other.end_pos)
end
alias_method :eql?, :==
##
# Support for Ranges be used in as Hash indices and in Sets.
#
def hash
[@source_buffer, @begin_pos, @end_pos].hash
end
##
# @return [String] a human-readable representation of this range.
#
def inspect
"#<Parser::Source::Range #{@source_buffer.name} #{@begin_pos}...#{@end_pos}>"
end
end
end
end
| 27.137615 | 97 | 0.569078 |
5d94700cdd013d362ab7658e06f75372c47d1098 | 1,570 | # Please don't update this formula until the release is official via
# mailing list or blog post. There's a history of GitHub tags moving around.
# https://github.com/hashicorp/vault/issues/1051
class Vault < Formula
desc "Secures, stores, and tightly controls access to secrets"
homepage "https://vaultproject.io/"
url "https://github.com/hashicorp/vault.git",
:tag => "v0.9.3",
:revision => "5acd6a21d5a69ab49d0f7c0bf540123a9b2c696d"
head "https://github.com/hashicorp/vault.git"
bottle do
cellar :any_skip_relocation
sha256 "c80c574aa0046be96d8f88ac28cf1f942504846fae77bfd28c285285e33bf71a" => :high_sierra
sha256 "e41ff20ad5673fa6f08040df2bdc07f5060fda7be7609b47a5a837f4614522cb" => :sierra
sha256 "dab4b1bb85d2c754fb0090ca0eebfd8ba3bf2c64d961bd536e75e14d01944df3" => :el_capitan
end
option "with-dynamic", "Build dynamic binary with CGO_ENABLED=1"
depends_on "go" => :build
depends_on "gox" => :build
def install
ENV["GOPATH"] = buildpath
contents = buildpath.children - [buildpath/".brew_home"]
(buildpath/"src/github.com/hashicorp/vault").install contents
(buildpath/"bin").mkpath
cd "src/github.com/hashicorp/vault" do
target = build.with?("dynamic") ? "dev-dynamic" : "dev"
system "make", target
bin.install "bin/vault"
prefix.install_metafiles
end
end
test do
pid = fork { exec bin/"vault", "server", "-dev" }
sleep 1
ENV.append "VAULT_ADDR", "http://127.0.0.1:8200"
system bin/"vault", "status"
Process.kill("TERM", pid)
end
end
| 32.708333 | 93 | 0.708917 |
117ae5b8d3e1b67f298beba3d6285d66c2760bb6 | 884 | cask 'mongoclient' do
version '2.1.0'
sha256 '4ae7a761f82d315c43f238f98ff5dabc0a78b8445fe392a1bf521b7a30c977d3'
# github.com/mongoclient/mongoclient was verified as official when first introduced to the cask
url "https://github.com/mongoclient/mongoclient/releases/download/#{version}/osx-portable.zip"
appcast 'https://github.com/mongoclient/mongoclient/releases.atom',
checkpoint: '5979ef2c12d00e088649c32b45e6ceae2b721bf81d19b1b8186a39942236623f'
name 'Mongoclient'
homepage 'https://www.mongoclient.com/'
app 'Mongoclient-darwin-x64/Mongoclient.app'
zap delete: [
'~/Library/Application Support/Mongoclient',
'~/Library/Preferences/com.electron.mongoclient.helper.plist',
'~/Library/Preferences/com.electron.mongoclient.plist',
'~/Library/Preferences/Mongoclient',
]
end
| 42.095238 | 97 | 0.720588 |
1df9caa5ffb4a99d920830130fb2ffd3b63fd210 | 359 | require "bundler/setup"
require "rql"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 23.933333 | 66 | 0.749304 |
1d1697598bd978ec6d74dfecde8ddc33245db3c7 | 1,861 | Pod::Spec.new do |s|
s.name = 'GiniCapture'
s.version = '1.0.0'
s.summary = 'Computer Vision Library for scanning documents.'
s.description = <<-DESC
Gini provides an information extraction system for analyzing documents (e. g. invoices or
contracts), specifically information such as the document sender or the amount to pay in an invoice.
The Gini Capture SDK for iOS provides functionality to capture documents with mobile phones.
DESC
s.homepage = 'https://www.gini.net/en/developer/'
s.license = { :type => 'Private', :file => 'LICENSE' }
s.author = { 'Gini GmbH' => '[email protected]' }
s.frameworks = 'AVFoundation', 'CoreMotion', 'Photos'
s.source = { :git => 'https://github.com/gini/gini-capture-sdk-ios.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/gini'
s.swift_version = '5.0'
s.ios.deployment_target = '10.0'
s.default_subspec = 'Core'
s.subspec 'Core' do |core|
core.source_files = 'GiniCapture/Classes/Core/**/*'
core.resources = 'GiniCapture/Assets/*'
end
s.subspec 'Networking' do |networking|
networking.source_files = 'GiniCapture/Classes/Networking/*.swift', 'GiniCapture/Classes/Networking/Extensions/*.swift'
networking.dependency "GiniCapture/Core"
networking.dependency 'GiniPayApiLib/DocumentsAPI', '>= 1.0.2'
end
s.subspec 'Networking+Pinning' do |pinning|
pinning.source_files = 'GiniCapture/Classes/Networking/Pinning/*'
pinning.dependency "GiniCapture/Networking"
pinning.dependency 'GiniPayApiLib/Pinning', '>= 1.0.2'
end
s.test_spec 'Tests' do |test_spec|
test_spec.source_files = 'GiniCapture/Tests/*.swift'
test_spec.resources = 'GiniCapture/Tests/Assets/*'
test_spec.requires_app_host = true
end
end
| 38.770833 | 123 | 0.671145 |
388e5264fe58c36757aac23718018b905cc4ca69 | 73 | # frozen_string_literal: true
Stripe.api_key = ENV["STRIPE_SECRET_KEY"]
| 18.25 | 41 | 0.794521 |
ed8574ce779b94951a8ffb226ce0ea6b97c4187f | 202 | # frozen_string_literal: true
module ErrorHandler
def self.included(klass)
klass.class_eval do
rescue_from StandardError do |e|
render_error_msg(e.to_s)
end
end
end
end
| 16.833333 | 38 | 0.693069 |
e2ec36356b153815c799baff24a507944162b399 | 4,284 | =begin
#Datadog API V2 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::V2
# An archive's destination.
module LogsArchiveDestination
class << self
attr_accessor :_unparsed
# List of class defined in oneOf (OpenAPI v3)
def openapi_one_of
[
:'LogsArchiveDestinationAzure',
:'LogsArchiveDestinationGCS',
:'LogsArchiveDestinationS3'
]
end
# Builds the object
# @param [Mixed] Data to be matched against the list of oneOf items
# @return [Object] Returns the model or the data itself
def build(data)
# Go through the list of oneOf items and attempt to identify the appropriate one.
# Note:
# - We do not attempt to check whether exactly one item matches.
# - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 })
# due to the way the deserialization is made in the base_object template (it just casts without verifying).
# - TODO: scalar values are de facto behaving as if they were nullable.
# - TODO: logging when debugging is set.
openapi_one_of.each do |klass|
begin
next if klass == :AnyType # "nullable: true"
typed_data = find_and_cast_into_type(klass, data)
next if typed_data._unparsed
return typed_data if typed_data
rescue # rescue all errors so we keep iterating even if the current item lookup raises
end
end
if openapi_one_of.include?(:AnyType)
data
else
self._unparsed = true
DatadogAPIClient::V2::UnparsedObject.new(data)
end
end
private
SchemaMismatchError = Class.new(StandardError)
# Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse.
def find_and_cast_into_type(klass, data)
return if data.nil?
case klass.to_s
when 'Boolean'
return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass)
when 'Float'
return data if data.instance_of?(Float)
when 'Integer'
return data if data.instance_of?(Integer)
when 'Time'
return Time.parse(data)
when 'Date'
return Date.parse(data)
when 'String'
return data if data.instance_of?(String)
when 'Object' # "type: object"
return data if data.instance_of?(Hash)
when /\AArray<(?<sub_type>.+)>\z/ # "type: array"
if data.instance_of?(Array)
sub_type = Regexp.last_match[:sub_type]
return data.map { |item| find_and_cast_into_type(sub_type, item) }
end
when /\AHash<String, (?<sub_type>.+)>\z/ # "type: object" with "additionalProperties: { ... }"
if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) }
sub_type = Regexp.last_match[:sub_type]
return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) }
end
else # model
const = DatadogAPIClient::V2.const_get(klass)
if const
if const.respond_to?(:openapi_one_of) # nested oneOf model
model = const.build(data)
return model if model
else
# raise if data contains keys that are not known to the model
raise unless (data.keys - const.acceptable_attributes).empty?
model = const.build_from_hash(data)
return model if model && model.valid?
end
end
end
raise # if no match by now, raise
rescue
raise SchemaMismatchError, "#{data} doesn't match the #{klass} type"
end
end
end
end
| 35.7 | 117 | 0.623016 |
623fdd8945647f72c38237af643c3e770f3cc2d6 | 3,173 | # frozen_string_literal: true
module Gitlab
# The SidekiqStatus module and its child classes can be used for checking if a
# Sidekiq job has been processed or not.
#
# To check if a job has been completed, simply pass the job ID to the
# `completed?` method:
#
# job_id = SomeWorker.perform_async(...)
#
# if Gitlab::SidekiqStatus.completed?(job_id)
# ...
# end
#
# For each job ID registered a separate key is stored in Redis, making lookups
# much faster than using Sidekiq's built-in job finding/status API. These keys
# expire after a certain period of time to prevent storing too many keys in
# Redis.
module SidekiqStatus
STATUS_KEY = 'gitlab-sidekiq-status:%s'
# The default time (in seconds) after which a status key is expired
# automatically. The default of 30 minutes should be more than sufficient
# for most jobs.
DEFAULT_EXPIRATION = 30.minutes.to_i
# Starts tracking of the given job.
#
# jid - The Sidekiq job ID
# expire - The expiration time of the Redis key.
def self.set(jid, expire = DEFAULT_EXPIRATION)
Sidekiq.redis do |redis|
redis.set(key_for(jid), 1, ex: expire)
end
end
# Stops the tracking of the given job.
#
# jid - The Sidekiq job ID to remove.
def self.unset(jid)
Sidekiq.redis do |redis|
redis.del(key_for(jid))
end
end
# Returns true if all the given job have been completed.
#
# job_ids - The Sidekiq job IDs to check.
#
# Returns true or false.
def self.all_completed?(job_ids)
self.num_running(job_ids) == 0
end
# Returns true if the given job is running or enqueued.
#
# job_id - The Sidekiq job ID to check.
def self.running?(job_id)
num_running([job_id]) > 0
end
# Returns the number of jobs that are running or enqueued.
#
# job_ids - The Sidekiq job IDs to check.
def self.num_running(job_ids)
responses = self.job_status(job_ids)
responses.count(&:present?)
end
# Returns the number of jobs that have completed.
#
# job_ids - The Sidekiq job IDs to check.
def self.num_completed(job_ids)
job_ids.size - self.num_running(job_ids)
end
# Returns the job status for each of the given job IDs.
#
# job_ids - The Sidekiq job IDs to check.
#
# Returns an array of true or false indicating job completion.
# true = job is still running or enqueued
# false = job completed
def self.job_status(job_ids)
keys = job_ids.map { |jid| key_for(jid) }
Sidekiq.redis do |redis|
redis.pipelined do
keys.each { |key| redis.exists(key) }
end
end
end
# Returns the JIDs that are completed
#
# job_ids - The Sidekiq job IDs to check.
#
# Returns an array of completed JIDs
def self.completed_jids(job_ids)
statuses = job_status(job_ids)
completed = []
job_ids.zip(statuses).each do |job_id, status|
completed << job_id unless status
end
completed
end
def self.key_for(jid)
STATUS_KEY % jid
end
end
end
| 27.119658 | 80 | 0.64387 |
5d6df20bdd6d6c158712330f5c8f775899e7075d | 3,318 | # frozen_string_literal: true
Rails.application.routes.draw do
devise_for :all_casa_admins, path: "all_casa_admins", controllers: {sessions: "all_casa_admins/sessions"}
devise_for :users, controllers: {sessions: "users/sessions"}
concern :with_datatable do
post "datatable", on: :collection
end
authenticated :all_casa_admin do
root to: "all_casa_admins/dashboard#show", as: :authenticated_all_casa_admin_root
end
authenticated :user do
root to: "dashboard#show", as: :authenticated_user_root
end
devise_scope :user do
root to: "devise/sessions#new"
end
devise_scope :all_casa_admins do
root to: "all_casa_admins/sessions#new", as: :unauthenticated_all_casa_root
end
get "/.well-known/assetlinks.json", to: "android_app_associations#index"
resources :casa_cases do
resource :emancipation do
member do
post "save"
end
end
resources :past_court_dates, only: %i[show]
member do
patch :deactivate
patch :reactivate
end
end
resources :casa_admins, except: %i[destroy] do
member do
patch :deactivate
patch :activate
patch :resend_invitation
end
end
resources :case_contacts, except: %i[show] do
member do
post :restore
end
resources :followups, only: %i[create], controller: "case_contacts/followups", shallow: true do
patch :resolve, on: :member
end
end
resources :reports, only: %i[index]
resources :case_court_reports, only: %i[index show] do
collection do
post :generate
end
end
resources :imports, only: %i[index create] do
collection do
get :download_failed
end
end
resources :case_contact_reports, only: %i[index]
resources :casa_orgs, only: %i[edit update]
resources :contact_type_groups, only: %i[new create edit update]
resources :contact_types, only: %i[new create edit update]
resources :hearing_types, only: %i[new create edit update]
resources :emancipation_checklists, only: %i[index]
resources :judges, only: %i[new create edit update]
resources :notifications, only: :index
resources :supervisors, except: %i[destroy] do
member do
patch :activate
patch :deactivate
patch :resend_invitation
end
end
resources :supervisor_volunteers, only: %i[create] do
member do
patch :unassign
end
end
resources :volunteers, except: %i[destroy], concerns: %i[with_datatable] do
member do
patch :activate
patch :deactivate
get :resend_invitation
patch :reminder
end
end
resources :case_assignments, only: %i[create destroy] do
member do
get :unassign
patch :unassign
end
end
resources :case_court_mandates, only: %i[destroy]
namespace :all_casa_admins do
resources :casa_orgs, only: [:new, :create, :show] do
resources :casa_admins, only: [:new, :create, :edit, :update] do
member do
patch :deactivate
patch :activate
end
end
end
end
resources :all_casa_admins, only: [:new, :create] do
collection do
get :edit
patch :update
patch "update_password"
end
end
resources :users, only: [] do
collection do
get :edit
patch :update
patch "update_password"
end
end
end
| 24.761194 | 107 | 0.679024 |
918c08c213c8d9d748dbe9fe5fe0851e937f986d | 605 | require 'test_helper'
require 'securitytxt/parser'
module SecurityTxt
class TestParser < ActiveSupport::TestCase
test 'Genereator class' do
assert_kind_of(Class, SecurityTxt::Parser)
end
test 'empty' do
assert_equal({}, Parser.new.parse(''))
end
test 'data simple' do
a = { 'foo' => 'bar', 'bar' => 'foo' }
assert_equal(a,
Parser.new.parse("Foo: bar\nBar: foo\n"))
end
test 'data multiple' do
a = { 'foo' => %w[bar foo] }
assert_equal(a,
Parser.new.parse("Foo: bar\nFoo: foo\n"))
end
end
end
| 23.269231 | 60 | 0.573554 |
61f84a13e363595471dfbb629cc97aa2953df28e | 1,063 | #
# is_ip_address.rb
#
module Puppet::Parser::Functions
newfunction(:is_ip_address, :type => :rvalue, :doc => <<-DOC
@summary
**Deprecated:** Returns true if the string passed to this function is a valid IP address.
@return [Boolean]
Returns `true` or `false`
> **Note:* **Deprecated** Will be removed in a future version of stdlib. See
[`validate_legacy`](#validate_legacy).
DOC
) do |arguments|
require 'ipaddr'
function_deprecation([:is_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function,
with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.'])
if arguments.size != 1
raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1")
end
begin
ip = IPAddr.new(arguments[0])
rescue ArgumentError
return false
end
return true if ip.ipv4? || ip.ipv6?
return false
end
end
# vim: set ts=2 sw=2 et :
| 27.973684 | 137 | 0.655691 |
219f74122d72de5ba86825b3d5a548e4cb263839 | 873 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "tddium_status_github"
s.version = "0.1.1"
s.platform = Gem::Platform::RUBY
s.authors = ["Steven Davidovitz"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/steved555/tddium-status-github"
s.summary = %q{Updates GitHub commits with their Tddium test status.}
s.description = %q{Installs pre- and post-build hooks for Tddium that update GitHub commits with the test status.}
s.license = 'Apache License Version 2.0'
s.required_ruby_version = ">= 1.8.7"
s.required_rubygems_version = ">= 1.3.6"
s.add_runtime_dependency "github_api"
s.files = `git ls-files -x Gemfile.lock`.split("\n") rescue ''
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
| 36.375 | 116 | 0.635739 |
bb2eb8c35c7b5399d9faf95612a86cc315219c85 | 632 | # Preview all emails at http://localhost:3000/rails/mailers/customer_mailer
class CustomerMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/customer_mailer/account_activation
def account_activation
customer = Customer.first
customer.activation_token = Customer.new_token
CustomerMailer.account_activation(customer)
end
# Preview this email at http://localhost:3000/rails/mailers/customer_mailer/password_reset
def password_reset
customer = Customer.first
customer.reset_token = Customer.new_token
CustomerMailer.password_reset(customer)
end
end
| 33.263158 | 96 | 0.799051 |
013daff34f1bdac4ce674ef407d98e28ff6d31f3 | 2,201 | class User < ApplicationRecord
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: {maximum:50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\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?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# ユーザーのログイン情報を破棄する
def forget
update_attribute(:remember_digest, nil)
end
# アカウントを有効にする
def activate
update_columns(activated: true, activated_at: Time.zone.now)
end
# 有効化用のメールを送信する
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# パスワード再設定の属性を設定する
def create_reset_digest
self.reset_token = User.new_token
update_columns(reset_digest: User.digest(reset_token),reset_sent_at: Time.zone.now)
end
# パスワード再設定のメールを送信する
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# パスワード再設定の期限が切れている場合はtrueを返す
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
private
#メールアドレスをすべて小文字にする
def downcase_email
self.email.downcase!
end
# 有効化トークンとダイジェストを作成および代入する
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
| 26.841463 | 87 | 0.719219 |
e2f2c9b7a12d955937ba56a0d40327c2d675416b | 1,295 | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
Rails.application.config.content_security_policy do |policy|
policy.base_uri :self
policy.default_src :none
policy.connect_src :self
policy.font_src :self
policy.img_src :self, :data, :https # TODO: Remove this once all gravatars are cached locally in the app
policy.object_src :none
policy.script_src :self, :unsafe_eval # TODO: Remove this once all use of js.erb templaces is removed
policy.style_src :self
policy.manifest_src :self
# Specify URI for violation reports
# policy.report_uri "/csp-violation-report-endpoint"
end
# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| 44.655172 | 114 | 0.765251 |
5d0c852d04a6896b3766d226bc229cf336de5d22 | 1,162 | require "active_support/all"
require "reserved_word/version"
require "reserved_word/word"
module ReservedWord
@words = ActiveSupport::OrderedOptions.new
@words.default_words = ReservedWord::Word::SITE_SLUG
def self.include?(word)
@words.default_words.include?(word)
end
def self.list
@words.default_words
end
def self.clear
@words.default_words = Array.new
end
def self.clear_all
@words = ActiveSupport::OrderedOptions.new
self.clear
end
def self.word_list
ReservedWord::Word.constants.map(&:downcase)
end
def self.all
@words.to_hash
end
def self.load!(type, key=nil)
if key == nil
@words.default_words = load_words(type)
else
@words[key] = load_words(type)
end
end
def self.load_words(type)
ReservedWord::Word.const_get(type.upcase)
end
def self.method_missing(sym, *args, &block)
sym = $1.to_sym if sym.to_s =~ /(.*)=$/
super if ReservedWord.singleton_methods.include? sym
if @words[sym] == nil
if args.first.class == Array
@words[sym] = args.first
else
super
end
else
@words[sym]
end
end
end
| 19.04918 | 56 | 0.663511 |
610afd0d8e1a8a1b7b7885c46df592f9a4603044 | 44 | # helper for heroes
module HeroesHelper
end
| 11 | 19 | 0.818182 |
08fe4d16d261114f5b77c144b61f5bb78b770716 | 1,564 | Gem::Specification.new do |spec|
spec.name = "embulk-output-bigquery"
spec.version = "0.6.4"
spec.authors = ["Satoshi Akama", "Naotoshi Seo"]
spec.summary = "Google BigQuery output plugin for Embulk"
spec.description = "Embulk plugin that insert records to Google BigQuery."
spec.email = ["[email protected]", "[email protected]"]
spec.licenses = ["MIT"]
spec.homepage = "https://github.com/embulk/embulk-output-bigquery"
# Exclude example directory which uses symlinks from generating gem.
# Symlinks do not work properly on the Windows platform without administrator privilege.
spec.files = `git ls-files`.split("\n") + Dir["classpath/*.jar"] - Dir["example/*" ]
spec.test_files = spec.files.grep(%r{^(test|spec)/})
spec.require_paths = ["lib"]
# TODO
# signet 0.12.0 and google-api-client 0.33.0 require >= Ruby 2.4.
# Embulk 0.9 use JRuby 9.1.X.Y and It compatible Ruby 2.3.
# So, Force install signet < 0.12 and google-api-client < 0.33.0
# Also, representable veresion > 3.1.0 requires Ruby version >= 2.4
spec.add_dependency 'signet', '~> 0.7', '< 0.12.0'
spec.add_dependency 'google-api-client','< 0.33.0'
spec.add_dependency 'time_with_zone'
spec.add_dependency "representable", ['~> 3.0.0', '< 3.1']
# faraday 1.1.0 require >= Ruby 2.4.
# googleauth 0.9.0 requires faraday ~> 0.12
spec.add_dependency "faraday", '~> 0.12'
spec.add_development_dependency 'bundler', ['>= 1.10.6']
spec.add_development_dependency 'rake', ['>= 10.0']
end
| 47.393939 | 94 | 0.662404 |
012eae87a2125edab9dd1f2cf3eff0496bb448ea | 4,784 | require 'spec_helper'
describe ActAsTimeAsBoolean do
it 'defines time_as_boolean class method' do
Article.singleton_methods.should include(:time_as_boolean)
end
describe 'calling time_as_boolean' do
describe 'without param' do
it 'raises an ArgumentError' do
expect do
class Article < ActiveRecord::Base
include ActAsTimeAsBoolean
time_as_boolean
end
end.to raise_error(ArgumentError)
end
end
describe 'with :active param' do
subject { Article.new.methods }
it 'defines active method' do
subject.should include(:active)
end
it 'defines active? method' do
subject.should include(:active?)
end
it 'defines active= method' do
subject.should include(:active=)
end
end
describe 'with :active and opposite param' do
subject { ArticleWithOpposite.new.methods }
it 'defines active method' do
subject.should include(:active)
end
it 'defines active? method' do
subject.should include(:active?)
end
it 'defines active= method' do
subject.should include(:active=)
end
it 'defines inactive method' do
subject.should include(:inactive)
end
it 'defines inactive? method' do
subject.should include(:inactive?)
end
end
describe 'scopes' do
describe 'with :active param' do
subject { Article.new }
it 'define active scope' do
subject.class.methods.should include(:active)
end
it 'defines active! method' do
subject.methods.should include(:active!)
end
end
describe 'with :active and opposite param' do
subject { ArticleWithOpposite.new }
it 'define active scope' do
subject.class.methods.should include(:active)
end
it 'define inactive scope' do
subject.class.methods.should include(:inactive)
end
it 'defines inactive! method' do
subject.methods.should include(:inactive!)
end
end
end
end
describe 'using ActAsTimeAsBoolean' do
describe 'with an active instance' do
let(:time) { Time.now }
subject { ArticleWithOpposite.new active_at: time }
describe 'calling active' do
it { subject.active.should be_true }
end
describe 'calling active?' do
it { subject.active?.should be_true }
end
describe 'calling active=' do
describe 'with true' do
before { subject.active = true }
it { subject.active_at.should == time }
end
describe 'with false' do
before { subject.active = false }
it { subject.active_at.should be_nil }
end
describe "with '1'" do
before { subject.active = '1' }
it { subject.active_at.should == time }
end
describe "with '0'" do
before { subject.active = '0' }
it { subject.active_at.should be_nil }
end
end
describe 'calling inactive' do
it { subject.inactive.should be_false }
end
describe 'calling inactive?' do
it { subject.inactive?.should be_false }
end
describe 'calling active!' do
before { subject.active! }
it { subject.active?.should be_true }
end
describe 'calling inactive!' do
before { subject.inactive! }
it { subject.active?.should be_false }
end
end
describe 'with an inactive instance' do
subject { ArticleWithOpposite.new }
describe 'calling active' do
it { subject.active.should be_false }
end
describe 'calling active?' do
it { subject.active?.should be_false }
end
describe 'calling active=' do
[true, '1'].each do |value|
describe "with #{value}" do
before { subject.active = value }
it { subject.active_at.class.should == ActiveSupport::TimeWithZone }
end
end
[false, '0'].each do |value|
describe "with #{value}" do
before { subject.active = value }
it { subject.active_at.should be_nil }
end
end
end
describe 'calling inactive' do
it { subject.inactive.should be_true }
end
describe 'calling inactive?' do
it { subject.inactive?.should be_true }
end
describe 'calling active!' do
before { subject.active! }
it { subject.active?.should be_true }
end
describe 'calling inactive!' do
before { subject.inactive! }
it { subject.active?.should be_false }
end
end
end
end
| 24.284264 | 80 | 0.590301 |
ab4f75d7736120bfb179ce62075801dd6f9d8c6a | 1,048 | require 'rubygems' # you need this when xbrlware is installed as gem
require 'edgar'
require 'xbrlware'
dl=Edgar::HTMLFeedDownloader.new()
url="http://www.sec.gov/Archives/edgar/data/843006/000135448809002030/0001354488-09-002030-index.htm"
download_dir=url.split("/")[-2] # download dir is : 000135448809002030
dl.download(url, download_dir)
# Name of xbrl documents downloaded from EDGAR system is in the following convention
# calculation linkbase document ends with _cal.xml
# definition linkbase document ends with _def.xml
# presentation linkbase ends with _pre.xml
# label linkbase document ends with _lab.xml
# taxonomy document ends with .xsd
# instance document ends with .xml
# Xbrl::file_grep understands above convention.
instance_file=Xbrlware.file_grep(download_dir)["ins"] # use file_grep to filter xbrl files and get instance file
instance=Xbrlware.ins(instance_file)
items=instance.item("OtherAssetsCurrent")
puts "Other-Assets \t Context"
items.each do |item|
puts item.value+" \t "+item.context.id
end | 38.814815 | 112 | 0.775763 |
f739fe781be9872f9db861fc4f7799b5698e147f | 541 | cask 'lytro-desktop' do
version '4.3.3,151118.98'
sha256 '500b28ed7d67aaf18a59a8770e3fb83a4b96e692728ddbd522a52879af758966'
# amazonaws.com/lytro-distro was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/lytro-distro/lytro-#{version.after_comma}.dmg"
appcast 'https://pictures.lytro.com/support/software_update',
checkpoint: 'c806ff660e791f181371f9946412ee07ebd03459db8791832ed4b0be378d587a'
name 'Lytro Desktop'
homepage 'https://www.lytro.com/'
app 'Lytro Desktop.app'
end
| 38.642857 | 89 | 0.780037 |
abdf044b0def463bb306169dfc63c76dfde4fa79 | 3,108 | require 'yaml'
spells_lines_names = { 0 => :name, 1 => :level, 2 => :casting_time, 3 => :range, 4 => :components, 5 => :duration }
spells = []
COMPONENTS = %w( V S M )
File.open( 'Spells - cleaned.txt', 'r' ) do |file|
spells_lines_start_lines = []
current_line = 0
file.each_line do |line|
current_line += 1
if line.strip =~ /Casting Time: \d+ \w+/
spells_lines_start_lines << current_line - 2
end
end
file.seek( 0, :SET )
current_line = 0
current_spell = {}
spell_lines_count = 0
spells_lines_start_lines.shift # Dont process the first line as it is not following something
spells_lines_start_lines = spells_lines_start_lines.map{ |e| e-1 } # Also the end line must be the line before the start of the spell.
file.each_line do |line|
current_line += 1
if spell_lines_count <= 5
current_spell[ :start_line ] = current_line if spell_lines_count == 0
current_spell[ spells_lines_names[ spell_lines_count ] ] = line.strip
spell_lines_count += 1
else
current_spell[ :description ] = [] unless current_spell[ :description ]
current_spell[ :description ] << line.strip unless line.strip.length == 0
end
if spells_lines_start_lines.include?( current_line )
spell_lines_count = 0
spells << current_spell
current_spell = {}
end
end
end
spells.each_entry do |entry|
# puts "#{entry[ :start_line ] } - #{entry[ :casting_time ].inspect}"
entry[ :casting_time ].gsub!( 'Casting Time: ', '' ) if entry[ :casting_time ]
entry[ :duration ].gsub!( 'Duration: ', '' ) if entry[ :duration ]
entry[ :components ].gsub!( 'Components: ', '' ) if entry[ :components ]
if entry[ :level ] =~ /cantrip/
entry[ :school ] = entry[ :level ].match( /(\w+)/ )[1].downcase.to_sym
entry[ :level ] = 0
entry[ :cantrip ] = true
else
result = entry[ :level ].match( /(\d+)[a-z\-]+ (\w+)(.*)/ )
entry[ :level ] = result[1].to_i
entry[ :school ] = result[2].downcase.to_sym
entry[ :ritual ] = true if result[3]
end
components = entry[ :components ].split( /[,()]/ ).map{ |e| e.strip }
entry[ :components ] = []
until components.empty?
c = components.shift
if COMPONENTS.include?( c )
entry[ :components ] << c
else
entry[ :material_components ] = c.capitalize
end
end
entry[ :range ].gsub!( 'Range: ', '' ) if entry[ :range ]
range_in_feet = entry[ :range ].match( /(\d+) feet/ )
range_in_feet = range_in_feet[ 1 ] if range_in_feet
range_in_yards = entry[ :range ].match( /(\d+) miles?/ )
range_in_yards = range_in_yards[ 1 ] if range_in_yards
range_in_feet = range_in_yards.to_i * 3 if range_in_yards
range_in_miles = entry[ :range ].match( /(\d+) miles?/ )
range_in_miles = range_in_miles[ 1 ] if range_in_miles
range_in_feet = range_in_miles.to_i * 5280 if range_in_miles
entry[ :range_in_feet ] = range_in_feet ? range_in_feet.to_i : 0
# ranges = [ entry[ :range ], entry[ :range_in_feet ] ].join( ' - ' )
# puts ranges
end
File.open( 'spell_database.yaml', 'w' ) do |file|
file.puts spells.to_yaml
end | 31.714286 | 136 | 0.644144 |
e9d7677f87dcc2a6526dd70edf7ce718ed5e0ab8 | 4,107 | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
def self.validate_changes(inputs, field_map, root_model, context, all_changes)
invalid_fields = {}
unknown_errors = []
changed_models = all_changes.group_by { |c| c[:model_instance] }
changed_models.reject { |m, _v| m.valid? }.each do |model, changes|
attrs_to_field = changes
.select { |c| c[:attribute] && c[:input_path] }
.map { |c| [c[:attribute], c[:input_path]] }
.to_h
model.errors.each do |attribute, message|
attribute = attribute.to_sym if attribute.is_a?(String)
# Cheap check, see if this is a field that the user provided a value for...
if attrs_to_field.include?(attribute)
add_error(attribute, message, attrs_to_field[attribute], invalid_fields)
else
# Didn't provide a value, expensive check... trace down the input field
path = detect_input_path_for_attribute(model, attribute, inputs, field_map, root_model, context)
if path
add_error(attribute, message, path, invalid_fields)
else
unknown_errors.push({
modelType: model.class.name,
modelRid: model.id,
attribute: attribute,
message: message,
})
end
end
end
end
unless invalid_fields.empty? && unknown_errors.empty?
raise ValidationError.new(invalid_fields, unknown_errors)
end
end
def self.add_error(_attribute, message, path, invalid_fields)
path = Array.wrap(path)
current = invalid_fields
path[0..-2].each do |ps|
current = current[ps] ||= {}
end
current[path[-1]] = message
end
# Given a model and an attribute, returns the path of the input field that would modify that attribute
def self.detect_input_path_for_attribute(target_model, attribute, inputs, field_map, starting_model, context)
# Case 1: The input field is inside of this field map.
candidate_fields = field_map.fields.select { |f| f[:attribute] == attribute }
candidate_fields.each do |field|
# Walk to this field. If the model we get is the same as the target model, we found a match.
candidate_model = model_to_change(starting_model, field[:path], [], create_if_missing: false)
return Array.wrap(field[:name]) if candidate_model == target_model
end
# Case 2: The input field *is* a nested map
candidate_maps = field_map.nested_maps.select { |m| m.association == attribute.to_s }
candidate_maps.each do |map|
# Walk to this field. If the model we get is the same as the target model, we found a match.
candidate_model = model_to_change(starting_model, map.path, [], create_if_missing: false)
return Array.wrap(map.name) if candidate_model == target_model
end
# Case 3: The input field is somewhere inside of a nested field map.
field_map.nested_maps.each do |child_map|
# If we don't have the values for this map, it can't be the right one.
next if inputs[child_map.name].blank?
# Walk to the model that contains the nested field
candidate_model = model_to_change(starting_model, child_map.path, [], create_if_missing: false)
# If the model for this map doesn't exist, it can't be the one we need, because the target_model does exist.
next if candidate_model.nil?
# Match up the inputs with the models, and then check each of them.
candidate_matches = match_inputs_to_models(candidate_model, child_map, inputs[child_map.name], [], context)
candidate_matches.each do |m|
result = detect_input_path_for_attribute(target_model, attribute, m[:child_inputs], child_map, m[:child_model], context)
next if result.nil?
path = Array.wrap(result)
path.unshift(m[:input_path]) if m[:input_path]
return path
end
end
nil
end
end
end
| 39.114286 | 130 | 0.648405 |
1d2dcabe55c49714d982920a0ce032faec5c0da6 | 1,986 | require 'rod/rest/exception'
module Rod
module Rest
# Cache used to store proxy objects.
class ProxyCache
# Initializes empty cache.
def initialize(cache_implementation={})
@cache_implementation = cache_implementation
end
# Returns true if the described object is in the cache.
def has_key?(description)
check_description(description)
@cache_implementation[description_signature(description)]
end
# Returns the object stored in the cache. Raises CacheMissed exception if
# the result is nil.
def [](description)
check_description(description)
value = @cache_implementation[description_signature(description)]
raise CacheMissed.new(missing_entry_message(description)) if value.nil?
end
# Store the +object+ in the cache.
def store(object)
check_object(object)
@cache_implementation[description_signature(rod_id: object.rod_id,type: object.type)] = object
end
private
def description_signature(description)
"#{description[:rod_id]},#{description[:type]}"
end
def check_object(object)
if !object.respond_to?(:rod_id) || !object.respond_to?(:type)
raise InvalidData.new(invalid_object_message(object))
end
end
def check_description(description)
if !description.respond_to?(:has_key?) || !description.has_key?(:rod_id) || !description.has_key?(:type)
raise InvalidData.new(invalid_description_message(description))
end
end
def missing_entry_message(description)
"No entry for object rod_id:#{description[:rod_id]} type:#{description[:type]}"
end
def invalid_object_message(object)
"The object cannot be stored in the cache: #{object}."
end
def invalid_description_message(description)
"The description of the object is invalid: #{description}."
end
end
end
end
| 31.52381 | 112 | 0.672709 |
915b93eb01daf3831e0a40ff5cc2012c9f1f7a4d | 2,122 | # server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
# server "example.com", user: "deploy", roles: %w{app db web}, my_property: :my_value
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", roles: %w{db}
server 'pw', roles: %w{app web db}
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{[email protected]}, my_property: :my_value
# role :web, %w{[email protected] [email protected]}, other_property: :other_value
# role :db, %w{[email protected]}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server "example.com",
# user: "user_name",
# roles: %w{web app},
# ssh_options: {
# user: "user_name", # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: "please use keys"
# }
| 34.225806 | 88 | 0.66918 |
edf4ea87e95b563c84c88bf4b2cccbce8ec71297 | 3,344 | require 'spec_helper'
describe Maestrano::Connector::Rails::Synchronization do
# Attributes
it { should validate_presence_of(:status) }
# Indexes
it { should have_db_index(:organization_id) }
#Associations
it { should belong_to(:organization) }
describe 'class methods' do
subject { Maestrano::Connector::Rails::Synchronization }
describe 'create_running' do
let(:organization) { create(:organization) }
it 'creates an organization' do
expect{ subject.create_running(organization) }.to change{ Maestrano::Connector::Rails::Synchronization.count }.by(1)
end
it { expect(subject.create_running(organization).status).to eql('RUNNING') }
end
end
describe 'instance methods' do
describe 'success?' do
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'SUCCESS').success?).to be(true) }
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'ERROR').success?).to be(false) }
end
describe 'error?' do
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'ERROR').error?).to be(true) }
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'RUNNING').error?).to be(false) }
end
describe 'running?' do
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'RUNNING').running?).to be(true) }
it { expect(Maestrano::Connector::Rails::Synchronization.new(status: 'ERROR').running?).to be(false) }
end
describe 'mark_as_success' do
let(:sync) { create(:synchronization, status: 'RUNNING') }
it 'set the synchronization status to success' do
sync.mark_as_success
sync.reload
expect(sync.status).to eql('SUCCESS')
end
end
describe 'mark_as_error' do
let(:sync) { create(:synchronization, status: 'RUNNING') }
it 'set the synchronization status to error with the message' do
sync.mark_as_error('msg')
sync.reload
expect(sync.status).to eql('ERROR')
expect(sync.message).to eql('msg')
end
end
describe 'mark_as_partial' do
let(:sync) { create(:synchronization, partial: false) }
it 'set the synchronization status to error with the message' do
sync.mark_as_partial
sync.reload
expect(sync.partial).to be(true)
end
end
describe 'clean_synchronizations on creation' do
let!(:organization) { create(:organization) }
context 'when less than 100 syncs' do
before {
2.times do
create(:synchronization, organization: organization)
end
}
it 'does nothing' do
expect{ organization.synchronizations.create(status: 'RUNNING') }.to change{ organization.synchronizations.count }.by(1)
end
end
context 'when more than 100 syncs' do
before {
100.times do
create(:synchronization, organization: organization)
end
}
it 'destroy the right syncs' do
sync = organization.synchronizations.create(status: 'RUNNING')
expect(Maestrano::Connector::Rails::Synchronization.count).to eql(100)
expect(Maestrano::Connector::Rails::Synchronization.all.map(&:id)).to eql([*2..101])
end
end
end
end
end
| 31.252336 | 130 | 0.650718 |
5d7174f24fa86987a8c0edae09d0177dec13ea4d | 2,345 | # frozen_string_literal: true
module Asciidoctor
class SyntaxHighlighter::CodeRayAdapter < SyntaxHighlighter::Base
register_for 'coderay'
def initialize *args
super
@pre_class = 'CodeRay'
@requires_stylesheet = nil
end
def highlight?
library_available?
end
def highlight node, source, lang, opts
@requires_stylesheet = true if (css_mode = opts[:css_mode]) == :class
lang = lang ? (::CodeRay::Scanners[lang = lang.to_sym] && lang rescue :text) : :text
highlighted = ::CodeRay::Duo[lang, :html,
css: css_mode,
line_numbers: (line_numbers = opts[:number_lines]),
line_number_start: opts[:start_line_number],
line_number_anchors: false,
highlight_lines: opts[:highlight_lines],
bold_every: false,
].highlight source
if line_numbers == :table && opts[:callouts]
[highlighted, (idx = highlighted.index CodeCellStartTagCs) ? idx + CodeCellStartTagCs.length : nil]
else
highlighted
end
end
def docinfo? location
@requires_stylesheet && location == :head
end
def docinfo location, doc, opts
if opts[:linkcss]
%(<link rel="stylesheet" href="#{doc.normalize_web_path stylesheet_basename, (doc.attr 'stylesdir', ''), false}"#{opts[:self_closing_tag_slash]}>)
else
%(<style>
#{read_stylesheet}
</style>)
end
end
def write_stylesheet? doc
@requires_stylesheet
end
def write_stylesheet doc, to_dir
::File.write (::File.join to_dir, stylesheet_basename), read_stylesheet, mode: FILE_WRITE_MODE
end
module Loader
private
def library_available?
(@@library_status ||= load_library) == :loaded ? true : nil
end
def load_library
(defined? ::CodeRay::Duo) ? :loaded : (Helpers.require_library 'coderay', true, :warn).nil? ? :unavailable : :loaded
end
end
module Styles
include Loader
def read_stylesheet
@@stylesheet_cache ||= (::File.read (::File.join Stylesheets::STYLESHEETS_DIR, stylesheet_basename), mode: FILE_READ_MODE).rstrip
end
def stylesheet_basename
'coderay-asciidoctor.css'
end
end
extend Styles # exports static methods
include Styles # adds methods to instance
include Loader # adds methods to instance
CodeCellStartTagCs = '<td class="code"><pre>'
private_constant :CodeCellStartTagCs
end
end
| 26.055556 | 152 | 0.689979 |
e827221394236906b74e0210519d70ad3b22ee50 | 564 | require_relative 'bench_helper'
module BenchGetuid
iter = ITER
module Posix
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function :getuid, [], :uint
end
puts "uid=#{Process.pid} Posix.getuid=#{Posix.getuid}"
puts "Benchmark FFI getuid performance, #{iter}x calls"
10.times {
puts Benchmark.measure {
iter.times { Posix.getuid }
}
}
puts "Benchmark Process.uid performance, #{iter}x calls"
10.times {
puts Benchmark.measure {
iter.times { Process.uid }
}
}
end unless FFI::Platform.windows?
| 20.142857 | 58 | 0.664894 |
abcc709acbf0d8c3204ec0e6dc6cc905d1c421c7 | 632 | module EventInventory::Catalog
class Performer < Base
class Parser
include ParseHelper
class Performer
include ParseHelper
element :row, :value => :event_id, :as => :id
element :row, :value => :event_name, :as => :name
element :row, :value => :event_type_id, :as => :event_type_id
element :row, :value => :category_id, :as => :category_id
end
elements :row, :as => :performers, :class => Performer
end
get :get_all_events, :as => :fetch
class << self
def all(parameters={})
fetch(parameters).performers
end
end
end
end
| 23.407407 | 69 | 0.593354 |
ffee86a3190a064284b628162f1e52698021a9a6 | 585 | cask 'max' do
if MacOS.version <= :mojave
version '0.9.1'
sha256 '722bf714696d3d39329ba98ffddc9f117f8cc6863f71670507cd12f62a5e5f14'
appcast 'https://sbooth.org/Max/appcast.xml'
url "https://files.sbooth.org/Max-#{version}.tar.bz2"
app "Max-#{version}/Max.app"
else
version '0.9.2b2'
sha256 'f8f6c60bb79d186de7907500459f4391025bd77f5e2fad4e240cae34aaa027cd'
url "https://files.sbooth.org/Max-#{version}.dmg"
app 'Max.app'
end
name 'Max'
homepage 'https://sbooth.org/Max/'
zap trash: '~/Library/Preferences/org.sbooth.Max.plist'
end
| 24.375 | 77 | 0.702564 |
e87c60df788117cf5b18c88af6835aba5d1ef889 | 602 | Pod::Spec.new do |s|
s.name = 'KLAddressSelector'
s.version = '0.1.2'
s.license = 'MIT'
s.summary = '地址选择器'
s.homepage = 'https://github.com/liuxiaolu/KLAddressSelector'
s.authors = { 'liuxiaolu' => '[email protected]' }
s.ios.deployment_target = '9.0'
# s.osx.deployment_target = '10.11'
# s.tvos.deployment_target = '9.0'
s.source = { :git => 'https://github.com/liuxiaolu/KLAddressSelector.git', :tag => s.version }
s.source_files = 'KLAddressSelectorExample/AddressView/*.swift'
s.resources = 'KLAddressSelectorExample/AddressView/*.plist'
#s.dependency 'SnapKit'
s.requires_arc = true
end
| 24.08 | 94 | 0.710963 |
1ab6c0b7b1e42fbe6b210cb78e56f28d153657df | 22,137 | #!/usr/bin/env ruby
require 'optparse'
require 'ostruct'
# Use this script to install and provision contrail nodes.
# sudo ruby $PWD/contrail-kubernetes/scripts/opencontrail-install/contrail_install.rb
@opt = OpenStruct.new
def parse_options
@opt.fix_docker_issue = false
@opt.intf = "eth0"
@opt.role = "controller"
@opt.setup_kubernetes = false
@opt.controller_host = "localhost"
@opt.kubernetes_master = "localhost"
@opt.controller_ip = ""
@opt.private_net = "10.0.0.0/16"
@opt.portal_net = "10.254.0.0/16"
@opt.public_net = "10.1.0.0/16"
@opt.user = "ubuntu"
@opt.password = "ubuntu"
@opt.setup_ssh = false
@opt.ssh_key = "/home/#{@opt.user}/.ssh/contrail_rsa"
@opt.contrail_install = true
@opt.provision_vgw = false
@opt.wait_for_kube_api = false
@opt.kubernetes_branch = "v0.20.1"
@opt.cassandra_db_path = "/var/lib/cassandra"
if File.directory? "/vagrant" then
@opt.intf = "eth1"
@opt.user = "vagrant"
@opt.portal_net = "10.247.0.0/16"
end
opt_parser = OptionParser.new { |o|
o.banner = "Usage: #{$0} [options]"
o.on("-b", "--public-net #{@opt.public_net}",
"Public network subnet value") { |net|
@opt.public_net = net
}
o.on("-c", "--controller-name #{@opt.controller_host}",
"Name of the contrail controller host") { |controller|
@opt.controller_host = controller
}
o.on("-d", "--password #{@opt.password}", "Guest user passwd") { |pass|
@opt.password = pass
}
o.on("--cassandra-db-path #{@opt.cassandra_db_path}",
"Contrail cassandra db path") { |db_path|
@opt.cassandra_db_path = db_path
}
o.on("-f", "--[no-]fix-docker-fs-issue", "#{@opt.fix_docker_issue}",
"Fix/work-around docker fs device mapper issue") { |f|
@opt.fix_docker_issue = f
}
o.on("-g", "--[no-]provision-vgw", "#{@opt.provision_vgw}",
"Provision vgw interface") { |f|
@opt.provision_vgw = f
}
o.on("-i", "--controller-ip #{@opt.controller_ip}",
"IP of the contrail controller host") { |ip|
@opt.controller_ip = ip
}
o.on("-I", "--intf #{@opt.intf}", "data interface name") { |i|
@opt.intf = i
}
o.on("-k", "--[no-]kubernetes-setup", "[#{@opt.setup_kubernetes}",
"Setup kubernetes plugin") { |kubernetes|
@opt.setup_kubernetes = kubernetes
}
o.on("-l", "--portal-net #{@opt.portal_net}",
"Portal network subnet value") { |net|
@opt.portal_net = net
}
o.on("-m", "--kubernetes-master #{@opt.kubernetes_master}",
"Name of the kubernetes master host") { |kubernetes_master|
@opt.kubernetes_master = kubernetes_master
}
o.on("-n", "--kubernetes-branch #{@opt.kubernetes_branch}",
"Name of the kubernetes branch") { |branch|
@opt.kubernetes_branch = branch
}
o.on("-p", "--private-net #{@opt.private_net}",
"Private network subnet value") { |net|
@opt.private_net = net
}
o.on("-r", "--role #{@opt.role}", "Configuration role") { |role|
@opt.role = role
}
o.on("-s", "--[no-]ssh-setup", "[#{@opt.setup_ssh}",
"Setup ssh configuration") { |setup|
@opt.setup_ssh = setup
}
o.on("-t", "--[no-]contrail-install", "[#{@opt.contrail_install}",
"Install and provision contrail software") { |contrail_install|
@opt.contrail_install = contrail_install
}
o.on("-u", "--user #{@opt.user}", "Guest user name") { |user|
@opt.user = user
}
o.on("-w", "--[no-]wait-for-kube-api", "[#{@opt.setup_ssh}",
"Wait until kubernetes api server is up") { |wait_for_kube_api|
@opt.wait_for_kube_api = wait_for_kube_api
}
o.on("-y", "--ssh-key #{@opt.ssh_key}",
"ssh key for user #{@opt.user} #{@opt.ssh_key}") { |key|
@opt.ssh_key = ssh_key
}
}
opt_parser.parse!(ARGV)
end
# Parse command line options.
parse_options
@ws="#{File.dirname($0)}"
require "#{@ws}/util"
# Find platform OS
sh(%{\grep -i "ubuntu 14" /etc/issue 2>&1 > /dev/null}, true)
@platform = $?.to_i == 0 ? "ubuntu1404" : "fedora20"
require "#{@ws}/#{@platform}/install"
@utils = @platform =~ /fedora/ ? "/opt/contrail/utils" :
"/usr/share/contrail-utils"
# Update ssh configuration
def setup_ssh
return unless @opt.setup_ssh
conf=<<EOF
UserKnownHostsFile=/dev/null
StrictHostKeyChecking=no
LogLevel=QUIET
EOF
sh("mkdir -p /root/.ssh")
File.open("/root/.ssh/config", "a") { |fp| fp.puts(conf) }
sh("chmod 600 /root/.ssh/config")
# Add ssh config to [email protected] also.
sh("mkdir -p /home/#{@opt.user}/.ssh")
File.open("/home/#{@opt.user}/.ssh/config", "a") { |fp| fp.puts(conf) }
sh("chmod 600 /home/#{@opt.user}/.ssh/config")
sh("chown #{@opt.user}.#{@opt.user} /home/#{@opt.user}/.ssh/config")
sh("chown #{@opt.user}.#{@opt.user} /home/#{@opt.user}/.ssh/.")
end
def resolve_controller_host_name
return if [email protected]_ip.empty?
begin
@opt.controller_ip = IPSocket.getaddress(@opt.controller_host)
rescue
# Check in /etc/hosts
@opt.controller_ip =
sh(%{grep #{@opt.controller_host} /etc/hosts | awk '{print $1}'})
end
error "Cannot resolve controller #{@opt.controller_host}" \
if @opt.controller_ip.empty?
end
# Do initial setup
def initial_setup
STDOUT.sync = true
raise 'Must run with superuser privilages' unless Process.uid == 0
@control_node_introspect_port =
@opt.controller_host == "aurora" ? 9083 : "8083"
setup_ssh
sh("service hostname restart", true) if @platform !~ /fedora/
resolve_controller_host_name
# Make sure that localhost resolves to 127.0.0.1
sh(%{\grep -q "127\.0\.0\.1.*localhost" /etc/hosts}, true)
sh("echo 127.0.0.1 localhost >> /etc/hosts") if $?.to_i != 0
Dir.chdir("#{@ws}")
sh("mkdir -p /var/crashes", true)
end
def update_controller_etc_hosts
# Update /etc/hosts with the IP address
@controller_ip, mask, gw, prefix_len = get_intf_ip(@opt.intf)
rip = sh("\grep #{@opt.controller_host} /etc/hosts | awk '{print $1}'", true)
return if rip != "127.0.0.1" and !rip.empty?
# If @opt.controller_host resolves to 127.0.0.1, take it out of /etc/hosts
sh("sed -i '/127.0.0.1 #{@opt.controller_host}/d' /etc/hosts") \
if rip == "127.0.0.1"
sh("echo #{@controller_ip} #{@opt.controller_host} >> /etc/hosts")
end
def verify_controller
sh("netstat -anp | \grep LISTEN | \grep -w 5672", false, 10, 3) # RabbitMQ
sh("netstat -anp | \grep LISTEN | \grep -w 2181", false, 10, 3) # ZooKeeper
sh("netstat -anp | \grep LISTEN | \grep -w 9160", false, 10, 3) # Cassandra
sh("netstat -anp |\grep LISTEN | \grep -w #{@control_node_introspect_port}",
false, 10, 3) # Control-Node
sh("netstat -anp | \grep LISTEN | \grep -w 5998", false, 10, 3) # discovery
sh("netstat -anp | \grep LISTEN | \grep -w 6379", false, 10, 3) # redis
sh("netstat -anp | \grep LISTEN | \grep -w 8443", false, 10, 3) # IFMAP
sh("netstat -anp | \grep LISTEN | \grep -w 8082", false, 10, 3) # API-Server
sh("netstat -anp | \grep LISTEN | \grep -w 8086", false, 10, 3) # Collector
sh("netstat -anp | \grep LISTEN | \grep -w 8087", false, 10, 3) # Schema
sh("netstat -anp | \grep LISTEN | \grep -w 8081", false, 10, 3) # OpServer
sh("netstat -anp | \grep LISTEN | \grep -w 8094", false, 10, 3) # DNS
sh("netstat -anp | \grep LISTEN | \grep -w 53", false, 10, 3) # named
sh("netstat -anp | \grep LISTEN | \grep -w 8143", false, 10, 3) # WebUI
sh("netstat -anp | \grep LISTEN | \grep -w 8070", false, 10, 3) # WebUI
puts "All contrail controller components up"
end
# Fix nodemgr configs
def fix_nodemgr_config_files
nodemgr_conf = <<EOF
[COLLECTOR]
server_list=127.0.0.1:8086
EOF
File.open("/etc/contrail/contrail-control-nodemgr.conf", "a") { |fp|
fp.puts nodemgr_conf
}
File.open("/etc/contrail/contrail-database-nodemgr.conf", "a") { |fp|
fp.puts nodemgr_conf
}
File.open("/etc/contrail/contrail-analytics-nodemgr.conf", "a") { |fp|
fp.puts nodemgr_conf
}
File.open("/etc/contrail/contrail-config-nodemgr.conf", "a") {|fp|
fp.puts nodemgr_conf
}
end
def provision_linklocal_service
# Get the service gateway IP
return if @opt.portal_net.split(/\//)[0] !~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/
portal_gw = "#{$1}.#{$2}.#{$3}.#{($4.to_i) | 1}"
# Provision kube-api access to DNS via link-local service
sh(%{python #{@utils}/provision_linklocal.py --api_server_ip #{@controller_ip} --api_server_port 8082 --linklocal_service_name kubernetes --linklocal_service_ip #{portal_gw} --linklocal_service_port 8080 --ipfabric_service_ip #{@controller_ip} --ipfabric_service_port 8080 --oper add}, true)
end
# Provision contrail-controller
def provision_contrail_controller
update_controller_etc_hosts
sh("ln -sf /bin/openstack-config /opt/contrail/bin/openstack-config") \
if @platform =~ /fedora/
if @platform =~ /fedora/ then
sh(%{sed -i 's/Xss180k/Xss280k/' /etc/cassandra/conf/cassandra-env.sh})
sh(%{echo "api-server:api-server" >> /etc/ifmap-server/basicauthusers.properties})
sh(%{echo "schema-transformer:schema-transformer" >> /etc/ifmap-server/basicauthusers.properties})
sh(%{echo "svc-monitor:svc-monitor" >> /etc/ifmap-server/basicauthusers.properties})
sh(%{echo "control-user:control-user-passwd" >> /etc/ifmap-server/basicauthusers.properties})
sh(%{sed -i 's/911%(process_num)01d/5998/' /etc/contrail/supervisord_config_files/contrail-discovery.ini})
sh(%{sed -i 's/91%(process_num)02d/8082/' /etc/contrail/supervisord_config_files/contrail-api.ini})
sh(%{sed -i 's/# port=5998/port=5998/' /etc/contrail/contrail-control.conf})
sh(%{sed -i 's/# server=127.0.0.1/server=127.0.0.1/' /etc/contrail/contrail-control.conf})
sh(%{sed -i 's/# port=5998/port=5998/' /etc/contrail/contrail-collector.conf})
sh(%{sed -i 's/# server=0.0.0.0/server=127.0.0.1/' /etc/contrail/contrail-collector.conf})
sh(%{sed -i 's/# user=control-user/user=control-user/g' /etc/contrail/contrail-control.conf})
sh(%{sed -i 's/# password=control-user-passwd/password=control-user-passwd/' /etc/contrail/contrail-control.conf})
sh(%{sed -i 's/Xss180k/Xss280k/' /etc/cassandra/conf/cassandra-env.sh})
end
# Reduce analytics cassandra db ttl
sh(%{/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-collector.conf DEFAULT analytics_data_ttl 1})
# Fix webui config
if !File.file? "/usr/bin/node" then
sh("ln -sf /usr/bin/nodejs /usr/bin/node", true)
end
sh(%{sed -i "s/config.orchestration.Manager = 'openstack'/config.orchestration.Manager = 'none'/" /etc/contrail/config.global.js})
sh(%{sed -i 's/8080/8070/' /etc/contrail/config.global.js})
sh(%{echo control-node:control-node >> /etc/ifmap-server/basicauthusers.properties})
if @platform =~ /fedora/
fix_nodemgr_config_files
sh("service zookeeper restart")
sh("service redis restart")
sh("service supervisor-webui restart")
sh("service supervisor-database restart")
else
sh("restart zookeeper")
sh("service redis-server restart")
sh("restart contrail-webui-webserver")
end
sh("service cassandra restart")
sh("service rabbitmq-server restart")
sh("service supervisor-control restart")
sh("service supervisor-config restart")
sh("service supervisor-analytics restart")
60.times {|i| print "\rWait for #{i}/60 seconds to settle down.. "; sleep 1}
verify_controller
sh(%{python #{@utils}/provision_control.py --api_server_ip } +
%{#{@controller_ip} --api_server_port 8082 --router_asn 64512 } +
%{--host_name #{@opt.controller_host} --host_ip #{@controller_ip} } +
%{--oper add })
provision_linklocal_service
end
def verify_compute
5.times {|i| print "\rWait for #{i}/5 seconds to settle down.. "; sleep 1}
sh("lsmod |\grep vrouter")
sh("netstat -anp | \grep -w LISTEN | \grep -w 8085", false, 10, 3) # agent
sh("ping -c 3 #{@opt.controller_host}")
sh("ping -c 3 github.com")
end
# Provision contrail-vrouter agent and vrouter kernel module
def provision_contrail_compute
sh("ln -sf /bin/openstack-config /opt/contrail/bin/openstack-config") \
if @platform =~ /fedora/
ip, mask, gw, prefix_len = get_intf_ip(@opt.intf)
create_vhost_interface(ip, mask, gw)
if @platform =~ /fedora/ then
ko = sh("find /usr/lib/modules/#{`uname -r`.chomp}/extra/net -name vrouter.ko")
else
ko="vrouter"
end
templ=<<EOF
LOG=/var/log/contrail.log
CONFIG=/etc/contrail/contrail-vrouter-agent.conf
prog=/usr/bin/contrail-vrouter-agent
kmod=#{ko}
pname=contrail-vrouter-agent
LIBDIR=/usr/lib64
DEVICE=vhost0
dev=#{@opt.intf}
vgw_subnet_ip=__VGW_SUBNET_IP__
vgw_intf=__VGW_INTF_LIST__
LOGFILE=--log-file=/var/log/contrail/vrouter.log
VHOST_CFG=/etc/sysconfig/network-scripts/ifcfg-vhost0
EOF
File.open("/etc/contrail/agent_param", "w") { |fp| fp.puts templ}
sh("touch /etc/contrail/default_pmac")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf HYPERVISOR type kvm")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf DISCOVERY server #{@opt.controller_ip}")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf VIRTUAL-HOST-INTERFACE name vhost0")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf VIRTUAL-HOST-INTERFACE ip #{ip}/#{prefix_len}")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf VIRTUAL-HOST-INTERFACE gateway #{gw}")
sh("/opt/contrail/bin/openstack-config --set /etc/contrail/contrail-vrouter-agent.conf VIRTUAL-HOST-INTERFACE physical_interface #{@opt.intf}")
sh("/opt/contrail/bin/openstack-config --del /etc/contrail/contrail-vrouter-agent.conf VIRTUAL-HOST-INTERFACE compute_node_address")
nodemgr_conf = <<EOF
[DISCOVERY]
server=#{@opt.controller_ip}
port=5998
[COLLECTOR]
server_list=#{@opt.controller_ip}:8086
EOF
File.open("/etc/contrail/contrail-vrouter-nodemgr.conf", "w") {|fp| fp.puts nodemgr_conf}
key = File.file?(@opt.ssh_key) ? "-i #{@opt.ssh_key}" : ""
sh("sshpass -p #{@opt.password} ssh -t #{key} #{@opt.user}@#{@opt.controller_host} sudo python #{@utils}/provision_vrouter.py --host_name #{sh('hostname')} --host_ip #{ip} --api_server_ip #{@opt.controller_ip} --oper add", false, 20, 6)
sh("sync; echo 3 > /proc/sys/vm/drop_caches") if @platform =~ /ubuntu/
sh("service supervisor-vrouter restart")
sh("service contrail-vrouter-agent restart")
# Remove ip address from the interface as that is taken over by vhost0
sh("ifdown #{@opt.intf}; ifup #{@opt.intf}", true, 1, 1, true)
sh("ip addr flush dev #{@opt.intf}", true, 1, 1, true)
# Restore default route
sh("ip route add 0.0.0.0/0 via #{gw}", true, 1, 1, true)
# Setup virtual gateway
sh("python #{@utils}/provision_vgw_interface.py --oper create --interface vgw_public --subnets #{@opt.public_net} --routes 0.0.0.0/0 --vrf default-domain:default-project:Public:Public", false, 5, 5) if @opt.provision_vgw
verify_compute
end
# http://www.fedora.hk/linux/yumwei/show_45.html
def fix_docker_file_system_issue
return unless @opt.fix_docker_issue
return if @platform !~ /ubuntu/
sh("service docker stop", true)
sh("mv /mnt/docker /mnt/docker.old", true)
sh("mkdir -p /root/docker", true)
sh("ln -sf /root/docker /mnt/docker", true)
sh("mkdir -p /mnt/docker/devicemapper/devicemapper", true)
sh("dd if=/dev/zero of=/mnt/docker/devicemapper/devicemapper/data bs=1G count=0 seek=250", true)
sh("service docker restart", true)
end
def provision_contrail_compute_kubernetes
return unless @opt.setup_kubernetes
# Copy kubectl from kubernets-master node
key = File.file?(@opt.ssh_key) ? "-i #{@opt.ssh_key}" : ""
sh("sshpass -p #{@opt.password} scp #{key} #{@opt.user}@#{@opt.controller_host}:/usr/local/bin/kubectl /usr/local/bin/.")
sh("ln -sf /usr/local/bin/kubectl /usr/bin/kubectl", true)
Dir.chdir("#{@ws}/../opencontrail-kubelet")
sh("python setup.py install")
plugin = "opencontrail"
sh("mkdir -p /usr/libexec/kubernetes/kubelet-plugins/net/exec/#{plugin}")
path = @platform =~ /fedora/ ? "/usr/bin/opencontrail-kubelet-plugin" :
"/usr/local/bin/opencontrail-kubelet-plugin"
sh("ln -sf #{path} " +
"/usr/libexec/kubernetes/kubelet-plugins/net/exec/#{plugin}/#{plugin}")
# Generate default plugin configuration file
plugin_conf = <<EOF
[DEFAULTS]
api_server = #{@opt.controller_ip}
net_mode = bridge
EOF
File.open("/usr/libexec/kubernetes/kubelet-plugins/net/exec/#{plugin}/config", "w") { |fp|
fp.puts plugin_conf
}
if @platform =~ /fedora/
sh(%{sed -i 's/DAEMON_ARGS=" /DAEMON_ARGS=" --network_plugin=#{plugin} /' /etc/sysconfig/kubelet})
sh("systemctl restart kubelet", true)
sh("systemctl stop kube-proxy", true)
else
sh(%{sed -i 's/DAEMON_ARGS /DAEMON_ARGS --network_plugin=#{plugin} /' /etc/default/kubelet})
sh("service kubelet restart", true)
# Disable kube-proxy monitoring and stop the service.
if File.file? "/etc/monit/conf.d/kube-proxy"
sh("mv /etc/monit/conf.d/kube-proxy /etc/monit/.", true)
sh("monit reload", true)
end
sh("service kube-proxy stop", true)
end
# Flush iptable nat entries
sh("iptables -F -t nat")
end
def provision_contrail_controller_kubernetes
return unless @opt.setup_kubernetes
# Start kube web server in background
# http://localhost:8001/static/app/#/dashboard/
sh("ln -sf /usr/local/bin/kubectl /usr/bin/kubectl", true)
target = @platform =~ /fedora/ ? "/root" : "/home/#{@opt.user}"
# Start kube-network-manager plugin daemon in background
sh(%{nohup #{target}/contrail/kube-network-manager --master=http://#{@opt.kubernetes_master}:8080 -- --contrail_api=#{@opt.controller_ip} --public_net="#{@opt.public_net}" --portal_net="#{@opt.portal_net}" --private_net="#{@opt.private_net}" 2>&1 > /var/log/contrail/kube-network-manager.log}, true, 1, 1, true) if @platform =~ /ubuntu/
end
def build_kube_network_manager
return unless @opt.setup_kubernetes
ENV["TARGET"]="#{ENV["HOME"]}/contrail"
ENV["CONTRAIL_BRANCH"]="master"
ENV["KUBERNETES_BRANCH"][email protected]_branch
ENV["GOPATH"]="#{ENV["TARGET"]}/kubernetes/Godeps/_workspace"
target = @platform =~ /fedora/ ? "/root" : "/home/#{@opt.user}"
sh("rm -rf #{ENV["TARGET"]}")
sh("mkdir -p #{ENV["TARGET"]}")
Dir.chdir(ENV["TARGET"])
commands=<<EOF
wget -q -O - https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | tar -C /usr/local -zx
rm -rf /usr/bin/go
ln -sf /usr/local/go/bin/go /usr/bin/go
git clone -b #{ENV["KUBERNETES_BRANCH"]} https://github.com/googlecloudplatform/kubernetes
go get github.com/Juniper/contrail-go-api
wget -q https://raw.githubusercontent.com/Juniper/contrail-controller/#{ENV["CONTRAIL_BRANCH"]}/src/schema/vnc_cfg.xsd
wget -q https://raw.githubusercontent.com/Juniper/contrail-controller/#{ENV["CONTRAIL_BRANCH"]}/src/schema/loadbalancer.xsd || true
git clone -b #{ENV["CONTRAIL_BRANCH"]} https://github.com/Juniper/contrail-generateDS.git
./contrail-generateDS/generateDS.py -f -o $GOPATH/src/github.com/Juniper/contrail-go-api/types -g golang-api vnc_cfg.xsd 2>/dev/null
ln -sf #{target}/contrail-kubernetes ./kubernetes/Godeps/_workspace/src/github.com/Juniper/contrail-kubernetes
mkdir -p #{ENV["GOPATH"]}/src/github.com/GoogleCloudPlatform
ln -sf #{ENV["TARGET"]}/kubernetes #{ENV["GOPATH"]}/src/github.com/GoogleCloudPlatform/kubernetes
go build github.com/Juniper/contrail-kubernetes/cmd/kube-network-manager
EOF
commands.split(/\n/).each { |cmd| sh(cmd) }
end
def wait_for_kupe_api
return unless @opt.wait_for_kube_api
# Make sure that kubeapi is up and running
key = File.file?(@opt.ssh_key) ? "-i #{@opt.ssh_key}" : ""
# XXX Relax kubeserer-api 8080 to listen on 0.0.0.0
if @opt.kubernetes_master == "localhost"
sh("sed -i s/address=127.0.0.1/address=0.0.0.0/i /etc/kubernetes/manifests/kube-apiserver.manifest", true)
sh("service kube-addons restart")
end
sh("sshpass -p #{@opt.password} ssh -t #{key} " +
"#{@opt.user}@#{@opt.kubernetes_master} " +
"netstat -anp | \grep LISTEN | \grep -w 8080", false, 60, 10)
end
def main
initial_setup
download_contrail_software if @opt.contrail_install
if @opt.role == "controller" or @opt.role == "all" then
wait_for_kupe_api
install_thirdparty_software_controller if @opt.contrail_install
install_contrail_software_controller if @opt.contrail_install
provision_contrail_controller if @opt.contrail_install
build_kube_network_manager
provision_contrail_controller_kubernetes
end
if @opt.role == "compute" or @opt.role == "all" then
fix_docker_file_system_issue # Work-around docker file system issues
install_thirdparty_software_compute if @opt.contrail_install
install_contrail_software_compute if @opt.contrail_install
provision_contrail_compute if @opt.contrail_install
provision_contrail_compute_kubernetes
end
sh("chown -R #{@opt.user}.#{@opt.user} /home/#{@opt.user}")
end
main
| 42.165714 | 340 | 0.644261 |
086b44e8fa55a6f5d291e8391bdc155cd7545722 | 81,425 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'uri'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# API for the API Gateway service. Use this API to manage gateways, deployments, and related items.
# For more information, see
# [Overview of API Gateway](/iaas/Content/APIGateway/Concepts/apigatewayoverview.htm).
class Apigateway::ApiGatewayClient
# Client used to make HTTP requests.
# @return [OCI::ApiClient]
attr_reader :api_client
# Fully qualified endpoint URL
# @return [String]
attr_reader :endpoint
# The default retry configuration to apply to all operations in this service client. This can be overridden
# on a per-operation basis. The default retry configuration value is `nil`, which means that an operation
# will not perform any retries
# @return [OCI::Retry::RetryConfig]
attr_reader :retry_config
# The region, which will usually correspond to a value in {OCI::Regions::REGION_ENUM}.
# @return [String]
attr_reader :region
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity
# Creates a new ApiGatewayClient.
# Notes:
# If a config is not specified, then the global OCI.config will be used.
#
# This client is not thread-safe
#
# Either a region or an endpoint must be specified. If an endpoint is specified, it will be used instead of the
# region. A region may be specified in the config or via or the region parameter. If specified in both, then the
# region parameter will be used.
# @param [Config] config A Config object.
# @param [String] region A region used to determine the service endpoint. This will usually
# correspond to a value in {OCI::Regions::REGION_ENUM}, but may be an arbitrary string.
# @param [String] endpoint The fully qualified endpoint URL
# @param [OCI::BaseSigner] signer A signer implementation which can be used by this client. If this is not provided then
# a signer will be constructed via the provided config. One use case of this parameter is instance principals authentication,
# so that the instance principals signer can be provided to the client
# @param [OCI::ApiClientProxySettings] proxy_settings If your environment requires you to use a proxy server for outgoing HTTP requests
# the details for the proxy can be provided in this parameter
# @param [OCI::Retry::RetryConfig] retry_config The retry configuration for this service client. This represents the default retry configuration to
# apply across all operations. This can be overridden on a per-operation basis. The default retry configuration value is `nil`, which means that an operation
# will not perform any retries
def initialize(config: nil, region: nil, endpoint: nil, signer: nil, proxy_settings: nil, retry_config: nil)
# If the signer is an InstancePrincipalsSecurityTokenSigner or SecurityTokenSigner and no config was supplied (they are self-sufficient signers)
# then create a dummy config to pass to the ApiClient constructor. If customers wish to create a client which uses instance principals
# and has config (either populated programmatically or loaded from a file), they must construct that config themselves and then
# pass it to this constructor.
#
# If there is no signer (or the signer is not an instance principals signer) and no config was supplied, this is not valid
# so try and load the config from the default file.
config = OCI::Config.validate_and_build_config_with_signer(config, signer)
signer = OCI::Signer.config_file_auth_builder(config) if signer.nil?
@api_client = OCI::ApiClient.new(config, signer, proxy_settings: proxy_settings)
@retry_config = retry_config
if endpoint
@endpoint = endpoint + '/20190501'
else
region ||= config.region
region ||= signer.region if signer.respond_to?(:region)
self.region = region
end
logger.info "ApiGatewayClient endpoint set to '#{@endpoint}'." if logger
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity
# Set the region that will be used to determine the service endpoint.
# This will usually correspond to a value in {OCI::Regions::REGION_ENUM},
# but may be an arbitrary string.
def region=(new_region)
@region = new_region
raise 'A region must be specified.' unless @region
@endpoint = OCI::Regions.get_service_endpoint_for_template(@region, 'https://apigateway.{region}.oci.{secondLevelDomain}') + '/20190501'
logger.info "ApiGatewayClient endpoint set to '#{@endpoint} from region #{@region}'." if logger
end
# @return [Logger] The logger for this client. May be nil.
def logger
@api_client.config.logger
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Changes the API compartment.
# @param [String] api_id The ocid of the API.
# @param [OCI::Apigateway::Models::ChangeApiCompartmentDetails] change_api_compartment_details Details of the target compartment.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case of a timeout or
# server error without risk of executing that same action again. Retry tokens expire after 24
# hours, but can be invalidated before then due to conflicting operations. For example, if a resource
# has been deleted and purged from the system, then a retry of the original creation request
# might be rejected.
# (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/change_api_compartment.rb.html) to see an example of how to use change_api_compartment API.
def change_api_compartment(api_id, change_api_compartment_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#change_api_compartment.' if logger
raise "Missing the required parameter 'api_id' when calling change_api_compartment." if api_id.nil?
raise "Missing the required parameter 'change_api_compartment_details' when calling change_api_compartment." if change_api_compartment_details.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}/actions/changeCompartment'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(change_api_compartment_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#change_api_compartment') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Changes the certificate compartment.
# @param [String] certificate_id The ocid of the certificate.
# @param [OCI::Apigateway::Models::ChangeCertificateCompartmentDetails] change_certificate_compartment_details Details of the target compartment.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case of a timeout or
# server error without risk of executing that same action again. Retry tokens expire after 24
# hours, but can be invalidated before then due to conflicting operations. For example, if a resource
# has been deleted and purged from the system, then a retry of the original creation request
# might be rejected.
# (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/change_certificate_compartment.rb.html) to see an example of how to use change_certificate_compartment API.
def change_certificate_compartment(certificate_id, change_certificate_compartment_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#change_certificate_compartment.' if logger
raise "Missing the required parameter 'certificate_id' when calling change_certificate_compartment." if certificate_id.nil?
raise "Missing the required parameter 'change_certificate_compartment_details' when calling change_certificate_compartment." if change_certificate_compartment_details.nil?
raise "Parameter value for 'certificate_id' must not be blank" if OCI::Internal::Util.blank_string?(certificate_id)
path = '/certificates/{certificateId}/actions/changeCompartment'.sub('{certificateId}', certificate_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(change_certificate_compartment_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#change_certificate_compartment') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Creates a new API.
#
# @param [OCI::Apigateway::Models::CreateApiDetails] create_api_details Details for the new API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case of a timeout or
# server error without risk of executing that same action again. Retry tokens expire after 24
# hours, but can be invalidated before then due to conflicting operations. For example, if a resource
# has been deleted and purged from the system, then a retry of the original creation request
# might be rejected.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Api Api}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/create_api.rb.html) to see an example of how to use create_api API.
def create_api(create_api_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#create_api.' if logger
raise "Missing the required parameter 'create_api_details' when calling create_api." if create_api_details.nil?
path = '/apis'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(create_api_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#create_api') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Api'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Creates a new Certificate.
#
# @param [OCI::Apigateway::Models::CreateCertificateDetails] create_certificate_details Details for the new certificate
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case of a timeout or
# server error without risk of executing that same action again. Retry tokens expire after 24
# hours, but can be invalidated before then due to conflicting operations. For example, if a resource
# has been deleted and purged from the system, then a retry of the original creation request
# might be rejected.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Certificate Certificate}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/create_certificate.rb.html) to see an example of how to use create_certificate API.
def create_certificate(create_certificate_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#create_certificate.' if logger
raise "Missing the required parameter 'create_certificate_details' when calling create_certificate." if create_certificate_details.nil?
path = '/certificates'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(create_certificate_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#create_certificate') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Certificate'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Creates a new SDK.
# @param [OCI::Apigateway::Models::CreateSdkDetails] create_sdk_details Details for the new SDK.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_retry_token A token that uniquely identifies a request so it can be retried in case of a timeout or
# server error without risk of executing that same action again. Retry tokens expire after 24
# hours, but can be invalidated before then due to conflicting operations. For example, if a resource
# has been deleted and purged from the system, then a retry of the original creation request
# might be rejected.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Sdk Sdk}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/create_sdk.rb.html) to see an example of how to use create_sdk API.
def create_sdk(create_sdk_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#create_sdk.' if logger
raise "Missing the required parameter 'create_sdk_details' when calling create_sdk." if create_sdk_details.nil?
path = '/sdks'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-retry-token'] = opts[:opc_retry_token] if opts[:opc_retry_token]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
header_params[:'opc-retry-token'] ||= OCI::Retry.generate_opc_retry_token
post_body = @api_client.object_to_http_body(create_sdk_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#create_sdk') do
@api_client.call_api(
:POST,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Sdk'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Deletes the API with the given identifier.
# @param [String] api_id The ocid of the API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/delete_api.rb.html) to see an example of how to use delete_api API.
def delete_api(api_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#delete_api.' if logger
raise "Missing the required parameter 'api_id' when calling delete_api." if api_id.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#delete_api') do
@api_client.call_api(
:DELETE,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Deletes the certificate with the given identifier.
# @param [String] certificate_id The ocid of the certificate.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/delete_certificate.rb.html) to see an example of how to use delete_certificate API.
def delete_certificate(certificate_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#delete_certificate.' if logger
raise "Missing the required parameter 'certificate_id' when calling delete_certificate." if certificate_id.nil?
raise "Parameter value for 'certificate_id' must not be blank" if OCI::Internal::Util.blank_string?(certificate_id)
path = '/certificates/{certificateId}'.sub('{certificateId}', certificate_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#delete_certificate') do
@api_client.call_api(
:DELETE,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Deletes provided SDK.
# @param [String] sdk_id The ocid of the SDK.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/delete_sdk.rb.html) to see an example of how to use delete_sdk API.
def delete_sdk(sdk_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#delete_sdk.' if logger
raise "Missing the required parameter 'sdk_id' when calling delete_sdk." if sdk_id.nil?
raise "Parameter value for 'sdk_id' must not be blank" if OCI::Internal::Util.blank_string?(sdk_id)
path = '/sdks/{sdkId}'.sub('{sdkId}', sdk_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#delete_sdk') do
@api_client.call_api(
:DELETE,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets an API by identifier.
# @param [String] api_id The ocid of the API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Api Api}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_api.rb.html) to see an example of how to use get_api API.
def get_api(api_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#get_api.' if logger
raise "Missing the required parameter 'api_id' when calling get_api." if api_id.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_api') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Api'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Get the raw API content.
# @param [String] api_id The ocid of the API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String, IO] :response_target Streaming http body into a file (specified by file name or File object) or IO object if the block is not given
# @option [Block] &block Streaming http body to the block
# @return [Response] A Response object with data of type String if response_target and block are not given, otherwise with nil data
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_api_content.rb.html) to see an example of how to use get_api_content API.
def get_api_content(api_id, opts = {}, &block)
logger.debug 'Calling operation ApiGatewayClient#get_api_content.' if logger
raise "Missing the required parameter 'api_id' when calling get_api_content." if api_id.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}/content'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = opts[:accept] if opts[:accept]
header_params[:accept] ||= 'application/json'
header_params[:'accept-encoding'] = opts[:accept_encoding] if opts[:accept_encoding]
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_api_content') do
if !block.nil?
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'Stream',
&block
)
elsif opts[:response_target]
if opts[:response_target].respond_to? :write
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'Stream',
&proc { |chunk, _response| opts[:response_target].write(chunk) }
)
elsif opts[:response_target].is_a?(String)
File.open(opts[:response_target], 'wb') do |output|
return @api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'Stream',
&proc { |chunk, _response| output.write(chunk) }
)
end
end
else
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'String'
)
end
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets an API Deployment specification by identifier.
# @param [String] api_id The ocid of the API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::ApiSpecification ApiSpecification}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_api_deployment_specification.rb.html) to see an example of how to use get_api_deployment_specification API.
def get_api_deployment_specification(api_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#get_api_deployment_specification.' if logger
raise "Missing the required parameter 'api_id' when calling get_api_deployment_specification." if api_id.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}/deploymentSpecification'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_api_deployment_specification') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::ApiSpecification'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets the API validation results.
# @param [String] api_id The ocid of the API.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::ApiValidations ApiValidations}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_api_validations.rb.html) to see an example of how to use get_api_validations API.
def get_api_validations(api_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#get_api_validations.' if logger
raise "Missing the required parameter 'api_id' when calling get_api_validations." if api_id.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}/validations'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_api_validations') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::ApiValidations'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Gets a certificate by identifier.
# @param [String] certificate_id The ocid of the certificate.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Certificate Certificate}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_certificate.rb.html) to see an example of how to use get_certificate API.
def get_certificate(certificate_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#get_certificate.' if logger
raise "Missing the required parameter 'certificate_id' when calling get_certificate." if certificate_id.nil?
raise "Parameter value for 'certificate_id' must not be blank" if OCI::Internal::Util.blank_string?(certificate_id)
path = '/certificates/{certificateId}'.sub('{certificateId}', certificate_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_certificate') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Certificate'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Return object store downloadable URL and metadata.
# @param [String] sdk_id The ocid of the SDK.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::Sdk Sdk}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/get_sdk.rb.html) to see an example of how to use get_sdk API.
def get_sdk(sdk_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#get_sdk.' if logger
raise "Missing the required parameter 'sdk_id' when calling get_sdk." if sdk_id.nil?
raise "Parameter value for 'sdk_id' must not be blank" if OCI::Internal::Util.blank_string?(sdk_id)
path = '/sdks/{sdkId}'.sub('{sdkId}', sdk_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#get_sdk') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::Sdk'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Returns a list of APIs.
#
# @param [String] compartment_id The ocid of the compartment in which to list resources.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :display_name A user-friendly name. Does not have to be unique, and it's changeable.
#
# Example: `My new resource`
# (default to null)
# @option opts [String] :lifecycle_state A filter to return only resources that match the given lifecycle state.
#
# Example: `ACTIVE`
# (default to null)
# @option opts [Integer] :limit The maximum number of items to return. (default to 100)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. (default to null)
# @option opts [String] :sort_order The sort order to use, either 'asc' or 'desc'. The default order depends on the sortBy value. (default to ASC)
# Allowed values are: ASC, DESC
# @option opts [String] :sort_by The field to sort by. You can provide one sort order (`sortOrder`).
# Default order for `timeCreated` is descending. Default order for
# `displayName` is ascending. The `displayName` sort order is case
# sensitive.
# (default to timeCreated)
# Allowed values are: timeCreated, displayName
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::ApiCollection ApiCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/list_apis.rb.html) to see an example of how to use list_apis API.
def list_apis(compartment_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#list_apis.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_apis." if compartment_id.nil?
if opts[:lifecycle_state] && !OCI::Apigateway::Models::ApiSummary::LIFECYCLE_STATE_ENUM.include?(opts[:lifecycle_state])
raise 'Invalid value for "lifecycle_state", must be one of the values in OCI::Apigateway::Models::ApiSummary::LIFECYCLE_STATE_ENUM.'
end
if opts[:sort_order] && !%w[ASC DESC].include?(opts[:sort_order])
raise 'Invalid value for "sort_order", must be one of ASC, DESC.'
end
if opts[:sort_by] && !%w[timeCreated displayName].include?(opts[:sort_by])
raise 'Invalid value for "sort_by", must be one of timeCreated, displayName.'
end
path = '/apis'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:displayName] = opts[:display_name] if opts[:display_name]
query_params[:lifecycleState] = opts[:lifecycle_state] if opts[:lifecycle_state]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
query_params[:sortOrder] = opts[:sort_order] if opts[:sort_order]
query_params[:sortBy] = opts[:sort_by] if opts[:sort_by]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#list_apis') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::ApiCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Returns a list of certificates.
#
# @param [String] compartment_id The ocid of the compartment in which to list resources.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :display_name A user-friendly name. Does not have to be unique, and it's changeable.
#
# Example: `My new resource`
# (default to null)
# @option opts [String] :lifecycle_state A filter to return only resources that match the given lifecycle state.
#
# Example: `ACTIVE` or `DELETED`
# (default to null)
# @option opts [Integer] :limit The maximum number of items to return. (default to 100)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. (default to null)
# @option opts [String] :sort_order The sort order to use, either 'asc' or 'desc'. The default order depends on the sortBy value. (default to ASC)
# Allowed values are: ASC, DESC
# @option opts [String] :sort_by The field to sort by. You can provide one sort order (`sortOrder`).
# Default order for `timeCreated` is descending. Default order for
# `displayName` is ascending. The `displayName` sort order is case
# sensitive.
# (default to timeCreated)
# Allowed values are: timeCreated, displayName
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::CertificateCollection CertificateCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/list_certificates.rb.html) to see an example of how to use list_certificates API.
def list_certificates(compartment_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#list_certificates.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_certificates." if compartment_id.nil?
if opts[:lifecycle_state] && !OCI::Apigateway::Models::Certificate::LIFECYCLE_STATE_ENUM.include?(opts[:lifecycle_state])
raise 'Invalid value for "lifecycle_state", must be one of the values in OCI::Apigateway::Models::Certificate::LIFECYCLE_STATE_ENUM.'
end
if opts[:sort_order] && !%w[ASC DESC].include?(opts[:sort_order])
raise 'Invalid value for "sort_order", must be one of ASC, DESC.'
end
if opts[:sort_by] && !%w[timeCreated displayName].include?(opts[:sort_by])
raise 'Invalid value for "sort_by", must be one of timeCreated, displayName.'
end
path = '/certificates'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:displayName] = opts[:display_name] if opts[:display_name]
query_params[:lifecycleState] = opts[:lifecycle_state] if opts[:lifecycle_state]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
query_params[:sortOrder] = opts[:sort_order] if opts[:sort_order]
query_params[:sortBy] = opts[:sort_by] if opts[:sort_by]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#list_certificates') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::CertificateCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Lists programming languages in which SDK can be generated.
# @param [String] compartment_id The ocid of the compartment in which to list resources.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :display_name A user-friendly name. Does not have to be unique, and it's changeable.
#
# Example: `My new resource`
# (default to null)
# @option opts [Integer] :limit The maximum number of items to return. (default to 100)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. (default to null)
# @option opts [String] :sort_order The sort order to use, either 'asc' or 'desc'. The default order depends on the sortBy value. (default to ASC)
# Allowed values are: ASC, DESC
# @option opts [String] :sort_by The field to sort by. You can provide one sort order (`sortOrder`).
# Default order for `timeCreated` is descending. Default order for
# `displayName` is ascending. The `displayName` sort order is case
# sensitive.
# (default to timeCreated)
# Allowed values are: timeCreated, displayName
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::SdkLanguageTypeCollection SdkLanguageTypeCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/list_sdk_language_types.rb.html) to see an example of how to use list_sdk_language_types API.
def list_sdk_language_types(compartment_id, opts = {})
logger.debug 'Calling operation ApiGatewayClient#list_sdk_language_types.' if logger
raise "Missing the required parameter 'compartment_id' when calling list_sdk_language_types." if compartment_id.nil?
if opts[:sort_order] && !%w[ASC DESC].include?(opts[:sort_order])
raise 'Invalid value for "sort_order", must be one of ASC, DESC.'
end
if opts[:sort_by] && !%w[timeCreated displayName].include?(opts[:sort_by])
raise 'Invalid value for "sort_by", must be one of timeCreated, displayName.'
end
path = '/sdkLanguageTypes'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:compartmentId] = compartment_id
query_params[:displayName] = opts[:display_name] if opts[:display_name]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
query_params[:sortOrder] = opts[:sort_order] if opts[:sort_order]
query_params[:sortBy] = opts[:sort_by] if opts[:sort_by]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#list_sdk_language_types') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::SdkLanguageTypeCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Returns list of generated SDKs.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :sdk_id The ocid of the SDK. (default to null)
# @option opts [String] :display_name A user-friendly name. Does not have to be unique, and it's changeable.
#
# Example: `My new resource`
# (default to null)
# @option opts [String] :lifecycle_state A filter to return only resources that match the given lifecycle state.
#
# Example: `ACTIVE` or `DELETED`
# (default to null)
# @option opts [Integer] :limit The maximum number of items to return. (default to 100)
# @option opts [String] :page The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. (default to null)
# @option opts [String] :sort_order The sort order to use, either 'asc' or 'desc'. The default order depends on the sortBy value. (default to ASC)
# Allowed values are: ASC, DESC
# @option opts [String] :sort_by The field to sort by. You can provide one sort order (`sortOrder`).
# Default order for `timeCreated` is descending. Default order for
# `displayName` is ascending. The `displayName` sort order is case
# sensitive.
# (default to timeCreated)
# Allowed values are: timeCreated, displayName
# @option opts [String] :api_id The ocid of the API. (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type {OCI::Apigateway::Models::SdkCollection SdkCollection}
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/list_sdks.rb.html) to see an example of how to use list_sdks API.
def list_sdks(opts = {})
logger.debug 'Calling operation ApiGatewayClient#list_sdks.' if logger
if opts[:lifecycle_state] && !OCI::Apigateway::Models::Sdk::LIFECYCLE_STATE_ENUM.include?(opts[:lifecycle_state])
raise 'Invalid value for "lifecycle_state", must be one of the values in OCI::Apigateway::Models::Sdk::LIFECYCLE_STATE_ENUM.'
end
if opts[:sort_order] && !%w[ASC DESC].include?(opts[:sort_order])
raise 'Invalid value for "sort_order", must be one of ASC, DESC.'
end
if opts[:sort_by] && !%w[timeCreated displayName].include?(opts[:sort_by])
raise 'Invalid value for "sort_by", must be one of timeCreated, displayName.'
end
path = '/sdks'
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
query_params[:sdkId] = opts[:sdk_id] if opts[:sdk_id]
query_params[:displayName] = opts[:display_name] if opts[:display_name]
query_params[:lifecycleState] = opts[:lifecycle_state] if opts[:lifecycle_state]
query_params[:limit] = opts[:limit] if opts[:limit]
query_params[:page] = opts[:page] if opts[:page]
query_params[:sortOrder] = opts[:sort_order] if opts[:sort_order]
query_params[:sortBy] = opts[:sort_by] if opts[:sort_by]
query_params[:apiId] = opts[:api_id] if opts[:api_id]
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = nil
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#list_sdks') do
@api_client.call_api(
:GET,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body,
return_type: 'OCI::Apigateway::Models::SdkCollection'
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Updates the API with the given identifier.
# @param [String] api_id The ocid of the API.
# @param [OCI::Apigateway::Models::UpdateApiDetails] update_api_details The information to be updated.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/update_api.rb.html) to see an example of how to use update_api API.
def update_api(api_id, update_api_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#update_api.' if logger
raise "Missing the required parameter 'api_id' when calling update_api." if api_id.nil?
raise "Missing the required parameter 'update_api_details' when calling update_api." if update_api_details.nil?
raise "Parameter value for 'api_id' must not be blank" if OCI::Internal::Util.blank_string?(api_id)
path = '/apis/{apiId}'.sub('{apiId}', api_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = @api_client.object_to_http_body(update_api_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#update_api') do
@api_client.call_api(
:PUT,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Updates a certificate with the given identifier
# @param [String] certificate_id The ocid of the certificate.
# @param [OCI::Apigateway::Models::UpdateCertificateDetails] update_certificate_details The information to be updated.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/update_certificate.rb.html) to see an example of how to use update_certificate API.
def update_certificate(certificate_id, update_certificate_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#update_certificate.' if logger
raise "Missing the required parameter 'certificate_id' when calling update_certificate." if certificate_id.nil?
raise "Missing the required parameter 'update_certificate_details' when calling update_certificate." if update_certificate_details.nil?
raise "Parameter value for 'certificate_id' must not be blank" if OCI::Internal::Util.blank_string?(certificate_id)
path = '/certificates/{certificateId}'.sub('{certificateId}', certificate_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = @api_client.object_to_http_body(update_certificate_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#update_certificate') do
@api_client.call_api(
:PUT,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines
# Updates the SDK with the given identifier.
# @param [String] sdk_id The ocid of the SDK.
# @param [OCI::Apigateway::Models::UpdateSdkDetails] update_sdk_details The information to be updated.
# @param [Hash] opts the optional parameters
# @option opts [OCI::Retry::RetryConfig] :retry_config The retry configuration to apply to this operation. If no key is provided then the service-level
# retry configuration defined by {#retry_config} will be used. If an explicit `nil` value is provided then the operation will not retry
# @option opts [String] :if_match For optimistic concurrency control. In the PUT or DELETE call
# for a resource, set the `if-match` parameter to the value of the
# etag from a previous GET or POST response for that resource.
# The resource will be updated or deleted only if the etag you
# provide matches the resource's current etag value.
# (default to null)
# @option opts [String] :opc_request_id The client request id for tracing. (default to null)
# @return [Response] A Response object with data of type nil
# @note Click [here](https://docs.cloud.oracle.com/en-us/iaas/tools/ruby-sdk-examples/latest/apigateway/update_sdk.rb.html) to see an example of how to use update_sdk API.
def update_sdk(sdk_id, update_sdk_details, opts = {})
logger.debug 'Calling operation ApiGatewayClient#update_sdk.' if logger
raise "Missing the required parameter 'sdk_id' when calling update_sdk." if sdk_id.nil?
raise "Missing the required parameter 'update_sdk_details' when calling update_sdk." if update_sdk_details.nil?
raise "Parameter value for 'sdk_id' must not be blank" if OCI::Internal::Util.blank_string?(sdk_id)
path = '/sdks/{sdkId}'.sub('{sdkId}', sdk_id.to_s)
operation_signing_strategy = :standard
# rubocop:disable Style/NegatedIf
# Query Params
query_params = {}
# Header Params
header_params = {}
header_params[:accept] = 'application/json'
header_params[:'content-type'] = 'application/json'
header_params[:'if-match'] = opts[:if_match] if opts[:if_match]
header_params[:'opc-request-id'] = opts[:opc_request_id] if opts[:opc_request_id]
# rubocop:enable Style/NegatedIf
post_body = @api_client.object_to_http_body(update_sdk_details)
# rubocop:disable Metrics/BlockLength
OCI::Retry.make_retrying_call(applicable_retry_config(opts), call_name: 'ApiGatewayClient#update_sdk') do
@api_client.call_api(
:PUT,
path,
endpoint,
header_params: header_params,
query_params: query_params,
operation_signing_strategy: operation_signing_strategy,
body: post_body
)
end
# rubocop:enable Metrics/BlockLength
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Style/IfUnlessModifier, Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines
private
def applicable_retry_config(opts = {})
return @retry_config unless opts.key?(:retry_config)
opts[:retry_config]
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 52.736399 | 245 | 0.713872 |
87749479d2cfc0dd60eca3d62b44c6fd5f83c59e | 2,407 | require 'spec_helper'
require "#{File.dirname(__FILE__)}/../support/tables_spec_helper"
require "#{File.dirname(__FILE__)}/../support/shared_example_spec_helper_for_integer_key"
module Partitioned
describe ById do
include TablesSpecHelper
module Id
class Employee < ById
belongs_to :company, :class_name => 'Company'
attr_accessible :company_id, :name, :integer_field
def self.partition_table_size
return 1
end
partitioned do |partition|
partition.foreign_key :company_id
end
end # Employee
end # Id
before(:all) do
@employee = Id::Employee
create_tables
@employee.create_new_partition_tables(Range.new(1, 5).step(@employee.partition_table_size))
ActiveRecord::Base.connection.execute <<-SQL
insert into employees_partitions.p1 (company_id,name) values (1,'Keith');
SQL
end
after(:all) do
drop_tables
end
let(:class_by_id) { ::Partitioned::ById }
describe "model is abstract class" do
it "returns true" do
class_by_id.abstract_class.should be_true
end
end # model is abstract class
describe "#prefetch_primary_key?" do
context "is :id set as a primary_key" do
it "returns true" do
class_by_id.prefetch_primary_key?.should be_true
end
end # is :id set as a primary_key
end # #prefetch_primary_key?
describe "#partition_table_size" do
it "returns 10000000" do
class_by_id.partition_table_size.should == 10000000
end
end # #partition_table_size
describe "#partition_integer_field" do
it "returns :id" do
class_by_id.partition_integer_field.should == :id
end
end # #partition_integer_field
describe "partitioned block" do
context "checks if there is data in the indexes field" do
it "returns :id" do
class_by_id.configurator_dsl.data.indexes.first.field.should == :id
end
it "returns { :unique => true }" do
class_by_id.configurator_dsl.data.indexes.first.options.should == { :unique => true }
end
end # checks if there is data in the indexes field
end # partitioned block
it_should_behave_like "check that basic operations with postgres works correctly for integer key", Id::Employee
end # ById
end # Partitioned | 24.814433 | 115 | 0.664728 |
7907aff409261c9ee756a40e8426ada400f4fb81 | 950 | require 'bulk_insert/worker'
module BulkInsert
extend ActiveSupport::Concern
module ClassMethods
def bulk_insert(*columns, values: nil, set_size:500, ignore: false, update_duplicates: false, return_primary_keys: false)
columns = default_bulk_columns if columns.empty?
worker = BulkInsert::Worker.new(connection, table_name, primary_key, columns, set_size, ignore, update_duplicates, return_primary_keys)
if values.present?
transaction do
worker.add_all(values)
worker.save!
end
nil
elsif block_given?
transaction do
yield worker
worker.save!
end
nil
else
worker
end
end
# helper method for preparing the columns before a call to :bulk_insert
def default_bulk_columns
self.column_names - %w(id)
end
end
end
ActiveSupport.on_load(:active_record) do
send(:include, BulkInsert)
end
| 24.358974 | 141 | 0.672632 |
d5807c94258ab5baa13cae3d1f509be67c288d49 | 313 | cask 'elyse' do
version '4.0.1'
sha256 '4741a9d1ebf8d707489b2282a3ac0be3d5ea3c60042db2f3443b6b04412b1465'
url "https://silkwoodsoftware.com/Elyse-#{version.no_dots}.dmg"
appcast 'https://silkwoodsoftware.com/download.html'
name 'Elyse'
homepage 'https://silkwoodsoftware.com/'
app 'Elyse.app'
end
| 26.083333 | 75 | 0.760383 |
accc3904a9b5fddb82328767348ae383e487b797 | 411 | require 'rails_helper'
RSpec.describe Course, type: :model do
it 'should be able to search a specific course' do
Course.search 'ee569'
Course.search 'csci580'
Course.search 'csci574'
Course.search 'ee450'
end
it 'should be able to list courses in a department' do
Course.search 'ee*'
end
it 'should be able to list courses with wildcard' do
Course.search 'csci5*'
end
end
| 21.631579 | 56 | 0.695864 |
7ae51797c2c20dd26f3adbe520b41581aae3e9b4 | 4,523 | #!/usr/bin/ruby
#
# Copyright 2017 Istio Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'webrick'
require 'json'
require 'net/http'
if ARGV.length < 1 then
puts "usage: #{$PROGRAM_NAME} port"
exit(-1)
end
port = Integer(ARGV[0])
server = WEBrick::HTTPServer.new :BindAddress => '0.0.0.0', :Port => port
trap 'INT' do server.shutdown end
server.mount_proc '/health' do |req, res|
res.status = 200
res.body = {'status' => 'Details is healthy'}.to_json
res['Content-Type'] = 'application/json'
end
server.mount_proc '/details' do |req, res|
pathParts = req.path.split('/')
headers = get_forward_headers(req)
begin
begin
id = Integer(pathParts[-1])
rescue
raise 'please provide numeric product id'
end
details = get_book_details(id, headers)
res.body = details.to_json
res['Content-Type'] = 'application/json'
rescue => error
res.body = {'error' => error}.to_json
res['Content-Type'] = 'application/json'
res.status = 400
end
end
# TODO: provide details on different books.
def get_book_details(id, headers)
if ENV['ENABLE_EXTERNAL_BOOK_SERVICE'] === 'true' then
# the ISBN of one of Comedy of Errors on the Amazon
# that has Shakespeare as the single author
isbn = '0486424618'
return fetch_details_from_external_service(isbn, id, headers)
end
return {
'id' => id,
'author': 'William Shakespeare',
'year': 1595,
'type' => 'paperback',
'pages' => 200,
'publisher' => 'PublisherA',
'language' => 'English',
'ISBN-10' => '1234567890',
'ISBN-13' => '123-1234567890'
}
end
def fetch_details_from_external_service(isbn, id, headers)
uri = URI.parse('https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn)
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = 5 # seconds
# WITH_ISTIO means that the details app runs with an Istio sidecar injected.
#
# With the Istio sidecar injected, the requests must be sent by HTTP protocol (without TLS),
# while the sidecar proxy will perform TLS origination. An Egress Rule
# must be defined to enable the trafic to www.googleapis.com and to perform the TLS origination.
#
# Without the Istio sidecar injected, the TLS origination must be performed by the `http` object,
# by setting `use_ssl` field to true.
unless ENV['WITH_ISTIO'] === 'true' then
http.use_ssl = true
end
request = Net::HTTP::Get.new(uri.request_uri)
headers.each { |header, value| request[header] = value }
response = http.request(request)
json = JSON.parse(response.body)
book = json['items'][0]['volumeInfo']
language = book['language'] === 'en'? 'English' : 'unknown'
type = book['printType'] === 'BOOK'? 'paperback' : 'unknown'
isbn10 = get_isbn(book, 'ISBN_10')
isbn13 = get_isbn(book, 'ISBN_13')
return {
'id' => id,
'author': book['authors'][0],
'year': book['publishedDate'],
'type' => type,
'pages' => book['pageCount'],
'publisher' => book['publisher'],
'language' => language,
'ISBN-10' => isbn10,
'ISBN-13' => isbn13
}
end
def get_isbn(book, isbn_type)
isbn_dentifiers = book['industryIdentifiers'].select do |identifier|
identifier['type'] === isbn_type
end
return isbn_dentifiers[0]['identifier']
end
def get_forward_headers(request)
headers = {}
incoming_headers = [ 'x-request-id',
'x-b3-traceid',
'x-b3-spanid',
'x-b3-parentspanid',
'x-b3-sampled',
'x-b3-flags',
'x-ot-span-context'
]
request.each do |header, value|
if incoming_headers.include? header then
headers[header] = value
end
end
return headers
end
server.start
| 29.562092 | 101 | 0.620606 |
088cd7e782492e133a5a193fa00a87f100121e56 | 309 | FactoryBot.define do
factory :category do
name { Faker::Company.name }
icon { Faker::Company.logo }
user
factory :category_with_deals do
transient do
deals_count { 5 }
end
deals do
Array.new(deals_count) { association(:deal) }
end
end
end
end
| 17.166667 | 53 | 0.601942 |
acc85f32ecc9f31b8b8337c440132e20c87e3b2e | 1,226 | # frozen_string_literal: true
require 'spec_helper'
describe Projects::RestoreService do
let(:user) { create(:user) }
let(:pending_delete) { nil }
let(:project) do
create(:project,
:repository,
namespace: user.namespace,
marked_for_deletion_at: 1.day.ago,
deleting_user: user,
archived: true,
pending_delete: pending_delete)
end
context 'restoring project' do
before do
described_class.new(project, user).execute
end
it 'marks project as unarchived and not marked for deletion' do
expect(Project.unscoped.all).to include(project)
expect(project.archived).to eq(false)
expect(project.marked_for_deletion_at).to be_nil
expect(project.deleting_user).to eq(nil)
end
end
context 'restoring project already in process of removal' do
let(:deletion_date) { 2.days.ago }
let(:pending_delete) { true }
it 'does not allow to restore' do
expect(described_class.new(project, user).execute).to include(status: :error)
end
end
context 'audit events' do
it 'saves audit event' do
expect { described_class.new(project, user).execute }
.to change { AuditEvent.count }.by(1)
end
end
end
| 25.541667 | 83 | 0.682708 |
ede55f4a4669740722d04b3c252e86e7a4acfbd5 | 8,370 | require 'spec_helper'
require 'pact_broker/pacticipants/service'
require 'pact_broker/domain/tag'
require 'pact_broker/domain/pact'
module PactBroker
module Pacticipants
describe Service do
let(:td) { TestDataBuilder.new }
subject{ Service }
describe ".update" do
before do
td.create_pacticipant("Foo")
end
let(:params) { { 'name' => 'Foo', 'repositoryUrl' => 'http://foo' } }
subject { Service.update(params) }
it "updates the repositoryUrl" do
expect(subject.repository_url).to eq 'http://foo'
end
end
describe ".messages_for_potential_duplicate_pacticipants" do
let(:base_url) { 'http://example.org' }
let(:fred_duplicates) { [double('Frederich pacticipant')] }
let(:mary_dulicates) { [double('Marta pacticipant')] }
before do
allow(Service).to receive(:find_potential_duplicate_pacticipants).with("Fred").and_return(fred_duplicates)
allow(Service).to receive(:find_potential_duplicate_pacticipants).with("Mary").and_return(mary_dulicates)
allow(Messages).to receive(:potential_duplicate_pacticipant_message).and_return("message1", "message2")
end
subject { Service.messages_for_potential_duplicate_pacticipants ["Fred", "Mary"], base_url }
it "finds the potential duplicates for each name" do
expect(Service).to receive(:find_potential_duplicate_pacticipants).with("Fred")
expect(Service).to receive(:find_potential_duplicate_pacticipants).with("Mary")
subject
end
context "when there are potential duplicates" do
it "creates a message for each dupliate" do
expect(Messages).to receive(:potential_duplicate_pacticipant_message).with("Fred", fred_duplicates, base_url)
expect(Messages).to receive(:potential_duplicate_pacticipant_message).with("Mary", mary_dulicates, base_url)
subject
end
it "returns an array of messages" do
expect(subject).to eq ["message1", "message2"]
end
end
context "when there are no potential duplicates" do
let(:fred_duplicates) { [] }
let(:mary_dulicates) { [] }
it "returns an empty array" do
expect(subject).to eq []
end
end
end
describe ".find_potential_duplicate_pacticipants" do
let(:pacticipant_name) { 'pacticipant_name' }
let(:duplicates) { ["Fred", "Mary"] }
let(:pacticipant_names) { double("pacticipant_names") }
let(:fred) { double('fred pacticipant')}
let(:mary) { double('mary pacticipant')}
let(:pacticipant_repository) { instance_double(PactBroker::Pacticipants::Repository)}
before do
allow(PactBroker::Pacticipants::FindPotentialDuplicatePacticipantNames).to receive(:call).and_return(duplicates)
allow(PactBroker::Pacticipants::Repository).to receive(:new).and_return(pacticipant_repository)
allow(pacticipant_repository).to receive(:pacticipant_names).and_return(pacticipant_names)
allow(pacticipant_repository).to receive(:find_by_name).with("Fred").and_return(fred)
allow(pacticipant_repository).to receive(:find_by_name).with("Mary").and_return(mary)
end
it "finds all the pacticipant names" do
expect(pacticipant_repository).to receive(:pacticipant_names)
subject.find_potential_duplicate_pacticipants pacticipant_name
end
it "calculates the duplicates" do
expect(PactBroker::Pacticipants::FindPotentialDuplicatePacticipantNames).to receive(:call).with(pacticipant_name, pacticipant_names)
subject.find_potential_duplicate_pacticipants pacticipant_name
end
it "retrieves the pacticipants by name" do
expect(pacticipant_repository).to receive(:find_by_name).with("Fred")
expect(pacticipant_repository).to receive(:find_by_name).with("Mary")
subject.find_potential_duplicate_pacticipants pacticipant_name
end
it "returns the duplicate pacticipants" do
expect(subject.find_potential_duplicate_pacticipants(pacticipant_name)).to eq [fred, mary]
end
it "logs the names" do
allow(PactBroker.logger).to receive(:info)
expect(PactBroker.logger).to receive(:info).with(/pacticipant_name.*Fred, Mary/)
subject.find_potential_duplicate_pacticipants pacticipant_name
end
end
describe "delete" do
before do
TestDataBuilder.new
.create_consumer("Consumer")
.create_consumer_version("2.3.4")
.create_provider("Provider")
.create_pact
.create_consumer_version("1.2.3")
.create_consumer_version_tag("prod")
.create_pact
.create_webhook
.create_triggered_webhook
.create_deprecated_webhook_execution
.create_verification
end
let(:delete_consumer) { subject.delete "Consumer" }
let(:delete_provider) { subject.delete "Provider" }
context "deleting a consumer" do
it "deletes the pacticipant" do
expect{ delete_consumer }.to change{
PactBroker::Domain::Pacticipant.all.count
}.by(-1)
end
it "deletes the child versions" do
expect{ delete_consumer }.to change{
PactBroker::Domain::Version.where(number: "1.2.3").count
}.by(-1)
end
it "deletes the child tags" do
expect{ delete_consumer }.to change{
PactBroker::Domain::Tag.where(name: "prod").count
}.by(-1)
end
it "deletes the webhooks" do
expect{ delete_consumer }.to change{
PactBroker::Webhooks::Webhook.count
}.by(-1)
end
it "deletes the triggered webhooks" do
expect{ delete_consumer }.to change{
PactBroker::Webhooks::TriggeredWebhook.count
}.by(-1)
end
it "deletes the webhook executions" do
expect{ delete_consumer }.to change{
PactBroker::Webhooks::Execution.count
}.by(-1)
end
it "deletes the child pacts" do
expect{ delete_consumer }.to change{
PactBroker::Pacts::PactPublication.count
}.by(-2)
end
it "deletes the verifications" do
expect{ delete_consumer }.to change{
PactBroker::Domain::Verification.count
}.by(-1)
end
end
context "deleting a provider" do
it "deletes the pacticipant" do
expect{ delete_provider }.to change{
PactBroker::Domain::Pacticipant.all.count
}.by(-1)
end
it "does not delete any versions" do
expect{ delete_provider }.to change{
PactBroker::Domain::Version.where(number: "1.2.3").count
}.by(0)
end
it "deletes the child tags only if there are any" do
expect{ delete_provider }.to change{
PactBroker::Domain::Tag.where(name: "prod").count
}.by(0)
end
it "deletes the webhooks" do
expect{ delete_provider }.to change{
PactBroker::Webhooks::Webhook.count
}.by(-1)
end
it "deletes the triggered webhooks" do
expect{ delete_provider }.to change{
PactBroker::Webhooks::TriggeredWebhook.count
}.by(-1)
end
it "deletes the webhook executions" do
expect{ delete_provider }.to change{
PactBroker::Webhooks::Execution.count
}.by(-1)
end
it "deletes the child pacts" do
expect{ delete_provider }.to change{
PactBroker::Pacts::PactPublication.count
}.by(-2)
end
it "deletes the verifications" do
expect{ delete_provider }.to change{
PactBroker::Domain::Verification.count
}.by(-1)
end
end
end
end
end
end
| 35.168067 | 142 | 0.608124 |
7a54c112e686a6583ce40a0724765ea7847e7f7e | 1,491 | require 'spec_helper'
require 'json'
describe 'web_configure' do
chef_run = ChefSpec::SoloRunner.new
before(:all) do
chef_run.node.normal_attrs = property[:chef_attributes]
chef_run.converge('role[web_configure]')
end
it 'is apache service is running ' do
expect(service(chef_run.node['apache']['service_name'])).to be_running
end
it 'is apache ports is listning' do
chef_run.node['apache']['listen_ports'].each do |listen_port|
expect(port(listen_port)).to be_listening.with('tcp')
end
end
it 'is workers.properties file set given mode, owned by a given user, grouped in to a given group, and exist'do
expect(file("#{chef_run.node['apache']['conf_dir']}/workers.properties"))
.to be_file
.and be_mode(664)
.and be_owned_by(chef_run.node['apache']['user'])
.and be_grouped_into(chef_run.node['apache']['group'])
end
it 'is workers.properties file contains the all ap server settings' do
ap_servers = chef_run.node['cloudconductor']['servers'].select { |_, s| s['roles'].include?('ap') }
ap_servers.each do |hostname, server|
expect(file("#{chef_run.node['apache']['conf_dir']}/workers.properties"))
.to contain("worker.#{hostname}.reference=worker.template")
.and contain("worker.#{hostname}.host=#{server['private_ip']}")
.and contain("worker.#{hostname}.route=#{server['route']}")
.and contain("worker.#{hostname}.lbfactor=#{server['weight']}")
end
end
end
| 36.365854 | 113 | 0.67941 |
edc3bb11f0267f547a0e6ca54f4d07fab9e1613a | 6,164 | require File.dirname(__FILE__) + '/beanstream/beanstream_core'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
# This class implements the Canadian {Beanstream}[http://www.beanstream.com] payment gateway.
# It is also named TD Canada Trust Online Mart payment gateway.
# To learn more about the specification of Beanstream gateway, please read the OM_Direct_Interface_API.pdf,
# which you can get from your Beanstream account or get from me by email.
#
# == Supported transaction types by Beanstream:
# * +P+ - Purchase
# * +PA+ - Pre Authorization
# * +PAC+ - Pre Authorization Completion
#
# == Secure Payment Profiles:
# BeanStream supports payment profiles (vaults). This allows you to store cc information with BeanStream and process subsequent transactions with a customer id.
# Secure Payment Profiles must be enabled on your account (must be done over the phone).
# Your API Access Passcode must be set in Administration => account settings => order settings.
# To learn more about storing credit cards with the Beanstream gateway, please read the BEAN_Payment_Profiles.pdf (I had to phone BeanStream to request it.)
#
# == Notes
# * Adding of order products information is not implemented.
# * Ensure that country and province data is provided as a code such as "CA", "US", "QC".
# * login is the Beanstream merchant ID, username and password should be enabled in your Beanstream account and passed in using the <tt>:user</tt> and <tt>:password</tt> options.
# * Test your app with your true merchant id and test credit card information provided in the api pdf document.
# * Beanstream does not allow Payment Profiles to be deleted with their API. The accounts are 'closed', but have to be deleted manually.
#
# Example authorization (Beanstream PA transaction type):
#
# twenty = 2000
# gateway = BeanstreamGateway.new(
# :login => '100200000',
# :user => 'xiaobozz',
# :password => 'password'
# )
#
# credit_card = CreditCard.new(
# :number => '4030000010001234',
# :month => 8,
# :year => 2011,
# :first_name => 'xiaobo',
# :last_name => 'zzz',
# :verification_value => 137
# )
# response = gateway.authorize(twenty, credit_card,
# :order_id => '1234',
# :billing_address => {
# :name => 'xiaobo zzz',
# :phone => '555-555-5555',
# :address1 => '1234 Levesque St.',
# :address2 => 'Apt B',
# :city => 'Montreal',
# :state => 'QC',
# :country => 'CA',
# :zip => 'H2C1X8'
# },
# :email => '[email protected]',
# :subtotal => 800,
# :shipping => 100,
# :tax1 => 100,
# :tax2 => 100,
# :custom => 'reference one'
# )
class BeanstreamGateway < Gateway
include BeanstreamCore
def authorize(money, source, options = {})
post = {}
add_amount(post, money)
add_invoice(post, options)
add_source(post, source)
add_address(post, options)
add_transaction_type(post, :authorization)
add_customer_ip(post, options)
commit(post)
end
def purchase(money, source, options = {})
post = {}
add_amount(post, money)
add_invoice(post, options)
add_source(post, source)
add_address(post, options)
add_transaction_type(post, purchase_action(source))
add_customer_ip(post, options)
commit(post)
end
def void(authorization, options = {})
reference, amount, type = split_auth(authorization)
post = {}
add_reference(post, reference)
add_original_amount(post, amount)
add_transaction_type(post, void_action(type))
commit(post)
end
def recurring(money, source, options = {})
post = {}
add_amount(post, money)
add_invoice(post, options)
add_credit_card(post, source)
add_address(post, options)
add_transaction_type(post, purchase_action(source))
add_recurring_type(post, options)
commit(post)
end
def update_recurring(amount, source, options = {})
post = {}
add_recurring_amount(post, amount)
add_recurring_invoice(post, options)
add_credit_card(post, source)
add_address(post, options)
add_recurring_operation_type(post, :update)
add_recurring_service(post, options)
recurring_commit(post)
end
def cancel_recurring(options = {})
post = {}
add_recurring_operation_type(post, :cancel)
add_recurring_service(post, options)
recurring_commit(post)
end
def interac
@interac ||= BeanstreamInteracGateway.new(@options)
end
# To match the other stored-value gateways, like TrustCommerce,
# store and unstore need to be defined
def store(credit_card, options = {})
post = {}
add_address(post, options)
add_credit_card(post, credit_card)
add_secure_profile_variables(post,options)
commit(post, true)
end
#can't actually delete a secure profile with the supplicaed API. This function sets the status of the profile to closed (C).
#Closed profiles will have to removed manually.
def delete(vault_id)
update(vault_id, false, {:status => "C"})
end
alias_method :unstore, :delete
# Update the values (such as CC expiration) stored at
# the gateway. The CC number must be supplied in the
# CreditCard object.
def update(vault_id, credit_card, options = {})
post = {}
add_address(post, options)
add_credit_card(post, credit_card)
options.merge!({:vault_id => vault_id, :operation => secure_profile_action(:modify)})
add_secure_profile_variables(post,options)
commit(post, true)
end
private
def build_response(*args)
Response.new(*args)
end
end
end
end
| 36.258824 | 182 | 0.624432 |
7afa350131825b64d2df108aeab0c989f3afa16f | 32 | # encoding: utf-8
puts '135°C'
| 8 | 17 | 0.625 |
11115788e6672e3875210b887e8b90a81454a6c2 | 2,055 | class Cmake < Formula
desc "Cross-platform make"
homepage "https://www.cmake.org/"
url "https://github.com/Kitware/CMake/releases/download/v3.19.4/cmake-3.19.4.tar.gz"
sha256 "7d0232b9f1c57e8de81f38071ef8203e6820fe7eec8ae46a1df125d88dbcc2e1"
license "BSD-3-Clause"
head "https://gitlab.kitware.com/cmake/cmake.git"
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "1658569ae8319c6cebd27b6b77bf8309c8b72e1af2e7fd353e4a6360d10d6910"
sha256 cellar: :any_skip_relocation, big_sur: "278f2ad1caf664019ff7b4a7fc5493999c06adf503637447af13a617d45cf484"
sha256 cellar: :any_skip_relocation, catalina: "c42d53380afdc00b76ec56a503fd6e27d8c64c65a6aa5dee0bebd45e35a78209"
sha256 cellar: :any_skip_relocation, mojave: "c4eac1fa4580a117a33f03cbd1ad8ccc5ec68770cc24bbe23bf9a3d55048ef70"
end
depends_on "sphinx-doc" => :build
uses_from_macos "ncurses"
on_linux do
depends_on "[email protected]"
end
# The completions were removed because of problems with system bash
# The `with-qt` GUI option was removed due to circular dependencies if
# CMake is built with Qt support and Qt is built with MySQL support as MySQL uses CMake.
# For the GUI application please instead use `brew install --cask cmake`.
def install
args = %W[
--prefix=#{prefix}
--no-system-libs
--parallel=#{ENV.make_jobs}
--datadir=/share/cmake
--docdir=/share/doc/cmake
--mandir=/share/man
--sphinx-build=#{Formula["sphinx-doc"].opt_bin}/sphinx-build
--sphinx-html
--sphinx-man
]
on_macos do
args += %w[
--system-zlib
--system-bzip2
--system-curl
]
end
system "./bootstrap", *args, "--", *std_cmake_args,
"-DCMake_INSTALL_EMACS_DIR=#{elisp}"
system "make"
system "make", "install"
end
test do
(testpath/"CMakeLists.txt").write("find_package(Ruby)")
system bin/"cmake", "."
end
end
| 31.136364 | 122 | 0.689051 |
03561d1caea860afebef4f738122b5566613e419 | 591 | class LRUCache
def initialize(size)
@size = size
@cache = []
end
def count
# returns number of elements currently in cache
self.cache.length
end
def add(el)
# adds element to cache according to LRU principle
if self.cache.include?(el)
self.cache.delete(el)
self.cache << el
elsif count >= self.size
self.cache.shift
self.cache << el
else
self.cache << el
end
end
def show
# shows the items in the cache, with the LRU item first
p self.cache
nil
end
private
# helper methods go here!
end
| 16.416667 | 59 | 0.619289 |
6a3f57d9e2bbaef0a385f005817c6325885b9032 | 133 | class GroupEquipmentship < ActiveRecord::Base
belongs_to :user
belongs_to :group
belongs_to :equipment, class_name: 'Item'
end | 22.166667 | 45 | 0.781955 |
38419f8e98d21a71a729c8a5919c91d8f5718125 | 4,996 | #!/usr/bin/env ruby
# encoding: utf-8
require_relative '../../environment.rb'
include Sinatra::Mimsy::Helpers
file = "/Users/dshorthouse/Desktop/Objects MXG Upload RTM Dec 2018 - Toronto BB.txt"
log = "/Users/dshorthouse/Desktop/Objects MXG Upload RTM Dec 2018 - Toronto BB.csv"
log_entries = []
CSV.foreach(file, :headers => true, :col_sep => "\t", :encoding => 'bom|utf-16le:utf-8') do |row|
puts row["CATALOGUE.ID_NUMBER"]
if !Catalog.find_by_catalog_number(row["CATALOGUE.ID_NUMBER"]).nil?
log_entries << [row["CATALOGUE.ID_NUMBER"], "catalog record already exists"]
next
end
#Get the linked site
site = nil
site_id = row["SITES.SITE_ID"].strip rescue nil
if !site_id.nil?
site = Site.find_by_site_id(site_id)
if site.nil?
log_entries << [row["CATALOGUE.ID_NUMBER"], "SITE_ID #{site_id} does not exist"]
end
end
#Get the linked placekey
placekey = row["CATALOGUE.PLACEKEY"].strip rescue nil
#create new catalog record
obj = Catalog.new
obj.catalog_number = row["CATALOGUE.ID_NUMBER"].strip
obj.collection = row["CATALOGUE.CATEGORY1"].strip
obj.scientific_name = row["CATALOGUE.ITEM_NAME"].strip
obj.whole_part = row["CATALOGUE.WHOLE_PART"].strip rescue "whole"
obj.item_count = row["CATALOGUE.ITEM_COUNT"].strip.to_i rescue nil
obj.materials = row["CATALOGUE.MATERIALS"].strip rescue nil
obj.description = row["CATALOGUE.DESCRIPTION"].strip rescue nil
obj.collector = row["CATALOGUE.COLLECTOR"].strip rescue nil
obj.note = row["CATALOGUE.NOTE"] rescue nil
obj.date_collected = row["CATALOGUE.DATE_COLLECTED"].strip rescue nil
obj.place_collected = row["CATALOGUE.PLACE_COLLECTED"].strip rescue nil
obj.site = row["CATALOGUE.SITE"] rescue nil
obj.credit_line = row["CATALOGUE.CREDIT_LINE"].strip rescue nil
obj.gbif = true
obj.publish = true
if !site.nil?
obj.site = site.site_name
end
obj.save
#Find object again - damn Oracle!
obj = Catalog.find_by_catalog_number(obj.catalog_number)
#create link to Taxonomy
taxon = row["ITEMS_TAXONOMY.TAXONOMY"].strip.gsub(/\A\p{Space}*|\p{Space}*\z/, '')
tax = Taxon.find_by_scientific_name(taxon)
#Find a variant if verbatim not found
if tax.nil?
tax = TaxonVariation.find_by_scientific_name(taxon).taxon rescue nil
end
if !tax.nil?
obj_tax = CatalogTaxon.new
obj_tax.taxon_id = tax.id
obj_tax.catalog_id = obj.id
obj_tax.attributor = row["ITEMS_TAXONOMY.ATTRIBUTOR"].strip rescue nil
obj_tax.attrib_date = row["ITEMS_TAXONOMY.ATTRIB_DATE"].strip rescue nil
obj_tax.attrib_comment = row["ITEMS_TAXONOMY.ATTRIB_COMMENT"].strip rescue nil
obj_tax.save
else
log_entries << [obj.catalog_number, "taxon name #{taxon} not found in MIMSY"]
end
#create link to Catalog Name
cn = CatalogName.new
cn.scientific_name = obj.scientific_name
cn.catalog_id = obj.id
cn.save
#create link to Person (collector)
if !obj.collector.nil?
obj.collector.split("; ").each do |collector|
pers = Person.find_by_preferred_name(collector)
if pers.nil?
log_entries << [obj.catalog_number, "collector #{collector} not found"]
next
end
cat_coll = CatalogCollector.new
cat_coll.catalog_id = obj.id
cat_coll.person_id = pers.id
cat_coll.relationship = "collector"
cat_coll.note = row["CATALOGUE.COLLECTOR_NOTE"].strip rescue nil
cat_coll.save
end
end
#create link to collected date
if !obj.date_collected.nil?
cd = CollectedDate.new
cd.catalog_id = obj.id
cd.date_text = obj.date_collected
cd.collection_method = row["CATALOGUE.DATE_COLLECTED.COLLECTION_METHOD"].strip rescue nil
cd.save
end
#link to site
if !site.nil?
catsite = CatalogSite.new
catsite.catalog_id = obj.id
catsite.site_id = site.id
catsite.save
end
#link to place collected
if !placekey.nil?
collplace = CatalogCollectionPlace.new
collplace.catalog_id = obj.id
collplace.place_id = placekey
collplace.save
obj.reload
obj.place_collected = Place.find(placekey).location_hierarchy
obj.save
end
#other numbers
(1..5).each do |num|
number = row["OTHER_NUMBERS.OTHER_NUMBER#{num}"].strip rescue nil
if !number.nil?
other_number = CatalogOtherNumber.new
other_number.catalog_id = obj.id
other_number.other_number = number
other_number.on_type = row["OTHER_NUMBERS.ON_TYPE#{num}"].strip rescue nil
other_number.save
end
end
#link to acquisition
if !obj.credit_line.nil?
acquisition_number = obj.credit_line
acquisition = Acquisition.find_by_ref_number(acquisition_number) rescue nil
if !acquisition.nil?
acq_cat = AcquisitionCatalog.new
acq_cat.catalog_id = obj.id
acq_cat.acquisition_id = acquisition.id
acq_cat.id_number = obj.catalog_number
acq_cat.save
end
end
end
CSV.open(log, 'w') do |csv|
csv << ["Item", "Note"]
log_entries.each do |item|
csv << item
end
end | 30.650307 | 97 | 0.707166 |
e83e4ec17766f464ae008777e577e80978e63086 | 491 | module Mulukhiya
class GitHubWebhookContractTest < TestCase
def setup
@contract = GitHubWebhookContract.new
end
def test_call
errors = @contract.call(digest: 'fuga').errors
assert(errors.empty?)
errors = @contract.call(digest: 11).errors
assert_false(errors.empty?)
errors = @contract.call(digest: nil).errors
assert_false(errors.empty?)
errors = @contract.call({}).errors
assert_false(errors.empty?)
end
end
end
| 22.318182 | 52 | 0.663951 |
ed97b6cb577e95c33ac3f25c434507dc8180bf27 | 3,340 | require 'spec_helper'
feature 'Project', feature: true do
describe 'description' do
let(:project) { create(:project) }
let(:path) { namespace_project_path(project.namespace, project) }
before do
login_as(:admin)
end
it 'parses Markdown' do
project.update_attribute(:description, 'This is **my** project')
visit path
expect(page).to have_css('.project-home-desc > p > strong')
end
it 'passes through html-pipeline' do
project.update_attribute(:description, 'This project is the :poop:')
visit path
expect(page).to have_css('.project-home-desc > p > img')
end
it 'sanitizes unwanted tags' do
project.update_attribute(:description, "```\ncode\n```")
visit path
expect(page).not_to have_css('.project-home-desc code')
end
it 'permits `rel` attribute on links' do
project.update_attribute(:description, 'https://google.com/')
visit path
expect(page).to have_css('.project-home-desc a[rel]')
end
end
describe 'remove forked relationship', js: true do
let(:user) { create(:user) }
let(:project) { create(:project, namespace: user.namespace) }
before do
login_with user
create(:forked_project_link, forked_to_project: project)
visit edit_namespace_project_path(project.namespace, project)
end
it 'should remove fork' do
expect(page).to have_content 'Remove fork relationship'
remove_with_confirm('Remove fork relationship', project.path)
expect(page).to have_content 'The fork relationship has been removed.'
expect(project.forked?).to be_falsey
expect(page).not_to have_content 'Remove fork relationship'
end
end
describe 'removal', js: true do
let(:user) { create(:user) }
let(:project) { create(:project, namespace: user.namespace) }
before do
login_with(user)
project.team << [user, :master]
visit edit_namespace_project_path(project.namespace, project)
end
it 'should remove project' do
expect { remove_with_confirm('Remove project', project.path) }.to change {Project.count}.by(-1)
end
end
describe 'leave project link' do
let(:user) { create(:user) }
let(:project) { create(:project, namespace: user.namespace) }
before do
login_with(user)
project.team.add_user(user, Gitlab::Access::MASTER)
visit namespace_project_path(project.namespace, project)
end
it 'click project-settings and find leave project' do
find('#project-settings-button').click
expect(page).to have_link('Leave Project')
end
end
describe 'project title' do
include WaitForAjax
let(:user) { create(:user) }
let(:project) { create(:project, namespace: user.namespace) }
before do
login_with(user)
project.team.add_user(user, Gitlab::Access::MASTER)
visit namespace_project_path(project.namespace, project)
end
it 'click toggle and show dropdown', js: true do
find('.js-projects-dropdown-toggle').click
wait_for_ajax
expect(page).to have_css('.select2-results li', count: 1)
end
end
def remove_with_confirm(button_text, confirm_with)
click_button button_text
fill_in 'confirm_name_input', with: confirm_with
click_button 'Confirm'
end
end
| 29.298246 | 101 | 0.673353 |
7adf7874d230cf8fa9c0dc11ba60110af01347aa | 863 | class OrganizationsController < ApplicationController
def show
authorize Organization
end
# alert: no authlevel!
def new
@organization = Organization.new
authorize @organization
end
# alert: no authlevel!
def create
@organization = Organization.new(organization_params)
authorize @organization
if @organization.save
@organization.permissions.create!(user_id: current_user.id,
authlevel: DmUniboCommon::Authorization::TO_MANAGE)
render 'subscriptions/create'
else
render :new
end
end
def edit
end
def update
@organization.update(organization_params)
redirect_to organizations_path, notice: 'La struttura è stata aggiornata.'
end
private
def organization_params
params[:organization].permit(:code, :name, :description)
end
end
| 22.128205 | 91 | 0.695249 |
11067a3c8ea0cf8356dbb749d992bc38cb387150 | 6,963 | # frozen_string_literal: true
require 'test_helper'
class Admin::Api::ApplicationPlanMetricLimitsTest < ActionDispatch::IntegrationTest
def setup
@provider = FactoryBot.create(:provider_account, domain: 'provider.example.com')
@service = FactoryBot.create(:service, account: @provider)
@app_plan = FactoryBot.create(:application_plan, issuer: @service)
@metric = FactoryBot.create(:metric, service: @service)
@limit = FactoryBot.create(:usage_limit, plan: @app_plan, metric: @metric)
host! @provider.admin_domain
end
class AccessTokenTest < Admin::Api::ApplicationPlanMetricLimitsTest
def setup
super
user = FactoryBot.create(:member, account: @provider, admin_sections: %w[partners plans])
@token = FactoryBot.create(:access_token, owner: user, scopes: 'account_management')
User.any_instance.stubs(:has_access_to_all_services?).returns(false)
end
test 'index with no token' do
get admin_api_application_plan_metric_limits_path(@app_plan, @metric)
assert_response :forbidden
end
test 'index with access to no services' do
User.any_instance.expects(:member_permission_service_ids).returns([]).at_least_once
get admin_api_application_plan_metric_limits_path(@app_plan, @metric), params: params
assert_response :not_found
end
test 'index with access to some service' do
User.any_instance.expects(:member_permission_service_ids).returns([@service.id]).at_least_once
get admin_api_application_plan_metric_limits_path(@app_plan, @metric), params: params
assert_response :success
end
test 'index with access to all services' do
User.any_instance.stubs(:has_access_to_all_services?).returns(true)
User.any_instance.expects(:member_permission_service_ids).never
get admin_api_application_plan_metric_limits_path(@app_plan, @metric), params: params
assert_response :success
end
private
def access_token_params(token = @token)
{ access_token: token.value }
end
alias params access_token_params
end
class ProviderKeyTest < Admin::Api::ApplicationPlanMetricLimitsTest
test 'application_plan not found' do
get admin_api_application_plan_metric_limits_path(application_plan_id: 0, metric_id: @metric.id), params: params
assert_response :not_found
end
test 'application metric not found' do
get admin_api_application_plan_metric_limits_path(application_plan_id: @app_plan.id, metric_id: 0, format: :xml), params: params
assert_response :not_found
end
test 'application_plan_metric_limits_index only limits of this metric are returned' do
# Regression test
another_metric = FactoryBot.create(:metric, service: @service)
FactoryBot.create(:usage_limit, plan: @app_plan, metric: another_metric)
get admin_api_application_plan_metric_limits_path(@app_plan, @metric, format: :xml), params: params
assert_response :success
assert_usage_limits(body, { plan_id: @app_plan.id, metric_id: @metric.id })
end
test 'application_plan_metric_limits_index with a backend api used by service returns success' do
backend = FactoryBot.create(:backend_api)
metric = FactoryBot.create(:metric, owner: backend)
FactoryBot.create(:backend_api_config, backend_api: backend, service: @app_plan.service)
get admin_api_application_plan_metric_limits_path(@app_plan, metric, format: :xml), params: params
assert_response :success
end
test 'application_plan_metric_limits_index with a backend api not used by service returns not found' do
backend = FactoryBot.create(:backend_api)
metric = FactoryBot.create(:metric, owner: backend)
get admin_api_application_plan_metric_limits_path(@app_plan, metric, format: :xml), params: params
assert_response :not_found
end
test 'application_plan_metric_limit_show' do
get admin_api_application_plan_metric_limit_path(@app_plan, @metric, @limit, format: :xml), params: params
assert_response :success
assert_usage_limit(body, { id: @limit.id, plan_id: @app_plan.id, metric_id: @metric.id })
end
test 'application_plan_plan_metric show not found' do
get admin_api_application_plan_metric_limit_path(application_plan_id: @app_plan.id, metric_id: @metric.id, id: 0, format: :xml), params: params
assert_response :not_found
end
test 'application_plan_metric create' do
post admin_api_application_plan_metric_limits_path(@app_plan, @metric, format: :xml), params: params.merge({ period: 'week', value: 15 })
assert_response :success
assert_usage_limit(body, { plan_id: @app_plan.id, metric_id: @metric.id, period: 'week', value: 15 })
metric_limit = @metric.usage_limits.last
assert_equal :week, metric_limit.period
assert_equal 15, metric_limit.value
end
test 'application_plan_metric create errors' do
post admin_api_application_plan_metric_limits_path(@app_plan, @metric, format: :xml), params: params.merge({ period: 'a-while' })
assert_response :unprocessable_entity
assert_xml_error body, "Period is invalid"
end
test 'application_plan_metric_limits update' do
@limit.update(period: 'week', value: 10)
put admin_api_application_plan_metric_limit_path(@app_plan, @metric, @limit), params: params.merge({ period: 'month', value: "20", format: :xml })
assert_response :success
assert_usage_limit(body, { plan_id: @app_plan.id, metric_id: @metric.id, period: "month", value: "20" })
@limit.reload
assert_equal :month, @limit.period
assert_equal 20, @limit.value
end
test 'application_plan_metrics_limit update not found' do
put admin_api_application_plan_metric_limit_path(@app_plan, @metric, id: 0, format: :xml), params: params
assert_response :not_found
end
test 'application_plan_metrics_limit update errors' do
put admin_api_application_plan_metric_limit_path(@app_plan, @metric, @limit, format: :xml), params: params.merge({ period: 'century' })
assert_response :unprocessable_entity
assert_xml_error body, "Period is invalid"
end
test 'application_plan_metrics_limit destroy' do
delete admin_api_application_plan_metric_limit_path(@app_plan, @metric, @limit, format: :xml), params: params.merge({ method: "_destroy" })
assert_response :success
assert_empty_xml body
assert_raise ActiveRecord::RecordNotFound do
@limit.reload
end
end
test 'application_plan_metrics_limit destroy not found' do
delete admin_api_application_plan_metric_limit_path(@app_plan, @metric, id: 0, format: :xml), params: params.merge({ method: "_destroy" })
assert_response :not_found
end
private
def provider_key_params
{ provider_key: @provider.api_key }
end
alias params provider_key_params
end
end
| 39.788571 | 152 | 0.736895 |
1ad12b9e047d114a92736ece7ab95c9f8eb6f7c5 | 34,451 | # NOTE: file contains code adapted from **oracle-enhanced** adapter, license follows
=begin
Copyright (c) 2008-2011 Graham Jenkins, Michael Schoen, Raimonds Simanovskis
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=end
ArJdbc.load_java_part :Oracle
module ArJdbc
module Oracle
require 'arjdbc/oracle/column'
# @private
def self.extended(adapter); initialize!; end
# @private
@@_initialized = nil
# @private
def self.initialize!
return if @@_initialized; @@_initialized = true
require 'arjdbc/util/serialized_attributes'
Util::SerializedAttributes.setup /LOB\(|LOB$/i, 'after_save_with_oracle_lob'
unless ActiveRecord::ConnectionAdapters::AbstractAdapter.
instance_methods(false).detect { |m| m.to_s == "prefetch_primary_key?" }
require 'arjdbc/jdbc/quoted_primary_key'
ActiveRecord::Base.extend ArJdbc::QuotedPrimaryKeyExtension
end
end
# @see ActiveRecord::ConnectionAdapters::JdbcAdapter#jdbc_connection_class
def self.jdbc_connection_class
::ActiveRecord::ConnectionAdapters::OracleJdbcConnection
end
# @see ActiveRecord::ConnectionAdapters::JdbcAdapter#jdbc_column_class
def jdbc_column_class; ::ActiveRecord::ConnectionAdapters::OracleColumn end
# @private
@@update_lob_values = true
# Updating records with LOB values (binary/text columns) in a separate
# statement can be disabled using :
#
# ArJdbc::Oracle.update_lob_values = false
#
# @note This only applies when prepared statements are not used.
def self.update_lob_values?; @@update_lob_values; end
# @see #update_lob_values?
def self.update_lob_values=(update); @@update_lob_values = update; end
# @see #update_lob_values?
# @see ArJdbc::Util::SerializedAttributes#update_lob_columns
def update_lob_value?(value, column = nil)
Oracle.update_lob_values? && ! prepared_statements? && ! ( value.nil? || value == '' )
end
# @private
@@emulate_booleans = true
# Boolean emulation can be disabled using :
#
# ArJdbc::Oracle.emulate_booleans = false
#
# @see ActiveRecord::ConnectionAdapters::OracleAdapter#emulate_booleans
def self.emulate_booleans?; @@emulate_booleans; end
# @deprecated Use {#emulate_booleans?} instead.
def self.emulate_booleans; @@emulate_booleans; end
# @see #emulate_booleans?
def self.emulate_booleans=(emulate); @@emulate_booleans = emulate; end
class TableDefinition < ::ActiveRecord::ConnectionAdapters::TableDefinition
def raw(*args)
options = args.extract_options!
column(args[0], 'raw', options)
end unless AR42
def raw(name, options={})
column(name, :raw, options)
end if AR42
def xml(*args)
options = args.extract_options!
column(args[0], 'xml', options)
end unless AR42
def raw(name, options={})
column(name, :xml, options)
end if AR42
def aliased_types(name, fallback)
# NOTE: disable aliasing :timestamp as :datetime :
fallback # 'timestamp' == name ? :datetime : fallback
end if AR42
end
def table_definition(*args)
new_table_definition(TableDefinition, *args)
end
def create_table_definition(name, temporary, options, as = nil)
TableDefinition.new native_database_types, name, temporary, options, as
end if AR42
ADAPTER_NAME = 'Oracle'.freeze
def adapter_name
ADAPTER_NAME
end
def initialize_type_map(m)
super
m.register_type(%r(NUMBER)i) do |sql_type|
scale = extract_scale(sql_type)
precision = extract_precision(sql_type)
limit = extract_limit(sql_type)
if scale == 0
if Oracle.emulate_booleans? && limit == 1
ActiveRecord::Type::Boolean.new
else
ActiveRecord::Type::Integer.new(:precision => precision, :limit => limit)
end
else
ActiveRecord::Type::Decimal.new(:precision => precision, :scale => scale)
end
end
register_class_with_limit m, %r(date)i, ActiveRecord::Type::DateTime
register_class_with_limit m, %r(raw)i, RawType
register_class_with_limit m, %r(timestamp)i, TimestampType
m.register_type %r(xmltype)i, XmlType.new
end if AR42
def clear_cache!
super
reload_type_map
end if AR42
# @private
class RawType < ActiveRecord::Type::String
def type; :raw end
end if AR42
# @private
class TimestampType < ActiveRecord::Type::DateTime
def type; :timestamp end
end if AR42
# @private
class XmlType < ActiveRecord::Type::String
def type; :xml end
def type_cast_for_database(value)
return unless value
Data.new(super)
end
class Data
def initialize(value)
@value = value
end
def to_s; @value end
end
end if AR42
NATIVE_DATABASE_TYPES = {
:primary_key => "NUMBER(38) NOT NULL PRIMARY KEY",
:string => { :name => "VARCHAR2", :limit => 255 },
:text => { :name => "CLOB" },
:integer => { :name => "NUMBER", :limit => 38 },
:float => { :name => "NUMBER" },
:decimal => { :name => "DECIMAL" },
:datetime => { :name => "DATE" },
:timestamp => { :name => "TIMESTAMP" },
:time => { :name => "DATE" },
:date => { :name => "DATE" },
:binary => { :name => "BLOB" },
:boolean => { :name => "NUMBER", :limit => 1 },
:raw => { :name => "RAW", :limit => 2000 },
:xml => { :name => 'XMLTYPE' }
}
def native_database_types
super.merge(NATIVE_DATABASE_TYPES)
end
def modify_types(types)
super(types)
NATIVE_DATABASE_TYPES.each do |key, value|
types[key] = value.dup
end
types
end
# Prevent ORA-01795 for in clauses with more than 1000
def in_clause_length
1000
end
alias_method :ids_in_list_limit, :in_clause_length
IDENTIFIER_LENGTH = 30
# maximum length of Oracle identifiers is 30
def table_alias_length; IDENTIFIER_LENGTH; end
def table_name_length; IDENTIFIER_LENGTH; end
def index_name_length; IDENTIFIER_LENGTH; end
def column_name_length; IDENTIFIER_LENGTH; end
def sequence_name_length; IDENTIFIER_LENGTH end
# @private
# Will take all or first 26 characters of table name and append _seq suffix
def default_sequence_name(table_name, primary_key = nil)
len = IDENTIFIER_LENGTH - 4
table_name.to_s.gsub (/(^|\.)([\w$-]{1,#{len}})([\w$-]*)$/), '\1\2_seq'
end
# @private
def default_trigger_name(table_name)
"#{table_name.to_s[0, IDENTIFIER_LENGTH - 4]}_pkt"
end
# @override
def create_table(name, options = {})
super(name, options)
unless options[:id] == false
seq_name = options[:sequence_name] || default_sequence_name(name)
start_value = options[:sequence_start_value] || 10000
raise ActiveRecord::StatementInvalid.new("name #{seq_name} too long") if seq_name.length > table_alias_length
execute "CREATE SEQUENCE #{quote_table_name(seq_name)} START WITH #{start_value}"
end
end
# @override
def rename_table(name, new_name)
if new_name.to_s.length > table_name_length
raise ArgumentError, "New table name '#{new_name}' is too long; the limit is #{table_name_length} characters"
end
if "#{new_name}_seq".to_s.length > sequence_name_length
raise ArgumentError, "New sequence name '#{new_name}_seq' is too long; the limit is #{sequence_name_length} characters"
end
execute "RENAME #{quote_table_name(name)} TO #{quote_table_name(new_name)}"
execute "RENAME #{quote_table_name("#{name}_seq")} TO #{quote_table_name("#{new_name}_seq")}" rescue nil
end
# @override
def drop_table(name, options = {})
outcome = super(name)
return outcome if name == 'schema_migrations'
seq_name = options.key?(:sequence_name) ? # pass nil/false - no sequence
options[:sequence_name] : default_sequence_name(name)
return outcome unless seq_name
execute_quietly "DROP SEQUENCE #{quote_table_name(seq_name)}"
end
# @override
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
case type.to_sym
when :binary
# { BLOB | BINARY LARGE OBJECT } [ ( length [{K |M |G }] ) ]
# although Oracle does not like limit (length) with BLOB (or CLOB) :
#
# CREATE TABLE binaries (data BLOB, short_data BLOB(1024));
# ORA-00907: missing right parenthesis *
#
# TODO do we need to worry about NORMAL vs. non IN-TABLE BLOBs ?!
# http://dba.stackexchange.com/questions/8770/improve-blob-writing-performance-in-oracle-11g
# - if the LOB is smaller than 3900 bytes it can be stored inside the
# table row; by default this is enabled,
# unless you specify DISABLE STORAGE IN ROW
# - normal LOB - stored in a separate segment, outside of table,
# you may even put it in another tablespace;
super(type, nil, nil, nil)
when :text
super(type, nil, nil, nil)
else
super
end
end
def indexes(table, name = nil)
@connection.indexes(table, name, schema_owner)
end
# @note Only used with (non-AREL) ActiveRecord **2.3**.
# @see Arel::Visitors::Oracle
def add_limit_offset!(sql, options)
offset = options[:offset] || 0
if limit = options[:limit]
sql.replace "SELECT * FROM " <<
"(select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_ where rownum <= #{offset + limit})" <<
" WHERE raw_rnum_ > #{offset}"
elsif offset > 0
sql.replace "SELECT * FROM " <<
"(select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_)" <<
" WHERE raw_rnum_ > #{offset}"
end
end if ::ActiveRecord::VERSION::MAJOR < 3
def current_user
@current_user ||= execute("SELECT sys_context('userenv', 'session_user') su FROM dual").first['su']
end
def current_database
@current_database ||= execute("SELECT sys_context('userenv', 'db_name') db FROM dual").first['db']
end
def current_schema
execute("SELECT sys_context('userenv', 'current_schema') schema FROM dual").first['schema']
end
def current_schema=(schema_owner)
execute("ALTER SESSION SET current_schema=#{schema_owner}")
end
# @override
def release_savepoint(name = nil)
# no RELEASE SAVEPOINT statement in Oracle (JDBC driver throws "Unsupported feature")
end
# @override
def add_index(table_name, column_name, options = {})
index_name, index_type, quoted_column_names, tablespace, index_options = add_index_options(table_name, column_name, options)
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{quoted_column_names})#{tablespace} #{index_options}"
if index_type == 'UNIQUE'
unless quoted_column_names =~ /\(.*\)/
execute "ALTER TABLE #{quote_table_name(table_name)} ADD CONSTRAINT #{quote_column_name(index_name)} #{index_type} (#{quoted_column_names})"
end
end
end if AR42
# @private
def add_index_options(table_name, column_name, options = {})
column_names = Array(column_name)
index_name = index_name(table_name, column: column_names)
options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :tablespace, :options, :using)
index_type = options[:unique] ? "UNIQUE" : ""
index_name = options[:name].to_s if options.key?(:name)
tablespace = '' # tablespace_for(:index, options[:tablespace])
max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
index_options = '' # index_options = options[:options]
if index_name.to_s.length > max_index_length
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
end
if index_name_exists?(table_name, index_name, false)
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
end
quoted_column_names = column_names.map { |e| quote_column_name(e, true) }.join(", ")
[ index_name, index_type, quoted_column_names, tablespace, index_options ]
end if AR42
# @override
def remove_index(table_name, options = {})
index_name = index_name(table_name, options)
unless index_name_exists?(table_name, index_name, true)
# sometimes options can be String or Array with column names
options = {} unless options.is_a?(Hash)
if options.has_key? :name
options_without_column = options.dup
options_without_column.delete :column
index_name_without_column = index_name(table_name, options_without_column)
return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
end
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
end
execute "ALTER TABLE #{quote_table_name(table_name)} DROP CONSTRAINT #{quote_column_name(index_name)}" rescue nil
execute "DROP INDEX #{quote_column_name(index_name)}"
end if AR42
# @private
def remove_index(table_name, options = {})
execute "DROP INDEX #{index_name(table_name, options)}"
end unless AR42
def change_column_default(table_name, column_name, default)
execute "ALTER TABLE #{quote_table_name(table_name)} MODIFY #{quote_column_name(column_name)} DEFAULT #{quote(default)}"
end
# @override
def add_column_options!(sql, options)
# handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly
if options_include_default?(options) && (column = options[:column]) && column.type == :text
sql << " DEFAULT #{quote(options.delete(:default))}"
end
super
end
# @override
def change_column(table_name, column_name, type, options = {})
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} " <<
"MODIFY #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}"
add_column_options!(change_column_sql, options)
execute(change_column_sql)
end
# @override
def rename_column(table_name, column_name, new_column_name)
execute "ALTER TABLE #{quote_table_name(table_name)} " <<
"RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
end
if ActiveRecord::VERSION::MAJOR >= 4
# @override
def remove_column(table_name, column_name, type = nil, options = {})
do_remove_column(table_name, column_name)
end
else
# @override
def remove_column(table_name, *column_names)
for column_name in column_names.flatten
do_remove_column(table_name, column_name)
end
end
alias remove_columns remove_column
end
def do_remove_column(table_name, column_name)
execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)}"
end
private :do_remove_column
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
#
# Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT
# queries. However, with those columns included in the SELECT DISTINCT list, you
# won't actually get a distinct list of the column you want (presuming the column
# has duplicates with multiple values for the ordered-by columns. So we use the
# FIRST_VALUE function to get a single (first) value for each column, effectively
# making every row the same.
#
# distinct("posts.id", "posts.created_at desc")
#
# @override
def distinct(columns, order_by)
"DISTINCT #{columns_for_distinct(columns, order_by)}"
end
# @override Since AR 4.0 (on 4.1 {#distinct} is gone and won't be called).
def columns_for_distinct(columns, orders)
return columns if orders.blank?
if orders.is_a?(Array) # AR 3.x vs 4.x
orders = orders.map { |column| column.is_a?(String) ? column : column.to_sql }
else
orders = extract_order_columns(orders)
end
# construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using
# FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT
order_columns = orders.map do |c, i|
"FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__"
end
columns = [ columns ]; columns.flatten!
columns.push( *order_columns ).join(', ')
end
# ORDER BY clause for the passed order option.
#
# Uses column aliases as defined by {#distinct}.
def add_order_by_for_association_limiting!(sql, options)
return sql if options[:order].blank?
order_columns = extract_order_columns(options[:order]) do |columns|
columns.map! { |s| $1 if s =~ / (.*)/ }; columns
end
order = order_columns.map { |s, i| "alias_#{i}__ #{s}" } # @see {#distinct}
sql << "ORDER BY #{order.join(', ')}"
end
def extract_order_columns(order_by)
columns = order_by.split(',')
columns.map!(&:strip); columns.reject!(&:blank?)
columns = yield(columns) if block_given?
columns.zip( (0...columns.size).to_a )
end
private :extract_order_columns
def temporary_table?(table_name)
select_value("SELECT temporary FROM user_tables WHERE table_name = '#{table_name.upcase}'") == 'Y'
end
def tables
@connection.tables(nil, oracle_schema)
end
# NOTE: better to use current_schema instead of the configured one ?!
def columns(table_name, name = nil)
@connection.columns_internal(table_name.to_s, nil, oracle_schema)
end
def tablespace(table_name)
select_value "SELECT tablespace_name FROM user_tables WHERE table_name='#{table_name.to_s.upcase}'"
end
def charset
database_parameters['NLS_CHARACTERSET']
end
def collation
database_parameters['NLS_COMP']
end
def database_parameters
return @database_parameters unless ( @database_parameters ||= {} ).empty?
@connection.execute_query_raw("SELECT * FROM NLS_DATABASE_PARAMETERS") do
|name, value| @database_parameters[name] = value
end
@database_parameters
end
# QUOTING ==================================================
# @override
def quote_table_name(name)
name.to_s.split('.').map{ |n| n.split('@').map{ |m| quote_column_name(m) }.join('@') }.join('.')
end
# @private
LOWER_CASE_ONLY = /\A[a-z][a-z_0-9\$#]*\Z/
# @override
def quote_column_name(name, handle_expression = false)
# if only valid lowercase column characters in name
if ( name = name.to_s ) =~ LOWER_CASE_ONLY
# putting double-quotes around an identifier causes Oracle to treat the
# identifier as case sensitive (otherwise assumes case-insensitivity) !
# all upper case is an exception, where double-quotes are meaningless
"\"#{name.upcase}\"" # name.upcase
else
if handle_expression
name =~ /^[a-z][a-z_0-9\$#\-]*$/i ? "\"#{name}\"" : name
else
# remove double quotes which cannot be used inside quoted identifier
"\"#{name.gsub('"', '')}\""
end
end
end
def unquote_table_name(name)
name = name[1...-1] if name[0, 1] == '"'
name.upcase == name ? name.downcase : name
end
# @override
def quote(value, column = nil)
return value if sql_literal?(value)
column_type = column && column.type
if column_type == :text || column_type == :binary
return 'NULL' if value.nil? || value == ''
if update_lob_value?(value, column)
if /(.*?)\([0-9]+\)/ =~ ( sql_type = column.sql_type )
%Q{empty_#{ $1.downcase }()}
else
%Q{empty_#{ sql_type.respond_to?(:downcase) ? sql_type.downcase : 'blob' }()}
end
else
"'#{quote_string(value.to_s)}'"
end
elsif column_type == :xml
"XMLTYPE('#{quote_string(value)}')" # XMLTYPE ?
elsif column_type == :raw
quote_raw(value)
else
if column.respond_to?(:primary) && column.primary && column.klass != String
return value.to_i.to_s
end
if column_type == :datetime || column_type == :time
if value.acts_like?(:time)
%Q{TO_DATE('#{get_time(value).strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')}
else
value.blank? ? 'NULL' : %Q{DATE'#{value}'} # assume correctly formated DATE (string)
end
elsif ( like_date = value.acts_like?(:date) ) || column_type == :date
if value.acts_like?(:time) # value.respond_to?(:strftime)
%Q{DATE'#{get_time(value).strftime("%Y-%m-%d")}'}
elsif like_date
%Q{DATE'#{quoted_date(value)}'} # DATE 'YYYY-MM-DD'
else
value.blank? ? 'NULL' : %Q{DATE'#{value}'} # assume correctly formated DATE (string)
end
elsif ( like_time = value.acts_like?(:time) ) || column_type == :timestamp
if like_time
%Q{TIMESTAMP'#{quoted_date(value, true)}'} # TIMESTAMP 'YYYY-MM-DD HH24:MI:SS.FF'
else
value.blank? ? 'NULL' : %Q{TIMESTAMP'#{value}'} # assume correctly formated TIMESTAMP (string)
end
else
super
end
end
end
# Quote date/time values for use in SQL input.
# Includes milliseconds if the value is a Time responding to usec.
# @override
def quoted_date(value, time = nil)
if time || ( time.nil? && value.acts_like?(:time) )
usec = value.respond_to?(:usec) && (value.usec / 10000.0).round # .428000 -> .43
return "#{get_time(value).to_s(:db)}.#{sprintf("%02d", usec)}" if usec
# value.strftime("%Y-%m-%d %H:%M:%S")
end
value.to_s(:db)
end
def quote_raw(value)
value = value.unpack('C*') if value.is_a?(String)
"'#{value.map { |x| "%02X" % x }.join}'"
end
# @override
def supports_migrations?; true end
# @override
def supports_primary_key?; true end
# @override
def supports_savepoints?; true end
# @override
def supports_explain?; true end
# @override
def supports_views?; true end
def truncate(table_name, name = nil)
execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name
end
def explain(arel, binds = [])
sql = "EXPLAIN PLAN FOR #{to_sql(arel, binds)}"
return if sql =~ /FROM all_/
exec_update(sql, 'EXPLAIN', binds)
select_values("SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY)", 'EXPLAIN').join("\n")
end
def select(sql, name = nil, binds = [])
result = super # AR::Result (4.0) or Array (<= 3.2)
result.columns.delete('raw_rnum_') if result.respond_to?(:columns)
result.each { |row| row.delete('raw_rnum_') } # Hash rows even for AR::Result
result
end
@@do_not_prefetch_primary_key = {}
# Returns true for Oracle adapter (since Oracle requires primary key
# values to be pre-fetched before insert).
# @see #next_sequence_value
# @override
def prefetch_primary_key?(table_name = nil)
return true if table_name.nil?
do_not_prefetch_hash = @@do_not_prefetch_primary_key
do_not_prefetch = do_not_prefetch_hash[ table_name = table_name.to_s ]
if do_not_prefetch.nil?
owner, desc_table_name, db_link = describe(table_name)
do_not_prefetch_hash[table_name] = do_not_prefetch =
! has_primary_key?(table_name, owner, desc_table_name, db_link) ||
has_primary_key_trigger?(table_name, owner, desc_table_name, db_link)
end
! do_not_prefetch
end
# used to clear prefetch primary key flag for all tables
# @private
def clear_prefetch_primary_key; @@do_not_prefetch_primary_key = {} end
# @private
def has_primary_key?(table_name, owner = nil, desc_table_name = nil, db_link = nil)
! pk_and_sequence_for(table_name, owner, desc_table_name, db_link).nil?
end
# @private check if table has primary key trigger with _pkt suffix
def has_primary_key_trigger?(table_name, owner = nil, desc_table_name = nil, db_link = nil)
(owner, desc_table_name, db_link) = describe(table_name) unless desc_table_name
trigger_name = default_trigger_name(table_name).upcase
pkt_sql = "SELECT trigger_name FROM all_triggers#{db_link} WHERE owner = '#{owner}'" <<
" AND trigger_name = '#{trigger_name}'" <<
" AND table_owner = '#{owner}'" <<
" AND table_name = '#{desc_table_name}'" <<
" AND status = 'ENABLED'"
select_value(pkt_sql, 'Primary Key Trigger') ? true : false
end
# use in set_sequence_name to avoid fetching primary key value from sequence
AUTOGENERATED_SEQUENCE_NAME = 'autogenerated'.freeze
# Returns the next sequence value from a sequence generator. Not generally
# called directly; used by ActiveRecord to get the next primary key value
# when inserting a new database record (see #prefetch_primary_key?).
def next_sequence_value(sequence_name)
# if sequence_name is set to :autogenerated then it means that primary key will be populated by trigger
return nil if sequence_name == AUTOGENERATED_SEQUENCE_NAME
sequence_name = quote_table_name(sequence_name)
sql = "SELECT #{sequence_name}.NEXTVAL id FROM dual"
log(sql, 'SQL') { @connection.next_sequence_value(sequence_name) }
end
def pk_and_sequence_for(table_name, owner = nil, desc_table_name = nil, db_link = nil)
(owner, desc_table_name, db_link) = describe(table_name) unless desc_table_name
seqs = "SELECT us.sequence_name" <<
" FROM all_sequences#{db_link} us" <<
" WHERE us.sequence_owner = '#{owner}'" <<
" AND us.sequence_name = '#{desc_table_name}_SEQ'"
seqs = select_values(seqs, 'Sequence')
# changed back from user_constraints to all_constraints for consistency
pks = "SELECT cc.column_name" <<
" FROM all_constraints#{db_link} c, all_cons_columns#{db_link} cc" <<
" WHERE c.owner = '#{owner}'" <<
" AND c.table_name = '#{desc_table_name}'" <<
" AND c.constraint_type = 'P'" <<
" AND cc.owner = c.owner" <<
" AND cc.constraint_name = c.constraint_name"
pks = select_values(pks, 'Primary Key')
# only support single column keys
pks.size == 1 ? [oracle_downcase(pks.first), oracle_downcase(seqs.first)] : nil
end
private :pk_and_sequence_for
# Returns just a table's primary key
def primary_key(table_name)
pk_and_sequence = pk_and_sequence_for(table_name)
pk_and_sequence && pk_and_sequence.first
end
# @override
def supports_foreign_keys?; true end
# @private
def disable_referential_integrity
sql_constraints = "SELECT constraint_name, owner, table_name FROM user_constraints WHERE constraint_type = 'R' AND status = 'ENABLED'"
old_constraints = select_all(sql_constraints)
begin
old_constraints.each do |constraint|
execute "ALTER TABLE #{constraint["table_name"]} DISABLE CONSTRAINT #{constraint["constraint_name"]}"
end
yield
ensure
old_constraints.reverse_each do |constraint|
execute "ALTER TABLE #{constraint["table_name"]} ENABLE CONSTRAINT #{constraint["constraint_name"]}"
end
end
end
# @override (for AR <= 3.0)
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
# if PK is already pre-fetched from sequence or if there is no PK :
if id_value || pk.nil?
execute(sql, name)
return id_value
end
if pk && use_insert_returning? # true by default on AR <= 3.0
sql = "#{sql} RETURNING #{quote_column_name(pk)} INTO ?"
exec_insert_returning(sql, name, nil, pk)
else
execute(sql, name)
end
end
protected :insert_sql
# @override
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
unless id_value || pk.nil?
if pk && use_insert_returning?
sql = "#{sql} RETURNING #{quote_column_name(pk)} INTO ?"
end
end
[ sql, binds ]
end
# @override
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
# NOTE: ActiveRecord::Relation calls our {#next_sequence_value}
# (from its `insert`) and passes the returned id_value here ...
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
if id_value
exec_update(sql, name, binds)
return id_value
else
value = exec_insert(sql, name, binds, pk, sequence_name)
id_value || last_inserted_id(value)
end
end
# @override
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
if pk && use_insert_returning?
if sql.is_a?(String) && sql.index('RETURNING')
return exec_insert_returning(sql, name, binds, pk)
end
end
super(sql, name, binds) # assume no generated id for table
end
def exec_insert_returning(sql, name, binds, pk = nil)
sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)
if prepared_statements?
log(sql, name, binds) { @connection.execute_insert_returning(sql, binds) }
else
log(sql, name) { @connection.execute_insert_returning(sql, nil) }
end
end
# private :exec_insert_returning
def next_id_value(sql, sequence_name = nil)
# Assume the SQL contains a bind-variable for the ID
sequence_name ||= begin
# Extract the table from the insert SQL. Yuck.
table = extract_table_ref_from_insert_sql(sql)
default_sequence_name(table)
end
next_sequence_value(sequence_name)
end
private :next_id_value
def use_insert_returning?
if @use_insert_returning.nil?
@use_insert_returning = false
end
@use_insert_returning
end
private
def _execute(sql, name = nil)
if self.class.select?(sql)
@connection.execute_query_raw(sql)
elsif self.class.insert?(sql)
@connection.execute_insert(sql)
else
@connection.execute_update(sql)
end
end
def extract_table_ref_from_insert_sql(sql)
table = sql.split(" ", 4)[2]
if idx = table.index('(')
table = table[0...idx] # INTO table(col1, col2) ...
end
unquote_table_name(table)
end
# In Oracle, schemas are usually created under your username :
# http://www.oracle.com/technology/obe/2day_dba/schema/schema.htm
#
# A schema is the set of objects (tables, views, indexes, etc) that belongs
# to an user, often used as another way to refer to an Oracle user account.
#
# But allow separate configuration as "schema:" anyway (see #53)
def oracle_schema
if @config[:schema]
@config[:schema].to_s
elsif @config[:username]
@config[:username].to_s
end
end
# default schema owner
def schema_owner(force = true)
unless defined? @schema_owner
username = config[:username] ? config[:username].to_s : nil
username = jdbc_connection.meta_data.user_name if force && username.nil?
@schema_owner = username.nil? ? nil : username.upcase
end
@schema_owner
end
# do not force reading schema_owner as we're read on our own ...
def describe(table_name, owner = schema_owner(false))
@connection.describe(table_name, owner)
end
def oracle_downcase(column_name)
return nil if column_name.nil?
column_name =~ /[a-z]/ ? column_name : column_name.downcase
end
end
end
require 'arjdbc/util/quoted_cache'
module ActiveRecord::ConnectionAdapters
remove_const(:OracleAdapter) if const_defined?(:OracleAdapter)
class OracleAdapter < JdbcAdapter
include ::ArJdbc::Oracle
include ::ArJdbc::Util::QuotedCache
# By default, the OracleAdapter will consider all columns of type
# <tt>NUMBER(1)</tt> as boolean. If you wish to disable this :
#
# ActiveRecord::ConnectionAdapters::OracleAdapter.emulate_booleans = false
#
def self.emulate_booleans?; ::ArJdbc::Oracle.emulate_booleans?; end
def self.emulate_booleans; ::ArJdbc::Oracle.emulate_booleans?; end # oracle-enhanced
def self.emulate_booleans=(emulate); ::ArJdbc::Oracle.emulate_booleans = emulate; end
def initialize(*args)
::ArJdbc::Oracle.initialize!
super # configure_connection happens in super
@use_insert_returning = config.key?(:insert_returning) ?
self.class.type_cast_config_to_boolean(config[:insert_returning]) : nil
end
end
class OracleColumn < JdbcColumn
include ::ArJdbc::Oracle::Column
# def returning_id?; @returning_id ||= nil end
# def returning_id!; @returning_id = true end
end
end
| 36.150052 | 165 | 0.653827 |
01a8ee8632fa3d572763431b19a811930f817cc6 | 458 | require 'rails_helper'
RSpec.describe Question, type: :model do
subject { described_class.new(title: 'Question?', description: 'Description') }
it 'is valid with valid attributes' do
expect(subject).to be_valid
end
it 'is not valid without a title' do
subject.title = nil
expect(subject).to_not be_valid
end
it 'is not valid without a description' do
subject.description = nil
expect(subject).to_not be_valid
end
end
| 19.913043 | 81 | 0.71179 |
0852dfb1eaf34ea29b0a908560549db4b4a917bb | 126 | # http://www.codewars.com/kata/56fa3c5ce4d45d2a52001b3c
# --- iteration 1 ---
def xor(a,b)
[!!a, !!b].count(true) == 1
end
| 18 | 55 | 0.626984 |
03df65edf1b104d2a8daecdd6231d812f3e277bb | 553 | Дэвид Бекхэм попал в ДТП, пытаясь скрыться от кроме
Дэвид Бекхэм попал в аварию на мотоцикле, пытаясь спасти себя от кроме.
Это случилось в Лос-Анджелесе на бульваре Сансет.
Британский футболист легко отделалась лишь сотрясением и ресторан, правую руку.
Бэкхем покинул комнату татуировки, где находились кроме лагерем, ждала его.
При попытке к бегству своей погони на мотоцикле, он потерял управление на повороте и упал, пишет TMZ, со ссылкой на источники, близкие к футболист.
В общем, Бекхэм получил сотрясение мозга, правая рука, ресторан и царапин.
| 69.125 | 147 | 0.815552 |
334414bcf41880b9e60e0bdf5060c3245641b7ce | 878 | Hanami::Model.migration do
change do
create_table :songs do
column :title, String
column :useless, String
foreign_key :artist_id, :artists
index :artist_id
add_constraint(:useless_min_length) { char_length(useless) > 2 }
end
alter_table :songs do
add_primary_key :id
add_column :downloads_count, Integer
set_column_type :useless, File
rename_column :title, :primary_title
set_column_default :primary_title, 'Unknown title'
# add_index :album_id
# drop_index :artist_id
# add_foreign_key :album_id, :albums, on_delete: :cascade
# drop_foreign_key :artist_id
# add_constraint(:title_min_length) { char_length(title) > 2 }
# add_unique_constraint [:album_id, :title]
drop_constraint :useless_min_length
drop_column :useless
end
end
end
| 23.72973 | 70 | 0.676538 |
b9c20b2199e227ad31a783e82457b3ec9bbbf675 | 6,834 | WORKSPACE_DIR = File.expand_path(File.dirname(__FILE__) + '/..')
def in_dir(dir)
current = Dir.pwd
begin
Dir.chdir(dir)
yield
ensure
Dir.chdir(current)
end
end
ENV['PREVIOUS_PRODUCT_VERSION'] = nil if ENV['PREVIOUS_PRODUCT_VERSION'].to_s == ''
ENV['PRODUCT_VERSION'] = nil if ENV['PRODUCT_VERSION'].to_s == ''
def stage(stage_name, description, options = {})
if ENV['STAGE'].nil? || ENV['STAGE'] == stage_name || options[:always_run]
puts "🚀 Release Stage: #{stage_name} - #{description}"
begin
yield
rescue Exception => e
puts '💣 Error completing stage.'
puts "Fix the error and re-run release process passing: STAGE=#{stage_name}#{ ENV['PREVIOUS_PRODUCT_VERSION'] ? " PREVIOUS_PRODUCT_VERSION=#{ENV['PREVIOUS_PRODUCT_VERSION']}" : ''}#{ ENV['PREVIOUS_PRODUCT_VERSION'] ? " PRODUCT_VERSION=#{ENV['PRODUCT_VERSION']}" : ''}"
raise e
end
ENV['STAGE'] = nil unless options[:always_run]
elsif !ENV['STAGE'].nil?
puts "Skipping Stage: #{stage_name} - #{description}"
end
if ENV['LAST_STAGE'] == stage_name
ENV['STAGE'] = ENV['LAST_STAGE']
end
end
desc 'Perform a release'
task 'perform_release' do
in_dir(WORKSPACE_DIR) do
stage('ExtractVersion', 'Extract the last version from CHANGELOG.md and derive next version unless specified', :always_run => true) do
changelog = IO.read('CHANGELOG.md')
ENV['PREVIOUS_PRODUCT_VERSION'] ||= changelog[/^### \[v(\d+\.\d+(\.\d+)?)\]/, 1] || '0.00'
next_version = ENV['PRODUCT_VERSION']
unless next_version
version_parts = ENV['PREVIOUS_PRODUCT_VERSION'].split('.')
next_version = "#{version_parts[0]}.#{sprintf('%02d', version_parts[1].to_i + 1)}#{version_parts.length > 2 ? ".#{version_parts[2]}" : ''}"
ENV['PRODUCT_VERSION'] = next_version
end
# Also initialize release date if required
ENV['RELEASE_DATE'] ||= Time.now.strftime('%Y-%m-%d')
end
stage('ZapWhite', 'Ensure that zapwhite produces no changes') do
sh "bundle exec zapwhite"
end
stage('GitClean', 'Ensure there is nothing to commit and the working tree is clean') do
status_output = `git status -s 2>&1`.strip
raise 'Uncommitted changes in git repository. Please commit them prior to release.' if 0 != status_output.size
end
stage('StagingCleanup', 'Remove artifacts from staging repository') do
task('staging:cleanup').invoke
end
stage('Build', 'Build the project to ensure that the tests pass') do
sh "bundle exec buildr clean package install PRODUCT_VERSION=#{ENV['PRODUCT_VERSION']}#{ENV['TEST'].nil? ? '' : " TEST=#{ENV['TEST']}"}#{Buildr.application.options.trace ? ' --trace' : ''}"
end
stage('PatchChangelog', 'Patch the changelog to update from previous release') do
changelog = IO.read('CHANGELOG.md')
from = '0.00' == ENV['PREVIOUS_PRODUCT_VERSION'] ? `git rev-list --max-parents=0 HEAD`.strip : "v#{ENV['PREVIOUS_PRODUCT_VERSION']}"
changelog = changelog.gsub("### Unreleased\n", <<HEADER)
### [v#{ENV['PRODUCT_VERSION']}](https://github.com/realityforge/namgen/tree/v#{ENV['PRODUCT_VERSION']}) (#{ENV['RELEASE_DATE']})
[Full Changelog](https://github.com/realityforge/namgen/compare/#{from}...v#{ENV['PRODUCT_VERSION']})
HEADER
IO.write('CHANGELOG.md', changelog)
sh 'git reset 2>&1 1> /dev/null'
sh 'git add CHANGELOG.md'
sh 'git commit -m "Update CHANGELOG.md in preparation for release"'
end
stage('PatchReadme', 'Patch the README to update from previous release') do
contents = IO.read('README.md')
contents = contents.
gsub("<version>#{ENV['PREVIOUS_PRODUCT_VERSION']}</version>", "<version>#{ENV['PRODUCT_VERSION']}</version>").
gsub("/#{ENV['PREVIOUS_PRODUCT_VERSION']}/", "/#{ENV['PRODUCT_VERSION']}/").
gsub("-#{ENV['PREVIOUS_PRODUCT_VERSION']}-", "-#{ENV['PRODUCT_VERSION']}-")
IO.write('README.md', contents)
sh 'git reset 2>&1 1> /dev/null'
sh 'git add README.md'
sh 'git commit -m "Update README.md in preparation for release"'
end
stage('TagProject', 'Tag the project') do
sh "git tag v#{ENV['PRODUCT_VERSION']}"
end
stage('StageRelease', 'Stage the release') do
IO.write('_buildr.rb', "repositories.release_to = { :url => 'https://stocksoftware.jfrog.io/stocksoftware/staging', :username => '#{ENV['STAGING_USERNAME']}', :password => '#{ENV['STAGING_PASSWORD']}' }")
sh 'bundle exec buildr clean upload TEST=no'
sh 'rm -f _buildr.rb'
end
stage('MavenCentralPublish', 'Publish artifacts to Maven Central') do
sh 'bundle exec buildr clean mcrt:publish_if_tagged TEST=no GWT=no'
end
stage('PatchChangelogPostRelease', 'Patch the changelog post release to prepare for next development iteration') do
changelog = IO.read('CHANGELOG.md')
changelog = changelog.gsub("# Change Log\n", <<HEADER)
# Change Log
### Unreleased
HEADER
IO.write('CHANGELOG.md', changelog)
`bundle exec zapwhite`
sh 'git add CHANGELOG.md'
sh 'git commit -m "Update CHANGELOG.md in preparation for next development iteration"'
end
stage('PushChanges', 'Push changes to git repository') do
sh 'git push'
sh 'git push --tags'
end
stage('GithubRelease', 'Create a Release on GitHub') do
changelog = IO.read('CHANGELOG.md')
start = changelog.index("### [v#{ENV['PRODUCT_VERSION']}]")
raise "Unable to locate version #{ENV['PRODUCT_VERSION']} in change log" if -1 == start
start = changelog.index("\n", start)
start = changelog.index("\n", start + 1)
end_index = changelog.index('### [v', start)
end_index = changelog.length if end_index.nil?
changes = changelog[start, end_index - start]
changes = changes.strip
tag = "v#{ENV['PRODUCT_VERSION']}"
version_parts = ENV['PRODUCT_VERSION'].split('.')
prerelease = '0' == version_parts[0]
require 'octokit'
client = Octokit::Client.new(:netrc => true, :auto_paginate => true)
client.login
client.create_release('realityforge/namgen', tag, :name => tag, :body => changes, :draft => false, :prerelease => prerelease)
candidates = client.list_milestones('realityforge/namgen').select {|m| m[:title].to_s == tag}
unless candidates.empty?
milestone = candidates[0]
unless milestone[:state] == 'closed'
client.update_milestone('realityforge/namgen', milestone[:number], :state => 'closed')
end
end
end
end
if ENV['STAGE']
if ENV['LAST_STAGE'] == ENV['STAGE']
puts "LAST_STAGE specified '#{ENV['LAST_STAGE']}', later stages were skipped"
else
raise "Invalid STAGE specified '#{ENV['STAGE']}' that did not match any stage"
end
end
end
| 39.275862 | 274 | 0.649985 |
e9363b69a6076c78d47c06eeb16f7aeb0063e490 | 1,846 | # frozen_string_literal: true
require_relative '../helpers'
module Adventofcode
module Year2020
class Day4 < Adventofcode::Day
REQUIRED_FIELDS = {
"byr" => ->(field) { (1920..2002).cover?(field.to_i) },
"iyr" => ->(field) { (2010..2020).cover?(field.to_i) },
"eyr" => ->(field) { (2020..2030).cover?(field.to_i) },
"hgt" => ->(field) do
if field.end_with?("cm")
(150..193).cover?(field[0..-3].to_i)
elsif field.end_with?("in")
(59..76).cover?(field[0..-3].to_i)
else
false
end
end,
"hcl" => ->(field) { field.length == 7 && !!(field =~ /^#[a-f0-9]{6}/) },
"ecl" => ->(field) { %w(amb blu brn gry grn hzl oth).one? { |cl| cl == field } },
"pid" => ->(field) { !!(field =~ /^\d{9}$/) },
"cid" => ->(field) { true },
}
def default_input
raw_input.split("\n\n")
end
def part_one
valid_passports = 0
input.each do |data|
fields = data.split(" ").flatten.map {|i| i.split(":") }
result = REQUIRED_FIELDS.keys - fields.map {|a| a.first }
if (result == [] || result == ["cid"])
valid_passports += 1
end
end
valid_passports
end
def part_two
valid_passports = 0
input.each do |data|
fields = data.split(" ").flatten.map {|i| i.split(":") }
result = REQUIRED_FIELDS.keys - fields.map {|a| a.first }
if (result == [] || result == ["cid"]) && all_fields_valid?(fields)
valid_passports += 1
end
end
valid_passports
end
def all_fields_valid?(fields)
fields.map { |(field, value)| REQUIRED_FIELDS[field].call(value) }.uniq == [true]
end
end
end
end
| 28.84375 | 89 | 0.490791 |
6152d560046e0cc1cf58bfa6593b4135fa3dac79 | 1,368 | # typed: true
module Kuby
module Redis
module DSL
module Databases
module V1
class RedisFailoverSpecSentinelAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector < ::KubeDSL::DSLObject
key_value_field(:match_labels, format: :string)
array_field(:match_expression) { Kuby::Redis::DSL::Databases::V1::RedisFailoverSpecSentinelAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions.new }
validates :match_labels, kv: { value_format: :string }, presence: true
validates :match_expressions, array: { kind_of: Kuby::Redis::DSL::Databases::V1::RedisFailoverSpecSentinelAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions }, presence: false
def serialize
{}.tap do |result|
result[:matchLabels] = match_labels.serialize
result[:matchExpressions] = match_expressions.map(&:serialize)
end
end
def kind_sym
:redis_failover_spec_sentinel_affinity_pod_anti_affinity_preferred_during_scheduling_ignored_during_execution_pod_affinity_term_label_selector
end
end
end
end
end
end
end | 45.6 | 251 | 0.726608 |
913feeb92a6fd723283ea74d2cd17b015cea2653 | 637 | Pod::Spec.new do |s|
s.name = "OEXRemoteConfig"
s.version = "0.0.1"
s.summary = "This contains custom configuration details for edX on iOS."
s.homepage = "https://github.com/appsembler/edx-app-ios-config"
s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE.txt' }
s.author = { "J'aime Ohm" => "[email protected]" }
s.platform = :ios
s.source = { :git => "https://github.com/appsembler/edx-app-ios-config.git", :tag => "0.0.1" }
s.resource_bundle = { "OEXRemoteConfig" => [ "**/config.yaml", "**/edx.properties", "**/local.yaml", "LICENSE.txt" ] }
end
| 45.5 | 120 | 0.590267 |
ffb80ecb4b8b11a2796668ac097df46bf43c29e5 | 49,807 | # encoding: UTF-8
unless defined? ASCIIDOCTOR_PROJECT_DIR
$: << File.dirname(__FILE__); $:.uniq!
require 'test_helper'
end
context 'Tables' do
context 'PSV' do
test 'renders simple psv table' do
input = <<-EOS
|=======
|A |B |C
|a |b |c
|1 |2 |3
|=======
EOS
cells = [%w(A B C), %w(a b c), %w(1 2 3)]
doc = document_from_string input, :header_footer => false
table = doc.blocks[0]
assert 100, table.columns.map {|col| col.attributes['colpcwidth'] }.reduce(:+)
output = doc.convert
assert_css 'table', output, 1
assert_css 'table.tableblock.frame-all.grid-all.stretch', output, 1
assert_css 'table > colgroup > col[style*="width: 33.3333%"]', output, 2
assert_css 'table > colgroup > col:last-of-type[style*="width: 33.3334%"]', output, 1
assert_css 'table tr', output, 3
assert_css 'table > tbody > tr', output, 3
assert_css 'table td', output, 9
assert_css 'table > tbody > tr > td.tableblock.halign-left.valign-top > p.tableblock', output, 9
cells.each_with_index {|row, rowi|
assert_css "table > tbody > tr:nth-child(#{rowi + 1}) > td", output, row.size
assert_css "table > tbody > tr:nth-child(#{rowi + 1}) > td > p", output, row.size
row.each_with_index {|cell, celli|
assert_xpath "(//tr)[#{rowi + 1}]/td[#{celli + 1}]/p[text()='#{cell}']", output, 1
}
}
end
test 'renders caption on simple psv table' do
input = <<-EOS
.Simple psv table
|=======
|A |B |C
|a |b |c
|1 |2 |3
|=======
EOS
output = render_embedded_string input
assert_xpath '/table/caption[@class="title"][text()="Table 1. Simple psv table"]', output, 1
assert_xpath '/table/caption/following-sibling::colgroup', output, 1
end
test 'only increments table counter for tables that have a title' do
input = <<-EOS
.First numbered table
|=======
|1 |2 |3
|=======
|=======
|4 |5 |6
|=======
.Second numbered table
|=======
|7 |8 |9
|=======
EOS
output = render_embedded_string input
assert_css 'table:root', output, 3
assert_xpath '(/table)[1]/caption', output, 1
assert_xpath '(/table)[1]/caption[text()="Table 1. First numbered table"]', output, 1
assert_xpath '(/table)[2]/caption', output, 0
assert_xpath '(/table)[3]/caption', output, 1
assert_xpath '(/table)[3]/caption[text()="Table 2. Second numbered table"]', output, 1
end
test 'renders explicit caption on simple psv table' do
input = <<-EOS
[caption="All the Data. "]
.Simple psv table
|=======
|A |B |C
|a |b |c
|1 |2 |3
|=======
EOS
output = render_embedded_string input
assert_xpath '/table/caption[@class="title"][text()="All the Data. Simple psv table"]', output, 1
assert_xpath '/table/caption/following-sibling::colgroup', output, 1
end
test 'ignores escaped separators' do
input = <<-EOS
|===
|A \\| here| a \\| there
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 1
assert_css 'table > tbody > tr > td', output, 2
assert_xpath '/table/tbody/tr/td[1]/p[text()="A | here"]', output, 1
assert_xpath '/table/tbody/tr/td[2]/p[text()="a | there"]', output, 1
end
test 'preserves escaped delimiters at the end of the line' do
input = <<-EOS
[%header,cols="1,1"]
|====
|A |B\\|
|A1 |B1\\|
|A2 |B2\\|
|====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr:nth-child(1) > th', output, 2
assert_xpath '/table/thead/tr[1]/th[2][text()="B|"]', output, 1
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 2
assert_xpath '/table/tbody/tr[1]/td[2]/p[text()="B1|"]', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td', output, 2
assert_xpath '/table/tbody/tr[2]/td[2]/p[text()="B2|"]', output, 1
end
test 'should treat trailing pipe as an empty cell' do
input = <<-EOS
|====
|A1 |
|B1 |B2
|C1 |C2
|====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 3
assert_xpath '/table/tbody/tr[1]/td', output, 2
assert_xpath '/table/tbody/tr[1]/td[1]/p[text()="A1"]', output, 1
assert_xpath '/table/tbody/tr[1]/td[2]/p', output, 0
assert_xpath '/table/tbody/tr[2]/td[1]/p[text()="B1"]', output, 1
end
test 'should auto recover with warning if missing leading separator on first cell' do
input = <<-EOS
|===
A | here| a | there
|===
EOS
output, warnings = redirect_streams {|_, err| [(render_embedded_string input), err.string] }
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 4
assert_css 'table > tbody > tr', output, 1
assert_css 'table > tbody > tr > td', output, 4
assert_xpath '/table/tbody/tr/td[1]/p[text()="A"]', output, 1
assert_xpath '/table/tbody/tr/td[2]/p[text()="here"]', output, 1
assert_xpath '/table/tbody/tr/td[3]/p[text()="a"]', output, 1
assert_xpath '/table/tbody/tr/td[4]/p[text()="there"]', output, 1
assert_includes warnings, 'table missing leading separator'
end
test 'performs normal substitutions on cell content' do
input = <<-EOS
:show_title: Cool new show
|===
|{show_title} |Coming soon...
|===
EOS
output = render_embedded_string input
assert_xpath '//tbody/tr/td[1]/p[text()="Cool new show"]', output, 1
assert_xpath %(//tbody/tr/td[2]/p[text()='Coming soon#{decode_char 8230}#{decode_char 8203}']), output, 1
end
test 'should only substitute specialchars for literal table cells' do
input = <<-EOS
|===
l|one
*two*
three
<four>
|===
EOS
output = render_embedded_string input
result = xmlnodes_at_xpath('/table//pre', output, 1)
assert_equal %(<pre>one\n*two*\nthree\n<four></pre>), result.to_s
end
test 'should preserving leading spaces but not leading endlines or trailing spaces in literal table cells' do
input = <<-EOS
[cols=2*]
|===
l|
one
two
three
| normal
|===
EOS
output = render_embedded_string input
result = xmlnodes_at_xpath('/table//pre', output, 1)
assert_equal %(<pre> one\n two\nthree</pre>), result.to_s
end
test 'should preserving leading spaces but not leading endlines or trailing spaces in verse table cells' do
input = <<-EOS
[cols=2*]
|===
v|
one
two
three
| normal
|===
EOS
output = render_embedded_string input
result = xmlnodes_at_xpath('/table//div[@class="verse"]', output, 1)
assert_equal %(<div class="verse"> one\n two\nthree</div>), result.to_s
end
test 'table and col width not assigned when autowidth option is specified' do
input = <<-EOS
[options="autowidth"]
|=======
|A |B |C
|a |b |c
|1 |2 |3
|=======
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table[style*="width"]', output, 0
assert_css 'table colgroup col', output, 3
assert_css 'table colgroup col[width]', output, 0
end
test 'explicit table width is used even when autowidth option is specified' do
input = <<-EOS
[%autowidth,width=75%]
|=======
|A |B |C
|a |b |c
|1 |2 |3
|=======
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table[style*="width"]', output, 1
assert_css 'table colgroup col', output, 3
assert_css 'table colgroup col[width]', output, 0
end
test 'first row sets number of columns when not specified' do
input = <<-EOS
|====
|first |second |third |fourth
|1 |2 |3
|4
|====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 4
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 4
assert_css 'table > tbody > tr:nth-child(2) > td', output, 4
end
test 'colspec attribute using asterisk syntax sets number of columns' do
input = <<-EOS
[cols="3*"]
|===
|A |B |C |a |b |c |1 |2 |3
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > tbody > tr', output, 3
end
test 'table with explicit column count can have multiple rows on a single line' do
input = <<-EOS
[cols="3*"]
|===
|one |two
|1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
end
test 'table with explicit deprecated colspec syntax can have multiple rows on a single line' do
input = <<-EOS
[cols="3"]
|===
|one |two
|1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
end
test 'columns are added for empty records in colspec attribute' do
input = <<-EOS
[cols="<,"]
|===
|one |two
|1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 3
end
test 'cols attribute may include spaces' do
input = <<-EOS
[cols=" 1, 1 "]
|===
|one |two |1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'col[style="width: 50%;"]', output, 2
assert_css 'table > tbody > tr', output, 3
end
test 'blank cols attribute should be ignored' do
input = <<-EOS
[cols=" "]
|===
|one |two
|1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'col[style="width: 50%;"]', output, 2
assert_css 'table > tbody > tr', output, 3
end
test 'empty cols attribute should be ignored' do
input = <<-EOS
[cols=""]
|===
|one |two
|1 |2 |a |b
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'col[style="width: 50%;"]', output, 2
assert_css 'table > tbody > tr', output, 3
end
test 'table with header and footer' do
input = <<-EOS
[frame="topbot",options="header,footer"]
|===
|Item |Quantity
|Item 1 |1
|Item 2 |2
|Item 3 |3
|Total |6
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 2
assert_css 'table > tfoot', output, 1
assert_css 'table > tfoot > tr', output, 1
assert_css 'table > tfoot > tr > td', output, 2
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 3
table_section_names = (xmlnodes_at_css 'table > *', output).map(&:node_name).select {|n| n.start_with? 't' }
assert_equal %w(thead tbody tfoot), table_section_names
end
test 'table with header and footer docbook' do
input = <<-EOS
.Table with header, body and footer
[frame="topbot",options="header,footer"]
|===
|Item |Quantity
|Item 1 |1
|Item 2 |2
|Item 3 |3
|Total |6
|===
EOS
output = render_embedded_string input, :backend => 'docbook'
assert_css 'table', output, 1
assert_css 'table[frame="topbot"]', output, 1
assert_css 'table > title', output, 1
assert_css 'table > tgroup', output, 1
assert_css 'table > tgroup[cols="2"]', output, 1
assert_css 'table > tgroup[cols="2"] > colspec', output, 2
assert_css 'table > tgroup[cols="2"] > colspec[colwidth="50*"]', output, 2
assert_css 'table > tgroup > thead', output, 1
assert_css 'table > tgroup > thead > row', output, 1
assert_css 'table > tgroup > thead > row > entry', output, 2
assert_css 'table > tgroup > thead > row > entry > simpara', output, 0
assert_css 'table > tgroup > tfoot', output, 1
assert_css 'table > tgroup > tfoot > row', output, 1
assert_css 'table > tgroup > tfoot > row > entry', output, 2
assert_css 'table > tgroup > tfoot > row > entry > simpara', output, 2
assert_css 'table > tgroup > tbody', output, 1
assert_css 'table > tgroup > tbody > row', output, 3
assert_css 'table > tgroup > tbody > row', output, 3
table_section_names = (xmlnodes_at_css 'table > tgroup > *', output).map(&:node_name).select {|n| n.start_with? 't' }
assert_equal %w(thead tbody tfoot), table_section_names
end
test 'table with landscape orientation in DocBook' do
['orientation=landscape', '%rotate'].each do |attrs|
input = <<-EOS
[#{attrs}]
|===
|Column A | Column B | Column C
|===
EOS
output = render_embedded_string input, :backend => 'docbook'
assert_css 'informaltable', output, 1
assert_css 'informaltable[orient="land"]', output, 1
end
end
test 'table with implicit header row' do
input = <<-EOS
|===
|Column 1 |Column 2
|Data A1
|Data B1
|Data A2
|Data B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 2
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 2
end
test 'table with implicit header row only' do
input = <<-EOS
|===
|Column 1 |Column 2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 2
assert_css 'table > tbody', output, 0
end
test 'table with implicit header row when other options set' do
input = <<-EOS
[%autowidth]
|===
|Column 1 |Column 2
|Data A1
|Data B1
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table[style*="width"]', output, 0
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 2
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 1
end
test 'no implicit header row if second line not blank' do
input = <<-EOS
|===
|Column 1 |Column 2
|Data A1
|Data B1
|Data A2
|Data B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 3
end
test 'no implicit header row if cell in first line spans multiple lines' do
input = <<-EOS
[cols=2*]
|===
|A1
A1 continued|B1
|A2
|B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 2
assert_xpath '(//td)[1]/p', output, 2
end
test 'no implicit header row if AsciiDoc cell in first line spans multiple lines' do
input = <<-EOS
[cols=2*]
|===
a|contains AsciiDoc content
* a
* b
* c
a|contains no AsciiDoc content
just text
|A2
|B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 2
assert_xpath '(//td)[1]//ul', output, 1
end
test 'no implicit header row if first line blank' do
input = <<-EOS
|===
|Column 1 |Column 2
|Data A1
|Data B1
|Data A2
|Data B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 3
end
test 'no implicit header row if noheader option is specified' do
input = <<-EOS
[%noheader]
|===
|Column 1 |Column 2
|Data A1
|Data B1
|Data A2
|Data B2
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 3
end
test 'styles not applied to header cells' do
input = <<-EOS
[cols="1h,1s,1e",options="header,footer"]
|====
|Name |Occupation| Website
|Octocat |Social coding| https://github.com
|Name |Occupation| Website
|====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > thead > tr > th', output, 3
assert_css 'table > thead > tr > th > *', output, 0
assert_css 'table > tfoot > tr > th', output, 1
assert_css 'table > tfoot > tr > td', output, 2
assert_css 'table > tfoot > tr > td > p > strong', output, 1
assert_css 'table > tfoot > tr > td > p > em', output, 1
assert_css 'table > tbody > tr > th', output, 1
assert_css 'table > tbody > tr > td', output, 2
assert_css 'table > tbody > tr > td > p.header', output, 0
assert_css 'table > tbody > tr > td > p > strong', output, 1
assert_css 'table > tbody > tr > td > p > em > a', output, 1
end
test 'vertical table headers use th element instead of header class' do
input = <<-EOS
[cols="1h,1s,1e"]
|====
|Name |Occupation| Website
|Octocat |Social coding| https://github.com
|Name |Occupation| Website
|====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > tbody > tr > th', output, 3
assert_css 'table > tbody > tr > td', output, 6
assert_css 'table > tbody > tr .header', output, 0
assert_css 'table > tbody > tr > td > p > strong', output, 3
assert_css 'table > tbody > tr > td > p > em', output, 3
assert_css 'table > tbody > tr > td > p > em > a', output, 1
end
test 'supports horizontal and vertical source data with blank lines and table header' do
input = <<-EOS
.Horizontal and vertical source data
[width="80%",cols="3,^2,^2,10",options="header"]
|===
|Date |Duration |Avg HR |Notes
|22-Aug-08 |10:24 | 157 |
Worked out MSHR (max sustainable heart rate) by going hard
for this interval.
|22-Aug-08 |23:03 | 152 |
Back-to-back with previous interval.
|24-Aug-08 |40:00 | 145 |
Moderately hard interspersed with 3x 3min intervals (2 min
hard + 1 min really hard taking the HR up to 160).
I am getting in shape!
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table[style*="width: 80%"]', output, 1
assert_xpath '/table/caption[@class="title"][text()="Table 1. Horizontal and vertical source data"]', output, 1
assert_css 'table > colgroup > col', output, 4
assert_css 'table > colgroup > col:nth-child(1)[@style*="width: 17.647%"]', output, 1
assert_css 'table > colgroup > col:nth-child(2)[@style*="width: 11.7647%"]', output, 1
assert_css 'table > colgroup > col:nth-child(3)[@style*="width: 11.7647%"]', output, 1
assert_css 'table > colgroup > col:nth-child(4)[@style*="width: 58.8236%"]', output, 1
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 4
assert_css 'table > tbody > tr', output, 3
assert_css 'table > tbody > tr:nth-child(1) > td', output, 4
assert_css 'table > tbody > tr:nth-child(2) > td', output, 4
assert_css 'table > tbody > tr:nth-child(3) > td', output, 4
assert_xpath "/table/tbody/tr[1]/td[4]/p[text()='Worked out MSHR (max sustainable heart rate) by going hard\nfor this interval.']", output, 1
assert_css 'table > tbody > tr:nth-child(3) > td:nth-child(4) > p', output, 2
assert_xpath '/table/tbody/tr[3]/td[4]/p[2][text()="I am getting in shape!"]', output, 1
end
test 'percentages as column widths' do
input = <<-EOS
[cols="<.^10%,<90%"]
|===
|column A |column B
|===
EOS
output = render_embedded_string input
assert_xpath '/table/colgroup/col', output, 2
assert_xpath '(/table/colgroup/col)[1][@style="width: 10%;"]', output, 1
assert_xpath '(/table/colgroup/col)[2][@style="width: 90%;"]', output, 1
end
test 'spans, alignments and styles' do
input = <<-EOS
[cols="e,m,^,>s",width="25%"]
|===
|1 >s|2 |3 |4
^|5 2.2+^.^|6 .3+<.>m|7
^|8
d|9 2+>|10
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col[style*="width: 25%"]', output, 4
assert_css 'table > tbody > tr', output, 4
assert_css 'table > tbody > tr > td', output, 10
assert_css 'table > tbody > tr:nth-child(1) > td', output, 4
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
assert_css 'table > tbody > tr:nth-child(3) > td', output, 1
assert_css 'table > tbody > tr:nth-child(4) > td', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(1).halign-left.valign-top p em', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(2).halign-right.valign-top p strong', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(3).halign-center.valign-top p', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(3).halign-center.valign-top p *', output, 0
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(4).halign-right.valign-top p strong', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td:nth-child(1).halign-center.valign-top p em', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td:nth-child(2).halign-center.valign-middle[colspan="2"][rowspan="2"] p code', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td:nth-child(3).halign-left.valign-bottom[rowspan="3"] p code', output, 1
assert_css 'table > tbody > tr:nth-child(3) > td:nth-child(1).halign-center.valign-top p em', output, 1
assert_css 'table > tbody > tr:nth-child(4) > td:nth-child(1).halign-left.valign-top p', output, 1
assert_css 'table > tbody > tr:nth-child(4) > td:nth-child(1).halign-left.valign-top p em', output, 0
assert_css 'table > tbody > tr:nth-child(4) > td:nth-child(2).halign-right.valign-top[colspan="2"] p code', output, 1
end
test 'sets up columns correctly if first row has cell that spans columns' do
input = <<-EOS
|===
2+^|AAA |CCC
|AAA |BBB |CCC
|AAA |BBB |CCC
|===
EOS
output = render_embedded_string input
assert_css 'table > tbody > tr:nth-child(1) > td', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(1)[colspan="2"]', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(2):not([colspan])', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td:not([colspan])', output, 3
assert_css 'table > tbody > tr:nth-child(3) > td:not([colspan])', output, 3
end
test 'supports repeating cells' do
input = <<-EOS
|===
3*|A
|1 3*|2
|b |c
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 3
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
assert_css 'table > tbody > tr:nth-child(3) > td', output, 3
assert_xpath '/table/tbody/tr[1]/td[1]/p[text()="A"]', output, 1
assert_xpath '/table/tbody/tr[1]/td[2]/p[text()="A"]', output, 1
assert_xpath '/table/tbody/tr[1]/td[3]/p[text()="A"]', output, 1
assert_xpath '/table/tbody/tr[2]/td[1]/p[text()="1"]', output, 1
assert_xpath '/table/tbody/tr[2]/td[2]/p[text()="2"]', output, 1
assert_xpath '/table/tbody/tr[2]/td[3]/p[text()="2"]', output, 1
assert_xpath '/table/tbody/tr[3]/td[1]/p[text()="2"]', output, 1
assert_xpath '/table/tbody/tr[3]/td[2]/p[text()="b"]', output, 1
assert_xpath '/table/tbody/tr[3]/td[3]/p[text()="c"]', output, 1
end
test 'calculates colnames correctly when using implicit column count and single cell with colspan' do
input = <<-EOS
|===
2+|Two Columns
|One Column |One Column
|===
EOS
output = render_embedded_string input, :backend => 'docbook'
assert_xpath '//colspec', output, 2
assert_xpath '(//colspec)[1][@colname="col_1"]', output, 1
assert_xpath '(//colspec)[2][@colname="col_2"]', output, 1
assert_xpath '//row', output, 2
assert_xpath '(//row)[1]/entry', output, 1
assert_xpath '(//row)[1]/entry[@namest="col_1"][@nameend="col_2"]', output, 1
end
test 'calculates colnames correctly when using implicit column count and cells with mixed colspans' do
input = <<-EOS
|===
2+|Two Columns | One Column
|One Column |One Column |One Column
|===
EOS
output = render_embedded_string input, :backend => 'docbook'
assert_xpath '//colspec', output, 3
assert_xpath '(//colspec)[1][@colname="col_1"]', output, 1
assert_xpath '(//colspec)[2][@colname="col_2"]', output, 1
assert_xpath '(//colspec)[3][@colname="col_3"]', output, 1
assert_xpath '//row', output, 2
assert_xpath '(//row)[1]/entry', output, 2
assert_xpath '(//row)[1]/entry[@namest="col_1"][@nameend="col_2"]', output, 1
assert_xpath '(//row)[2]/entry[@namest]', output, 0
assert_xpath '(//row)[2]/entry[@nameend]', output, 0
end
test 'assigns unique column names for table with implicit column count and colspans in first row' do
input = <<-EOS
|====
| 2+| Node 0 2+| Node 1
| Host processes | Core 0 | Core 1 | Core 4 | Core 5
| Guest processes | Core 2 | Core 3 | Core 6 | Core 7
|====
EOS
output = render_embedded_string input, :backend => 'docbook'
assert_xpath '//colspec', output, 5
(1..5).each do |n|
assert_xpath %((//colspec)[#{n}][@colname="col_#{n}"]), output, 1
end
assert_xpath '(//row)[1]/entry', output, 3
assert_xpath '((//row)[1]/entry)[1][@namest]', output, 0
assert_xpath '((//row)[1]/entry)[1][@namend]', output, 0
assert_xpath '((//row)[1]/entry)[2][@namest="col_2"][@nameend="col_3"]', output, 1
assert_xpath '((//row)[1]/entry)[3][@namest="col_4"][@nameend="col_5"]', output, 1
end
test 'ignores cell with colspan that exceeds colspec' do
input = <<-EOS
[cols="1,1"]
|===
3+|A
|B
a|C
more C
|===
EOS
output, warnings = redirect_streams {|_, err| [(render_embedded_string input), err.string] }
assert_css 'table', output, 1
assert_css 'table *', output, 0
assert_includes warnings, 'exceeds specified number of columns'
end
test 'paragraph, verse and literal content' do
input = <<-EOS
[cols=",^v,^l",options="header"]
|===
|Paragraphs |Verse |Literal
3*|The discussion about what is good,
what is beautiful, what is noble,
what is pure, and what is true
could always go on.
Why is that important?
Why would I like to do that?
Because that's the only conversation worth having.
And whether it goes on or not after I die, I don't know.
But, I do know that it is the conversation I want to have while I am still alive.
Which means that to me the offer of certainty,
the offer of complete security,
the offer of an impermeable faith that can't give way
is an offer of something not worth having.
I want to live my life taking the risk all the time
that I don't know anything like enough yet...
that I haven't understood enough...
that I can't know enough...
that I am always hungrily operating on the margins
of a potentially great harvest of future knowledge and wisdom.
I wouldn't have it any other way.
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > thead', output, 1
assert_css 'table > thead > tr', output, 1
assert_css 'table > thead > tr > th', output, 3
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 1
assert_css 'table > tbody > tr > td', output, 3
assert_css 'table > tbody > tr > td:nth-child(1).halign-left.valign-top > p.tableblock', output, 7
assert_css 'table > tbody > tr > td:nth-child(2).halign-center.valign-top > div.verse', output, 1
verse = xmlnodes_at_css 'table > tbody > tr > td:nth-child(2).halign-center.valign-top > div.verse', output, 1
assert_equal 26, verse.text.lines.entries.size
assert_css 'table > tbody > tr > td:nth-child(3).halign-center.valign-top > div.literal > pre', output, 1
literal = xmlnodes_at_css 'table > tbody > tr > td:nth-child(3).halign-center.valign-top > div.literal > pre', output, 1
assert_equal 26, literal.text.lines.entries.size
end
test 'should strip trailing endline when splitting paragraphs' do
input = <<-EOS
|===
|first wrapped
paragraph
second paragraph
third paragraph
|===
EOS
result = render_embedded_string input
assert_xpath %((//p[@class="tableblock"])[1][text()="first wrapped\nparagraph"]), result, 1
assert_xpath %((//p[@class="tableblock"])[2][text()="second paragraph"]), result, 1
assert_xpath %((//p[@class="tableblock"])[3][text()="third paragraph"]), result, 1
end
test 'basic AsciiDoc cell' do
input = <<-EOS
|===
a|--
NOTE: content
content
--
|===
EOS
result = render_embedded_string input
assert_css 'table.tableblock', result, 1
assert_css 'table.tableblock td.tableblock', result, 1
assert_css 'table.tableblock td.tableblock .openblock', result, 1
assert_css 'table.tableblock td.tableblock .openblock .admonitionblock', result, 1
assert_css 'table.tableblock td.tableblock .openblock .paragraph', result, 1
end
test 'AsciiDoc table cell should be wrapped in div with class "content"' do
input = <<-EOS
|===
a|AsciiDoc table cell
|===
EOS
result = render_embedded_string input
assert_css 'table.tableblock td.tableblock > div.content', result, 1
assert_css 'table.tableblock td.tableblock > div.content > div.paragraph', result, 1
end
test 'doctype can be set in AsciiDoc table cell' do
input = <<-EOS
|===
a|
:doctype: inline
content
|===
EOS
result = render_embedded_string input
assert_css 'table.tableblock', result, 1
assert_css 'table.tableblock .paragraph', result, 0
end
test 'should reset doctype to default in AsciiDoc table cell' do
input = <<-EOS
= Book Title
:doctype: book
== Chapter 1
|===
a|
= AsciiDoc Table Cell
doctype={doctype}
{backend-html5-doctype-article}
{backend-html5-doctype-book}
|===
EOS
result = render_embedded_string input, :attributes => { 'attribute-missing' => 'skip' }
assert_includes result, 'doctype=article'
refute_includes result, '{backend-html5-doctype-article}'
assert_includes result, '{backend-html5-doctype-book}'
end
test 'should update doctype-related attributes in AsciiDoc table cell when doctype is set' do
input = <<-EOS
= Document Title
:doctype: article
== Chapter 1
|===
a|
= AsciiDoc Table Cell
:doctype: book
doctype={doctype}
{backend-html5-doctype-book}
{backend-html5-doctype-article}
|===
EOS
result = render_embedded_string input, :attributes => { 'attribute-missing' => 'skip' }
assert_includes result, 'doctype=book'
refute_includes result, '{backend-html5-doctype-book}'
assert_includes result, '{backend-html5-doctype-article}'
end
test 'AsciiDoc content' do
input = <<-EOS
[cols="1e,1,5a",frame="topbot",options="header"]
|===
|Name |Backends |Description
|badges |xhtml11, html5 |
Link badges ('XHTML 1.1' and 'CSS') in document footers.
NOTE: The path names of images, icons and scripts are relative path
names to the output document not the source document.
|[[X97]] docinfo, docinfo1, docinfo2 |All backends |
These three attributes control which document information
files will be included in the the header of the output file:
docinfo:: Include `<filename>-docinfo.<ext>`
docinfo1:: Include `docinfo.<ext>`
docinfo2:: Include `docinfo.<ext>` and `<filename>-docinfo.<ext>`
Where `<filename>` is the file name (sans extension) of the AsciiDoc
input file and `<ext>` is `.html` for HTML outputs or `.xml` for
DocBook outputs. If the input file is the standard input then the
output file name is used.
|===
EOS
doc = document_from_string input
table = doc.blocks.first
refute_nil table
tbody = table.rows.body
assert_equal 2, tbody.size
body_cell_1_3 = tbody[0][2]
refute_nil body_cell_1_3.inner_document
assert body_cell_1_3.inner_document.nested?
assert_equal doc, body_cell_1_3.inner_document.parent_document
assert_equal doc.converter, body_cell_1_3.inner_document.converter
output = doc.render
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(3) div.admonitionblock', output, 1
assert_css 'table > tbody > tr:nth-child(2) > td:nth-child(3) div.dlist', output, 1
end
test 'preprocessor directive on first line of an AsciiDoc table cell should be processed' do
input = <<-EOS
|===
a|include::fixtures/include-file.asciidoc[]
|===
EOS
output = render_embedded_string input, :safe => :safe, :base_dir => File.dirname(__FILE__)
assert_match(/included content/, output)
end
test 'cross reference link in an AsciiDoc table cell should resolve to reference in main document' do
input = <<-EOS
== Some
|===
a|See <<_more>>
|===
== More
content
EOS
result = render_string input
assert_xpath '//a[@href="#_more"]', result, 1
assert_xpath '//a[@href="#_more"][text()="More"]', result, 1
end
test 'footnotes should not be shared between an AsciiDoc table cell and the main document' do
input = <<-EOS
|===
a|AsciiDoc footnote:[A lightweight markup language.]
|===
EOS
result = render_string input
assert_css '#_footnote_1', result, 1
end
test 'callout numbers should be globally unique, including AsciiDoc table cells' do
input = <<-EOS
= Document Title
== Section 1
|====
a|
[source, yaml]
----
key: value <1>
----
<1> First callout
|====
== Section 2
|====
a|
[source, yaml]
----
key: value <1>
----
<1> Second callout
|====
== Section 3
[source, yaml]
----
key: value <1>
----
<1> Third callout
EOS
result = render_string input, :backend => 'docbook'
conums = xmlnodes_at_xpath '//co', result
assert_equal 3, conums.size
['CO1-1', 'CO2-1', 'CO3-1'].each_with_index do |conum, idx|
assert_equal conum, conums[idx].attribute('xml:id').value
end
callouts = xmlnodes_at_xpath '//callout', result
assert_equal 3, callouts.size
['CO1-1', 'CO2-1', 'CO3-1'].each_with_index do |callout, idx|
assert_equal callout, callouts[idx].attribute('arearefs').value
end
end
test 'compat mode can be activated in AsciiDoc table cell' do
input = <<-EOS
|===
a|
:compat-mode:
The word 'italic' is emphasized.
|===
EOS
result = render_embedded_string input
assert_xpath '//em[text()="italic"]', result, 1
end
test 'compat mode in AsciiDoc table cell inherits from parent document' do
input = <<-EOS
:compat-mode:
The word 'italic' is emphasized.
[cols=1*]
|===
|The word 'oblique' is emphasized.
a|
The word 'slanted' is emphasized.
|===
The word 'askew' is emphasized.
EOS
result = render_embedded_string input
assert_xpath '//em[text()="italic"]', result, 1
assert_xpath '//em[text()="oblique"]', result, 1
assert_xpath '//em[text()="slanted"]', result, 1
assert_xpath '//em[text()="askew"]', result, 1
end
test 'compat mode in AsciiDoc table cell can be unset if set in parent document' do
input = <<-EOS
:compat-mode:
The word 'italic' is emphasized.
[cols=1*]
|===
|The word 'oblique' is emphasized.
a|
:!compat-mode:
The word 'slanted' is not emphasized.
|===
The word 'askew' is emphasized.
EOS
result = render_embedded_string input
assert_xpath '//em[text()="italic"]', result, 1
assert_xpath '//em[text()="oblique"]', result, 1
assert_xpath '//em[text()="slanted"]', result, 0
assert_xpath '//em[text()="askew"]', result, 1
end
test 'nested table' do
input = <<-EOS
[cols="1,2a"]
|===
|Normal cell
|Cell with nested table
[cols="2,1"]
!===
!Nested table cell 1 !Nested table cell 2
!===
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 2
assert_css 'table table', output, 1
assert_css 'table > tbody > tr > td:nth-child(2) table', output, 1
assert_css 'table > tbody > tr > td:nth-child(2) table > tbody > tr > td', output, 2
end
test 'can set format of nested table to psv' do
input = <<-EOS
[cols="2*"]
|===
|normal cell
a|
[format=psv]
!===
!nested cell
!===
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 2
assert_css 'table table', output, 1
assert_css 'table > tbody > tr > td:nth-child(2) table', output, 1
assert_css 'table > tbody > tr > td:nth-child(2) table > tbody > tr > td', output, 1
end
test 'toc from parent document should not be included in an AsciiDoc table cell' do
input = <<-EOS
= Document Title
:toc:
== Section A
|===
a|AsciiDoc content
|===
EOS
output = render_string input
assert_css '.toc', output, 1
assert_css 'table .toc', output, 0
end
test 'should be able to enable toc in an AsciiDoc table cell' do
input = <<-EOS
= Document Title
== Section A
|===
a|
= Subdocument Title
:toc:
== Subdocument Section A
content
|===
EOS
output = render_string input
assert_css '.toc', output, 1
assert_css 'table .toc', output, 1
end
test 'should be able to enable toc in both outer document and in an AsciiDoc table cell' do
input = <<-EOS
= Document Title
:toc:
== Section A
|===
a|
= Subdocument Title
:toc: macro
[#table-cell-toc]
toc::[]
== Subdocument Section A
content
|===
EOS
output = render_string input
assert_css '.toc', output, 2
assert_css '#toc', output, 1
assert_css 'table .toc', output, 1
assert_css 'table #table-cell-toc', output, 1
end
test 'document in an AsciiDoc table cell should not see doctitle of parent' do
input = <<-EOS
= Document Title
[cols="1a"]
|===
|AsciiDoc content
|===
EOS
output = render_string input
assert_css 'table', output, 1
assert_css 'table > tbody > tr > td', output, 1
assert_css 'table > tbody > tr > td #preamble', output, 0
assert_css 'table > tbody > tr > td .paragraph', output, 1
end
test 'cell background color' do
input = <<-EOS
[cols="1e,1", options="header"]
|===
|{set:cellbgcolor:green}green
|{set:cellbgcolor!}
plain
|{set:cellbgcolor:red}red
|{set:cellbgcolor!}
plain
|===
EOS
output = render_embedded_string input
assert_xpath '(/table/thead/tr/th)[1][@style="background-color: green;"]', output, 1
assert_xpath '(/table/thead/tr/th)[2][@style="background-color: green;"]', output, 0
assert_xpath '(/table/tbody/tr/td)[1][@style="background-color: red;"]', output, 1
assert_xpath '(/table/tbody/tr/td)[2][@style="background-color: green;"]', output, 0
end
end
context 'DSV' do
test 'renders simple dsv table' do
input = <<-EOS
[width="75%",format="dsv"]
|===
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
mysql:x:27:27:MySQL\\:Server:/var/lib/mysql:/bin/bash
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
|===
EOS
doc = document_from_string input, :header_footer => false
table = doc.blocks[0]
assert 100, table.columns.map {|col| col.attributes['colpcwidth'] }.reduce(:+)
output = doc.convert
assert_css 'table', output, 1
assert_css 'table > colgroup > col[style*="width: 14.2857"]', output, 6
assert_css 'table > colgroup > col:last-of-type[style*="width: 14.2858%"]', output, 1
assert_css 'table > tbody > tr', output, 6
assert_xpath '//tr[4]/td[5]/p/text()', output, 0
assert_xpath '//tr[3]/td[5]/p[text()="MySQL:Server"]', output, 1
end
test 'dsv format shorthand' do
input = <<-EOS
:===
a:b:c
1:2:3
:===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
end
test 'single cell in DSV table should only produce single row' do
input = <<-EOS
:===
single cell
:===
EOS
output = render_embedded_string input
assert_css 'table td', output, 1
end
test 'should treat trailing colon as an empty cell' do
input = <<-EOS
:====
A1:
B1:B2
C1:C2
:====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 3
assert_xpath '/table/tbody/tr[1]/td', output, 2
assert_xpath '/table/tbody/tr[1]/td[1]/p[text()="A1"]', output, 1
assert_xpath '/table/tbody/tr[1]/td[2]/p', output, 0
assert_xpath '/table/tbody/tr[2]/td[1]/p[text()="B1"]', output, 1
end
end
context 'CSV' do
test 'should treat trailing comma as an empty cell' do
input = <<-EOS
,====
A1,
B1,B2
C1,C2
,====
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 3
assert_xpath '/table/tbody/tr[1]/td', output, 2
assert_xpath '/table/tbody/tr[1]/td[1]/p[text()="A1"]', output, 1
assert_xpath '/table/tbody/tr[1]/td[2]/p', output, 0
assert_xpath '/table/tbody/tr[2]/td[1]/p[text()="B1"]', output, 1
end
test 'mixed unquoted records and quoted records with escaped quotes, commas, and wrapped lines' do
input = <<-EOS
[format="csv",options="header"]
|===
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
2000,Toyota,Tundra,"""This one's gonna to blow you're socks off,"" per the sticker",10000.00
2000,Toyota,Tundra,"Check it, ""this one's gonna to blow you're socks off"", per the sticker",10000.00
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col[style*="width: 20%"]', output, 5
assert_css 'table > thead > tr', output, 1
assert_css 'table > tbody > tr', output, 6
assert_xpath '((//tbody/tr)[1]/td)[4]/p[text()="ac, abs, moon"]', output, 1
assert_xpath %(((//tbody/tr)[2]/td)[3]/p[text()='Venture "Extended Edition"']), output, 1
assert_xpath '((//tbody/tr)[4]/td)[4]/p[text()="MUST SELL! air, moon roof, loaded"]', output, 1
assert_xpath %(((//tbody/tr)[5]/td)[4]/p[text()='"This one#{decode_char 8217}s gonna to blow you#{decode_char 8217}re socks off," per the sticker']), output, 1
assert_xpath %(((//tbody/tr)[6]/td)[4]/p[text()='Check it, "this one#{decode_char 8217}s gonna to blow you#{decode_char 8217}re socks off", per the sticker']), output, 1
end
test 'csv format shorthand' do
input = <<-EOS
,===
a,b,c
1,2,3
,===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
end
test 'tsv as format' do
input = <<-EOS
[format=tsv]
,===
a\tb\tc
1\t2\t3
,===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
end
test 'custom csv separator' do
input = <<-EOS
[format=csv,separator=;]
|===
a;b;c
1;2;3
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
end
test 'tab as separator' do
input = <<-EOS
[separator=\\t]
,===
a\tb\tc
1\t2\t3
,===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 3
assert_css 'table > tbody > tr', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td', output, 3
assert_css 'table > tbody > tr:nth-child(2) > td', output, 3
end
test 'custom separator for an AsciiDoc table cell' do
input = <<-EOS
[cols=2,separator=!]
|===
!Pipe output to vim
a!
----
asciidoctor -o - -s test.adoc | view -
----
|===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > tbody > tr', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td', output, 2
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(1) p', output, 1
assert_css 'table > tbody > tr:nth-child(1) > td:nth-child(2) .listingblock', output, 1
end
test 'single cell in CSV table should only produce single row' do
input = <<-EOS
,===
single cell
,===
EOS
output = render_embedded_string input
assert_css 'table td', output, 1
end
test 'table with breakable db45' do
input = <<-EOS
.Table with breakable
[options="breakable"]
|===
|Item |Quantity
|Item 1 |1
|===
EOS
output = render_embedded_string input, :backend => 'docbook45'
assert_includes output, '<?dbfo keep-together="auto"?>'
end
test 'table with breakable db5' do
input = <<-EOS
.Table with breakable
[options="breakable"]
|===
|Item |Quantity
|Item 1 |1
|===
EOS
output = render_embedded_string input, :backend => 'docbook5'
assert_includes output, '<?dbfo keep-together="auto"?>'
end
test 'table with unbreakable db5' do
input = <<-EOS
.Table with unbreakable
[options="unbreakable"]
|===
|Item |Quantity
|Item 1 |1
|===
EOS
output = render_embedded_string input, :backend => 'docbook5'
assert_includes output, '<?dbfo keep-together="always"?>'
end
test 'table with unbreakable db45' do
input = <<-EOS
.Table with unbreakable
[options="unbreakable"]
|===
|Item |Quantity
|Item 1 |1
|===
EOS
output = render_embedded_string input, :backend => 'docbook45'
assert_includes output, '<?dbfo keep-together="always"?>'
end
test 'no implicit header row if cell in first line is quoted and spans multiple lines' do
input = <<-EOS
[cols=2*]
,===
"A1
A1 continued",B1
A2,B2
,===
EOS
output = render_embedded_string input
assert_css 'table', output, 1
assert_css 'table > colgroup > col', output, 2
assert_css 'table > thead', output, 0
assert_css 'table > tbody', output, 1
assert_css 'table > tbody > tr', output, 2
assert_xpath '(//td)[1]/p[text()="A1 A1 continued"]', output, 1
end
end
end
| 29.95009 | 175 | 0.620756 |
87ca62785b769290c16c1aa26fde287fe945c653 | 1,311 | # frozen_string_literal: true
require 'chefspec'
require 'chefspec/berkshelf'
require 'pathname'
def dummy_context(node)
OpenStruct.new(node: node)
end
def fixture_path(*path)
Pathname.new(File.expand_path('fixtures', __dir__)).join(*path)
end
# Stolen from https://github.com/rails/rails/pull/30275 and put
# into a dedicated class to avoid collisions in any environment
# that has already monkey-patched Hash.deep_merge
module RubyOpsworksTests
class DeepMergeableHash
def initialize(hsh = {})
@target = hsh
end
def deep_merge(other_hash, &block)
deep_merge!(other_hash, &block)
end
def deep_merge!(other, &block)
@target.dup.merge!(other) do |key, old_val, new_val|
if old_val.is_a?(Hash) && new_val.is_a?(Hash)
DeepMergeableHash.new(old_val).deep_merge(new_val, &block)
elsif block_given?
yield(key, old_val, new_val)
else
new_val
end
end
end
end
end
# Require all libraries
require File.expand_path('../libraries/all.rb', __dir__)
# Require all fixtures
Dir[File.expand_path('fixtures/*.rb', __dir__)].sort.each { |f| require f }
RSpec.configure do |config|
config.log_level = :error
end
# coveralls
require 'coveralls'
Coveralls.wear!
at_exit { ChefSpec::Coverage.report! }
| 23 | 75 | 0.697941 |
7a0f6b4a4f0489d785b667eedb50056fe60343d1 | 493 | class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
| 15.40625 | 60 | 0.58215 |
e2e61b08a68a81173a6bd97ac5165a12501e3286 | 691 | #
# Cookbook Name:: masala_cassandra
# Recipe:: agent
#
# Copyright 2016, Paytm Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
include_recipe 'cassandra-dse::opscenter_agent_datastax'
| 31.409091 | 74 | 0.762663 |
d5f027fa3e44a680602a2870054f5bf3d1c95abe | 5,766 | class MysqlAT56 < Formula
desc "Open source relational database management system"
homepage "https://dev.mysql.com/doc/refman/5.6/en/"
url "https://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.51.tar.gz"
sha256 "262ccaf2930fca1f33787505dd125a7a04844f40d3421289a51974b5935d9abc"
license "GPL-2.0-only"
bottle do
rebuild 1
sha256 big_sur: "30a530ddb785efe7542641366126d7b4afcce09bde0fa104b869814fa69fc9e2"
sha256 catalina: "a5309a985dccc02490ff9bd0be1575a4e8908ca3e15dcfaa77e7d2b2bd616cfd"
sha256 mojave: "1ba2347383b539258d1c0a29cbbee722c30e6c28446c22a669a8a7deabd5f53e"
sha256 x86_64_linux: "05df8ecb9af5ecc0213e00e96db47e4cc48547d426ff67bcc79c940eee30bb49" # linuxbrew-core
end
keg_only :versioned_formula
deprecate! date: "2021-02-01", because: :unsupported
depends_on "cmake" => :build
depends_on "[email protected]"
uses_from_macos "libedit"
def datadir
var/"mysql"
end
# Fixes loading of VERSION file, backported from mysql/mysql-server@51675dd
patch :DATA
def install
# Don't hard-code the libtool path. See:
# https://github.com/Homebrew/homebrew/issues/20185
inreplace "cmake/libutils.cmake",
"COMMAND /usr/bin/libtool -static -o ${TARGET_LOCATION}",
"COMMAND libtool -static -o ${TARGET_LOCATION}"
# Fix loading of VERSION file; required in conjunction with patch
File.rename "VERSION", "MYSQL_VERSION"
# -DINSTALL_* are relative to `CMAKE_INSTALL_PREFIX` (`prefix`)
args = %W[
-DCOMPILATION_COMMENT=Homebrew
-DDEFAULT_CHARSET=utf8
-DDEFAULT_COLLATION=utf8_general_ci
-DINSTALL_DOCDIR=share/doc/#{name}
-DINSTALL_INCLUDEDIR=include/mysql
-DINSTALL_INFODIR=share/info
-DINSTALL_MANDIR=share/man
-DINSTALL_MYSQLSHAREDIR=share/mysql
-DMYSQL_DATADIR=#{datadir}
-DSYSCONFDIR=#{etc}
-DWITH_EDITLINE=system
-DWITH_NUMA=OFF
-DWITH_SSL=yes
-DWITH_UNIT_TESTS=OFF
-DWITH_EMBEDDED_SERVER=ON
-DWITH_ARCHIVE_STORAGE_ENGINE=1
-DWITH_BLACKHOLE_STORAGE_ENGINE=1
-DENABLED_LOCAL_INFILE=1
-DWITH_INNODB_MEMCACHED=ON
]
system "cmake", ".", *std_cmake_args, *args
system "make"
system "make", "install"
# Avoid references to the Homebrew shims directory
os = if OS.mac?
"mac"
else
"linux"
end
inreplace bin/"mysqlbug", HOMEBREW_SHIMS_PATH/"#{os}/super/", ""
(prefix/"mysql-test").cd do
system "./mysql-test-run.pl", "status", "--vardir=#{Dir.mktmpdir}"
end
# Remove the tests directory
rm_rf prefix/"mysql-test"
# Don't create databases inside of the prefix!
# See: https://github.com/Homebrew/homebrew/issues/4975
rm_rf prefix/"data"
# Link the setup script into bin
bin.install_symlink prefix/"scripts/mysql_install_db"
# Fix up the control script and link into bin.
inreplace "#{prefix}/support-files/mysql.server",
/^(PATH=".*)(")/,
"\\1:#{HOMEBREW_PREFIX}/bin\\2"
bin.install_symlink prefix/"support-files/mysql.server"
libexec.install bin/"mysqlaccess"
libexec.install bin/"mysqlaccess.conf"
# Install my.cnf that binds to 127.0.0.1 by default
(buildpath/"my.cnf").write <<~EOS
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
EOS
etc.install "my.cnf"
end
def post_install
# Make sure the var/mysql directory exists
(var/"mysql").mkpath
# Don't initialize database, it clashes when testing other MySQL-like implementations.
return if ENV["HOMEBREW_GITHUB_ACTIONS"]
unless (datadir/"mysql/general_log.CSM").exist?
ENV["TMPDIR"] = nil
system bin/"mysql_install_db", "--verbose", "--user=#{ENV["USER"]}",
"--basedir=#{prefix}", "--datadir=#{datadir}", "--tmpdir=/tmp"
end
end
def caveats
<<~EOS
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
MySQL is configured to only allow connections from localhost by default
To connect:
mysql -uroot
EOS
end
service do
run [opt_bin/"mysqld_safe", "--datadir=#{var}/mysql"]
keep_alive true
working_dir var/"mysql"
end
test do
(testpath/"mysql").mkpath
(testpath/"tmp").mkpath
system bin/"mysql_install_db", "--no-defaults", "--user=#{ENV["USER"]}",
"--basedir=#{prefix}", "--datadir=#{testpath}/mysql", "--tmpdir=#{testpath}/tmp"
port = free_port
fork do
system "#{bin}/mysqld", "--no-defaults", "--user=#{ENV["USER"]}",
"--datadir=#{testpath}/mysql", "--port=#{port}", "--tmpdir=#{testpath}/tmp"
end
sleep 5
assert_match "information_schema",
shell_output("#{bin}/mysql --port=#{port} --user=root --password= --execute='show databases;'")
system "#{bin}/mysqladmin", "--port=#{port}", "--user=root", "--password=", "shutdown"
end
end
__END__
diff --git a/cmake/mysql_version.cmake b/cmake/mysql_version.cmake
index 34ed6f4..4becbbc 100644
--- a/cmake/mysql_version.cmake
+++ b/cmake/mysql_version.cmake
@@ -31,7 +31,7 @@ SET(DOT_FRM_VERSION "6")
# Generate "something" to trigger cmake rerun when VERSION changes
CONFIGURE_FILE(
- ${CMAKE_SOURCE_DIR}/VERSION
+ ${CMAKE_SOURCE_DIR}/MYSQL_VERSION
${CMAKE_BINARY_DIR}/VERSION.dep
)
@@ -39,7 +39,7 @@ CONFIGURE_FILE(
MACRO(MYSQL_GET_CONFIG_VALUE keyword var)
IF(NOT ${var})
- FILE (STRINGS ${CMAKE_SOURCE_DIR}/VERSION str REGEX "^[ ]*${keyword}=")
+ FILE (STRINGS ${CMAKE_SOURCE_DIR}/MYSQL_VERSION str REGEX "^[ ]*${keyword}=")
IF(str)
STRING(REPLACE "${keyword}=" "" str ${str})
STRING(REGEX REPLACE "[ ].*" "" str "${str}")
| 31.681319 | 108 | 0.673084 |
26167172c7e3368af0017f4661d49341bab87a20 | 1,226 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'aws-sdk-core'
require 'aws-sigv4'
require_relative 'aws-sdk-organizations/types'
require_relative 'aws-sdk-organizations/client_api'
require_relative 'aws-sdk-organizations/client'
require_relative 'aws-sdk-organizations/errors'
require_relative 'aws-sdk-organizations/resource'
require_relative 'aws-sdk-organizations/customizations'
# This module provides support for AWS Organizations. This module is available in the
# `aws-sdk-organizations` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS Organizations all
# extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::Organizations::Errors::ServiceError
# # rescues all service API errors
# end
#
# See {Errors} for more information.
#
# @service
module Aws::Organizations
GEM_VERSION = '1.17.0'
end
| 25.541667 | 85 | 0.755302 |
bb4ab4ac495ec8e6068f29e778ee3011f75b251a | 1,511 | require 'spec_helper'
module CMIS
describe CMIS::Query do
before :all do
@folder = create_folder
21.times { create_document }
end
after :all do
@folder.delete_tree
end
context 'when querying with a limit' do
it 'should execute only one query if limit is under 10' do
expect_any_instance_of(CMIS::Query).to receive(:do_query).once.and_call_original
documents_query_result(limit: 3)
end
it 'should execute only 2 queries if limit is 20' do
expect_any_instance_of(CMIS::Query).to receive(:do_query).twice.and_call_original
documents_query_result(limit: 20)
end
it 'should receive 5 documents if limit is 5' do
result = documents_query_result(limit: 5)
expect(result.size).to eq(5)
end
end
def create_folder
folder = repository.new_folder
folder.name = 'test_query'
folder.object_type_id = 'cmis:folder'
repository.root.create(folder)
end
def create_document
document = repository.new_document
document.name = 'apple_document'
document.object_type_id = 'cmis:document'
document.create_in_folder(@folder)
end
def documents_query_result(opts)
results = []
query_string = "select cmis:objectId from cmis:document" \
" where IN_FOLDER('#{@folder.cmis_object_id}')"
@query = repository.query(query_string)
@query.each_result(opts) { |r| results << r }
results
end
end
end
| 27.472727 | 89 | 0.663799 |
26bb9502405625450da6fe73e04ae7dcdded334e | 4,193 | # Adds conversion methods to the Collins::Asset class for obtaining Jetpants equivalents
module Collins
class Asset
# Convert a Collins::Asset to a Jetpants::DB. Requires asset TYPE to be SERVER_NODE.
def to_db
raise "Can only call to_db on SERVER_NODE assets, but #{self} has type #{type}" unless type.upcase == 'SERVER_NODE'
backend_ip_address.to_db
end
# Convert a Collins::Asset to a Jetpants::Host. Requires asset TYPE to be SERVER_NODE.
def to_host
raise "Can only call to_host on SERVER_NODE assets, but #{self} has type #{type}" unless type.upcase == 'SERVER_NODE'
backend_ip_address.to_host
end
# Convert a Collins:Asset to a Jetpants::ShardPool
def to_shard_pool
raise "Can only call to_shard_pool on CONFIGURATION assets, but #{self} has type #{type}" unless type.upcase == 'CONFIGURATION'
raise "Unknown primary role #{primary_role} for configuration asset #{self}" unless primary_role.upcase == 'MYSQL_SHARD_POOL'
raise "No shard_pool attribute set on asset #{self}" unless shard_pool && shard_pool.length > 0
Jetpants::ShardPool.new(shard_pool)
end
# Convert a Collins::Asset to either a Jetpants::Pool or a Jetpants::Shard, depending
# on the value of PRIMARY_ROLE. Requires asset TYPE to be CONFIGURATION.
def to_pool
raise "Can only call to_pool on CONFIGURATION assets, but #{self} has type #{type}" unless type.upcase == 'CONFIGURATION'
raise "Unknown primary role #{primary_role} for configuration asset #{self}" unless ['MYSQL_POOL', 'MYSQL_SHARD'].include?(primary_role.upcase)
raise "No pool attribute set on asset #{self}" unless pool && pool.length > 0
# if this node is iniitalizing we know there will be no server assets
# associated with it
if !shard_state.nil? and shard_state.upcase == "INITIALIZING"
master_assets = []
else
# Find the master(s) for this pool. If we got back multiple masters, first
# try ignoring the remote datacenter ones
master_assets = Jetpants.topology.server_node_assets(pool.downcase, :master)
end
if master_assets.count > 1
results = master_assets.select {|a| a.location.nil? || a.location.upcase == Jetpants::Plugin::JetCollins.datacenter}
master_assets = results if results.count > 0
end
puts "WARNING: multiple masters found for pool #{pool}; using first match" if master_assets.count > 1
if master_assets.count == 0
puts "WARNING: no masters found for pool #{pool}; ignoring pool entirely"
result = nil
elsif primary_role.upcase == 'MYSQL_POOL'
result = Jetpants::Pool.new(pool.downcase, master_assets.first.to_db)
if aliases
aliases.split(',').each {|a| result.add_alias(a.downcase)}
end
result.slave_name = slave_pool_name if slave_pool_name
result.master_read_weight = master_read_weight if master_read_weight
active_slave_assets = Jetpants.topology.server_node_assets(pool.downcase, :active_slave)
active_slave_assets.each do |asset|
weight = asset.slave_weight && asset.slave_weight.to_i > 0 ? asset.slave_weight.to_i : 100
result.has_active_slave(asset.to_db, weight)
end
elsif primary_role.upcase == 'MYSQL_SHARD'
result = Jetpants::Shard.new(shard_min_id.to_i,
shard_max_id == 'INFINITY' ? 'INFINITY' : shard_max_id.to_i,
master_assets.first.to_db,
shard_state.downcase.to_sym,
shard_pool)
# We'll need to set up the parent/child relationship if a shard split is in progress,
# BUT we need to wait to do that later since the shards may have been returned by
# Collins out-of-order, so the parent shard object might not exist yet.
# For now we just remember the NAME of the parent shard.
result.has_parent = shard_parent if shard_parent
else
raise "Unknown configuration asset primary role #{primary_role} for asset #{self}"
end
result
end
end
end
| 46.076923 | 149 | 0.674457 |
6277e320ea887356f5418ab63f9acb9228fd9f55 | 148 | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def hello
render html: "Hello,World!"
end
end
| 18.5 | 52 | 0.763514 |
39d302c385375baf77d847706248751cf617adae | 2,583 | class CustomersController < ApplicationController
before_filter :signed_in_user, only: [:create, :show, :index]
before_filter :correct_user, only: [ :destroy , :show ,:edit ]
autocomplete :customer, :name
def index
@customers = current_user.customers.paginate(page: params[:page])
end
def create
object = @customer
@customer = current_user.customers.build(params[:customer])
object = @customer
if @customer.save
if Rails.cache.read('mp_id')==nil
@micropost = current_user.microposts.build
else
@micropost = current_user.microposts.find(Rails.cache.read('mp_id'))
end
if Rails.cache.read('root') == 1
respond_to do |format|
@customer = current_user.customers.build()
format.html {redirect_to :back}
format.js
end
else
redirect_to customers_url
end
else
respond_to do |format|
format.html {redirect_to :back
flash[:error] = @customer.errors.full_messages.to_s}
format.js {render :js => "alert("[email protected]_messages.to_s+");"}
end
end
end
def destroy
@customer.destroy
redirect_to customers_url
end
def edit
render 'new'
@object = @customer
end
def update
@customer = current_user.customers.find_by_id(params[:id])
@object = @customer
if @customer.update_attributes(params[:customer])
flash[:success] = "Customer information updated"
redirect_to @customer
else
respond_to do |format|
format.html {redirect_to :back
flash[:error] = @customer.errors.full_messages.to_s}
end
end
end
def new
@customer=Customer.new
@object = @customer
Rails.cache.write('root',0)
end
def show
@customer=current_user.customers.find_by_id(params[:id])
end
def upload
end
def import
file = params[:file]
file_name = file.original_filename.split(".").first
extension = File.extname(file.original_filename)
tmp_file = Tempfile.new([ file_name, extension ])
tmp_file.binmode
tmp_file.write(file.read)
tmp_file.rewind
Customer.import(tmp_file,current_user.id)
flash[:notice] = "Successfully imported"
redirect_to root_url
end
private
def correct_user
@customer = current_user.customers.find_by_id(params[:id])
redirect_to root_url if @customer.nil?
end
end | 25.83 | 82 | 0.619048 |
620b782c2e683a38b28596e396ea93ceed875ce9 | 1,760 | # frozen_string_literal: true
require 'zoho_hub/records/base_record'
module ZohoHub
class Potential < BaseRecord
attributes :id, :code, :deal_name, :amount, :description, :stage
attributes :company_age_years, :company_age_months, :term, :use_proceeds, :proceeds_detail
attributes :currency, :territory, :employee_count, :turnover, :industry, :region
attributes :review_outcome, :first_created, :last_modified, :preferred_term, :project_notes
attributes :campaign_id, :account_id, :contact_id, :campaign_detail, :reviewers_comment
DEFAULTS = {
currency: 'GBP',
territory: 'UK all',
campaign_detail: 'Web Sign Up'
}.freeze
# The translation from attribute name to the JSON field on Zoho. The default behaviour will be
# to Camel_Case the attribute so on this list we should only have exceptions to this rule.
attribute_translation(
id: :id,
code: :Project_Ref_No,
description: :Project_description,
employee_count: :Number_of_Employees,
use_proceeds: :use_proceeds
)
def initialize(params)
attributes.each do |attr|
zoho_key = attr_to_zoho_key(attr)
send("#{attr}=", params[zoho_key] || params[attr] || DEFAULTS[attr])
end
# Setup values as they come from the Zoho API if needed
@account_id ||= params.dig(:Account_Name, :id)
@contact_id ||= params.dig(:Contact_Name, :id)
@campaign_id ||= params.dig(:Campaign_Source, :id)
end
def to_params
params = super
params[:Campaign_Source] = { id: @campaign_id } if @campaign_id
params[:Account_Name] = { id: @account_id } if @account_id
params[:Contact_Name] = { id: @contact_id } if @contact_id
params
end
end
end
| 33.207547 | 98 | 0.684091 |
332759704319a3c065b335cea13dee26c52aa6dd | 623 | require 'test_helper'
class UsersProfileTest < ActionDispatch::IntegrationTest
include ApplicationHelper
def setup
@user = users(:michael)
end
# test "profile display" do
# get user_path(@user)
# assert_template 'users/show'
# assert_select 'title', full_title(@user.name)
# assert_select 'h1', text: @user.name
# assert_select 'h1>img.gravatar'
# assert_match @user.microposts.count.to_s, response.body
# assert_select 'div.pagination'
# @user.microposts.paginate(page: 1).each do |micropost|
# assert_match micropost.content, response.body
# end
# end
end | 28.318182 | 62 | 0.693419 |
4aa066a468d78518f8e9da6f85deec85671780ad | 11,240 | # -*- coding: binary -*-
require 'msf/core'
require 'pathname'
#
# Define used for a place-holder module that is used to indicate that the
# module has not yet been demand-loaded. Soon to go away.
#
Msf::SymbolicModule = '__SYMBOLIC__'
###
#
# A module set contains zero or more named module classes of an arbitrary
# type.
#
###
class Msf::ModuleSet < Hash
include Msf::Framework::Offspring
# Wrapper that detects if a symbolic module is in use. If it is, it creates an instance to demand load the module
# and then returns the now-loaded class afterwords.
#
# @param [String] name the module reference name
# @return [Msf::Module] instance of the of the Msf::Module subclass with the given reference name
def [](name)
if (super == Msf::SymbolicModule)
create(name)
end
super
end
# Create an instance of the supplied module by its reference name
#
# @param reference_name [String] The module reference name.
# @return [Msf::Module,nil] Instance of the named module or nil if it
# could not be created.
def create(reference_name)
klass = fetch(reference_name, nil)
instance = nil
# If there is no module associated with this class, then try to demand
# load it.
if klass.nil? or klass == Msf::SymbolicModule
framework.modules.load_cached_module(module_type, reference_name)
recalculate
klass = fetch(reference_name, nil)
end
# If the klass is valid for this reference_name, try to create it
unless klass.nil? or klass == Msf::SymbolicModule
instance = klass.new
end
# Notify any general subscribers of the creation event
if instance
self.framework.events.on_module_created(instance)
end
return instance
end
# Overrides the builtin 'each' operator to avoid the following exception on Ruby 1.9.2+
# "can't add a new key into hash during iteration"
#
# @yield [module_reference_name, module]
# @yieldparam [String] module_reference_name the reference_name of the module.
# @yieldparam [Class] module The module class: a subclass of Msf::Module.
# @return [void]
def each(&block)
list = []
self.keys.sort.each do |sidx|
list << [sidx, self[sidx]]
end
list.each(&block)
end
# Enumerates each module class in the set.
#
# @param opts (see #each_module_list)
# @yield (see #each_module_list)
# @yieldparam (see #each_module_list)
# @return (see #each_module_list)
def each_module(opts = {}, &block)
demand_load_modules
self.mod_sorted = self.sort
each_module_list(mod_sorted, opts, &block)
end
# Custom each_module filtering if an advanced set supports doing extended filtering.
#
# @param opts (see #each_module_list)
# @param [String] name the module reference name
# @param [Array<String, Class>] entry pair of the module reference name and the module class.
# @return [false] if the module should not be filtered; it should be yielded by {#each_module_list}.
# @return [true] if the module should be filtered; it should not be yielded by {#each_module_list}.
def each_module_filter(opts, name, entry)
return false
end
# Enumerates each module class in the set based on their relative ranking to one another. Modules that are ranked
# higher are shown first.
#
# @param opts (see #each_module_list)
# @yield (see #each_module_list)
# @yieldparam (see #each_module_list)
# @return (see #each_module_list)
def each_module_ranked(opts = {}, &block)
demand_load_modules
self.mod_ranked = rank_modules
each_module_list(mod_ranked, opts, &block)
end
# Forces all modules in this set to be loaded.
#
# @return [void]
def force_load_set
each_module { |name, mod| }
end
# Initializes a module set that will contain modules of a specific type and expose the mechanism necessary to create
# instances of them.
#
# @param [String] type The type of modules cached by this {Msf::ModuleSet}.
def initialize(type = nil)
#
# Defaults
#
self.ambiguous_module_reference_name_set = Set.new
# Hashes that convey the supported architectures and platforms for a
# given module
self.architectures_by_module = {}
self.platforms_by_module = {}
self.mod_sorted = nil
self.mod_ranked = nil
self.mod_extensions = []
#
# Arguments
#
self.module_type = type
end
# @!attribute [r] module_type
# The type of modules stored by this {Msf::ModuleSet}.
#
# @return [String] type of modules
attr_reader :module_type
# Gives the module set an opportunity to handle a module reload event
#
# @param [Class] mod the module class: a subclass of Msf::Module
# @return [void]
def on_module_reload(mod)
end
# Dummy placeholder to recalculate aliases and other fun things.
#
# @return [void]
def recalculate
end
# Checks to see if the supplied module reference name is valid.
#
# @param reference_name [String] The module reference name.
# @return [true] if the module can be {#create created} and cached.
# @return [false] otherwise
def valid?(reference_name)
create(reference_name)
(self[reference_name]) ? true : false
end
# Adds a module with a the supplied reference_name.
#
# @param [Class<Msf::Module>] klass The module class.
# @param [String] reference_name The module reference name.
# @param [Hash{String => Object}] info optional module information.
# @option info [Array<String>] 'files' List of paths to files that defined
# +klass+.
# @return [Class] The klass parameter modified to have
# {Msf::Module#framework}, {Msf::Module#refname}, {Msf::Module#file_path},
# and {Msf::Module#orig_cls} set.
def add_module(klass, reference_name, info = {})
# Set the module's reference_name so that it can be referenced when
# instances are created.
klass.framework = framework
klass.refname = reference_name
klass.file_path = ((info and info['files']) ? info['files'][0] : nil)
klass.orig_cls = klass
# don't want to trigger a create, so use fetch
cached_module = self.fetch(reference_name, nil)
if (cached_module and cached_module != Msf::SymbolicModule)
ambiguous_module_reference_name_set.add(reference_name)
# TODO this isn't terribly helpful since the refnames will always match, that's why they are ambiguous.
wlog("The module #{klass.refname} is ambiguous with #{self[reference_name].refname}.")
end
self[reference_name] = klass
klass
end
protected
# Load all modules that are marked as being symbolic.
#
# @return [void]
def demand_load_modules
found_symbolics = false
# Pre-scan the module list for any symbolic modules
self.each_pair { |name, mod|
if (mod == Msf::SymbolicModule)
found_symbolics = true
mod = create(name)
next if (mod.nil?)
end
}
# If we found any symbolic modules, then recalculate.
if (found_symbolics)
recalculate
end
end
# Enumerates the modules in the supplied array with possible limiting factors.
#
# @param [Array<Array<String, Class>>] ary Array of module reference name and module class pairs
# @param [Hash{String => Object}] opts
# @option opts [Array<String>] 'Arch' List of 1 or more architectures that the module must support. The module need
# only support one of the architectures in the array to be included, not all architectures.
# @option opts [Array<String>] 'Platform' List of 1 or more platforms that the module must support. The module need
# only support one of the platforms in the array to be include, not all platforms.
# @yield [module_reference_name, module]
# @yieldparam [String] module_reference_name the name of module
# @yieldparam [Class] module The module class: a subclass of {Msf::Module}.
# @return [void]
def each_module_list(ary, opts, &block)
ary.each { |entry|
name, mod = entry
# Skip any lingering symbolic modules.
next if (mod == Msf::SymbolicModule)
# Filter out incompatible architectures
if (opts['Arch'])
if (!architectures_by_module[mod])
architectures_by_module[mod] = mod.new.arch
end
next if ((architectures_by_module[mod] & opts['Arch']).empty? == true)
end
# Filter out incompatible platforms
if (opts['Platform'])
if (!platforms_by_module[mod])
platforms_by_module[mod] = mod.new.platform
end
next if ((platforms_by_module[mod] & opts['Platform']).empty? == true)
end
# Custom filtering
next if (each_module_filter(opts, name, entry) == true)
block.call(name, mod)
}
end
# @!attribute [rw] ambiguous_module_reference_name_set
# Set of module reference names that are ambiguous because two or more paths have modules with the same reference
# name
#
# @return [Set<String>] set of module reference names loaded from multiple paths.
attr_accessor :ambiguous_module_reference_name_set
# @!attribute [rw] architectures_by_module
# Maps a module to the list of architectures it supports.
#
# @return [Hash{Class => Array<String>}] Maps module class to Array of architecture Strings.
attr_accessor :architectures_by_module
attr_accessor :mod_extensions
# @!attribute [rw] platforms_by_module
# Maps a module to the list of platforms it supports.
#
# @return [Hash{Class => Array<String>}] Maps module class to Array of platform Strings.
attr_accessor :platforms_by_module
# @!attribute [rw] mod_ranked
# Array of module names and module classes ordered by their Rank with the higher Ranks first.
#
# @return (see #rank_modules)
attr_accessor :mod_ranked
# @!attribute [rw] mod_sorted
# Array of module names and module classes ordered by their names.
#
# @return [Array<Array<String, Class>>] Array of arrays where the inner array is a pair of the module reference
# name and the module class.
attr_accessor :mod_sorted
# @!attribute [w] module_type
# The type of modules stored by this {Msf::ModuleSet}.
#
# @return [String] type of modules
attr_writer :module_type
# Ranks modules based on their constant rank value, if they have one. Modules without a Rank are treated as if they
# had {Msf::NormalRanking} for Rank.
#
# @return [Array<Array<String, Class>>] Array of arrays where the inner array is a pair of the module reference name
# and the module class.
def rank_modules
self.mod_ranked = self.sort { |a, b|
a_name, a_mod = a
b_name, b_mod = b
# Dynamically loads the module if needed
a_mod = create(a_name) if a_mod == Msf::SymbolicModule
b_mod = create(b_name) if b_mod == Msf::SymbolicModule
# Extract the ranking between the two modules
a_rank = a_mod.const_defined?('Rank') ? a_mod.const_get('Rank') : Msf::NormalRanking
b_rank = b_mod.const_defined?('Rank') ? b_mod.const_get('Rank') : Msf::NormalRanking
# Compare their relevant rankings. Since we want highest to lowest,
# we compare b_rank to a_rank in terms of higher/lower precedence
b_rank <=> a_rank
}
end
end
| 33.452381 | 118 | 0.69137 |
1c2999f362d69ac635725eb1a6abee60b3069858 | 1,347 | describe "migration order" do
let(:current_release_migrations) do
File.read(File.join(__dir__, 'data/released_migrations')).split.map(&:to_i).sort
end
let(:migrations_now) do
Dir.glob(File.join(Rails.root, "db/migrate/*.rb")).map do |f|
File.basename(f, ".rb").split("_").first.to_i
end.sort
end
let(:new_migrations) do
migrations_now - current_release_migrations
end
let(:last_released_migration) do
current_release_migrations.last
end
def invalid_migrations_message(incorrect_migration_time_stamps, last_released_migration)
<<-EOS
The following migration timestamps are too early to be included in the next release:
#{incorrect_migration_time_stamps.join("\n")}
These migrations must be regenerated so that they will run after the latest
released migration, #{last_released_migration}.
This is done to prevent schema differences between migrated databases and
newly created ones where all the migrations are run in timestamp order.
EOS
end
it "is correct" do
incorrect_migration_time_stamps = []
new_migrations.each do |m|
incorrect_migration_time_stamps << m if m < last_released_migration
end
expect(incorrect_migration_time_stamps).to(
be_empty,
invalid_migrations_message(incorrect_migration_time_stamps, last_released_migration)
)
end
end
| 29.282609 | 90 | 0.76095 |
5dce9ed248c99d1d9cdc2833088ca23e53c0ecc7 | 636 | require 'spec_helper_acceptance'
describe 'secure_apache class' do
context 'default parameters' do
# Using puppet_apply as a helper
it 'should work idempotently with no errors' do
pp = <<-EOS
class { 'secure_apache': }
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
describe package('secure_apache') do
it { is_expected.to be_installed }
end
describe service('secure_apache') do
it { is_expected.to be_enabled }
it { is_expected.to be_running }
end
end
end
| 24.461538 | 51 | 0.665094 |
edb186344ef503c4699fe7ffbd9927bdfbf1d1df | 714 | # frozen_string_literal: true
require "spec_helper"
describe Montrose do
it { assert ::Montrose::VERSION }
describe ".r" do
it { Montrose.r.must_be_kind_of(Montrose::Recurrence) }
it { Montrose.r.default_options.to_h.must_equal({}) }
it { Montrose.r(every: :day).must_be_kind_of(Montrose::Recurrence) }
it { Montrose.r(every: :day).default_options[:every].must_equal(:day) }
it { Montrose.recurrence.must_be_kind_of(Montrose::Recurrence) }
it { Montrose.recurrence.default_options.to_h.must_equal({}) }
it { Montrose.recurrence(every: :day).must_be_kind_of(Montrose::Recurrence) }
it { Montrose.recurrence(every: :day).default_options[:every].must_equal(:day) }
end
end
| 32.454545 | 84 | 0.718487 |
1dc3231cedf3d6696f5201ac8627adddf0c8c892 | 592 | require 'test_helper'
module Landlord
class Accounts::MembershipsControllerTest < ActionDispatch::IntegrationTest
include Engine.routes.url_helpers
include Devise::Test::IntegrationHelpers
test "should only allow owner access" do
owner_mem = landlord_memberships(:owner_1)
admin_mem = landlord_memberships(:admin_1)
sign_in owner_mem.user
get account_memberships_url(owner_mem.account)
assert_response :success
sign_in admin_mem.user
get account_memberships_url(admin_mem.account)
assert_response :redirect
end
end
end
| 25.73913 | 77 | 0.753378 |
26e5514a04cd1b86938f54d95ed4eb19c4cea86d | 406 | # name: user-themes
# about: Make Discourse have users be able to switch from available forum themes on the fly.
# version: 0.0.1
# authors: lunarmuffins
enabled_site_setting :DiscourseThemes_enabled
add_admin_route 'DiscourseThemes.title', 'DiscourseThemes'
Discourse::Application.routes.append do
get '/admin/plugins/DiscourseThemes' => 'admin/plugins#index', constraints: StaffConstraint.new
end | 33.833333 | 99 | 0.793103 |
030c899badc3263ca45c39656414d27113838b22 | 11,459 | require "spec_helper"
describe Mongoid::Relations::Embedded::In do
describe "#===" do
let(:base) do
Name.new
end
let(:target) do
Person.new
end
let(:metadata) do
Name.relations["namable"]
end
let(:relation) do
described_class.new(base, target, metadata)
end
context "when the proxied document is same class" do
context "when the document is a different instance" do
it "returns false" do
(relation === Person.new).should be_false
end
end
context "when the document is the same instance" do
it "returns true" do
(relation === target).should be_true
end
end
end
end
describe "#=" do
context "when the inverse of an embeds one" do
context "when the child is a new record" do
let(:person) do
Person.new
end
let(:name) do
Name.new
end
before do
name.namable = person
end
it "sets the target of the relation" do
name.namable.should eq(person)
end
it "sets the base on the inverse relation" do
person.name.should eq(name)
end
it "sets the same instance on the inverse relation" do
person.name.should eql(name)
end
it "does not save the target" do
person.should_not be_persisted
end
end
context "when the parent is not a new record" do
let(:person) do
Person.create
end
let(:name) do
Name.new
end
before do
name.namable = person
end
it "sets the target of the relation" do
name.namable.should eq(person)
end
it "sets the base on the inverse relation" do
person.name.should eq(name)
end
it "sets the same instance on the inverse relation" do
person.name.should eql(name)
end
it "does not save the base" do
name.should_not be_persisted
end
end
end
context "when the inverse of an embeds many" do
context "when the child is a new record" do
let(:person) do
Person.new
end
let(:address) do
Address.new
end
before do
address.addressable = person
end
it "sets the target of the relation" do
address.addressable.should eq(person)
end
it "appends the base on the inverse relation" do
person.addresses.should eq([ address ])
end
it "sets the same instance in the inverse relation" do
person.addresses.first.should eql(address)
end
it "does not save the target" do
person.should_not be_persisted
end
end
context "when the parent is not a new record" do
let!(:person) do
Person.create!
end
let(:address) do
Address.new
end
before do
address.addressable = person
end
it "sets the target of the relation" do
address.addressable.should eq(person)
end
it "sets the same instance in the inverse relation" do
person.addresses.first.should eql(address)
end
it "appends the base on the inverse relation" do
person.addresses.should eq([ address ])
end
end
end
end
describe "#= nil" do
context "when the inverse of an embeds one" do
context "when the parent is a new record" do
let(:person) do
Person.new
end
let(:name) do
Name.new
end
before do
name.namable = person
name.namable = nil
end
it "sets the relation to nil" do
name.namable.should be_nil
end
it "removes the inverse relation" do
person.name.should be_nil
end
end
context "when the inverse is already nil" do
let(:person) do
Person.new
end
let(:name) do
Name.new
end
before do
name.namable = nil
end
it "sets the relation to nil" do
name.namable.should be_nil
end
it "removes the inverse relation" do
person.name.should be_nil
end
end
context "when the documents are not new records" do
let(:person) do
Person.create
end
let(:name) do
Name.new
end
before do
name.namable = person
name.namable = nil
end
it "sets the relation to nil" do
name.namable.should be_nil
end
it "removed the inverse relation" do
person.name.should be_nil
end
it "deletes the child document" do
name.should be_destroyed
end
end
end
context "when the inverse of an embeds many" do
context "when the parent is a new record" do
let(:person) do
Person.new
end
let(:address) do
Address.new
end
before do
address.addressable = person
address.addressable = nil
end
it "sets the relation to nil" do
address.addressable.should be_nil
end
it "removes the inverse relation" do
person.addresses.should be_empty
end
end
context "when the inverse is already nil" do
let(:address) do
Address.new
end
before do
address.addressable = nil
end
it "sets the relation to nil" do
address.addressable.should be_nil
end
end
context "when the documents are not new records" do
let(:person) do
Person.create
end
let(:address) do
Address.new
end
before do
address.addressable = person
address.addressable = nil
end
it "sets the relation to nil" do
address.addressable.should be_nil
end
it "removed the inverse relation" do
person.addresses.should be_empty
end
it "deletes the child document" do
address.should be_destroyed
end
end
context "when a child already exists on the parent" do
let(:person) do
Person.create
end
let(:address_one) do
Address.new(street: "first")
end
let(:address_two) do
Address.new(street: "second")
end
before do
person.addresses = [ address_one, address_two ]
address_one.addressable = nil
end
it "sets the relation to nil" do
address_one.addressable.should be_nil
end
it "removed the inverse relation" do
person.addresses.should eq([ address_two ])
end
it "deletes the child document" do
address_one.should be_destroyed
end
it "reindexes the children" do
address_two._index.should eq(0)
end
end
end
end
describe ".builder" do
let(:builder_klass) do
Mongoid::Relations::Builders::Embedded::In
end
let(:base) do
Name.new
end
let(:target) do
Person.new
end
let(:metadata) do
Name.relations["namable"]
end
it "returns the embedded one builder" do
described_class.builder(base, metadata, target).should be_a(builder_klass)
end
end
describe ".embedded?" do
it "returns true" do
described_class.should be_embedded
end
end
describe ".macro" do
it "returns embeds_one" do
described_class.macro.should eq(:embedded_in)
end
end
describe ".nested_builder" do
let(:nested_builder_klass) do
Mongoid::Relations::Builders::NestedAttributes::One
end
let(:metadata) do
Name.relations["namable"]
end
let(:attributes) do
{}
end
it "returns the single nested builder" do
described_class.nested_builder(metadata, attributes, {}).should
be_a(nested_builder_klass)
end
end
describe "#respond_to?" do
let(:person) do
Person.new
end
let!(:name) do
person.build_name(first_name: "Tony")
end
let(:document) do
name.namable
end
Mongoid::Document.public_instance_methods(true).each do |method|
context "when checking #{method}" do
it "returns true" do
document.respond_to?(method).should be_true
end
end
end
end
describe ".valid_options" do
it "returns the valid options" do
described_class.valid_options.should eq(
[ :autobuild, :cyclic, :polymorphic ]
)
end
end
describe ".validation_default" do
it "returns false" do
described_class.validation_default.should be_false
end
end
context "when creating the tree through initialization" do
let!(:person) do
Person.create
end
let!(:address) do
Address.create(addressable: person)
end
let!(:first_location) do
Location.create(address: address)
end
let!(:second_location) do
Location.create(address: address)
end
it "saves the child" do
Person.last.addresses.last.should eq(address)
end
it "indexes the child" do
address._index.should eq(0)
end
it "saves the first location with the correct index" do
first_location._index.should eq(0)
end
it "saves the second location with the correct index" do
second_location._index.should eq(1)
end
it "has the locations in the association array" do
Person.last.addresses.last.locations.should eq(
[first_location, second_location]
)
end
end
context "when instantiating a new child with a persisted parent" do
let!(:person) do
Person.create
end
let!(:address) do
Address.new(addressable: person)
end
let!(:location) do
Location.new(address: address)
end
it "does not save the child" do
address.should_not be_persisted
end
it "does not save the deeply embedded children" do
address.locations.first.should_not be_persisted
end
end
context "when replacing the relation with another" do
let!(:person) do
Person.create
end
let!(:person_two) do
Person.create
end
let!(:address) do
person.addresses.create(street: "Kotbusser Damm")
end
let!(:name) do
person_two.create_name(first_name: "Syd")
end
before do
name.namable = address.addressable
name.namable.save
end
it "sets the new parent" do
name.namable.should eq(person)
end
it "removes the previous parent relation" do
person_two.name.should be_nil
end
it "sets the new child relation" do
person.name.should eq(name)
end
context "when reloading" do
before do
person.reload
end
it "sets the new parent" do
name.namable.should eq(person)
end
it "removes the previous parent relation" do
person_two.name.should be_nil
end
it "sets the new child relation" do
person.name.should eq(name)
end
end
end
end
| 19.963415 | 80 | 0.58033 |
b94309db45eb7d479d78fe9613d509c28c0fed06 | 1,206 | # frozen_string_literal: true
module Jekyll
module TableOfContents
# jekyll-toc configuration class
class Configuration
attr_accessor :toc_levels, :no_toc_class, :no_toc_section_class,
:list_class, :sublist_class, :item_class, :item_prefix
DEFAULT_CONFIG = {
'min_level' => 1,
'max_level' => 6,
'no_toc_section_class' => 'no_toc_section',
'list_class' => 'section-nav',
'sublist_class' => '',
'item_class' => 'toc-entry',
'item_prefix' => 'toc-'
}.freeze
def initialize(options)
options = generate_option_hash(options)
@toc_levels = options['min_level']..options['max_level']
@no_toc_class = 'no_toc'
@no_toc_section_class = options['no_toc_section_class']
@list_class = options['list_class']
@sublist_class = options['sublist_class']
@item_class = options['item_class']
@item_prefix = options['item_prefix']
end
private
def generate_option_hash(options)
DEFAULT_CONFIG.merge(options)
rescue TypeError
DEFAULT_CONFIG
end
end
end
end
| 28.714286 | 75 | 0.601161 |
1c8e88f3230836d5f87679ae6b36a9dbe60c5da2 | 82 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'lita/weather'
| 27.333333 | 58 | 0.731707 |
26fac381aaffd612c0920058462f3ec5979b7f74 | 6,658 | class VidgameScraper::Scraper
def self.scrape_all_items(url)
#open the url and scrape all the items ps4,ps5 etc.ur
# url =" https://austin.craigslist.org/#{type}"
webpage = Nokogiri::HTML(open(url))
section = webpage.css(".rows").css(".result-row").css(".result-info").css(".result-heading")
array_of_links = section.css("h3 a.hdrlnk")
array_of_links.map do |link|
VidgameScraper::Category.new(link.text, link.attributes["href"].value)
end
# binding.pry
#will return a list of the items for sale??
end
def self.scrape_items(category)
webpage = Nokogiri::HTML(open(category.url))
items = webpage.css(".body")
items.each do |card|
# binding.pry
deal = VidgameScraper::Deal.new
title = card.css("#titletextonly").text.strip #shows the title of the item.
price = card.css(".price").text
location = card.css("h1.postingtitle").css("span.postingtitletext").css("small").text.strip #shows the date when posted.
time_posted = card.css("#display-date").css("time").text.strip.split(" ")[0]
condition = card.css("p.attrgroup").text.gsub(" ","").gsub("\n", "")
# first_condition = card.css("p.attrgroup span").children[0].text.strip # => "condition: "
if card.css("p.attrgroup span").children[0]
first_condition = card.css("p.attrgroup span").children[0].text.strip
else
first_condition = "Condition:".colorize(:yellow)
end
# sec_condition = card.css("p.attrgroup span").children[1].text.strip # => "new"
if card.css("p.attrgroup span").children[1]
sec_condition = card.css("p.attrgroup span").children[1].text.strip
else
sec_condition = "Not listed.".colorize(:red)
end
if card.css("p.attrgroup span").children[4] # check if selector exists
number_condition_left = card.css("p.attrgroup span").children[4].text.strip # get text of element
else
number_condition_left = "Model Name / Number:" # element did not exist
end
# number_condition_right = card.css("p.attrgroup span").children[5] ? card.css("p.attrgroup span").children[5].text.strip : #"Where it was made from" (2b/2b)
if card.css("p.attrgroup span").children[5]
number_condition_right = card.css("p.attrgroup span").children[5].text.strip
else
number_condition_right = "Not listed.".colorize(:red)
end
# if card.css("p.attrgroup span").children[5]
# crypto = card.css("p.attrgroup span").children[0].text.strip # => "cryptocurrency ok"
if card.css("p.attrgroup span").children[0]
crypto = card.css("p.attrgroup span").children[0].text.strip
else
crypto = "Crypto Currency: Not listed"
end
# delivery = card.css("p.attrgroup span").children[1].text # => "delivery available"
if card.css("p.attrgroup span").children[1]
delivery = card.css("p.attrgroup span").children[1].text
else
delivery = "Delivery: Not listed."
end
# make = card.css("p.attrgroup span").children[2].text.strip # => "make / manufacturer:" (1a/2a)
if card.css("p.attrgroup span").children[2]
make = card.css("p.attrgroup span").children[2].text.strip
else
make = "Make / Manufacturer:"
end
# brand = card.css("p.attrgroup span").children[3].text.strip # => "microsoft" (2a/2a)
if card.css("p.attrgroup span").children[3]
brand = card.css("p.attrgroup span").children[3].text.strip
else
brand = "Not listed.".colorize(:red)
end
# dimensions_one = card.css("p.attrgroup span").children[6].text.strip # => "size / dimensions: 15,75x18.1x31.5"
if card.css("p.attrgroup span").children[6]
dimensions_one = card.css("p.attrgroup span").children[6].text.strip
else
dimensions_one = "Size / Dimensions:"
end
# dimensions_two = card.css("p.attrgroup span").children[7].text.strip # => "15,75x18.1x31.5"
if card.css("p.attrgroup span").children[7]
dimensions_two = card.css("p.attrgroup span").children[7].text.strip
else
dimensions_two = "Size Not listed.".colorize(:red)
end
description = card.css("#postingbody").inner_text.gsub(" ", "").gsub("QR Code Link to This Post", "").gsub("\n", "").gsub("-", " -") #shwos desc.
notice = card.css("ul.notices").css("li").text # shows the bullet point desc.
# # post_id = card.css("div.postinginfos").css("p.postinginfo").children[0].text
post_id = card.css("div.postinginfos").css("p.postinginfo").children[0].text.split(":")[0]
num_id = card.css("div.postinginfos").css("p.postinginfo").children[0].text.split(":")[1].strip
# ########deal#########
deal.title = title
deal.price = price
deal.location = location
deal.first_condition = first_condition
deal.sec_condition = sec_condition
deal.number_condition_left = number_condition_left
deal.number_condition_right = number_condition_right
deal.make = make
deal.brand = brand
deal.crypto = crypto
deal.delivery = delivery
deal.time_posted = time_posted
deal.post_id = post_id
deal.num_id = num_id
deal.notice = notice
deal.description = description
deal.dimensions_two = dimensions_two
deal.dimensions_one = dimensions_one
category.add_deal(deal)
# binding.pry
end
end
end
#link.attributes["href"].valu shows the URL
#** will show the price of the item being sold **
# [25] pry(VidgameScraper::Scraper)> webpage.css(".body").css("h1.postingtitle").css(".price").text
# => "$1"
#** for any listed things on the page**
# [37] pry(VidgameScraper::Scraper)> webpage.css("ul.notices").css("li").text
# => "do NOT contact me with unsolicited services or offers" | 44.986486 | 170 | 0.56158 |
bfe356725ca55fd42246901c786e57286b2d2809 | 687 | # This file is managed via modulesync
# https://github.com/voxpupuli/modulesync
# https://github.com/voxpupuli/modulesync_config
RSpec.configure do |c|
c.mock_with :rspec
end
# puppetlabs_spec_helper will set up coverage if the env variable is set.
# We want to do this if lib exists and it hasn't been explicitly set.
ENV['COVERAGE'] ||= 'yes' if Dir.exist?(File.expand_path('../../lib', __FILE__))
require 'voxpupuli/test/spec_helper'
if File.exist?(File.join(__dir__, 'default_module_facts.yml'))
facts = YAML.load(File.read(File.join(__dir__, 'default_module_facts.yml')))
if facts
facts.each do |name, value|
add_custom_fact name.to_sym, value
end
end
end
| 29.869565 | 80 | 0.73508 |
7a0aeac57bc3792fbbcf0305eb5fc25fac234b1a | 2,536 | require 'one_gadget/gadget'
# https://gitlab.com/libcdb/libcdb/blob/master/libc/libc0.1-2.24-7/lib/i386-kfreebsd-gnu/libc-2.24.so
#
# Intel 80386
#
# GNU C Library (Debian GLIBC 2.24-7) stable release version 2.24, by Roland McGrath et al.
# Copyright (C) 2016 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Compiled by GNU CC version 6.2.1 20161119.
# Available extensions:
# crypt add-on version 2.1 by Michael Glad and others
# Native POSIX Threads Library by Ulrich Drepper et al
# GNU Libidn by Simon Josefsson
# BIND-8.2.3-T5B
# libc ABIs: UNIQUE
# For bug reporting instructions, please see:
# <http://www.debian.org/Bugs/>.
build_id = File.basename(__FILE__, '.rb').split('-').last
OneGadget::Gadget.add(build_id, 234309,
constraints: ["ebx is the GOT address of libc", "[esp+0x2c] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x2c, environ)")
OneGadget::Gadget.add(build_id, 234311,
constraints: ["ebx is the GOT address of libc", "[esp+0x30] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x30, environ)")
OneGadget::Gadget.add(build_id, 234315,
constraints: ["ebx is the GOT address of libc", "[esp+0x34] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x34, environ)")
OneGadget::Gadget.add(build_id, 234322,
constraints: ["ebx is the GOT address of libc", "[esp+0x38] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x38, environ)")
OneGadget::Gadget.add(build_id, 234357,
constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp]] == NULL || [esp] == NULL"],
effect: "execve(\"/bin/sh\", eax, [esp])")
OneGadget::Gadget.add(build_id, 234358,
constraints: ["ebx is the GOT address of libc", "[[esp]] == NULL || [esp] == NULL", "[[esp+0x4]] == NULL || [esp+0x4] == NULL"],
effect: "execve(\"/bin/sh\", [esp], [esp+0x4])")
OneGadget::Gadget.add(build_id, 384879,
constraints: ["ebx is the GOT address of libc", "eax == NULL"],
effect: "execl(\"/bin/sh\", eax)")
OneGadget::Gadget.add(build_id, 384880,
constraints: ["ebx is the GOT address of libc", "[esp] == NULL"],
effect: "execl(\"/bin/sh\", [esp])")
| 53.957447 | 150 | 0.586356 |
79a0cd3005b4db30bb933f89476ca00a806ba33c | 2,650 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'inspec/version'
Gem::Specification.new do |spec|
spec.name = 'inspec'
spec.version = Inspec::VERSION
spec.authors = ['Dominik Richter']
spec.email = ['[email protected]']
spec.summary = 'Infrastructure and compliance testing.'
spec.description = 'InSpec provides a framework for creating end-to-end infrastructure tests. You can use it for integration or even compliance testing. Create fully portable test profiles and use them in your workflow to ensure stability and security. Integrate InSpec in your change lifecycle for local testing, CI/CD, and deployment verification.'
spec.homepage = 'https://github.com/inspec/inspec'
spec.license = 'Apache-2.0'
# the gemfile and gemspec are necessary for appbundler so don't remove it
spec.files = %w{Gemfile inspec.gemspec README.md LICENSE} + Dir.glob(
'{bin,lib,etc}/**/*', File::FNM_DOTMATCH
).reject { |f| File.directory?(f) }
spec.executables = %w{inspec}
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
.reject { |f| File.directory?(f) || f =~ %r{lib/plugins/.*/test/} }
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.4'
spec.add_dependency 'train', '~> 2.0' # Inspec 4 must have train 2+
# Train plugins we ship with InSpec
spec.add_dependency 'train-habitat', '~> 0.1'
spec.add_dependency 'train-aws', '~> 0.1'
# Implementation dependencies
spec.add_dependency 'license-acceptance', '>= 0.2.13', '< 2.0'
spec.add_dependency 'thor', '~> 0.20'
spec.add_dependency 'json', '>= 1.8', '< 3.0'
spec.add_dependency 'method_source', '~> 0.8'
spec.add_dependency 'rubyzip', '~> 1.2', '>= 1.2.2'
spec.add_dependency 'rspec', '~> 3'
spec.add_dependency 'rspec-its', '~> 1.2'
spec.add_dependency 'pry', '~> 0'
spec.add_dependency 'hashie', '~> 3.4'
spec.add_dependency 'mixlib-log'
spec.add_dependency 'sslshake', '~> 1.2'
spec.add_dependency 'parallel', '~> 1.9'
spec.add_dependency 'faraday', '>=0.9.0'
spec.add_dependency 'tty-table', '~> 0.10'
spec.add_dependency 'tty-prompt', '~> 0.17'
# Used for Azure profile until integrated into train
spec.add_dependency 'faraday_middleware', '~> 0.12.2'
spec.add_dependency 'tomlrb', '~> 1.2'
spec.add_dependency 'addressable', '~> 2.4'
spec.add_dependency 'parslet', '~> 1.5'
spec.add_dependency 'semverse'
spec.add_dependency 'htmlentities'
spec.add_dependency 'multipart-post'
spec.add_dependency 'term-ansicolor'
end
| 44.915254 | 354 | 0.676226 |
d5b9903ea36b427289d2ad90d8b70678649a7eed | 493 | class TransactionsController < ApplicationController
def new
@transaction = Transaction.new
end
def create
@transaction = Transaction.new(transaction_params)
@transaction.user = current_user
if txid = @transaction.create_with_eth
redirect_to user_path(current_user), notice: "Transaction is created. TxHash: #{txid}"
else
render :new
end
end
private
def transaction_params
params.require(:transaction).permit(:to, :eth_value)
end
end
| 20.541667 | 92 | 0.720081 |
6216f189c20823ef45e88a6f6237654c044f00cf | 284 | Допустим(/^есть строк[иа] ссылки:$/) do |string|
@parser = Bukovina::Parsers::Link.new
@res = @parser.parse( YAML.load( string ) ) ; end
То(/^обработанные данные ссылки будут выглядеть как:$/) do |string|
expect( @res[ :link ].to_yaml.strip ).to be_eql( string.to_s ) ; end
| 40.571429 | 71 | 0.665493 |
ff9731993b7b5fc436089cac286ce53f1f3006fc | 717 | module Spree
class Calculator::FlatPercentTaxonTotal < Calculator
preference :flat_percent, :decimal, :default => 0
preference :taxon, :string, :default => ''
attr_accessible :preferred_flat_percent, :preferred_taxon
def self.description
I18n.t(:flat_percent_taxon)
end
def compute(object)
return unless object.present? and object.line_items.present?
item_total = 0.0
object.line_items.each do |line_item|
item_total += line_item.amount if line_item.product.taxons.where(:name => preferred_taxon).present?
end
value = item_total * BigDecimal(self.preferred_flat_percent.to_s) / 100.0
(value * 100).round.to_f / 100
end
end
end
| 29.875 | 107 | 0.695955 |
bb3466b46107ef03d765a2f547ba3e563377bb98 | 367 | class AddAlertMarkedThroughToVendors < ActiveRecord::Migration
def change
add_column :vendors, :alert_marked_through_text, :boolean, default: false
add_column :vendors, :alert_marked_through_app, :boolean, default: false
add_column :vendors, :alert_marked_through_flag, :boolean, default: true
remove_column :users, :alert_marked_through
end
end
| 40.777778 | 77 | 0.790191 |
395d6c07bd6771d3dcb97371357e92655bb88ca5 | 951 | cask 'remote-desktop-manager' do
version '5.4.0.0'
sha256 '04a460944353df93e1b75080e3f0fc6baa1a56780f0244cc22d520831d20ee74'
# devolutions.net was verified as official when first introduced to the cask
url "http://cdn.devolutions.net/download/Mac/Devolutions.RemoteDesktopManager.Mac.#{version}.dmg"
appcast 'http://cdn.devolutions.net/download/Mac/RemoteDesktopManager.xml'
name 'Remote Desktop Manager'
homepage 'https://mac.remotedesktopmanager.com/'
app 'Remote Desktop Manager.app'
zap trash: [
'~/Library/Application Support/Remote Desktop Manager',
'~/Library/Application Support/com.devolutions.remotedesktopmanager',
'~/Library/Caches/com.devolutions.remotedesktopmanager',
'~/Library/Preferences/com.devolutions.remotedesktopmanager.plist',
'~/Library/Saved Application State/com.devolutions.remotedesktopmanager.savedState',
]
end
| 45.285714 | 99 | 0.726604 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.