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
|
---|---|---|---|---|---|
283df6ba06970559bda57c14b8ec415fa2850f4b | 169 | require 'test_helper'
class SessionsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get login_path
assert_response :success
end
end
| 13 | 62 | 0.786982 |
2133c86567410fb969b54d490e44e5c0bb61d635 | 580 | # This class represents a Marathon Deployment step.
class Marathon::DeploymentStep < Marathon::Base
attr_reader :actions
# Create a new deployment step object.
# ++hash++: Hash returned by API, including 'actions'
def initialize(hash)
super(hash)
if hash.is_a?(Array)
@actions = info.map { |e| Marathon::DeploymentAction.new(e) }
else
@actions = (info[:actions] || []).map { |e| Marathon::DeploymentAction.new(e) }
end
end
def to_s
"Marathon::DeploymentStep { :actions => #{actions.map { |e| e.to_pretty_s }.join(',')} }"
end
end
| 26.363636 | 93 | 0.653448 |
ab739bec5c5449905956f3893f6082dbeb9f0d89 | 6,156 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Selenium
module WebDriver
module Remote
class Bridge
include Atoms
include BridgeHelper
PORT = 4444
COMMANDS = {
new_session: [:post, 'session'.freeze]
}.freeze
attr_accessor :context, :http, :file_detector
attr_reader :capabilities, :dialect
#
# Implements protocol handshake which:
#
# 1. Creates session with driver.
# 2. Sniffs response.
# 3. Based on the response, understands which dialect we should use.
#
# @return [OSS:Bridge, W3C::Bridge]
#
def self.handshake(**opts)
desired_capabilities = opts.delete(:desired_capabilities)
if desired_capabilities.is_a?(Symbol)
unless Remote::Capabilities.respond_to?(desired_capabilities)
raise Error::WebDriverError, "invalid desired capability: #{desired_capabilities.inspect}"
end
desired_capabilities = Remote::Capabilities.__send__(desired_capabilities)
end
bridge = new(opts)
capabilities = bridge.create_session(desired_capabilities)
case bridge.dialect
when :oss
Remote::OSS::Bridge.new(capabilities, bridge.session_id, opts)
when :w3c
Remote::W3C::Bridge.new(capabilities, bridge.session_id, opts)
else
raise WebDriverError, 'cannot understand dialect'
end
end
#
# Initializes the bridge with the given server URL
# @param [Hash] opts options for the driver
# @option opts [String] :url url for the remote server
# @option opts [Object] :http_client an HTTP client instance that implements the same protocol as Http::Default
# @option opts [Capabilities] :desired_capabilities an instance of Remote::Capabilities describing the capabilities you want
# @api private
#
def initialize(opts = {})
opts = opts.dup
http_client = opts.delete(:http_client) { Http::Default.new }
url = opts.delete(:url) { "http://#{Platform.localhost}:#{PORT}/wd/hub" }
unless opts.empty?
raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}"
end
uri = url.is_a?(URI) ? url : URI.parse(url)
uri.path += '/' unless uri.path =~ %r{\/$}
http_client.server_url = uri
@http = http_client
@file_detector = nil
end
#
# Creates session handling both OSS and W3C dialects.
#
def create_session(desired_capabilities)
response = execute(:new_session, {}, merged_capabilities(desired_capabilities))
@session_id = response['sessionId']
oss_status = response['status']
value = response['value']
if value.is_a?(Hash)
@session_id = value['sessionId'] if value.key?('sessionId')
if value.key?('capabilities')
value = value['capabilities']
elsif value.key?('value')
value = value['value']
end
end
unless @session_id
raise Error::WebDriverError, 'no sessionId in returned payload'
end
if oss_status
WebDriver.logger.info 'Detected OSS dialect.'
@dialect = :oss
Capabilities.json_create(value)
else
WebDriver.logger.info 'Detected W3C dialect.'
@dialect = :w3c
W3C::Capabilities.json_create(value)
end
end
#
# Returns the current session ID.
#
def session_id
@session_id || raise(Error::WebDriverError, 'no current session exists')
end
def browser
@browser ||= begin
name = @capabilities.browser_name
name ? name.tr(' ', '_').to_sym : 'unknown'
end
end
private
#
# executes a command on the remote server.
#
# @return [WebDriver::Remote::Response]
#
def execute(command, opts = {}, command_hash = nil)
verb, path = commands(command) || raise(ArgumentError, "unknown command: #{command.inspect}")
path = path.dup
path[':session_id'] = session_id if path.include?(':session_id')
begin
opts.each { |key, value| path[key.inspect] = escaper.escape(value.to_s) }
rescue IndexError
raise ArgumentError, "#{opts.inspect} invalid for #{command.inspect}"
end
WebDriver.logger.info("-> #{verb.to_s.upcase} #{path}")
http.call(verb, path, command_hash)
end
def escaper
@escaper ||= defined?(URI::Parser) ? URI::DEFAULT_PARSER : URI
end
def commands(command)
raise NotImplementedError unless command == :new_session
COMMANDS[command]
end
def merged_capabilities(oss_capabilities)
w3c_capabilities = W3C::Capabilities.from_oss(oss_capabilities)
{
desiredCapabilities: oss_capabilities,
capabilities: {
firstMatch: [w3c_capabilities]
}
}
end
end # Bridge
end # Remote
end # WebDriver
end # Selenium
| 32.230366 | 132 | 0.597953 |
f76a229d0ee08a59e529d10530959b047f0aec13 | 314 | require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'
describe "Kernel#getc" do
it "is a private method" do
Kernel.private_instance_methods.should include("getc")
end
end
describe "Kernel.getc" do
it "needs to be reviewed for spec completeness"
end
| 24.153846 | 58 | 0.738854 |
1c1637a53816c174d4367272cd65ad53ae87a0e3 | 2,354 | require "spec_helper"
describe Volunteer do
describe '#name' do
it 'returns the name of the volunteer' do
test_volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
expect(test_volunteer.name).to eq 'Jane'
end
end
describe '#project_id' do
it 'returns the project_id of the volunteer' do
test_volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
expect(test_volunteer.project_id).to eq 1
end
end
describe '#==' do
it 'checks for equality based on the name of a volunteer' do
volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer2 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
expect(volunteer1 == volunteer2).to eq true
end
end
context '.all' do
it 'is empty to start' do
expect(Volunteer.all).to eq []
end
it 'returns all volunteers' do
volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer1.save
volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil})
volunteer2.save
expect(Volunteer.all).to eq [volunteer1, volunteer2]
end
end
describe '#save' do
it 'adds a volunteer to the database' do
volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer1.save
expect(Volunteer.all).to eq [volunteer1]
end
end
describe '.find' do
it 'returns a volunteer by id' do
volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer1.save
volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil})
volunteer2.save
expect(Volunteer.find(volunteer1.id)).to eq volunteer1
end
end
context '#delete' do
it 'allows a user to delete a volunteer' do
volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer.save
volunteer.delete
expect(Volunteer.all).to eq []
end
end
describe '#update' do
it 'allows a user to update a volunteer' do
volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil})
volunteer.save
volunteer.update({:name => "Zinfira", :project_id => 1, :id => nil})
expect(volunteer.name).to eq 'Zinfira'
end
end
end | 30.973684 | 85 | 0.613424 |
79704730a43c2190a7be509dbe0e9c5b625195eb | 3,754 | class Logstash < Formula
desc "Tool for managing events and logs"
homepage "https://www.elastic.co/products/logstash"
url "https://github.com/elastic/logstash/archive/v7.13.1.tar.gz"
sha256 "b88a5d571833c7e72474246acff8f773dee2093acf4f2efafc20ea2f693e23c0"
license "Apache-2.0"
version_scheme 1
head "https://github.com/elastic/logstash.git"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any, big_sur: "3366ad5ba5301c65f9ae308d5ee58ae52271b9c9b4ddfe461f538c134e9ef2c1"
sha256 cellar: :any, catalina: "d90d34ec2b6e1957a17c44bfbc671fdc42ac648adc14db419f4092aee28b2383"
sha256 cellar: :any, mojave: "9e181d1f93c952eb530860dbdcd58a9cdd2133146faed8b5d6db6b1d15d5e3d8"
end
depends_on "openjdk@11"
uses_from_macos "ruby" => :build
def install
# remove non open source files
rm_rf "x-pack"
ENV["OSS"] = "true"
# Build the package from source
system "rake", "artifact:no_bundle_jdk_tar"
# Extract the package to the current directory
mkdir "tar"
system "tar", "--strip-components=1", "-xf", Dir["build/logstash-*.tar.gz"].first, "-C", "tar"
cd "tar"
inreplace "bin/logstash",
%r{^\. "\$\(cd `dirname \$\{SOURCEPATH\}`/\.\.; pwd\)/bin/logstash\.lib\.sh"},
". #{libexec}/bin/logstash.lib.sh"
inreplace "bin/logstash-plugin",
%r{^\. "\$\(cd `dirname \$0`/\.\.; pwd\)/bin/logstash\.lib\.sh"},
". #{libexec}/bin/logstash.lib.sh"
inreplace "bin/logstash.lib.sh",
/^LOGSTASH_HOME=.*$/,
"LOGSTASH_HOME=#{libexec}"
libexec.install Dir["*"]
# Move config files into etc
(etc/"logstash").install Dir[libexec/"config/*"]
(libexec/"config").rmtree
bin.install libexec/"bin/logstash", libexec/"bin/logstash-plugin"
bin.env_script_all_files(libexec/"bin", Language::Java.overridable_java_home_env("11"))
end
def post_install
ln_s etc/"logstash", libexec/"config"
end
def caveats
<<~EOS
Configuration files are located in #{etc}/logstash/
EOS
end
plist_options manual: "logstash"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/logstash</string>
</array>
<key>EnvironmentVariables</key>
<dict>
</dict>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/logstash.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/logstash.log</string>
</dict>
</plist>
EOS
end
test do
# workaround https://github.com/elastic/logstash/issues/6378
(testpath/"config").mkpath
["jvm.options", "log4j2.properties", "startup.options"].each do |f|
cp prefix/"libexec/config/#{f}", testpath/"config"
end
(testpath/"config/logstash.yml").write <<~EOS
path.queue: #{testpath}/queue
EOS
(testpath/"data").mkpath
(testpath/"logs").mkpath
(testpath/"queue").mkpath
data = "--path.data=#{testpath}/data"
logs = "--path.logs=#{testpath}/logs"
settings = "--path.settings=#{testpath}/config"
output = pipe_output("#{bin}/logstash -e '' #{data} #{logs} #{settings} --log.level=fatal", "hello world\n")
assert_match "hello world", output
end
end
| 31.283333 | 112 | 0.617208 |
01c80432f134f28cf40935d11b6c5eac5b7824e5 | 2,883 | # frozen_string_literal: true
require "rails_helper"
describe Eve::CorporationImporter do
let(:corporation_id) { double }
subject { described_class.new(corporation_id) }
it { should be_a(Eve::BaseImporter) }
describe "#import" do
before { expect(subject).to receive(:configure_middlewares) }
before { expect(subject).to receive(:configure_etag) }
let(:eve_corporation) { instance_double(Eve::Corporation) }
before { expect(Eve::Corporation).to receive(:find_or_initialize_by).with(corporation_id: corporation_id).and_return(eve_corporation) }
context "when etag cache hit" do
let(:esi) { instance_double(EveOnline::ESI::Corporation, not_modified?: true) }
before { expect(subject).to receive(:esi).and_return(esi) }
specify { expect { subject.import }.not_to raise_error }
end
context "when etag cache miss" do
context "when eve corporation found" do
let(:json) { double }
let(:esi) { instance_double(EveOnline::ESI::Corporation, not_modified?: false, as_json: json) }
before { expect(subject).to receive(:esi).and_return(esi).twice }
before { expect(eve_corporation).to receive(:update!).with(json) }
before { expect(subject).to receive(:update_etag) }
specify { expect { subject.import }.not_to raise_error }
end
context "when eve group not found" do
before { expect(subject).to receive(:esi).and_raise(EveOnline::Exceptions::ResourceNotFound) }
let(:eve_etag) { instance_double(Eve::Etag) }
before { expect(subject).to receive(:etag).and_return(eve_etag) }
before do
#
# Rails.logger.info("EveOnline::Exceptions::ResourceNotFound: Eve Corporation ID #{corporation_id}")
#
expect(Rails).to receive(:logger) do
double.tap do |a|
expect(a).to receive(:info).with("EveOnline::Exceptions::ResourceNotFound: Eve Corporation ID #{corporation_id}")
end
end
end
before { expect(eve_etag).to receive(:destroy!) }
before { expect(eve_corporation).to receive(:destroy!) }
specify { expect { subject.import }.not_to raise_error }
end
end
end
describe "#esi" do
context "when @esi is set" do
let(:esi) { instance_double(EveOnline::ESI::Corporation) }
before { subject.instance_variable_set(:@esi, esi) }
specify { expect(subject.esi).to eq(esi) }
end
context "when @esi not set" do
let(:esi) { instance_double(EveOnline::ESI::Corporation) }
before { expect(EveOnline::ESI::Corporation).to receive(:new).with(corporation_id: corporation_id).and_return(esi) }
specify { expect(subject.esi).to eq(esi) }
specify { expect { subject.esi }.to change { subject.instance_variable_get(:@esi) }.from(nil).to(esi) }
end
end
end
| 31.681319 | 139 | 0.659036 |
ab8da2ff36daa572b4fbeb70d3651d3962272a2e | 127 | require 'test_helper'
class FavoritesListTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.875 | 49 | 0.716535 |
2627c3afa98d3a6f0e3f18c26b480a79d78d667e | 6,921 | require "rails_helper"
require "controller_spec_helper"
RSpec.describe FacilityAccountUsersController, if: SettingsHelper.feature_on?(:edit_accounts) do
render_views
before(:all) { create_users }
before(:each) do
@authable = FactoryBot.create(:facility)
@account = create_nufs_account_with_owner
end
context "user_search" do
before(:each) do
@method = :get
@action = :user_search
@params = { facility_id: @authable.url_name, account_id: @account.id }
end
it_should_require_login
it_should_deny :staff
it_should_allow_all facility_managers do
expect(assigns(:account)).to eq(@account)
is_expected.to render_template("user_search")
end
end
context "new" do
before(:each) do
@method = :get
@action = :new
@params = { facility_id: @authable.url_name, account_id: @account.id, user_id: @guest.id }
end
it_should_require_login
it_should_deny :staff
it_should_allow_all facility_managers do
expect(assigns(:account)).to eq(@account)
expect(assigns(:user)).to eq(@guest)
expect(assigns(:account_user)).to be_kind_of AccountUser
expect(assigns(:account_user)).to be_new_record
is_expected.to render_template("new")
end
end
context "create" do
before(:each) do
@method = :post
@action = :create
@params = {
facility_id: @authable.url_name,
account_id: @account.id,
user_id: @purchaser.id,
account_user: { user_role: AccountUser::ACCOUNT_PURCHASER },
}
end
it_should_require_login
it_should_deny :staff
it_should_allow_all facility_managers do |user|
expect(assigns(:account)).to eq(@account)
expect(assigns(:user)).to eq(@purchaser)
expect(assigns(:account_user).user_role).to eq(AccountUser::ACCOUNT_PURCHASER)
expect(assigns(:account_user).user).to eq(@purchaser)
expect(assigns(:account_user).created_by).to eq(user.id)
is_expected.to set_flash
assert_redirected_to facility_account_members_path(@authable, @account)
end
context "changing roles" do
before :each do
maybe_grant_always_sign_in :director
end
context "with an existing owner" do
before :each do
@params[:account_user][:user_role] = AccountUser::ACCOUNT_OWNER
expect(@account.account_users.owners).to be_one
expect(@account.owner_user).to eq(@owner)
do_request
end
it "changes the owner of an account" do
expect(assigns(:account)).to eq(@account)
expect(assigns(:user)).to eq(@purchaser)
expect(assigns(:account_user).user_role).to eq(AccountUser::ACCOUNT_OWNER)
expect(assigns(:account_user).user).to eq(@purchaser)
expect(assigns(:account_user).created_by).to eq(@director.id)
expect(@account.reload.account_users.owners.count).to eq(1)
expect(@account.deleted_account_users.count).to eq(1)
expect(assigns(:account).reload.owner_user).to eq(@purchaser)
is_expected.to set_flash
assert_redirected_to facility_account_members_path(@authable, @account)
end
end
context "with a missing owner" do
before :each do
@account_user = @account.owner
AccountUser.delete(@account_user.id)
@params[:account_user][:user_role] = AccountUser::ACCOUNT_OWNER
expect(@account.account_users.owners).not_to be_any
do_request
end
it "adds the owner" do
expect(assigns(:account)).to eq(@account)
expect(@account.account_users.owners.count).to eq(1)
is_expected.to set_flash
assert_redirected_to facility_account_members_path(@authable, @account)
end
end
context "changing a user's role" do
context "from business admin to purchaser" do
before :each do
@business_admin = FactoryBot.create(:user)
FactoryBot.create(:account_user, account: @account, user: @business_admin, user_role: AccountUser::ACCOUNT_ADMINISTRATOR)
@params.merge!(
account_id: @account.id,
user_id: @business_admin.id,
account_user: { user_role: AccountUser::ACCOUNT_PURCHASER },
)
expect(@account.account_users.purchasers).not_to be_any
expect(@account.account_users.business_administrators).to be_one
do_request
end
it "should change the role" do
expect(assigns(:account)).to eq(@account)
expect(@account.account_users.purchasers.map(&:user)).to eq([@business_admin])
expect(@account.account_users.business_administrators).not_to be_any
is_expected.to set_flash
assert_redirected_to facility_account_members_path(@authable, @account)
end
end
context "from owner to purchaser" do
before :each do
@params[:user_id] = @owner.id
@params[:account_user][:user_role] = AccountUser::ACCOUNT_PURCHASER
expect(@account.account_users.owners.map(&:user)).to eq([@owner])
expect(@account.account_users.purchasers).not_to be_any
end
it "should be prevented" do
do_request
expect(assigns(:account)).to eq(@account)
expect(assigns(:account).owner_user).to eq(@owner)
expect(@account.account_users.owners.map(&:user)).to eq([@owner])
expect(@account.account_users.purchasers).not_to be_any
expect(flash[:error]).to be_present
expect(response).to render_template :new
end
it "should not send an email" do
expect(Notifier).not_to receive(:user_update)
do_request
end
end
end
end
end
context "destroy" do
before(:each) do
@method = :delete
@action = :destroy
@account_user = FactoryBot.create(:account_user, user: @purchaser,
account: @account,
user_role: AccountUser::ACCOUNT_PURCHASER,
created_by: @admin.id)
@params = { facility_id: @authable.url_name, account_id: @account.id, id: @account_user.id }
end
it_should_require_login
it_should_deny :staff
it_should_allow_all facility_managers do |user|
expect(assigns(:account)).to eq(@account)
expect(assigns(:account_user)).to eq(@account_user)
expect(assigns(:account_user).deleted_at).not_to be_nil
expect(assigns(:account_user).deleted_by).to eq(user.id)
is_expected.to set_flash
assert_redirected_to facility_account_members_path(@authable, @account)
end
end
end
| 32.957143 | 133 | 0.636613 |
08e0190f1470bd3c4e0efa2251554ec154bdbd20 | 1,741 | #
# Author:: Seth Chisamore (<[email protected]>)
# Copyright:: Copyright (c) 2013-2018 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
shared_examples "serializable" do |version_strings|
describe "#to_s" do
version_strings.each do |v|
it "reconstructs the initial input for #{v}" do
expect(described_class.new(v).to_s).to eq(v)
end # it
end # version_strings
end # describe
describe "#to_semver_string" do
version_strings.each do |v|
it "generates a semver version string for #{v}" do
subject = described_class.new(v)
string = subject.to_semver_string
semver = Mixlib::Versioning::Format::SemVer.new(string)
expect(string).to eq semver.to_s
end # it
end # version_strings
end # describe
describe "#to_rubygems_string" do
version_strings.each do |v|
it "generates a rubygems version string for #{v}" do
subject = described_class.new(v)
string = subject.to_rubygems_string
rubygems = Mixlib::Versioning::Format::Rubygems.new(string)
expect(string).to eq rubygems.to_s
end # it
end # version_strings
end # describe
end # shared_examples
| 34.82 | 74 | 0.700172 |
87e1fc7efa739b11c08cf5fb98e50cd7be1bd001 | 1,924 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Elasticsearch
module API
module MachineLearning
module Actions
# Updates certain properties of an anomaly detection job.
#
# @option arguments [String] :job_id The ID of the job to create
# @option arguments [Hash] :headers Custom HTTP headers
# @option arguments [Hash] :body The job update settings (*Required*)
#
# @see https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-update-job.html
#
def update_job(arguments = {})
raise ArgumentError, "Required argument 'body' missing" unless arguments[:body]
raise ArgumentError, "Required argument 'job_id' missing" unless arguments[:job_id]
headers = arguments.delete(:headers) || {}
arguments = arguments.clone
_job_id = arguments.delete(:job_id)
method = Elasticsearch::API::HTTP_POST
path = "_ml/anomaly_detectors/#{Utils.__listify(_job_id)}/_update"
params = {}
body = arguments[:body]
perform_request(method, path, params, body, headers).body
end
end
end
end
end
| 37.72549 | 97 | 0.68815 |
2839a622afb349d249e89793b61fd90fb286245a | 4,960 | require 'spec_helper'
describe 'taxa/overview/show' do
before(:all) do
Language.create_english
UriType.create_enumerated
Vetted.create_enumerated
Visibility.create_enumerated
License.create_enumerated
ContentPartnerStatus.create_enumerated
end
before(:each) do
# TODO - generalize these extends for the other view specs.
taxon_concept = double(TaxonConcept)
taxon_concept.stub(:id) { 1 }
taxon_data = double(TaxonData, distinct_predicates: [])
data = []
data.stub(:categorize) { {} }
data.stub(:count) { 0 }
data.stub(:blank?) { true }
overview = double(TaxonOverview)
overview.stub(:taxon_concept) { taxon_concept }
overview.stub(:media) { [] }
overview.stub(:map?) { false }
overview.stub(:iucn_status) { 'lucky' }
overview.stub(:iucn_url) { 'http://iucn.org' }
overview.stub(:summary?) { false }
overview.stub(:details?) { false }
overview.stub(:collections_count) { 0 }
overview.stub(:communities_count) { 0 }
overview.stub(:classification_filter?) { false }
overview.stub(:classification_curated?) { false }
overview.stub(:classifications_count) { 0 }
overview.stub(:curators_count) { 0 }
overview.stub(:hierarchy_entry) { nil } # This is a little dangerous, but it avoids rendinger the entire node partial..
overview.stub(:activity_log) { [].paginate } # CHEAT! :D
taxon_page = double(TaxonPage, id: 123, scientific_name: 'Aus bus')
taxon_page.stub(:data) { taxon_data }
assign(:taxon_page, taxon_page)
assign(:overview, double(TaxonOverview))
assign(:overview_data, { })
assign(:range_data, { })
assign(:assistive_section_header, 'assist my overview')
assign(:rel_canonical_href, 'some canonical stuff')
assign(:overview, overview)
view.stub(:meta_open_graph_data).and_return([])
view.stub(:tweet_data).and_return({})
view.stub(:current_language) { Language.default }
view.stub(:current_url) { 'http://yes.we/really_have/this-helper.method' }
end
context 'logged out' do
before(:each) do
user = EOL::AnonymousUser.new(Language.default)
view.stub(:current_user) { user }
view.stub(:logged_in?) { false }
end
it "should NOT show quick facts when the user doesn't have access (FOR NOW)" do
render
expect(rendered).to_not match /#{I18n.t(:data_summary_header_with_count, count: 0)}/
end
end
context 'logged with see_data permission' do
before(:each) do
user = double(User)
user.stub(:min_curator_level?) { false }
user.stub(:watch_collection) { nil }
user.stub(:logo_url) { 'whatever' }
view.stub(:current_user) { user }
view.stub(:logged_in?) { false }
allow(EolConfig).to receive(:data?) { true }
end
it "should show quick facts" do
point = DataPointUri.gen
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview){{ point => { data_point_uris: [ point ]} }}
assign(:data, taxon_page)
render
expect(rendered).to match /#{I18n.t(:data_summary_header_with_count, count: 0)}/
end
it "should have a show more link when a row has more data" do
point = DataPointUri.gen
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview){{ point => { data_point_uris: [ point ], show_more: true } }}
assign(:data, taxon_page)
render
expect(rendered).to have_tag('td a', text: 'more')
end
it "should show statistical method" do
point = DataPointUri.gen(statistical_method: 'Itsmethod')
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview) {{ point => { data_point_uris: [ point ] } }}
assign(:data, taxon_page)
render
expect(rendered).to have_tag('span.stat', text: /Itsmethod/)
end
it "should show life stage" do
point = DataPointUri.gen(life_stage: 'Itslifestage')
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview) {{ point => { data_point_uris: [ point ] } }}
assign(:data, taxon_page)
render
expect(rendered).to have_tag('span.stat', text: /Itslifestage/)
end
it "should show sex" do
point = DataPointUri.gen(sex: 'Itssex')
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview) {{ point => { data_point_uris: [ point ] } }}
assign(:data, taxon_page)
render
expect(rendered).to have_tag('span.stat', text: /Itssex/)
end
it "should show combinations of context modifiers" do
point = DataPointUri.gen(statistical_method: 'Itsmethod', life_stage: 'Itslifestage', sex: 'Itssex')
taxon_page = double(TaxonPage)
taxon_page.stub(:get_data_for_overview) {{ point => { data_point_uris: [ point ] } }}
assign(:data, taxon_page)
render
expect(rendered).to have_tag('span.stat', text: /Itsmethod, Itslifestage, Itssex/)
end
end
end
| 35.942029 | 123 | 0.665726 |
ab56f38f0c1272ccb078f83f863fe60d38ae901e | 744 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Metrics::RackMiddleware do
let(:app) { double(:app) }
let(:middleware) { described_class.new(app) }
let(:env) { { 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/foo' } }
describe '#call' do
it 'tracks a transaction' do
expect(app).to receive(:call).with(env).and_return('yay')
expect(middleware.call(env)).to eq('yay')
end
it 'tracks any raised exceptions' do
expect(app).to receive(:call).with(env).and_raise(RuntimeError)
expect_any_instance_of(Gitlab::Metrics::Transaction)
.to receive(:add_event).with(:rails_exception)
expect { middleware.call(env) }.to raise_error(RuntimeError)
end
end
end
| 25.655172 | 70 | 0.673387 |
62165bc43a70f715d385d37bf11d2a4366e90cea | 49 | require 'creature'
class Troll < Creature
end
| 7 | 22 | 0.734694 |
b98efc732ca0ef17d716ecef5568c4016c44ce14 | 42,897 | require 'spec_helper'
describe GenericFile, :type => :model do
let(:user) { FactoryGirl.find_or_create(:jill) }
before(:each) do
@file = GenericFile.new
@file.apply_depositor_metadata(user.user_key)
end
describe "created for someone (proxy)" do
before do
@transfer_to = FactoryGirl.find_or_create(:jill)
end
after do
@file.destroy
end
it "transfers the request" do
@file.on_behalf_of = @transfer_to.user_key
stub_job = double('change depositor job')
allow(ContentDepositorChangeEventJob).to receive(:new).and_return(stub_job)
expect(Sufia.queue).to receive(:push).with(stub_job).once.and_return(true)
@file.save!
end
end
describe "delegations" do
before do
@file.proxy_depositor = "[email protected]"
end
it "should include proxies" do
expect(@file).to respond_to(:relative_path)
expect(@file).to respond_to(:depositor)
expect(@file.proxy_depositor).to eq '[email protected]'
end
end
subject { GenericFile.new }
before do
subject.apply_depositor_metadata('jcoyne')
end
describe '#to_s' do
it 'uses the provided titles' do
subject.title = ["Hello", "World"]
expect(subject.to_s).to eq("Hello | World")
end
it 'falls back on label if no titles are given' do
subject.title = []
subject.label = 'Spam'
expect(subject.to_s).to eq("Spam")
end
it 'with no label or titles it is "No Title"' do
subject.title = []
subject.label = nil
expect(subject.to_s).to eq("No Title")
end
end
describe "assign_pid" do
it "should use the noid id service" do
expect_any_instance_of(Rubydora::Fc3Service).to_not receive(:next_pid)
GenericFile.assign_pid(nil)
end
end
describe "mime type recognition" do
context "when image?" do
it "should be true for jpeg2000" do
subject.mime_type = 'image/jp2'
expect(subject).to be_image
end
it "should be true for jpeg" do
subject.mime_type = 'image/jpg'
expect(subject).to be_image
end
it "should be true for png" do
subject.mime_type = 'image/png'
expect(subject).to be_image
end
it "should be true for tiff" do
subject.mime_type = 'image/tiff'
expect(subject).to be_image
end
end
context "when pdf?" do
it "should be true for pdf" do
subject.mime_type = 'application/pdf'
expect(subject).to be_pdf
end
end
context "when audio?" do
it "should be true for wav" do
subject.mime_type = 'audio/x-wave'
expect(subject).to be_audio
subject.mime_type = 'audio/x-wav'
expect(subject).to be_audio
end
it "should be true for mpeg" do
subject.mime_type = 'audio/mpeg'
expect(subject).to be_audio
subject.mime_type = 'audio/mp3'
expect(subject).to be_audio
end
it "should be true for ogg" do
subject.mime_type = 'audio/ogg'
expect(subject).to be_audio
end
end
context "when video?" do
it "should be true for avi" do
subject.mime_type = 'video/avi'
expect(subject).to be_video
end
it "should be true for webm" do
subject.mime_type = 'video/webm'
expect(subject).to be_video
end
it "should be true for mpeg" do
subject.mime_type = 'video/mp4'
expect(subject).to be_video
subject.mime_type = 'video/mpeg'
expect(subject).to be_video
end
it "should be true for quicktime" do
subject.mime_type = 'video/quicktime'
expect(subject).to be_video
end
it "should be true for mxf" do
subject.mime_type = 'application/mxf'
expect(subject).to be_video
end
end
end
describe "visibility" do
it "should not be changed when it's new" do
expect(subject).not_to be_visibility_changed
end
it "should be changed when it has been changed" do
subject.visibility= 'open'
expect(subject).to be_visibility_changed
end
it "should not be changed when it's set to its previous value" do
subject.visibility= 'restricted'
expect(subject).not_to be_visibility_changed
end
end
describe "attributes" do
it "should have rightsMetadata" do
expect(subject.rightsMetadata).to be_instance_of ParanoidRightsDatastream
end
it "should have properties datastream for depositor" do
expect(subject.properties).to be_instance_of PropertiesDatastream
end
it "should have apply_depositor_metadata" do
expect(subject.rightsMetadata.edit_access).to eq(['jcoyne'])
expect(subject.depositor).to eq('jcoyne')
end
it "should have a set of permissions" do
subject.read_groups=['group1', 'group2']
subject.edit_users=['user1']
subject.read_users=['user2', 'user3']
expect(subject.permissions).to eq([{type: "group", access: "read", name: "group1"},
{type: "group", access: "read", name: "group2"},
{type: "user", access: "read", name: "user2"},
{type: "user", access: "read", name: "user3"},
{type: "user", access: "edit", name: "user1"}])
end
describe "updating permissions" do
it "should create new group permissions" do
subject.permissions = {new_group_name: {'group1'=>'read'}}
expect(subject.permissions).to eq([{type: "group", access: "read", name: "group1"},
{type: "user", access: "edit", name: "jcoyne"}])
end
it "should create new user permissions" do
subject.permissions = {new_user_name: {'user1'=>'read'}}
expect(subject.permissions).to eq([{type: "user", access: "read", name: "user1"},
{type: "user", access: "edit", name: "jcoyne"}])
end
it "should not replace existing groups" do
subject.permissions = {new_group_name: {'group1' => 'read'}}
subject.permissions = {new_group_name: {'group2' => 'read'}}
expect(subject.permissions).to eq([{type: "group", access: "read", name: "group1"},
{type: "group", access: "read", name: "group2"},
{type: "user", access: "edit", name: "jcoyne"}])
end
it "should not replace existing users" do
subject.permissions = {new_user_name:{'user1'=>'read'}}
subject.permissions = {new_user_name:{'user2'=>'read'}}
expect(subject.permissions).to eq([{type: "user", access: "read", name: "user1"},
{type: "user", access: "read", name: "user2"},
{type: "user", access: "edit", name: "jcoyne"}])
end
it "should update permissions on existing users" do
subject.permissions = {new_user_name:{'user1'=>'read'}}
subject.permissions = {user:{'user1'=>'edit'}}
expect(subject.permissions).to eq([{type: "user", access: "edit", name: "user1"},
{type: "user", access: "edit", name: "jcoyne"}])
end
it "should update permissions on existing groups" do
subject.permissions = {new_group_name:{'group1'=>'read'}}
subject.permissions = {group:{'group1'=>'edit'}}
expect(subject.permissions).to eq([{type: "group", access: "edit", name: "group1"},
{type: "user", access: "edit", name: "jcoyne"}])
end
end
it "should have a characterization datastream" do
expect(subject.characterization).to be_kind_of FitsDatastream
end
it "should have a dc desc metadata" do
expect(subject.descMetadata).to be_kind_of GenericFileRdfDatastream
end
it "should have content datastream" do
subject.add_file(File.open(fixture_path + '/world.png'), 'content', 'world.png')
expect(subject.content).to be_kind_of FileContentDatastream
end
end
describe "delegations" do
it "should delegate methods to properties metadata" do
expect(subject).to respond_to(:relative_path)
expect(subject).to respond_to(:depositor)
end
it "should delegate methods to descriptive metadata" do
expect(subject).to respond_to(:related_url)
expect(subject).to respond_to(:based_near)
expect(subject).to respond_to(:part_of)
expect(subject).to respond_to(:contributor)
expect(subject).to respond_to(:creator)
expect(subject).to respond_to(:title)
expect(subject).to respond_to(:description)
expect(subject).to respond_to(:publisher)
expect(subject).to respond_to(:date_created)
expect(subject).to respond_to(:date_uploaded)
expect(subject).to respond_to(:date_modified)
expect(subject).to respond_to(:subject)
expect(subject).to respond_to(:language)
expect(subject).to respond_to(:rights)
expect(subject).to respond_to(:resource_type)
expect(subject).to respond_to(:identifier)
end
it "should delegate methods to characterization metadata" do
expect(subject).to respond_to(:format_label)
expect(subject).to respond_to(:mime_type)
expect(subject).to respond_to(:file_size)
expect(subject).to respond_to(:last_modified)
expect(subject).to respond_to(:filename)
expect(subject).to respond_to(:original_checksum)
expect(subject).to respond_to(:well_formed)
expect(subject).to respond_to(:file_title)
expect(subject).to respond_to(:file_author)
expect(subject).to respond_to(:page_count)
end
it "should redefine to_param to make redis keys more recognizable" do
expect(subject.to_param).to eq(subject.noid)
end
describe "that have been saved" do
# This file has no content, so it doesn't characterize
# before(:each) do
# Sufia.queue.should_receive(:push).once
# end
after(:each) do
unless subject.inner_object.class == ActiveFedora::UnsavedDigitalObject
begin
subject.delete
rescue ActiveFedora::ObjectNotFoundError
# do nothing
end
end
end
it "should have activity stream-related methods defined" do
subject.save
f = subject.reload
expect(f).to respond_to(:stream)
expect(f).to respond_to(:events)
expect(f).to respond_to(:create_event)
expect(f).to respond_to(:log_event)
end
it "should be able to set values via delegated methods" do
subject.related_url = ["http://example.org/"]
subject.creator = ["John Doe"]
subject.title = ["New work"]
subject.save
f = subject.reload
expect(f.related_url).to eq(["http://example.org/"])
expect(f.creator).to eq(["John Doe"])
expect(f.title).to eq(["New work"])
end
it "should be able to be added to w/o unexpected graph behavior" do
subject.creator = ["John Doe"]
subject.title = ["New work"]
subject.save
f = subject.reload
expect(f.creator).to eq(["John Doe"])
expect(f.title).to eq(["New work"])
f.creator = ["Jane Doe"]
f.title << "Newer work"
f.save
f = subject.reload
expect(f.creator).to eq(["Jane Doe"])
expect(f.title).to eq(["New work", "Newer work"])
end
end
end
describe "to_solr" do
before do
allow(subject).to receive(:pid).and_return('stubbed_pid')
subject.part_of = ["Arabiana"]
subject.contributor = ["Mohammad"]
subject.creator = ["Allah"]
subject.title = ["The Work"]
subject.description = ["The work by Allah"]
subject.publisher = ["Vertigo Comics"]
subject.date_created = ["1200-01-01"]
subject.date_uploaded = Date.parse("2011-01-01")
subject.date_modified = Date.parse("2012-01-01")
subject.subject = ["Theology"]
subject.language = ["Arabic"]
subject.rights = ["Wide open, buddy."]
subject.resource_type = ["Book"]
subject.identifier = ["urn:isbn:1234567890"]
subject.based_near = ["Medina, Saudi Arabia"]
subject.related_url = ["http://example.org/TheWork/"]
subject.mime_type = "image/jpeg"
subject.format_label = ["JPEG Image"]
subject.full_text.content = 'abcxyz'
end
it "supports to_solr" do
local = subject.to_solr
expect(local[Solrizer.solr_name("desc_metadata__part_of")]).to be_nil
expect(local[Solrizer.solr_name("desc_metadata__date_uploaded")]).to be_nil
expect(local[Solrizer.solr_name("desc_metadata__date_modified")]).to be_nil
expect(local[Solrizer.solr_name("desc_metadata__date_uploaded", :stored_sortable, type: :date)]).to eq '2011-01-01T00:00:00Z'
expect(local[Solrizer.solr_name("desc_metadata__date_modified", :stored_sortable, type: :date)]).to eq '2012-01-01T00:00:00Z'
expect(local[Solrizer.solr_name("desc_metadata__rights")]).to eq ["Wide open, buddy."]
expect(local[Solrizer.solr_name("desc_metadata__related_url")]).to eq ["http://example.org/TheWork/"]
expect(local[Solrizer.solr_name("desc_metadata__contributor")]).to eq ["Mohammad"]
expect(local[Solrizer.solr_name("desc_metadata__creator")]).to eq ["Allah"]
expect(local[Solrizer.solr_name("desc_metadata__title")]).to eq ["The Work"]
expect(local["desc_metadata__title_sim"]).to eq ["The Work"]
expect(local[Solrizer.solr_name("desc_metadata__description")]).to eq ["The work by Allah"]
expect(local[Solrizer.solr_name("desc_metadata__publisher")]).to eq ["Vertigo Comics"]
expect(local[Solrizer.solr_name("desc_metadata__subject")]).to eq ["Theology"]
expect(local[Solrizer.solr_name("desc_metadata__language")]).to eq ["Arabic"]
expect(local[Solrizer.solr_name("desc_metadata__date_created")]).to eq ["1200-01-01"]
expect(local[Solrizer.solr_name("desc_metadata__resource_type")]).to eq ["Book"]
expect(local[Solrizer.solr_name("file_format")]).to eq "jpeg (JPEG Image)"
expect(local[Solrizer.solr_name("desc_metadata__identifier")]).to eq ["urn:isbn:1234567890"]
expect(local[Solrizer.solr_name("desc_metadata__based_near")]).to eq ["Medina, Saudi Arabia"]
expect(local[Solrizer.solr_name("mime_type")]).to eq ["image/jpeg"]
expect(local["noid_tsi"]).to eq 'stubbed_pid'
expect(local['all_text_timv']).to eq('abcxyz')
end
end
it "should support multi-valued fields in solr" do
subject.tag = ["tag1", "tag2"]
expect { subject.save }.not_to raise_error
subject.delete
end
it "should support setting and getting the relative_path value" do
subject.relative_path = "documents/research/NSF/2010"
expect(subject.relative_path).to eq("documents/research/NSF/2010")
end
describe "create_thumbnail" do
before do
@f = GenericFile.new
@f.apply_depositor_metadata('mjg36')
end
after do
@f.delete
end
describe "with a video", if: Sufia.config.enable_ffmpeg do
before do
allow(@f).to receive_messages(mime_type: 'video/quicktime') #Would get set by the characterization job
@f.add_file(File.open("#{fixture_path}/countdown.avi", 'rb'), 'content', 'countdown.avi')
@f.save
end
it "should make a png thumbnail" do
@f.create_thumbnail
expect(@f.thumbnail.content.size).to eq(4768) # this is a bad test. I just want to show that it did something.
expect(@f.thumbnail.mimeType).to eq('image/png')
end
end
end
describe "trophies" do
before do
u = FactoryGirl.find_or_create(:jill)
@f = GenericFile.new.tap do |gf|
gf.apply_depositor_metadata(u)
gf.save!
end
@t = Trophy.create(user_id: u.id, generic_file_id: @f.noid)
end
it "should have a trophy" do
expect(Trophy.where(generic_file_id: @f.noid).count).to eq 1
end
it "should remove all trophies when file is deleted" do
@f.destroy
expect(Trophy.where(generic_file_id: @f.noid).count).to eq 0
end
end
describe "audit" do
before do
u = FactoryGirl.find_or_create(:jill)
f = GenericFile.new
f.add_file(File.open(fixture_path + '/world.png'), 'content', 'world.png')
f.apply_depositor_metadata(u)
f.save!
@f = f.reload
end
it "should schedule a audit job for each datastream" do
s0 = double('zero')
expect(AuditJob).to receive(:new).with(@f.pid, 'descMetadata', "descMetadata.0").and_return(s0)
expect(Sufia.queue).to receive(:push).with(s0)
s1 = double('one')
expect(AuditJob).to receive(:new).with(@f.pid, 'DC', "DC1.0").and_return(s1)
expect(Sufia.queue).to receive(:push).with(s1)
s2 = double('two')
expect(AuditJob).to receive(:new).with(@f.pid, 'RELS-EXT', "RELS-EXT.0").and_return(s2)
expect(Sufia.queue).to receive(:push).with(s2)
s3 = double('three')
expect(AuditJob).to receive(:new).with(@f.pid, 'rightsMetadata', "rightsMetadata.0").and_return(s3)
expect(Sufia.queue).to receive(:push).with(s3)
s4 = double('four')
expect(AuditJob).to receive(:new).with(@f.pid, 'properties', "properties.0").and_return(s4)
expect(Sufia.queue).to receive(:push).with(s4)
s5 = double('five')
expect(AuditJob).to receive(:new).with(@f.pid, 'content', "content.0").and_return(s5)
expect(Sufia.queue).to receive(:push).with(s5)
@f.audit!
end
it "should log a failing audit" do
@f.datastreams.each { |ds| allow(ds).to receive(:dsChecksumValid).and_return(false) }
allow(GenericFile).to receive(:run_audit).and_return(double(:respose, pass:1, created_at: '2005-12-20', pid: 'foo:123', dsid: 'foo', version: '1'))
@f.audit!
expect(ChecksumAuditLog.all).to be_all { |cal| cal.pass == 0 }
end
it "should log a passing audit" do
allow(GenericFile).to receive(:run_audit).and_return(double(:respose, pass:1, created_at: '2005-12-20', pid: 'foo:123', dsid: 'foo', version: '1'))
@f.audit!
expect(ChecksumAuditLog.all).to be_all { |cal| cal.pass == 1 }
end
it "should return true on audit_status" do
expect(@f.audit_stat).to be_truthy
end
end
describe "run_audit" do
before do
@f = GenericFile.new
@f.add_file(File.open(fixture_path + '/world.png'), 'content', 'world.png')
@f.apply_depositor_metadata('mjg36')
@f.save!
@version = @f.datastreams['content'].versions.first
@old = ChecksumAuditLog.create(pid: @f.pid, dsid: @version.dsid, version: @version.versionID, pass: 1, created_at: 2.minutes.ago)
@new = ChecksumAuditLog.create(pid: @f.pid, dsid: @version.dsid, version: @version.versionID, pass: 0)
end
it "should not prune failed audits" do
expect(@version).to receive(:dsChecksumValid).and_return(true)
GenericFile.run_audit(@version)
expect(@version).to receive(:dsChecksumValid).and_return(false)
GenericFile.run_audit(@version)
expect(@version).to receive(:dsChecksumValid).and_return(false)
GenericFile.run_audit(@version)
expect(@version).to receive(:dsChecksumValid).and_return(true)
GenericFile.run_audit(@version)
expect(@version).to receive(:dsChecksumValid).and_return(false)
GenericFile.run_audit(@version)
expect(@f.logs(@version.dsid).map(&:pass)).to eq([0, 1, 0, 0, 1, 0, 1])
end
end
describe "#related_files" do
let!(:f1) do
GenericFile.new.tap do |f|
f.apply_depositor_metadata('mjg36')
f.batch_id = batch_id
f.save
end
end
let!(:f2) do
GenericFile.new.tap do |f|
f.apply_depositor_metadata('mjg36')
f.batch_id = batch_id
f.save
end
end
let!(:f3) do
GenericFile.new.tap do |f|
f.apply_depositor_metadata('mjg36')
f.batch_id = batch_id
f.save
end
end
context "when the files belong to a batch" do
let(:batch) { Batch.create }
let(:batch_id) { batch.id }
it "shouldn't return itself from the related_files method" do
expect(f1.related_files).to match_array [f2, f3]
expect(f2.related_files).to match_array [f1, f3]
expect(f3.related_files).to match_array [f1, f2]
end
end
context "when there are no related files" do
let(:batch_id) { nil }
it "should return an empty array when there are no related files" do
expect(f1.related_files).to eq []
end
end
end
describe "noid integration" do
before(:all) do
@new_file = GenericFile.new(pid: 'ns:123')
@new_file.apply_depositor_metadata('mjg36')
@new_file.save
end
after(:all) do
@new_file.delete
end
it "should support the noid method" do
expect(@new_file).to respond_to(:noid)
end
it "should return the expected identifier" do
expect(@new_file.noid).to eq('123')
end
it "should work outside of an instance" do
new_id = Sufia::IdService.mint
noid = new_id.split(':').last
expect(Sufia::Noid.noidify(new_id)).to eq(noid)
end
end
describe "characterize" do
it "should return expected results when called", unless: $in_travis do
subject.add_file(File.open(fixture_path + '/world.png'), 'content', 'world.png')
subject.characterize
doc = Nokogiri::XML.parse(subject.characterization.content)
expect(doc.root.xpath('//ns:imageWidth/text()', {'ns'=>'http://hul.harvard.edu/ois/xml/ns/fits/fits_output'}).inner_text).to eq('50')
end
context "after characterization" do
before(:all) do
myfile = GenericFile.new
myfile.add_file(File.open(fixture_path + '/sufia/sufia_test4.pdf', 'rb').read, 'content', 'sufia_test4.pdf')
myfile.label = 'label123'
myfile.apply_depositor_metadata('mjg36')
# characterize method saves
myfile.characterize
@myfile = myfile.reload
end
after(:all) do
@myfile.destroy
end
it "should return expected results after a save" do
expect(@myfile.file_size).to eq(['218882'])
expect(@myfile.original_checksum).to eq(['5a2d761cab7c15b2b3bb3465ce64586d'])
end
it "should return a hash of all populated values from the characterization terminology" do
expect(@myfile.characterization_terms[:format_label]).to eq(["Portable Document Format"])
expect(@myfile.characterization_terms[:mime_type]).to eq("application/pdf")
expect(@myfile.characterization_terms[:file_size]).to eq(["218882"])
expect(@myfile.characterization_terms[:original_checksum]).to eq(["5a2d761cab7c15b2b3bb3465ce64586d"])
expect(@myfile.characterization_terms.keys).to include(:last_modified)
expect(@myfile.characterization_terms.keys).to include(:filename)
end
it "should append metadata from the characterization" do
expect(@myfile.title).to include("Microsoft Word - sample.pdf.docx")
expect(@myfile.filename[0]).to eq(@myfile.label)
end
it "should append each term only once" do
@myfile.append_metadata
expect(@myfile.format_label).to eq(["Portable Document Format"])
expect(@myfile.title).to include("Microsoft Word - sample.pdf.docx")
end
it 'includes extracted full-text content' do
expect(@myfile.full_text.content).to eq("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nMicrosoft Word - sample.pdf.docx\n\n\n \n \n\n \n\n \n\n \n\nThis PDF file was created using CutePDF. \n\nwww.cutepdf.com")
end
end
end
describe "label" do
it "should set the inner label" do
subject.label = "My New Label"
expect(subject.inner_object.label).to eq("My New Label")
end
end
context "with rightsMetadata" do
subject do
m = GenericFile.new()
m.rightsMetadata.update_permissions("person"=>{"person1"=>"read","person2"=>"read"}, "group"=>{'group-6' => 'read', "group-7"=>'read', 'group-8'=>'edit'})
#m.save
m
end
it "should have read groups accessor" do
expect(subject.read_groups).to eq(['group-6', 'group-7'])
end
it "should have read groups string accessor" do
expect(subject.read_groups_string).to eq('group-6, group-7')
end
it "should have read groups writer" do
subject.read_groups = ['group-2', 'group-3']
expect(subject.rightsMetadata.groups).to eq({'group-2' => 'read', 'group-3'=>'read', 'group-8' => 'edit'})
expect(subject.rightsMetadata.users).to eq({"person1"=>"read","person2"=>"read", 'jcoyne' => 'edit'})
end
it "should have read groups string writer" do
subject.read_groups_string = 'umg/up.dlt.staff, group-3'
expect(subject.rightsMetadata.groups).to eq({'umg/up.dlt.staff' => 'read', 'group-3'=>'read', 'group-8' => 'edit'})
expect(subject.rightsMetadata.users).to eq({"person1"=>"read","person2"=>"read", 'jcoyne' => 'edit'})
end
it "should only revoke eligible groups" do
subject.set_read_groups(['group-2', 'group-3'], ['group-6'])
# 'group-7' is not eligible to be revoked
expect(subject.rightsMetadata.groups).to eq({'group-2' => 'read', 'group-3'=>'read', 'group-7' => 'read', 'group-8' => 'edit'})
expect(subject.rightsMetadata.users).to eq({"person1"=>"read","person2"=>"read", 'jcoyne' => 'edit'})
end
end
describe "permissions validation" do
context "depositor must have edit access" do
before(:each) do
@file = GenericFile.new
@file.apply_depositor_metadata('mjg36')
@rightsmd = @file.rightsMetadata
end
before(:all) do
@rights_xml = <<-RIGHTS
<rightsMetadata xmlns="http://hydra-collab.stanford.edu/schemas/rightsMetadata/v1" version="0.1">
<copyright>
<human></human>
<machine></machine>
</copyright>
<access type="read">
<human></human>
<machine></machine>
</access>
<access type="read">
<human></human>
<machine>
<person>mjg36</person>
</machine>
</access>
<access type="edit">
<human></human>
<machine></machine>
</access>
<embargo>
<human></human>
<machine></machine>
</embargo>
</rightsMetadata>
RIGHTS
end
it "should work via permissions=()" do
@file.permissions = {user: {'mjg36' => 'read'}}
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via update_attributes" do
# automatically triggers save
expect { @file.update_attributes(read_users_string: 'mjg36') }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via update_indexed_attributes" do
@rightsmd.update_indexed_attributes([:edit_access, :person] => '')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via permissions()" do
@rightsmd.permissions({person: "mjg36"}, "read")
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via update_permissions()" do
@rightsmd.update_permissions({"person" => {"mjg36" => "read"}})
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via content=()" do
@rightsmd.content=(@rights_xml)
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via ng_xml=()" do
@rightsmd.ng_xml=(Nokogiri::XML::Document.parse(@rights_xml))
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
it "should work via update_values()" do
@rightsmd.update_values([:edit_access, :person] => '')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_users)
expect(@file.errors[:edit_users]).to include('Depositor must have edit access')
expect(@file).to_not be_valid
end
end
context "public must not have edit access" do
before(:each) do
@file = GenericFile.new
@file.apply_depositor_metadata('mjg36')
@file.read_groups = ['public']
@rightsmd = @file.rightsMetadata
end
before(:all) do
@rights_xml = <<-RIGHTS
<rightsMetadata xmlns="http://hydra-collab.stanford.edu/schemas/rightsMetadata/v1" version="0.1">
<copyright>
<human></human>
<machine></machine>
</copyright>
<access type="read">
<human></human>
<machine></machine>
</access>
<access type="read">
<human></human>
<machine></machine>
</access>
<access type="edit">
<human></human>
<machine>
<group>public</group>
</machine>
</access>
<embargo>
<human></human>
<machine></machine>
</embargo>
</rightsMetadata>
RIGHTS
end
it "should work via permissions=()" do
@file.permissions = {group: {'public' => 'edit'}}
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_attributes" do
# automatically triggers save
expect { @file.update_attributes(edit_groups_string: 'public') }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_indexed_attributes" do
@rightsmd.update_indexed_attributes([:edit_access, :group] => 'public')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via permissions()" do
@rightsmd.permissions({group: "public"}, "edit")
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_permissions()" do
@rightsmd.update_permissions({"group" => {"public" => "edit"}})
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via content=()" do
@rightsmd.content=(@rights_xml)
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via ng_xml=()" do
@rightsmd.ng_xml=(Nokogiri::XML::Document.parse(@rights_xml))
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_values()" do
@rightsmd.update_values([:edit_access, :group] => 'public')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Public cannot have edit access')
expect(@file).to_not be_valid
end
end
context "registered must not have edit access" do
before(:each) do
@file = GenericFile.new
@file.apply_depositor_metadata('mjg36')
@file.read_groups = ['registered']
@rightsmd = @file.rightsMetadata
end
before(:all) do
@rights_xml = <<-RIGHTS
<rightsMetadata xmlns="http://hydra-collab.stanford.edu/schemas/rightsMetadata/v1" version="0.1">
<copyright>
<human></human>
<machine></machine>
</copyright>
<access type="read">
<human></human>
<machine></machine>
</access>
<access type="read">
<human></human>
<machine></machine>
</access>
<access type="edit">
<human></human>
<machine>
<group>registered</group>
</machine>
</access>
<embargo>
<human></human>
<machine></machine>
</embargo>
</rightsMetadata>
RIGHTS
end
it "should work via permissions=()" do
@file.permissions = {group: {'registered' => 'edit'}}
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_attributes" do
# automatically triggers save
expect { @file.update_attributes(edit_groups_string: 'registered') }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_indexed_attributes" do
@rightsmd.update_indexed_attributes([:edit_access, :group] => 'registered')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via permissions()" do
@rightsmd.permissions({group: "registered"}, "edit")
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_permissions()" do
@rightsmd.update_permissions({"group" => {"registered" => "edit"}})
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via content=()" do
@rightsmd.content=(@rights_xml)
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via ng_xml=()" do
@rightsmd.ng_xml=(Nokogiri::XML::Document.parse(@rights_xml))
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
it "should work via update_values()" do
@rightsmd.update_values([:edit_access, :group] => 'registered')
expect { @file.save }.not_to raise_error
expect(@file).to be_new_record
expect(@file.errors).to include(:edit_groups)
expect(@file.errors[:edit_groups]).to include('Registered cannot have edit access')
expect(@file).to_not be_valid
end
end
context "everything is copacetic" do
before(:each) do
@file = GenericFile.new
@file.apply_depositor_metadata('mjg36')
@file.read_groups = ['public']
@rightsmd = @file.rightsMetadata
end
after(:each) do
@file.delete
end
before(:all) do
@rights_xml = <<-RIGHTS
<rightsMetadata xmlns="http://hydra-collab.stanford.edu/schemas/rightsMetadata/v1" version="0.1">
<copyright>
<human></human>
<machine></machine>
</copyright>
<access type="read">
<human></human>
<machine>
<group>public</group>
<group>registered</group>
</machine>
</access>
<access type="edit">
<human></human>
<machine>
<person>mjg36</person>
</machine>
</access>
<embargo>
<human></human>
<machine></machine>
</embargo>
</rightsMetadata>
RIGHTS
end
it "should work via permissions=()" do
@file.permissions = {group: {'registered' => 'read'}}
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via update_attributes" do
# automatically triggers save
expect { @file.update_attributes(read_groups_string: 'registered') }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via update_indexed_attributes" do
@rightsmd.update_indexed_attributes([:read_access, :group] => 'registered')
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via permissions()" do
@rightsmd.permissions({group: "registered"}, "read")
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via update_permissions()" do
@rightsmd.update_permissions({"group" => {"registered" => "read"}})
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via content=()" do
@rightsmd.content=(@rights_xml)
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via ng_xml=()" do
@rightsmd.ng_xml=(Nokogiri::XML::Document.parse(@rights_xml))
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
it "should work via update_values()" do
@rightsmd.update_values([:read_access, :group] => 'registered')
expect { @file.save }.not_to raise_error
expect(@file).to_not be_new_record
expect(@file.errors).to be_empty
expect(@file).to be_valid
end
end
end
describe "file content validation" do
context "when file contains a virus" do
let(:f) { File.new(fixture_path + '/small_file.txt') }
after(:each) do
subject.destroy if subject.persisted?
end
it "populates the errors hash during validation" do
allow(Sufia::GenericFile::Actor).to receive(:virus_check).and_raise(Sufia::VirusFoundError, "A virus was found in #{f.path}: EL CRAPO VIRUS")
subject.add_file(f, 'content', 'small_file.txt')
subject.save
expect(subject).not_to be_persisted
expect(subject.errors.messages).to eq(base: ["A virus was found in #{f.path}: EL CRAPO VIRUS"])
end
it "does not save a new version of a GenericFile" do
subject.add_file(f, 'content', 'small_file.txt')
subject.save
allow(Sufia::GenericFile::Actor).to receive(:virus_check).and_raise(Sufia::VirusFoundError)
subject.add_file(File.new(fixture_path + '/sufia_generic_stub.txt') , 'content', 'sufia_generic_stub.txt')
subject.save
expect(subject.reload.content.content).to eq("small\n")
end
end
end
describe "should create a full to_solr record" do
before do
subject.save
end
after do
subject.destroy
end
it "gets both sets of data into solr" do
f1= GenericFile.find(subject.id)
f2 = GenericFile.find(subject.id)
f2.reload_on_save = true
f1.mime_type = "video/abc123"
f2.title = ["abc123"]
f1.save
mime_type_key = Solrizer.solr_name("mime_type")
title_key = Solrizer.solr_name("desc_metadata__title", :stored_searchable, type: :string)
expect(f1.to_solr[mime_type_key]).to eq([f1.mime_type])
expect(f1.to_solr[title_key]).to_not eq(f2.title)
f2.save
expect(f2.to_solr[mime_type_key]).to eq([f1.mime_type])
expect(f2.to_solr[title_key]).to eq(f2.title)
end
end
describe "public?" do
context "when read group is set to public" do
before { subject.read_groups = ['public'] }
it { is_expected.to be_public }
end
context "when read group is not set to public" do
before { subject.read_groups = ['foo'] }
it { is_expected.not_to be_public }
end
end
end
| 39.391185 | 220 | 0.641001 |
9143e75f9a9603461119fbb03f3768e701d01722 | 611 | # See https://docs.chef.io/config_rb_knife.html for more information on knife configuration options
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "webops"
client_key "#{current_dir}/webops.pem"
validation_client_name "awo-validator"
validation_key "#{current_dir}/awo-validator.pem"
chef_server_url "https://api.opscode.com/organizations/awo"
cache_type 'BasicFile'
cache_options( :path => "#{ENV['HOME']}/.chef/checksums" )
cookbook_path ["#{current_dir}/../cookbooks"]
| 43.642857 | 99 | 0.654664 |
3951356978434100f902beecf6c0311964955afb | 437 | # frozen_string_literal: true
module TimesheetReader
# Converter class
class Converter
attr_accessor :minute_multiplier
def initialize
@minute_multiplier = 60
end
def hour_to_minutes(hours)
hours.to_i * minute_multiplier
end
def minutes_to_time(minutes)
hours = (minutes / @minute_multiplier)
hours_part = (minutes % @minute_multiplier)
[hours, hours_part]
end
end
end
| 19 | 49 | 0.693364 |
0168f3460f752011047417cd18190f642832ded8 | 1,783 | # Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'spec_helper'
describe Walrat::ParsletOmission do
it 'raises if "parseable" argument is nil' do
expect do
Walrat::ParsletOmission.new nil
end.to raise_error(ArgumentError, /nil parseable/)
end
it 'complains if passed nil string for parsing' do
expect do
Walrat::ParsletOmission.new('foo'.to_parseable).parse nil
end.to raise_error(ArgumentError, /nil string/)
end
it 're-raises parse errors from lower levels' do
expect do
Walrat::ParsletOmission.new('foo'.to_parseable).parse 'bar'
end.to raise_error(Walrat::ParseError)
end
it 'indicates parse errors with a SubstringSkippedException' do
expect do
Walrat::ParsletOmission.new('foo'.to_parseable).parse 'foo'
end.to raise_error(Walrat::SkippedSubstringException)
end
specify 'the raised SubstringSkippedException includes the parsed substring' do
begin
Walrat::ParsletOmission.new('foo'.to_parseable).parse 'foobar'
rescue Walrat::SkippedSubstringException => e
substring = e.to_s
end
expect(substring).to eq('foo')
end
specify 'the parsed substring is an an empty string in the case of a zero-width parse success at a lower level' do
begin
Walrat::ParsletOmission.new('foo'.optional).parse 'bar' # a contrived example
rescue Walrat::SkippedSubstringException => e
substring = e.to_s
end
expect(substring).to eq('')
end
it 'can be compared for equality' do
expect(Walrat::ParsletOmission.new('foo')).
to eql(Walrat::ParsletOmission.new('foo'))
expect(Walrat::ParsletOmission.new('foo')).
not_to eql(Walrat::ParsletOmission.new('bar'))
end
end
| 31.839286 | 116 | 0.716209 |
ffe7f141e1f04171745cd42a32c4d7eedbfdac33 | 1,613 | module RetirementsHelper
def time_difference_from_now(end_time, format = :sentence)
start_time = Time.current.to_time
end_time = end_time.to_time if end_time.respond_to?(:to_time)
distance_in_seconds = ((end_time - start_time).abs).round
format = :sentence unless %i[sentence header score].include? format
components = []
%w[year month day].each do |interval|
# For each interval type, if the amount of time remaining is greater than
# one unit, calculate how many units fit into the remaining time.
next if (format == :sentence || format == :header) && distance_in_seconds < 1.send(interval)
delta = (distance_in_seconds / 1.send(interval)).floor
distance_in_seconds -= delta.send(interval)
components <<
if format == :score
delta
else
"<strong>#{delta}</strong> #{delta == 1 ? interval : interval.pluralize}"
end
end
return components.join('-') if format == :score
return strip_tags components.to_sentence if format == :sentence
components.join('<br>').html_safe
end
end
def retirement_name(retirement = @retirement)
return retirement.name unless retirement.display_initials?
retirement.name.split.map{ |v| "#{v[0].upcase}." }.join(' ')
end
def encoded_share_text(retirement = @retirement)
return nil unless retirement.present?
share_text =
if retirement.retired?
translate 'share_text.retired'
else
translate 'share_text.not_retired', countdown: time_difference_from_now(retirement.retirement_date)
end
URI.encode_www_form_component share_text
end
| 36.659091 | 105 | 0.701178 |
f7b22d6d6d206e42dba1eb7e17fe7ea80cea097f | 3,996 | require "rails_helper"
RSpec.describe Reports::QuarterlyFacilityState, {type: :model, reporting_spec: true} do
describe "Associations" do
it { should belong_to(:facility) }
end
around do |example|
freeze_time_for_reporting_specs(example)
end
it "has a row for every facility, every quarter" do
facility = create(:facility)
q3_2020 = june_2021[:now] - 9.months
q4_2020 = june_2021[:now] - 6.months
q1_2021 = june_2021[:now] - 3.months
create(:patient, assigned_facility: facility, recorded_at: q3_2020)
create(:patient, assigned_facility: facility, recorded_at: q4_2020)
create(:patient, assigned_facility: facility, recorded_at: q1_2021)
RefreshReportingViews.new.refresh_v2
with_reporting_time_zone do
expect(
described_class.where(facility: facility)
.where("quarter_string >= ?", "2020-1")
.where("quarter_string <= ?", "2021-2")
.count
).to eq 6
expect(described_class.where(quarter_string: "2021-1").count).to eq(Facility.count)
expect(described_class.find_by(facility: facility, quarter_string: "2021-2").quarterly_cohort_patients).to eq 1
expect(described_class.find_by(facility: facility, quarter_string: "2021-1").quarterly_cohort_patients).to eq 1
expect(described_class.find_by(facility: facility, quarter_string: "2020-4").quarterly_cohort_patients).to eq 1
expect(described_class.where(facility: facility).where("quarter_string < '2020-4'").count).to eq 11
expect(described_class.where(facility: facility).where("quarter_string < '2020-4'").pluck(:quarterly_cohort_patients)).to all eq nil
end
end
context "quarterly cohort outcomes" do
it "computes totals correctly" do
facility = create(:facility)
two_quarters_ago = june_2021[:now] - 6.months
previous_quarter = june_2021[:now] - 3.months
this_quarter = june_2021[:now]
patients_controlled = create_list(:patient, 2, assigned_facility: facility, recorded_at: previous_quarter)
patients_controlled.each do |patient|
create(:bp_with_encounter, :under_control, patient: patient, recorded_at: this_quarter)
end
patients_uncontrolled = create_list(:patient, 3, assigned_facility: facility, recorded_at: previous_quarter)
patients_uncontrolled.each do |patient|
create(:bp_with_encounter, :hypertensive, patient: patient, recorded_at: this_quarter)
end
_patient_no_visit = create(:patient, assigned_facility: facility, recorded_at: previous_quarter)
_patient_not_in_cohort = create(:patient, assigned_facility: facility, recorded_at: two_quarters_ago)
patients_missed_visit = create_list(:patient, 4, assigned_facility: facility, recorded_at: previous_quarter)
patients_missed_visit.each do |patient|
create(:bp_with_encounter, patient: patient, recorded_at: previous_quarter)
end
patients_visited_no_bp = create_list(:patient, 2, assigned_facility: facility, recorded_at: previous_quarter)
patients_visited_no_bp.each do |patient|
create(:prescription_drug,
device_created_at: this_quarter,
facility: facility,
patient: patient,
user: patient.registration_user)
create(:blood_pressure, patient: patient, recorded_at: previous_quarter)
end
RefreshReportingViews.new.refresh_v2
with_reporting_time_zone do
quarterly_facility_state_2021_q2 = described_class.find_by(facility: facility, quarter_string: "2021-2")
expect(quarterly_facility_state_2021_q2.quarterly_cohort_controlled).to eq 2
expect(quarterly_facility_state_2021_q2.quarterly_cohort_uncontrolled).to eq 3
expect(quarterly_facility_state_2021_q2.quarterly_cohort_visited_no_bp).to eq 2
expect(quarterly_facility_state_2021_q2.quarterly_cohort_missed_visit).to eq 5
expect(quarterly_facility_state_2021_q2.quarterly_cohort_patients).to eq 12
end
end
end
end
| 45.931034 | 138 | 0.738989 |
62a3df86052dbd1c1c4641756581be9cf8da9710 | 2,243 | require 'tests/test_helper.rb'
def test_game_turn_is_advanced_after_action(_args, assert)
$game.game_map = build_game_map_with_entities(Entities.player, build_actor)
$game.scene = Scenes::Gameplay.new(player: Entities.player)
scene_before = $game.scene
assert.will_advance_turn! do
$game.handle_input_events [
{ type: :wait }
]
end
assert.equal! $game.scene, scene_before, 'Scene changed'
end
def test_game_turn_is_not_advanced_after_opening_ui(_args, assert)
$game.game_map = build_game_map_with_entities(Entities.player, build_actor)
$game.scene = Scenes::Gameplay.new(player: Entities.player)
scene_before = $game.scene
assert.will_not_advance_turn! do
$game.handle_input_events [
{ type: :inventory }
]
end
assert.not_equal! $game.scene, scene_before
end
def test_game_log_impossible_actions(_args, assert)
$game.scene = GameTests.build_test_scene
$game.scene.next_action = -> { raise Action::Impossible, 'Something did not work.' }
$game.handle_input_events [{ type: :test }]
assert.includes! log_messages, 'Something did not work.'
end
def test_game_generate_next_floor_deletes_all_non_player_related_entities(_args, assert)
owned_item = build_item
owned_item.place(Entities.player.inventory)
other_item = build_item
enemy_owned_item = build_item
enemy = build_actor(items: [enemy_owned_item])
$game.game_map = build_game_map_with_entities(Entities.player, other_item, enemy)
generated_game_map = nil
generate_dungeon_stub = lambda { |*_args|
generated_game_map = build_game_map_with_entities(Entities.player)
}
with_replaced_method Procgen, :generate_dungeon, generate_dungeon_stub do
$game.generate_next_floor
end
assert.includes_all! Entities, [Entities.player, owned_item]
assert.includes_none_of! Entities, [other_item, enemy, enemy_owned_item]
assert.equal! $game.game_map, generated_game_map
end
module GameTests
class << self
def build_test_scene
scene_class = Class.new(Scenes::BaseScene) do
def next_action=(action_lambda)
replace_method self, :handle_input_event do |_|
stub(perform: action_lambda)
end
end
end
scene_class.new
end
end
end
| 29.906667 | 88 | 0.753009 |
211d01741cccfb92625304e78980916577a8131b | 920 | # frozen_string_literal: true
workers Integer(ENV.fetch('WEB_CONCURRENCY', 2))
threads_count = Integer(ENV.fetch('MAX_THREADS', 5))
threads threads_count, threads_count
tag 'sinatra-skeleton'
rackup DefaultRackup
environment ENV.fetch('RACK_ENV', 'development')
preload_app!
if ENV['RACK_ENV'] == 'production' || ENV['RACK_ENV'] == 'staging'
if ENV['DOCKER'] == 'true'
bind "tcp://#{ENV.fetch('LISTEN', '0.0.0.0')}:#{ENV.fetch('PORT', 5000)}"
else
bind "unix://#{File.join(Dir.pwd, 'tmp', 'sockets', 'puma.sock')}"
state_path File.join(Dir.pwd, 'tmp', 'sockets', 'puma.state')
activate_control_app "unix://#{File.join(Dir.pwd, 'tmp', 'sockets', 'pumactl.sock')}"
stdout_redirect File.join(Dir.pwd, 'log', 'puma.stdout.log'), File.join(Dir.pwd, 'log', 'puma.stderr.log')
end
else
bind "tcp://#{ENV.fetch('LISTEN', '127.0.0.1')}:#{ENV.fetch('PORT', 5000)}"
end
| 35.384615 | 115 | 0.644565 |
1ddc755239be0a0db5a7c6bcbfc7e1d8a3a96b7f | 764 | cask "font-iosevka-curly" do
version "8.0.2"
sha256 "b151a755b038e208db36f4be67b8554f0b35526e639bc45461edfd02b6708787"
url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-curly-#{version}.zip"
name "Iosevka Curly"
desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family"
homepage "https://github.com/be5invis/Iosevka/"
livecheck do
url :url
strategy :github_latest
end
font "iosevka-curly-bold.ttc"
font "iosevka-curly-extrabold.ttc"
font "iosevka-curly-extralight.ttc"
font "iosevka-curly-heavy.ttc"
font "iosevka-curly-light.ttc"
font "iosevka-curly-medium.ttc"
font "iosevka-curly-regular.ttc"
font "iosevka-curly-semibold.ttc"
font "iosevka-curly-thin.ttc"
end
| 30.56 | 106 | 0.751309 |
1d871daf1270f2e35854e36168db71d8af45b6e1 | 3,372 | FactoryGirl.define do
factory :orchestration_stack do
ems_ref "1"
end
factory :orchestration_stack_cloud, :parent => :orchestration_stack, :class => "ManageIQ::Providers::CloudManager::OrchestrationStack" do
end
factory :orchestration_stack_cloud_with_template, :parent => :orchestration_stack, :class => "ManageIQ::Providers::CloudManager::OrchestrationStack" do
orchestration_template { FactoryGirl.create(:orchestration_template) }
end
factory :orchestration_stack_amazon, :parent => :orchestration_stack, :class => "ManageIQ::Providers::Amazon::CloudManager::OrchestrationStack" do
end
factory :orchestration_stack_amazon_with_non_orderable_template, :parent => :orchestration_stack, :class => "ManageIQ::Providers::Amazon::CloudManager::OrchestrationStack" do
orchestration_template { FactoryGirl.create(:orchestration_template_cfn, :orderable => false) }
end
factory :orchestration_stack_azure, :parent => :orchestration_stack, :class => "ManageIQ::Providers::Azure::CloudManager::OrchestrationStack" do
end
factory :orchestration_stack_openstack, :parent => :orchestration_stack, :class => "ManageIQ::Providers::Openstack::CloudManager::OrchestrationStack" do
end
factory :orchestration_stack_openstack_infra,
:parent => :orchestration_stack,
:class => "ManageIQ::Providers::Openstack::InfraManager::OrchestrationStack" do
after :create do |x|
x.parameters << FactoryGirl.create(:orchestration_stack_parameter_openstack_infra_compute)
x.parameters << FactoryGirl.create(:orchestration_stack_parameter_openstack_infra_controller)
x.resources << FactoryGirl.create(:orchestration_stack_resource_openstack_infra_compute)
x.resources << FactoryGirl.create(:orchestration_stack_resource_openstack_infra_compute_parent)
end
end
factory :orchestration_stack_openstack_infra_nested,
:parent => :orchestration_stack,
:class => "ManageIQ::Providers::Openstack::InfraManager::OrchestrationStack" do
end
factory :orchestration_stack_parameter_openstack_infra, :class => "OrchestrationStackParameter" do
end
factory :orchestration_stack_parameter_openstack_infra_compute, :parent => :orchestration_stack_parameter_openstack_infra do
after :create do |x|
x.name = "compute-1::count"
x.value = "1"
end
end
factory :orchestration_stack_parameter_openstack_infra_controller, :parent => :orchestration_stack_parameter_openstack_infra do
after :create do |x|
x.name = "controller-1::count"
x.value = "1"
end
end
factory :orchestration_stack_resource_openstack_infra, :class => "OrchestrationStackResource" do
end
factory :orchestration_stack_resource_openstack_infra_compute,
:parent => :orchestration_stack_resource_openstack_infra do
after :create do |x|
x.physical_resource = "openstack-perf-host-nova-instance"
x.stack = FactoryGirl.create(:orchestration_stack_openstack_infra_nested)
end
end
factory :orchestration_stack_resource_openstack_infra_compute_parent,
:parent => :orchestration_stack_resource_openstack_infra do
after :create do |x|
x.physical_resource = "1"
x.logical_resource = "1"
end
end
factory :ansible_tower_job, :class => "ManageIQ::Providers::AnsibleTower::ConfigurationManager::Job" do
end
end
| 41.62963 | 176 | 0.765421 |
386007a03121dac17d7ec23d93eff0ef94fa34c7 | 1,215 | module Pupa
# A real person, alive or dead.
class Person
include Model
self.schema = 'popolo/person'
include Concerns::Timestamps
include Concerns::Sourceable
include Concerns::Nameable
include Concerns::Identifiable
include Concerns::Contactable
include Concerns::Linkable
attr_accessor :name, :email, :gender, :birth_date, :death_date, :image, :summary, :biography, :national_identity,
:family_name, :given_name, :additional_name, :honorific_prefix, :honorific_suffix, :patronymic_name, :sort_name
dump :name, :email, :gender, :birth_date, :death_date, :image, :summary, :biography, :national_identity,
:family_name, :given_name, :additional_name, :honorific_prefix, :honorific_suffix, :patronymic_name, :sort_name
# Returns the person's name.
#
# @return [String] the person's name
def to_s
name
end
# @todo This will obviously need to be scoped as in Python Pupa, to a
# jurisdiction, post, etc.
def fingerprint
if name
{
'$or' => [
{'name' => name},
{'other_names.name' => name},
],
}
else
{}
end
end
end
end
| 28.255814 | 117 | 0.633745 |
396771a57bed667006ee4c3633e6bee118ce9677 | 738 | module AnalyticsHelper
def can_use_analytics?
ENV["ANALYTICS"].present? && !masquerading?
end
def identify_hash(user = current_user)
{
created: user.created_at,
email: user.email,
first_name: user.first_name,
name: user.name,
unsubscribed_from_emails: user.unsubscribed_from_emails,
user_id: user.id,
username: user.github_username,
}
end
def intercom_hash(user = current_user)
{
'Intercom' => {
userHash: OpenSSL::HMAC.hexdigest(
'sha256',
ENV['INTERCOM_API_SECRET'],
user.id.to_s
)
}
}
end
def campaign_hash
{
context: {
campaign: session[:campaign_params]
}
}
end
end
| 19.421053 | 62 | 0.597561 |
39cd7f62dee8f80ea0dcf248a4772095f5ecb3d1 | 2,123 | # A mapping element connects source with targed field. It further does
# a conversion if needed
#
# == Conversions:
# - join: merges multiple incoming fields into a target
# - enum: maps source strings to enum target values
#
# - split: split source field into multiple target fields
#
class MappingElement < ActiveRecord::Base
CONVERT_TYPES = %w(enum date join price).freeze
belongs_to :mapping
validates :conversion_type, inclusion: {in: CONVERT_TYPES, message: "Unknown conversion type %{value}"}, allow_blank: true
validates :model_to_import, inclusion: {in: %w(line_item document)}
# validates :mapping, presence: true
serialize :conversion_options
scope :for_line_items, -> { where(model_to_import: 'line_item') }
scope :for_documents, -> { where(model_to_import: 'document') }
# @param [Array] data_row
def convert(data_row)
conversion_method = "convert_#{conversion_type}"
if conversion_type && self.respond_to?(conversion_method)
self.send(conversion_method, data_row)
else # simple field mapping
source_value(data_row)
end
end
# convert_opts = {"male":"Herr","female":"Frau"}
def convert_enum(data_row)
value = source_value(data_row)
res = conversion_options.detect {|trg_val, src_val| value == src_val }
res && res[0]
end
def convert_date(data_row)
value = source_value(data_row)
date = Date.strptime(value, conversion_options['date']) rescue Chronic.parse(value)
date.is_a?(Date) ? date.strftime("%Y.%m.%d") : value
end
def convert_price(data_row)
value = source_value(data_row)
value.try(:match, /([0-9\.,]+)/).try(:[], 1) || value
end
# == Params
# <Array>:. Incoming csv fields
def convert_join(data_row)
source.split(',').map{|i| data_row[i.to_i] }.join(' ')
end
def source_as_string
source_string = ""
source.split(",").each_with_index do |source_id, i|
source_string << mapping.attachments.first.rows.first[source_id.to_i]
source_string << "/" if i > 0
end
source_string
end
private
def source_value(data_row)
data_row[source.to_i]
end
end
| 29.082192 | 124 | 0.695243 |
5d3f487bc658f0b6f37c5fa91bb9b9eb983ce569 | 45,605 | require File.dirname(__FILE__) + '/../spec_helper'
describe "Standard Tags" do
dataset :users_and_pages, :file_not_found, :snippets
it '<r:page> should allow access to the current page' do
page(:home)
page.should render('<r:page:title />').as('Home')
page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home')
end
[:breadcrumb, :slug, :title, :url].each do |attr|
it "<r:#{attr}> should render the '#{attr}' attribute" do
value = page.send(attr)
page.should render("<r:#{attr} />").as(value.to_s)
end
end
it "<r:url> with a nil relative URL root should scope to the relative root of /" do
ActionController::Base.relative_url_root = nil
page(:home).should render("<r:url />").as("/")
end
it '<r:url> with a relative URL root should scope to the relative root' do
page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/")
end
it '<r:parent> should change the local context to the parent page' do
page(:parent)
page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title)
page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(page_eachable_children(pages(:home)).collect(&:title).join(""))
page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count)
end
it '<r:if_parent> should render the contained block if the current page has a parent page' do
page.should render('<r:if_parent>true</r:if_parent>').as('true')
page(:home).should render('<r:if_parent>true</r:if_parent>').as('')
end
it '<r:unless_parent> should render the contained block unless the current page has a parent page' do
page.should render('<r:unless_parent>true</r:unless_parent>').as('')
page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true')
end
it '<r:if_children> should render the contained block if the current page has child pages' do
page(:home).should render('<r:if_children>true</r:if_children>').as('true')
page(:childless).should render('<r:if_children>true</r:if_children>').as('')
end
it '<r:unless_children> should render the contained block if the current page has no child pages' do
page(:home).should render('<r:unless_children>true</r:unless_children>').as('')
page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true')
end
describe "<r:children:each>" do
it "should iterate through the children of the current page" do
page(:parent)
page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ')
page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ')
page(:assorted).should render(page_children_each_tags).as('a b c d e f g h i j ')
end
it 'should not list draft pages' do
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
end
it 'should include draft pages with status="all"' do
page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ')
end
it "should include draft pages by default on the dev host" do
page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com')
end
it 'should error with invalid "limit" attribute' do
message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{limit="a"})).with_error(message)
page.should render(page_children_each_tags(%{limit="-10"})).with_error(message)
page.should render(page_children_each_tags(%{limit="50000"})).with_error(message)
end
it 'should error with invalid "offset" attribute' do
message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{offset="a"})).with_error(message)
page.should render(page_children_each_tags(%{offset="-10"})).with_error(message)
page.should render(page_children_each_tags(%{offset="50000"})).with_error(message)
end
it 'should error with invalid "by" attribute' do
message = "`by' attribute of `each' tag must be set to a valid field name"
page.should render(page_children_each_tags(%{by="non-existant-field"})).with_error(message)
end
it 'should error with invalid "order" attribute' do
message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"}
page.should render(page_children_each_tags(%{order="asdf"})).with_error(message)
end
it "should limit the number of children when given a 'limit' attribute" do
page.should render(page_children_each_tags(%{limit="5"})).as('a b c d e ')
end
it "should limit and offset the children when given 'limit' and 'offset' attributes" do
page.should render(page_children_each_tags(%{offset="3" limit="5"})).as('d e f g h ')
end
it "should change the sort order when given an 'order' attribute" do
page.should render(page_children_each_tags(%{order="desc"})).as('j i h g f e d c b a ')
end
it "should sort by the 'by' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb"})).as('f e d c b a j i h g ')
end
it "should sort by the 'by' attribute according to the 'order' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ')
end
describe 'with "status" attribute' do
it "set to 'all' should list all children" do
page.should render(page_children_each_tags(%{status="all"})).as("a b c d e f g h i j draft ")
end
it "set to 'draft' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="draft"})).as('draft ')
end
it "set to 'published' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="published"})).as('a b c d e f g h i j ')
end
it "set to an invalid status should render an error" do
page.should render(page_children_each_tags(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status")
end
end
end
describe "<r:children:each:if_first>" do
it "should render for the first child" do
tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>'
expected = "FIRST:article article-2 article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_first>" do
it "should render for all but the first child" do
tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>'
expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:if_last>" do
it "should render for the last child" do
tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>'
expected = "article article-2 article-3 LAST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_last>" do
it "should render for all but the last child" do
tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>'
expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:header>" do
it "should render the header when it changes" do
tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>'
expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "name" attribute should maintain a separate header' do
tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to one name should restart that header' do
tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to two names should restart both headers' do
tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:count>" do
it 'should render the number of children of the current page' do
page(:parent).should render('<r:children:count />').as('3')
end
it "should accept the same scoping conditions as <r:children:each>" do
page.should render('<r:children:count />').as('10')
page.should render('<r:children:count status="all" />').as('11')
page.should render('<r:children:count status="draft" />').as('1')
page.should render('<r:children:count status="hidden" />').as('0')
end
end
describe "<r:children:first>" do
it 'should render its contents in the context of the first child page' do
page(:parent).should render('<r:children:first:title />').as('Child')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_first_tags).as('a')
page.should render(page_children_first_tags(%{limit="5"})).as('a')
page.should render(page_children_first_tags(%{offset="3" limit="5"})).as('d')
page.should render(page_children_first_tags(%{order="desc"})).as('j')
page.should render(page_children_first_tags(%{by="breadcrumb"})).as('f')
page.should render(page_children_first_tags(%{by="breadcrumb" order="desc"})).as('g')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:first:title />').as('')
end
end
describe "<r:children:last>" do
it 'should render its contents in the context of the last child page' do
page(:parent).should render('<r:children:last:title />').as('Child 3')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_last_tags).as('j')
page.should render(page_children_last_tags(%{limit="5"})).as('e')
page.should render(page_children_last_tags(%{offset="3" limit="5"})).as('h')
page.should render(page_children_last_tags(%{order="desc"})).as('a')
page.should render(page_children_last_tags(%{by="breadcrumb"})).as('g')
page.should render(page_children_last_tags(%{by="breadcrumb" order="desc"})).as('f')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:last:title />').as('')
end
end
describe "<r:content>" do
it "should render the 'body' part by default" do
page.should render('<r:content />').as('Assorted body.')
end
it "with 'part' attribute should render the specified part" do
page(:home).should render('<r:content part="extended" />').as("Just a test.")
end
it "should prevent simple recursion" do
page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.")
end
it "should prevent deep recursion" do
page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.")
page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.")
end
describe "with inherit attribute" do
it "missing or set to 'false' should render the current page's part" do
page.should render('<r:content part="sidebar" />').as('')
page.should render('<r:content part="sidebar" inherit="false" />').as('')
end
describe "set to 'true'" do
it "should render an ancestor's part" do
page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.')
end
it "should render nothing when no ancestor has the part" do
page.should render('<r:content part="part_that_doesnt_exist" inherit="true" />').as('')
end
describe "and contextual attribute" do
it "set to 'true' should render the part in the context of the current page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.')
page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.')
page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.')
end
it "set to 'false' should render the part in the context of its containing page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.')
end
it "should maintain the global page" do
page(:first)
page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First')
page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First')
end
end
end
it "set to an erroneous value should render an error" do
page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"})
end
it "should render parts with respect to the current contextual page" do
expected = "Child body. Child 2 body. Child 3 body. "
page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected)
end
end
end
describe "<r:if_content>" do
it "without 'part' attribute should render the contained block if the 'body' part exists" do
page.should render('<r:if_content>true</r:if_content>').as('true')
end
it "should render the contained block if the specified part exists" do
page.should render('<r:if_content part="body">true</r:if_content>').as('true')
end
it "should not render the contained block if the specified part does not exist" do
page.should render('<r:if_content part="asdf">true</r:if_content>').as('')
end
describe "with more than one part given (separated by comma)" do
it "should render the contained block only if all specified parts exist" do
page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true')
end
it "should not render the contained block if at least one of the specified parts does not exist" do
page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('')
end
describe "with inherit attribute set to 'true'" do
it 'should render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('')
end
end
describe "with inherit attribute set to 'false'" do
it 'should render the contained block if the current page has the specified parts' do
page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should render the contained block if any of the specified parts exist" do
page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should render the contained block if all of the specified parts exist" do
page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true')
end
it "should not render the contained block if all of the specified parts do not exist" do
page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('')
end
end
end
end
describe "<r:unless_content>" do
describe "with inherit attribute set to 'true'" do
it 'should not render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
it 'should render the contained block if the current or ancestor pages do not have the specified parts' do
page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('')
end
end
it "without 'part' attribute should not render the contained block if the 'body' part exists" do
page.should render('<r:unless_content>false</r:unless_content>').as('')
end
it "should not render the contained block if the specified part exists" do
page.should render('<r:unless_content part="body">false</r:unless_content>').as('')
end
it "should render the contained block if the specified part does not exist" do
page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false')
end
it "should render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false')
end
describe "with more than one part given (separated by comma)" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('')
end
it "should render the contained block if at least one of the specified parts exists" do
page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true')
end
describe "with the 'inherit' attribute set to 'true'" do
it "should render the contained block if the current or ancestor pages have none of the specified parts" do
page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do
page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('')
end
it "should render the contained block unless all of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should not render the contained block if any of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('')
end
end
end
end
describe "<r:author>" do
it "should render the author of the current page" do
page.should render('<r:author />').as('Admin')
end
it "should render nothing when the page has no author" do
page(:no_user).should render('<r:author />').as('')
end
end
describe "<r:date>" do
before :each do
page(:dated)
end
it "should render the published date of the page" do
page.should render('<r:date />').as('Wednesday, January 11, 2006')
end
it "should format the published date according to the 'format' attribute" do
page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006')
end
describe "with 'for' attribute" do
it "set to 'now' should render the current date" do
page.should render('<r:date for="now" />').as(Time.now.strftime("%A, %B %d, %Y"))
end
it "set to 'created_at' should render the creation date" do
page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006')
end
it "set to 'updated_at' should render the update date" do
page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006')
end
it "set to 'published_at' should render the publish date" do
page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006')
end
it "set to an invalid attribute should render an error" do
page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.")
end
end
it "should use the currently set timezone" do
Time.zone = "Tokyo"
format = "%H:%m"
expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format)
page.should render(%Q(<r:date format="#{format}" />) ).as(expected)
end
end
describe "<r:link>" do
it "should render a link to the current page" do
page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>')
end
it "should render its contents as the text of the link" do
page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>')
end
it "should pass HTML attributes to the <a> tag" do
expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>'
page.should render('<r:link class="test" id="assorted" />').as(expected)
end
it "should add the anchor attribute to the link as a URL anchor" do
page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>')
end
it "should render a link for the current contextual page" do
expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> }
page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected)
end
it "should scope the link within the relative URL root" do
page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>')
end
end
describe "<r:snippet>" do
it "should render the contents of the specified snippet" do
page.should render('<r:snippet name="first" />').as('test')
end
it "should render an error when the snippet does not exist" do
page.should render('<r:snippet name="non-existant" />').with_error('snippet not found')
end
it "should render an error when not given a 'name' attribute" do
page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute")
end
it "should filter the snippet with its assigned filter" do
page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>})
end
it "should maintain the global page inside the snippet" do
page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count)
end
it "should maintain the global page when the snippet renders recursively" do
page(:child).should render('<r:snippet name="recursive" />').as("Great GrandchildGrandchildChild")
end
it "should render the specified snippet when called as an empty double-tag" do
page.should render('<r:snippet name="first"></r:snippet>').as('test')
end
it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do
page.should render('<r:snippet name="yielding">inner</r:snippet>').
as('Before...inner...and after')
end
it "should do nothing with contents of double tag when snippet doesn't yield" do
page.should render('<r:snippet name="first">content disappears!</r:snippet>').
as('test')
end
it "should render nested yielding snippets" do
page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>').
as('<div>Before...Hello, World!...and after</div>')
end
it "should render double-tag snippets called from within a snippet" do
page.should render('<r:snippet name="nested_yields">the content</r:snippet>').
as('<snippet name="div_wrap">above the content below</snippet>')
end
it "should render contents each time yield is called" do
page.should render('<r:snippet name="yielding_often">French</r:snippet>').
as('French is Frencher than French')
end
end
it "should do nothing when called from page body" do
page.should render('<r:yield/>').as("")
end
it '<r:random> should render a randomly selected contained <r:option>' do
page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/)
end
it '<r:random> should render a randomly selected, dynamically set <r:option>' do
page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/)
end
it '<r:comment> should render nothing it contains' do
page.should render('just a <r:comment>small </r:comment>test').as('just a test')
end
describe "<r:navigation>" do
it "should render the nested <r:normal> tag by default" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
</r:navigation>}
expected = %{Home Assorted Parent}
page.should render(tags).as(expected)
end
it "should render the nested <r:selected> tag for URLs that match the current page" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/">
<r:normal><r:title /></r:normal>
<r:selected><strong><r:title/></strong></r:selected>
</r:navigation>}
expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius}
page(:parent).should render(tags).as(expected)
end
it "should render the nested <r:here> tag for URLs that exactly match the current page" do
tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here><strong><r:title /></strong></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>}
page.should render(tags).as(expected)
end
it "should render the nested <r:between> tag between each link" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
<r:between> :: </r:between>
</r:navigation>}
expected = %{Home :: Assorted :: Parent}
page.should render(tags).as(expected)
end
it 'without urls should render nothing' do
page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('')
end
it 'without a nested <r:normal> tag should render an error' do
page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag")
end
it 'with urls without trailing slashes should match corresponding pages' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:title /></r:normal>
<r:here><strong><r:title /></strong></r:here>
</r:navigation>}
expected = %{Home <strong>Assorted</strong> Parent Radius}
page.should render(tags).as(expected)
end
it 'should prune empty blocks' do
tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>}
page(:radius).should render(tags).as(expected)
end
end
describe "<r:find>" do
it "should change the local page to the page specified in the 'url' attribute" do
page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child')
end
it "should render an error without the 'url' attribute" do
page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute")
end
it "should render nothing when the 'url' attribute does not point to a page" do
page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do
page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should scope contained tags to the found page" do
page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ')
end
it "should accept a path relative to the current page" do
page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2")
end
end
it '<r:escape_html> should escape HTML-related characters into entities' do
page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('<strong>a bold move</strong>')
end
it '<r:rfc1123_date> should render an RFC1123-compatible date' do
page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT')
end
describe "<r:breadcrumbs>" do
it "should render a series of breadcrumb links separated by >" do
expected = %{<a href="/">Home</a> > <a href="/parent/">Parent</a> > <a href="/parent/child/">Child</a> > <a href="/parent/child/grandchild/">Grandchild</a> > Great Grandchild}
page(:great_grandchild).should render('<r:breadcrumbs />').as(expected)
end
it "with a 'separator' attribute should use the separator instead of >" do
expected = %{<a href="/">Home</a> :: Parent}
page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected)
end
it "with a 'nolinks' attribute set to 'true' should not render links" do
expected = %{Home > Parent}
page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected)
end
it "with a relative URL root should scope links to the relative root" do
expected = '<a href="/foo/">Home</a> > Assorted'
page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected)
end
end
describe "<r:if_url>" do
describe "with 'matches' attribute" do
it "should render the contained block if the page URL matches" do
page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true')
end
it "should not render the contained block if the page URL does not match" do
page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.")
end
end
describe "<r:unless_url>" do
describe "with 'matches' attribute" do
it "should not render the contained block if the page URL matches" do
page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('')
end
it "should render the contained block if the page URL does not match" do
page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.")
end
end
describe "<r:cycle>" do
it "should render passed values in succession" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second')
end
it "should return to the beginning of the cycle when reaching the end" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first')
end
it "should use a default cycle name of 'cycle'" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second')
end
it "should maintain separate cycle counters" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two')
end
it "should reset the counter" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first')
end
it "should require the values attribute" do
page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.")
end
end
describe "<r:if_dev>" do
it "should render the contained block when on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('--')
end
describe "on an included page" do
it "should render the contained block when on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('--')
end
end
end
describe "<r:unless_dev>" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-')
end
describe "on an included page" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-')
end
end
end
describe "<r:status>" do
it "should render the status of the current page" do
status_tag = "<r:status/>"
page(:a).should render(status_tag).as("Published")
page(:hidden).should render(status_tag).as("Hidden")
page(:draft).should render(status_tag).as("Draft")
end
describe "with the downcase attribute set to 'true'" do
it "should render the lowercased status of the current page" do
status_tag_lc = "<r:status downcase='true'/>"
page(:a).should render(status_tag_lc).as("published")
page(:hidden).should render(status_tag_lc).as("hidden")
page(:draft).should render(status_tag_lc).as("draft")
end
end
end
describe "<r:if_ancestor_or_self>" do
it "should render the tag's content when the current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:unless_ancestor_or_self>" do
it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:if_self>" do
it "should render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('')
end
end
describe "<r:unless_self>" do
it "should render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('')
end
end
describe "<r:meta>" do
it "should render <meta> tags for the description and keywords" do
page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />})
end
it "should render <meta> tags with escaped values for the description and keywords" do
page.should render('<r:meta/>').as(%{<meta name="description" content="sweet & harmonious biscuits" /><meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description and keywords" do
page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page})
end
it "should escape the contents of the description and keywords" do
page.should render('<r:meta tag="false" />').as("sweet & harmonious biscuitssweet & harmonious biscuits")
end
end
end
describe "<r:meta:description>" do
it "should render a <meta> tag for the description" do
page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />})
end
it "should render a <meta> tag with escaped value for the description" do
page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description" do
page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage})
end
it "should escape the contents of the description" do
page.should render('<r:meta:description tag="false" />').as("sweet & harmonious biscuits")
end
end
end
describe "<r:meta:keywords>" do
it "should render a <meta> tag for the keywords" do
page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />})
end
it "should render a <meta> tag with escaped value for the keywords" do
page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the keywords" do
page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page})
end
it "should escape the contents of the keywords" do
page.should render('<r:meta:keywords tag="false" />').as("sweet & harmonious biscuits")
end
end
end
private
def page(symbol = nil)
if symbol.nil?
@page ||= pages(:assorted)
else
@page = pages(symbol)
end
end
def page_children_each_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:each#{attr}><r:slug /> </r:children:each>"
end
def page_children_first_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:first#{attr}><r:slug /></r:children:first>"
end
def page_children_last_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:last#{attr}><r:slug /></r:children:last>"
end
def page_eachable_children(page)
page.children.select(&:published?).reject(&:virtual)
end
end | 45.972782 | 270 | 0.647517 |
62fd08b3d425a6a11c7a32ccad60a4c973d3469c | 7,301 | require 'rails_helper'
RSpec.describe Api::V1::Admin::RacesController, type: :request do
let(:random_name) { generate_random_string(16) }
let(:login_user) { create(:user, :admin) }
let(:race) { create(:race, name: random_name) }
before(:each) do
@headers = { 'ACCEPT': 'application/json', 'CONTENT-TYPE': 'application/json' }
sign_in login_user
end
describe "Races API Index " do
it 'returns http not authorized when not signed in' do
sign_out login_user
get "/api/v1/admin/races", headers: @headers
expect(response).to have_http_status(401)
end
it "returns http success when signed in" do
get "/api/v1/admin/races", headers: @headers
expect(response).to have_http_status(200)
end
it "returns the list of races" do
@races = []
@races << build(:race, name: "HISPANIC OR LATINO")
@races << build(:race, name: "AFRICAN AMERICAN")
@races << build(:race, name: "WHITE")
@races.sort!
get "/api/v1/admin/races", headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(true)
u[:races].each_with_index do |race, index|
expect(race[:id]).to eq(@races[index].id)
expect(race[:name]).to eq(@races[index].name)
end
end
end
describe "Races API Show" do
it "returns http not authorized when not signed in" do
race_params = { name: "AMERICAN INDIAN OR PACIFIC ISLANDER" }
race_params_json = race_params.to_json
sign_out login_user
get "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(401)
end
it "returns http success when signed in" do
race_params = { name: "AMERICAN INDIAN OR PACIFIC ISLANDER" }
race_params_json = race_params.to_json
get "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
end
it "returns the details of the specified race" do
race_params = { name: "AMERICAN INDIAN OR PACIFIC ISLANDER" }
race_params_json = race_params.to_json
get "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(true)
expect(u[:race][:id]).to eq(race.id)
expect(u[:race][:name]).to eq(race.name)
end
end
describe "Races API Create" do
it "returns http not authorized when not signed in" do
race_params = { name: "AFRICAN AMERICAN" }
race_params_json = race_params.to_json
sign_out login_user
post "/api/v1/admin/races", params: race_params_json, headers: @headers
expect(response).to have_http_status(401)
end
it "returns http success when signed in" do
race_params = { name: "AFRICAN AMERICAN" }
race_params_json = race_params.to_json
post "/api/v1/admin/races/", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
end
it "is successful with valid parameters" do
race_params = { name: "AFRICAN AMERICAN" }
race_params_json = race_params.to_json
post "/api/v1/admin/races", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(true)
expect(u[:race][:name]).to eq(race_params[:name])
end
it "is not successful without a name" do
race_params = { name: nil }
race_params_json = race_params.to_json
post "/api/v1/admin/races", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(false)
expect(u[:errors][:name]).to eq(["can't be blank"])
end
it "is not successful with a dupliate name" do
race_params = create(:race, name: "AFRICAN AMERICAN")
race_params_json = race_params.to_json
post "/api/v1/admin/races", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(false)
expect(u[:errors][:name]).to eq(["has already been taken"])
end
end
describe "Race API Update" do
it "returns http not authorized when not signed in" do
race_params = { name: "HISPANIC OR LATINO" }
race_params_json = race_params.to_json
sign_out login_user
patch "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(401)
end
it "returns http success when signed in" do
race_params = { name: "HISPANIC OR LATINO" }
race_params_json = race_params.to_json
patch "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
end
it "is successful with valid parameters" do
race_params = { name: "HISPANIC OR LATINO" }
race_params_json = race_params.to_json
patch "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(true)
expect(u[:race][:name]).to eq(race_params[:name])
end
it "is not successful without a name" do
race_params = { name: nil }
race_params_json = race_params.to_json
patch "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(false)
expect(u[:errors][:name]).to eq(["can't be blank"])
end
it "is not successful with a duplicate name" do
race_params = create(:race, name: "HISPANIC OR LATINO")
race_params_json = race_params.to_json
patch "/api/v1/admin/races/#{race.id}", params: race_params_json, headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(false)
expect(u[:errors][:name]).to eq(["has already been taken"])
end
end
describe "Race API Destroy" do
it "returns http not authorized when not signed in" do
sign_out login_user
delete "/api/v1/admin/races/#{race.id}", headers: @headers
expect(response).to have_http_status(401)
end
it "returns http success when signed in" do
delete "/api/v1/admin/races/#{race.id}", headers: @headers
expect(response).to have_http_status(200)
end
it "returns the list of races without the deleted race" do
delete "/api/v1/admin/races/#{race.id}", headers: @headers
expect(response).to have_http_status(200)
u = JSON.parse(response.body).deep_symbolize_keys
expect(u[:success]).to eq(true)
expect(u[:races].any? { |race| race }).to eq(false)
end
end
end
| 34.601896 | 89 | 0.661279 |
1dc2205644f935a41d869619a3e2556c453f14aa | 1,972 | describe ManageIQ::Providers::Nuage::NetworkManager::EventParser do
let(:ems) { FactoryBot.create(:ems_nuage_network) }
context ".event_to_hash" do
[
{
:name => 'with requestID',
:fixture => '/event_catcher/events/subnet_create.json',
:expected => {
:event_type => 'nuage_subnet_create',
:message => 'Audit-Subnet (4e08bf9c-b679-4c82-a6f7-b298a3901d25)',
:ems_ref => '56e69f6e-a1fd-457f-b4c5-844cfd790153'
}
},
{
:name => 'with null requestID',
:fixture => '/event_catcher/events/alarm_delete.json',
:expected => {
:event_type => 'nuage_alarm_nsgateway_delete_4707',
:message => 'MAJOR: Gateway with system-id [201.26.92.41] is disconnected'
}
},
{
:name => 'with empty requestID',
:fixture => '/event_catcher/events/alarm_create.json',
:expected => {
:event_type => 'nuage_alarm_nsgateway_create_4707',
:message => 'MAJOR: Gateway with system-id [213.50.60.102] is disconnected'
}
},
{
:name => 'alarm 4713',
:fixture => '/event_catcher/events/alarm_4713.json',
:expected => {
:event_type => 'nuage_alarm_nsgateway_delete_4713',
:message => 'MAJOR: Gateway with system-id [213.50.60.102] is disconnected from controller [vsc1:100.100.100.21]'
}
}
].each do |example|
it example[:name] do
message = JSON.parse(File.read(File.join(__dir__, example[:fixture])))
example[:expected][:ems_id] = ems.id
example[:expected][:vm_ems_ref] = nil
example[:expected][:source] = 'NUAGE'
example[:expected][:message] = example[:expected][:message]
example[:expected][:full_data] = message.to_hash
expect(described_class.event_to_hash(message, ems.id)).to include(example[:expected])
end
end
end
end
| 37.923077 | 126 | 0.5857 |
115d9fcbefa0f7d4fd0aecdb5b30504b75c843d8 | 1,829 | require "logstash/outputs/base"
require "logstash/namespace"
class LogStash::Outputs::Stomp < LogStash::Outputs::Base
config_name "stomp"
milestone 2
# The address of the STOMP server.
config :host, :validate => :string, :required => true
# The port to connect to on your STOMP server.
config :port, :validate => :number, :default => 61613
# The username to authenticate with.
config :user, :validate => :string, :default => ""
# The password to authenticate with.
config :password, :validate => :password, :default => ""
# The destination to read events from. Supports string expansion, meaning
# %{foo} values will expand to the field value.
#
# Example: "/topic/logstash"
config :destination, :validate => :string, :required => true
# The vhost to use
config :vhost, :validate => :string, :default => nil
# Enable debugging output?
config :debug, :validate => :boolean, :default => false
private
def connect
begin
@client.connect
@logger.debug("Connected to stomp server") if @client.connected?
rescue => e
@logger.debug("Failed to connect to stomp server, will retry",
:exception => e, :backtrace => e.backtrace)
sleep 2
retry
end
end
public
def register
require "onstomp"
@client = OnStomp::Client.new("stomp://#{@host}:#{@port}", :login => @user, :passcode => @password.value)
@client.host = @vhost if @vhost
# Handle disconnects
@client.on_connection_closed {
connect
}
connect
end # def register
def receive(event)
return unless output?(event)
@logger.debug(["stomp sending event", { :host => @host, :event => event }])
@client.send(event.sprintf(@destination), event.to_json)
end # def receive
end # class LogStash::Outputs::Stomp
| 27.298507 | 109 | 0.649535 |
0350f17ec92cc34645b16d003994b0ddcdc730a9 | 2,058 | require 'bosh/dev/command_helper'
module Bosh::Dev
class GitBranchMerger
include CommandHelper
def initialize(logger)
@logger = logger
end
def merge(source_sha, target_branch, commit_message)
stdout, stderr, status = exec_cmd("git fetch origin #{target_branch}")
raise "Failed fetching branch #{target_branch}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd("git checkout #{target_branch}")
raise "Failed checking out branch #{target_branch}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd("git merge #{source_sha} -m '#{commit_message}'")
raise "Failed merging to branch #{target_branch}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd("git push origin #{target_branch}")
raise "Failed pushing to branch #{target_branch}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
end
def branch_contains?(branch_name, commit_sha)
stdout, stderr, status = exec_cmd("git fetch origin #{branch_name}")
raise "Failed fetching branch #{branch_name}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd("git checkout #{branch_name}")
raise "Failed to git checkout #{branch_name}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd('git pull')
raise "Failed to git pull: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
stdout, stderr, status = exec_cmd("git branch --contains #{commit_sha}")
raise "Failed finding branches that contain sha #{commit_sha}: stdout: '#{stdout}', stderr: '#{stderr}'" unless status.success?
branches = stdout.strip.lines.map(&:strip)
# the currently checked out branch is prefixed with a star
branches = branches.map{ |line| line.sub(/^\* /, '') }
branches.include?(branch_name)
end
end
end
| 45.733333 | 133 | 0.673955 |
386258614286a46e99e5bd4be589bf258b71454f | 1,787 | class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :password)
end
end
| 23.826667 | 88 | 0.6385 |
6220008de2451656f7829877b4cd197760027bb0 | 2,987 | # -*- coding: utf-8 -*-
require 'helper'
class TestRegressionAutofilter03 < Minitest::Test
def setup
setup_dir_var
end
def teardown
@tempfile.close(true)
end
def test_autofilter03
@xlsx = 'autofilter03.xlsx'
workbook = WriteXLSX.new(@io)
worksheet = workbook.add_worksheet
data = []
data_lines.split(/\n/).each { |line| data << line.split }
worksheet.write('A1', headings)
worksheet.autofilter(0, 0, 50, 3)
worksheet.filter_column('A', 'x eq East or x eq South')
# Hide the rows that don't match the filter criteria.
row = 1
data.each do |row_data|
region = row_data[0]
if region == 'East' || region == 'South'
# Row is visible.
else
# Hide row.
worksheet.set_row(row, nil, nil, 1)
end
worksheet.write(row, 0, row_data)
row += 1
end
workbook.close
compare_for_regression(
nil,
{'xl/workbook.xml' => ['<workbookView']}
)
end
def headings
%w[Region Item Volume Month]
end
def data_lines
<<EOS
East Apple 9000 July
East Apple 5000 July
South Orange 9000 September
North Apple 2000 November
West Apple 9000 November
South Pear 7000 October
North Pear 9000 August
West Orange 1000 December
West Grape 1000 November
South Pear 10000 April
West Grape 6000 January
South Orange 3000 May
North Apple 3000 December
South Apple 7000 February
West Grape 1000 December
East Grape 8000 February
South Grape 10000 June
West Pear 7000 December
South Apple 2000 October
East Grape 7000 December
North Grape 6000 April
East Pear 8000 February
North Apple 7000 August
North Orange 7000 July
North Apple 6000 June
South Grape 8000 September
West Apple 3000 October
South Orange 10000 November
West Grape 4000 July
North Orange 5000 August
East Orange 1000 November
East Orange 4000 October
North Grape 5000 August
East Apple 1000 December
South Apple 10000 March
East Grape 7000 October
West Grape 1000 September
East Grape 10000 October
South Orange 8000 March
North Apple 4000 July
South Orange 5000 July
West Apple 4000 June
East Apple 5000 April
North Pear 3000 August
East Grape 9000 November
North Orange 8000 October
East Apple 10000 June
South Pear 1000 December
North Grape 10000 July
East Grape 6000 February
EOS
end
end
| 28.447619 | 61 | 0.556746 |
1a76cab173d4298a6f2d9ac3f5a3981adde86a7e | 444 | require 'rails_helper'
describe "MeasureComponent XML generation" do
let(:db_record) do
create(:measure_component)
end
let(:data_namespace) do
"oub:measure.component"
end
let(:fields_to_check) do
%i[
measure_sid
duty_expression_id
duty_amount
monetary_unit_code
measurement_unit_code
measurement_unit_qualifier_code
]
end
include_context "xml_generation_record_context"
end
| 17.76 | 49 | 0.720721 |
e26c1b0bc0393cf5d4e19b9897d5c9c0ad1cb1fa | 317 | module Gradebooks
class HistogramsController < BaseController
def show
authorize(:generic, :manage_results?)
@histogram = GradebookClient::Histogram.find_by_gradebook_assignment_id(
params[:gradebook_assignment_id],
number_of_bins: params[:number_of_bins],
)
end
end
end
| 26.416667 | 78 | 0.719243 |
f73b4c3716823bb0ce070b892cbf5b779753f1fd | 852 | module Trasto
module Translates
def translates(*columns)
extend Trasto::ClassMethods
include Trasto::InstanceMethods
# Don't overwrite values if running multiple times in the same class
# or in different classes of an inheritance chain.
unless respond_to?(:translatable_columns)
class_attribute :translatable_columns
self.translatable_columns = []
end
self.translatable_columns |= columns.map(&:to_sym)
columns.each { |column| define_localized_attribute(column) }
end
private
def define_localized_attribute(column)
define_method(column) do
read_localized_value(column)
end
define_method("#{column}=") do |value|
write_localized_value(column, value)
end
end
end
end
ActiveRecord::Base.send :extend, Trasto::Translates
| 25.058824 | 74 | 0.691315 |
d5813ad22e74405b1dcbf69429f17505f8b314ed | 45 | include_recipe 'daddy::wkhtmltopdf::install'
| 22.5 | 44 | 0.822222 |
1db52af59b608beb5b5fc022727a7d54dd85ec79 | 31,513 | require "cases/helper"
require 'models/minimalistic'
require 'models/developer'
require 'models/auto_id'
require 'models/boolean'
require 'models/computer'
require 'models/topic'
require 'models/company'
require 'models/category'
require 'models/reply'
require 'models/contact'
require 'models/keyboard'
class AttributeMethodsTest < ActiveRecord::TestCase
include InTimeZone
fixtures :topics, :developers, :companies, :computers
def setup
@old_matchers = ActiveRecord::Base.send(:attribute_method_matchers).dup
@target = Class.new(ActiveRecord::Base)
@target.table_name = 'topics'
end
teardown do
ActiveRecord::Base.send(:attribute_method_matchers).clear
ActiveRecord::Base.send(:attribute_method_matchers).concat(@old_matchers)
end
def test_attribute_for_inspect
t = topics(:first)
t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
assert_equal '"The First Topic Now Has A Title With\nNewlines And ..."', t.attribute_for_inspect(:title)
end
def test_attribute_present
t = Topic.new
t.title = "hello there!"
t.written_on = Time.now
t.author_name = ""
assert t.attribute_present?("title")
assert t.attribute_present?("written_on")
assert !t.attribute_present?("content")
assert !t.attribute_present?("author_name")
end
def test_attribute_present_with_booleans
b1 = Boolean.new
b1.value = false
assert b1.attribute_present?(:value)
b2 = Boolean.new
b2.value = true
assert b2.attribute_present?(:value)
b3 = Boolean.new
assert !b3.attribute_present?(:value)
b4 = Boolean.new
b4.value = false
b4.save!
assert Boolean.find(b4.id).attribute_present?(:value)
end
def test_caching_nil_primary_key
klass = Class.new(Minimalistic)
assert_called(klass, :reset_primary_key, returns: nil) do
2.times { klass.primary_key }
end
end
def test_attribute_keys_on_new_instance
t = Topic.new
assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
assert_raise(NoMethodError) { t.title2 }
end
def test_boolean_attributes
assert !Topic.find(1).approved?
assert Topic.find(2).approved?
end
def test_set_attributes
topic = Topic.find(1)
topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
topic.save
assert_equal("Budget", topic.title)
assert_equal("Jason", topic.author_name)
assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
end
def test_set_attributes_without_hash
topic = Topic.new
assert_raise(ArgumentError) { topic.attributes = '' }
end
def test_integers_as_nil
test = AutoId.create('value' => '')
assert_nil AutoId.find(test.id).value
end
def test_set_attributes_with_block
topic = Topic.new do |t|
t.title = "Budget"
t.author_name = "Jason"
end
assert_equal("Budget", topic.title)
assert_equal("Jason", topic.author_name)
end
def test_respond_to?
topic = Topic.find(1)
assert_respond_to topic, "title"
assert_respond_to topic, "title?"
assert_respond_to topic, "title="
assert_respond_to topic, :title
assert_respond_to topic, :title?
assert_respond_to topic, :title=
assert_respond_to topic, "author_name"
assert_respond_to topic, "attribute_names"
assert !topic.respond_to?("nothingness")
assert !topic.respond_to?(:nothingness)
end
def test_respond_to_with_custom_primary_key
keyboard = Keyboard.create
assert_not_nil keyboard.key_number
assert_equal keyboard.key_number, keyboard.id
assert keyboard.respond_to?('key_number')
assert keyboard.respond_to?('id')
end
def test_id_before_type_cast_with_custom_primary_key
keyboard = Keyboard.create
keyboard.key_number = '10'
assert_equal '10', keyboard.id_before_type_cast
assert_equal nil, keyboard.read_attribute_before_type_cast('id')
assert_equal '10', keyboard.read_attribute_before_type_cast('key_number')
assert_equal '10', keyboard.read_attribute_before_type_cast(:key_number)
end
# Syck calls respond_to? before actually calling initialize
def test_respond_to_with_allocated_object
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'topics'
end
topic = klass.allocate
assert !topic.respond_to?("nothingness")
assert !topic.respond_to?(:nothingness)
assert_respond_to topic, "title"
assert_respond_to topic, :title
end
# IRB inspects the return value of "MyModel.allocate".
def test_allocated_object_can_be_inspected
topic = Topic.allocate
assert_equal "#<Topic not initialized>", topic.inspect
end
def test_array_content
topic = Topic.new
topic.content = %w( one two three )
topic.save
assert_equal(%w( one two three ), Topic.find(topic.id).content)
end
def test_read_attributes_before_type_cast
category = Category.new({:name=>"Test category", :type => nil})
category_attrs = {"name"=>"Test category", "id" => nil, "type" => nil, "categorizations_count" => nil}
assert_equal category_attrs , category.attributes_before_type_cast
end
if current_adapter?(:Mysql2Adapter)
def test_read_attributes_before_type_cast_on_boolean
bool = Boolean.create!({ "value" => false })
if RUBY_PLATFORM =~ /java/
# JRuby will return the value before typecast as string
assert_equal "0", bool.reload.attributes_before_type_cast["value"]
else
assert_equal 0, bool.reload.attributes_before_type_cast["value"]
end
end
end
def test_read_attributes_before_type_cast_on_datetime
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = "345643456"
assert_equal "345643456", record.written_on_before_type_cast
assert_equal nil, record.written_on
record.written_on = "2009-10-11 12:13:14"
assert_equal "2009-10-11 12:13:14", record.written_on_before_type_cast
assert_equal Time.zone.parse("2009-10-11 12:13:14"), record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
end
end
def test_read_attributes_after_type_cast_on_datetime
tz = "Pacific Time (US & Canada)"
in_time_zone tz do
record = @target.new
date_string = "2011-03-24"
time = Time.zone.parse date_string
record.written_on = date_string
assert_equal date_string, record.written_on_before_type_cast
assert_equal time, record.written_on
assert_equal ActiveSupport::TimeZone[tz], record.written_on.time_zone
record.save
record.reload
assert_equal time, record.written_on
end
end
def test_hash_content
topic = Topic.new
topic.content = { "one" => 1, "two" => 2 }
topic.save
assert_equal 2, Topic.find(topic.id).content["two"]
topic.content_will_change!
topic.content["three"] = 3
topic.save
assert_equal 3, Topic.find(topic.id).content["three"]
end
def test_update_array_content
topic = Topic.new
topic.content = %w( one two three )
topic.content.push "four"
assert_equal(%w( one two three four ), topic.content)
topic.save
topic = Topic.find(topic.id)
topic.content << "five"
assert_equal(%w( one two three four five ), topic.content)
end
def test_case_sensitive_attributes_hash
# DB2 is not case-sensitive
return true if current_adapter?(:DB2Adapter)
assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.first.attributes
end
def test_attributes_without_primary_key
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'developers_projects'
end
assert_equal klass.column_names, klass.new.attributes.keys
assert_not klass.new.has_attribute?('id')
end
def test_hashes_not_mangled
new_topic = { :title => "New Topic" }
new_topic_values = { :title => "AnotherTopic" }
topic = Topic.new(new_topic)
assert_equal new_topic[:title], topic.title
topic.attributes= new_topic_values
assert_equal new_topic_values[:title], topic.title
end
def test_create_through_factory
topic = Topic.create("title" => "New Topic")
topicReloaded = Topic.find(topic.id)
assert_equal(topic, topicReloaded)
end
def test_write_attribute
topic = Topic.new
topic.send(:write_attribute, :title, "Still another topic")
assert_equal "Still another topic", topic.title
topic[:title] = "Still another topic: part 2"
assert_equal "Still another topic: part 2", topic.title
topic.send(:write_attribute, "title", "Still another topic: part 3")
assert_equal "Still another topic: part 3", topic.title
topic["title"] = "Still another topic: part 4"
assert_equal "Still another topic: part 4", topic.title
end
def test_read_attribute
topic = Topic.new
topic.title = "Don't change the topic"
assert_equal "Don't change the topic", topic.read_attribute("title")
assert_equal "Don't change the topic", topic["title"]
assert_equal "Don't change the topic", topic.read_attribute(:title)
assert_equal "Don't change the topic", topic[:title]
end
def test_read_attribute_raises_missing_attribute_error_when_not_exists
computer = Computer.select('id').first
assert_raises(ActiveModel::MissingAttributeError) { computer[:developer] }
assert_raises(ActiveModel::MissingAttributeError) { computer[:extendedWarranty] }
assert_raises(ActiveModel::MissingAttributeError) { computer[:no_column_exists] = 'Hello!' }
assert_nothing_raised { computer[:developer] = 'Hello!' }
end
def test_read_attribute_when_false
topic = topics(:first)
topic.approved = false
assert !topic.approved?, "approved should be false"
topic.approved = "false"
assert !topic.approved?, "approved should be false"
end
def test_read_attribute_when_true
topic = topics(:first)
topic.approved = true
assert topic.approved?, "approved should be true"
topic.approved = "true"
assert topic.approved?, "approved should be true"
end
def test_read_write_boolean_attribute
topic = Topic.new
topic.approved = "false"
assert !topic.approved?, "approved should be false"
topic.approved = "false"
assert !topic.approved?, "approved should be false"
topic.approved = "true"
assert topic.approved?, "approved should be true"
topic.approved = "true"
assert topic.approved?, "approved should be true"
end
def test_overridden_write_attribute
topic = Topic.new
def topic.write_attribute(attr_name, value)
super(attr_name, value.downcase)
end
topic.send(:write_attribute, :title, "Yet another topic")
assert_equal "yet another topic", topic.title
topic[:title] = "Yet another topic: part 2"
assert_equal "yet another topic: part 2", topic.title
topic.send(:write_attribute, "title", "Yet another topic: part 3")
assert_equal "yet another topic: part 3", topic.title
topic["title"] = "Yet another topic: part 4"
assert_equal "yet another topic: part 4", topic.title
end
def test_overridden_read_attribute
topic = Topic.new
topic.title = "Stop changing the topic"
def topic.read_attribute(attr_name)
super(attr_name).upcase
end
assert_equal "STOP CHANGING THE TOPIC", topic.read_attribute("title")
assert_equal "STOP CHANGING THE TOPIC", topic["title"]
assert_equal "STOP CHANGING THE TOPIC", topic.read_attribute(:title)
assert_equal "STOP CHANGING THE TOPIC", topic[:title]
end
def test_read_overridden_attribute
topic = Topic.new(:title => 'a')
def topic.title() 'b' end
assert_equal 'a', topic[:title]
end
def test_query_attribute_string
[nil, "", " "].each do |value|
assert_equal false, Topic.new(:author_name => value).author_name?
end
assert_equal true, Topic.new(:author_name => "Name").author_name?
end
def test_query_attribute_number
[nil, 0, "0"].each do |value|
assert_equal false, Developer.new(:salary => value).salary?
end
assert_equal true, Developer.new(:salary => 1).salary?
assert_equal true, Developer.new(:salary => "1").salary?
end
def test_query_attribute_boolean
[nil, "", false, "false", "f", 0].each do |value|
assert_equal false, Topic.new(:approved => value).approved?
end
[true, "true", "1", 1].each do |value|
assert_equal true, Topic.new(:approved => value).approved?
end
end
def test_query_attribute_with_custom_fields
object = Company.find_by_sql(<<-SQL).first
SELECT c1.*, c2.type as string_value, c2.rating as int_value
FROM companies c1, companies c2
WHERE c1.firm_id = c2.id
AND c1.id = 2
SQL
assert_equal "Firm", object.string_value
assert object.string_value?
object.string_value = " "
assert !object.string_value?
assert_equal 1, object.int_value.to_i
assert object.int_value?
object.int_value = "0"
assert !object.int_value?
end
def test_non_attribute_access_and_assignment
topic = Topic.new
assert !topic.respond_to?("mumbo")
assert_raise(NoMethodError) { topic.mumbo }
assert_raise(NoMethodError) { topic.mumbo = 5 }
end
def test_undeclared_attribute_method_does_not_affect_respond_to_and_method_missing
topic = @target.new(:title => 'Budget')
assert topic.respond_to?('title')
assert_equal 'Budget', topic.title
assert !topic.respond_to?('title_hello_world')
assert_raise(NoMethodError) { topic.title_hello_world }
end
def test_declared_prefixed_attribute_method_affects_respond_to_and_method_missing
topic = @target.new(:title => 'Budget')
%w(default_ title_).each do |prefix|
@target.class_eval "def #{prefix}attribute(*args) args end"
@target.attribute_method_prefix prefix
meth = "#{prefix}title"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
def test_declared_suffixed_attribute_method_affects_respond_to_and_method_missing
%w(_default _title_default _it! _candidate= able?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
topic = @target.new(:title => 'Budget')
meth = "title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
def test_declared_affixed_attribute_method_affects_respond_to_and_method_missing
[['mark_', '_for_update'], ['reset_', '!'], ['default_', '_value?']].each do |prefix, suffix|
@target.class_eval "def #{prefix}attribute#{suffix}(*args) args end"
@target.attribute_method_affix({ :prefix => prefix, :suffix => suffix })
topic = @target.new(:title => 'Budget')
meth = "#{prefix}title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
def test_should_unserialize_attributes_for_frozen_records
myobj = {:value1 => :value2}
topic = Topic.create("content" => myobj)
topic.freeze
assert_equal myobj, topic.content
end
def test_typecast_attribute_from_select_to_false
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter, :FbAdapter)
topic = Topic.all.merge!(:select => "topics.*, 0 as is_test").first
else
topic = Topic.all.merge!(:select => "topics.*, 1=2 as is_test").first
end
assert !topic.is_test?
end
def test_typecast_attribute_from_select_to_true
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter, :FbAdapter)
topic = Topic.all.merge!(:select => "topics.*, 1 as is_test").first
else
topic = Topic.all.merge!(:select => "topics.*, 2=2 as is_test").first
end
assert topic.is_test?
end
def test_raises_dangerous_attribute_error_when_defining_activerecord_method_in_model
%w(save create_or_update).each do |method|
klass = Class.new ActiveRecord::Base
klass.class_eval "def #{method}() 'defined #{method}' end"
assert_raise ActiveRecord::DangerousAttributeError do
klass.instance_method_already_implemented?(method)
end
end
end
def test_converted_values_are_returned_after_assignment
developer = Developer.new(name: 1337, salary: "50000")
assert_equal "50000", developer.salary_before_type_cast
assert_equal 1337, developer.name_before_type_cast
assert_equal 50000, developer.salary
assert_equal "1337", developer.name
developer.save!
assert_equal 50000, developer.salary
assert_equal "1337", developer.name
end
def test_write_nil_to_time_attributes
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = nil
assert_nil record.written_on
end
end
def test_write_time_to_date_attributes
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.last_read = Time.utc(2010, 1, 1, 10)
assert_equal Date.civil(2010, 1, 1), record.last_read
end
end
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
record[:written_on] = utc_time
assert_equal utc_time, record.written_on # record.written on is equal to (i.e., simultaneous with) utc_time
assert_kind_of ActiveSupport::TimeWithZone, record.written_on # but is a TimeWithZone
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time # and represents time values adjusted accordingly
end
end
def test_setting_time_zone_aware_attribute_to_utc
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
record.written_on = utc_time
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_setting_time_zone_aware_attribute_in_other_time_zone
utc_time = Time.utc(2008, 1, 1)
cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = cst_time
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_setting_time_zone_aware_read_attribute
utc_time = Time.utc(2008, 1, 1)
cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
in_time_zone "Pacific Time (US & Canada)" do
record = @target.create(:written_on => cst_time).reload
assert_equal utc_time, record[:written_on]
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record[:written_on].time_zone
assert_equal Time.utc(2007, 12, 31, 16), record[:written_on].time
end
end
def test_setting_time_zone_aware_attribute_with_string
utc_time = Time.utc(2008, 1, 1)
(-11..13).each do |timezone_offset|
time_string = utc_time.in_time_zone(timezone_offset).to_s
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
end
def test_time_zone_aware_attribute_saved
in_time_zone 1 do
record = @target.create(:written_on => '2012-02-20 10:00')
record.written_on = '2012-02-20 09:00'
record.save
assert_equal Time.zone.local(2012, 02, 20, 9), record.reload.written_on
end
end
def test_setting_time_zone_aware_attribute_to_blank_string_returns_nil
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = ' '
assert_nil record.written_on
assert_nil record[:written_on]
end
end
def test_setting_time_zone_aware_attribute_interprets_time_zone_unaware_string_in_time_zone
time_string = 'Tue Jan 01 00:00:00 2008'
(-11..13).each do |timezone_offset|
in_time_zone timezone_offset do
record = @target.new
record.written_on = time_string
assert_equal Time.zone.parse(time_string), record.written_on
assert_equal ActiveSupport::TimeZone[timezone_offset], record.written_on.time_zone
assert_equal Time.utc(2008, 1, 1), record.written_on.time
end
end
end
def test_setting_time_zone_aware_datetime_in_current_time_zone
utc_time = Time.utc(2008, 1, 1)
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = utc_time.in_time_zone
assert_equal utc_time, record.written_on
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
end
end
def test_yaml_dumping_record_with_time_zone_aware_attribute
in_time_zone "Pacific Time (US & Canada)" do
record = Topic.new(id: 1)
record.written_on = "Jan 01 00:00:00 2014"
assert_equal record, YAML.load(YAML.dump(record))
end
end
def test_setting_time_zone_aware_time_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
time_string = "10:00:00"
expected_time = Time.zone.parse("2000-01-01 #{time_string}")
record.bonus_time = time_string
assert_equal expected_time, record.bonus_time
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.bonus_time.time_zone
record.bonus_time = ''
assert_nil record.bonus_time
end
end
def test_setting_time_zone_aware_time_with_dst
in_time_zone "Pacific Time (US & Canada)" do
current_time = Time.zone.local(2014, 06, 15, 10)
record = @target.new(bonus_time: current_time)
time_before_save = record.bonus_time
record.save
record.reload
assert_equal time_before_save, record.bonus_time
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.bonus_time.time_zone
end
end
def test_removing_time_zone_aware_types
with_time_zone_aware_types(:datetime) do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new(bonus_time: "10:00:00")
expected_time = Time.utc(2000, 01, 01, 10)
assert_equal expected_time, record.bonus_time
assert record.bonus_time.utc?
end
end
end
def test_time_zone_aware_attributes_dont_recurse_infinitely_on_invalid_values
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new(bonus_time: [])
assert_equal nil, record.bonus_time
end
end
def test_setting_time_zone_conversion_for_attributes_should_write_value_on_class_variable
Topic.skip_time_zone_conversion_for_attributes = [:field_a]
Minimalistic.skip_time_zone_conversion_for_attributes = [:field_b]
assert_equal [:field_a], Topic.skip_time_zone_conversion_for_attributes
assert_equal [:field_b], Minimalistic.skip_time_zone_conversion_for_attributes
end
def test_read_attributes_respect_access_control
privatize("title")
topic = @target.new(:title => "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
assert exception.message.include?("private method")
assert_equal "I'm private", topic.send(:title)
end
def test_write_attributes_respect_access_control
privatize("title=(value)")
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = "Pants"}
assert exception.message.include?("private method")
topic.send(:title=, "Very large pants")
end
def test_question_attributes_respect_access_control
privatize("title?")
topic = @target.new(:title => "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
assert exception.message.include?("private method")
assert topic.send(:title?)
end
def test_bulk_update_respects_access_control
privatize("title=(value)")
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
end
def test_bulk_update_raise_unknown_attribute_error
error = assert_raises(ActiveRecord::UnknownAttributeError) {
Topic.new(hello: "world")
}
assert_instance_of Topic, error.record
assert_equal "hello", error.attribute
assert_equal "unknown attribute 'hello' for Topic.", error.message
end
def test_methods_override_in_multi_level_subclass
klass = Class.new(Developer) do
def name
"dev:#{read_attribute(:name)}"
end
end
2.times { klass = Class.new klass }
dev = klass.new(name: 'arthurnn')
dev.save!
assert_equal 'dev:arthurnn', dev.reload.name
end
def test_global_methods_are_overwritten
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'computers'
end
assert !klass.instance_method_already_implemented?(:system)
computer = klass.new
assert_nil computer.system
end
def test_global_methods_are_overwritten_when_subclassing
klass = Class.new(ActiveRecord::Base) { self.abstract_class = true }
subklass = Class.new(klass) do
self.table_name = 'computers'
end
assert !klass.instance_method_already_implemented?(:system)
assert !subklass.instance_method_already_implemented?(:system)
computer = subklass.new
assert_nil computer.system
end
def test_instance_method_should_be_defined_on_the_base_class
subklass = Class.new(Topic)
Topic.define_attribute_methods
instance = subklass.new
instance.id = 5
assert_equal 5, instance.id
assert subklass.method_defined?(:id), "subklass is missing id method"
Topic.undefine_attribute_methods
assert_equal 5, instance.id
assert subklass.method_defined?(:id), "subklass is missing id method"
end
def test_read_attribute_with_nil_should_not_asplode
assert_equal nil, Topic.new.read_attribute(nil)
end
# If B < A, and A defines an accessor for 'foo', we don't want to override
# that by defining a 'foo' method in the generated methods module for B.
# (That module will be inserted between the two, e.g. [B, <GeneratedAttributes>, A].)
def test_inherited_custom_accessors
klass = new_topic_like_ar_class do
self.abstract_class = true
def title; "omg"; end
def title=(val); self.author_name = val; end
end
subklass = Class.new(klass)
[klass, subklass].each(&:define_attribute_methods)
topic = subklass.find(1)
assert_equal "omg", topic.title
topic.title = "lol"
assert_equal "lol", topic.author_name
end
def test_inherited_custom_accessors_with_reserved_names
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'computers'
self.abstract_class = true
def system; "omg"; end
def system=(val); self.developer = val; end
end
subklass = Class.new(klass)
[klass, subklass].each(&:define_attribute_methods)
computer = subklass.find(1)
assert_equal "omg", computer.system
computer.developer = 99
assert_equal 99, computer.developer
end
def test_on_the_fly_super_invokable_generated_attribute_methods_via_method_missing
klass = new_topic_like_ar_class do
def title
super + '!'
end
end
real_topic = topics(:first)
assert_equal real_topic.title + '!', klass.find(real_topic.id).title
end
def test_on_the_fly_super_invokable_generated_predicate_attribute_methods_via_method_missing
klass = new_topic_like_ar_class do
def title?
!super
end
end
real_topic = topics(:first)
assert_equal !real_topic.title?, klass.find(real_topic.id).title?
end
def test_calling_super_when_parent_does_not_define_method_raises_error
klass = new_topic_like_ar_class do
def some_method_that_is_not_on_super
super
end
end
assert_raise(NoMethodError) do
klass.new.some_method_that_is_not_on_super
end
end
def test_attribute_method?
assert @target.attribute_method?(:title)
assert @target.attribute_method?(:title=)
assert_not @target.attribute_method?(:wibble)
end
def test_attribute_method_returns_false_if_table_does_not_exist
@target.table_name = 'wibble'
assert_not @target.attribute_method?(:title)
end
def test_attribute_names_on_new_record
model = @target.new
assert_equal @target.column_names, model.attribute_names
end
def test_attribute_names_on_queried_record
model = @target.last!
assert_equal @target.column_names, model.attribute_names
end
def test_attribute_names_with_custom_select
model = @target.select('id').last!
assert_equal ['id'], model.attribute_names
# Sanity check, make sure other columns exist
assert_not_equal ['id'], @target.column_names
end
def test_came_from_user
model = @target.first
assert_not model.id_came_from_user?
model.id = "omg"
assert model.id_came_from_user?
end
def test_accessed_fields
model = @target.first
assert_equal [], model.accessed_fields
model.title
assert_equal ["title"], model.accessed_fields
end
private
def new_topic_like_ar_class(&block)
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'topics'
class_eval(&block)
end
assert_empty klass.generated_attribute_methods.instance_methods(false)
klass
end
def with_time_zone_aware_types(*types)
old_types = ActiveRecord::Base.time_zone_aware_types
ActiveRecord::Base.time_zone_aware_types = types
yield
ensure
ActiveRecord::Base.time_zone_aware_types = old_types
end
def cached_columns
Topic.columns.map(&:name)
end
def time_related_columns_on_topic
Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) }
end
def privatize(method_signature)
@target.class_eval(<<-private_method, __FILE__, __LINE__ + 1)
private
def #{method_signature}
"I'm private"
end
private_method
end
end
| 31.799193 | 135 | 0.713134 |
21436f5beb345187afd461d2ec47bcffccccb424 | 32 | module FavouriteListsHelper
end
| 10.666667 | 27 | 0.90625 |
281ad32aac416822f11691631f20c9359745a3d9 | 831 | class Grails < Formula
version "20"
desc "Web application framework for the Groovy language"
homepage "http://grails.org"
url "http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-2.0.4.zip"
sha256 "51a273b8d51c08a21111bba774745db70370fbe7df906dba5551da2376f4f41b"
bottle :unneeded
# Grails 2.0.x doesn't support Java 8
depends_on :java => "1.7"
def install
rm_f Dir["bin/*.bat", "bin/cygrails", "*.bat"]
prefix.install %w[LICENSE README]
libexec.install Dir["*"]
bin.mkpath
Dir["#{libexec}/bin/*"].each do |f|
next unless File.extname(f).empty?
ln_s f, bin+File.basename(f)
end
end
test do
ENV["JAVA_HOME"] = `/usr/libexec/java_home`.chomp
assert_match "Grails version: #{version}",
shell_output("#{bin}/grails --version", 1)
end
end
| 27.7 | 88 | 0.677497 |
4a5492e9d7668ed0faeb9a83855b6c0d5bb6846b | 1,416 | require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "unsuccessful edit" do
log_in_as(@user)
get edit_user_path(@user)
assert_template 'users/edit'
patch user_path(@user), params: {user: {name: "", email: "foo@invalid",
password: "foo", password_confirmation: "bar"}}
assert_template 'users/edit'
assert_select "div.alert"
end
test "successful edit" do
log_in_as(@user)
get edit_user_path(@user)
assert_template "users/edit"
name = "FooBar"
email = "[email protected]"
patch user_path(@user), params: {user: {name: name, email: email,
password: "", password_confirmation: ""}}
assert_not flash.empty?
assert_redirected_to @user
@user.reload
assert_equal name, @user.name
assert_equal email, @user.email
end
test "successful edit with friendly forwarding" do
get edit_user_path(@user)
log_in_as(@user)
assert_redirected_to edit_user_url(@user)
name = "Foo Bar"
email = "[email protected]"
patch user_path(@user),
params: {user: {name: name, email: email, password: "",
password_confirmation: ""}}
assert_not flash.empty?
assert_redirected_to @user
@user.reload
assert_equal name, @user.name
assert_equal email, @user.email
end
end
| 28.32 | 91 | 0.641243 |
879cf56045eb0a9ffc27afe960e6b58b4ac46321 | 6,994 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Security::Mgmt::V2019_08_01
#
# A service client - single point of access to the REST API.
#
class SecurityCenter < MsRestAzure::AzureServiceClient
include MsRestAzure
include MsRestAzure::Serialization
# @return [String] the base URI of the service.
attr_accessor :base_url
# @return Credentials needed for the client to connect to Azure.
attr_reader :credentials
# @return [String] Azure subscription ID
attr_accessor :subscription_id
# @return [String] API version for the operation
attr_reader :api_version
# @return [String] The preferred language for the response.
attr_accessor :accept_language
# @return [Integer] The retry timeout in seconds for Long Running
# Operations. Default value is 30.
attr_accessor :long_running_operation_retry_timeout
# @return [Boolean] Whether a unique x-ms-client-request-id should be
# generated. When set to true a unique x-ms-client-request-id value is
# generated and included in each request. Default is true.
attr_accessor :generate_client_request_id
# @return [IoTSecuritySolutionsAnalytics] io_tsecurity_solutions_analytics
attr_reader :io_tsecurity_solutions_analytics
# @return [IoTSecuritySolutionsAnalyticsAggregatedAlerts]
# io_tsecurity_solutions_analytics_aggregated_alerts
attr_reader :io_tsecurity_solutions_analytics_aggregated_alerts
# @return [IoTSecuritySolutionsAnalyticsAggregatedAlert]
# io_tsecurity_solutions_analytics_aggregated_alert
attr_reader :io_tsecurity_solutions_analytics_aggregated_alert
# @return [IoTSecuritySolutionsAnalyticsRecommendation]
# io_tsecurity_solutions_analytics_recommendation
attr_reader :io_tsecurity_solutions_analytics_recommendation
# @return [IoTSecuritySolutionsAnalyticsRecommendations]
# io_tsecurity_solutions_analytics_recommendations
attr_reader :io_tsecurity_solutions_analytics_recommendations
# @return [IoTSecuritySolutions] io_tsecurity_solutions
attr_reader :io_tsecurity_solutions
# @return [IoTSecuritySolutionsResourceGroup]
# io_tsecurity_solutions_resource_group
attr_reader :io_tsecurity_solutions_resource_group
# @return [IotSecuritySolution] iot_security_solution
attr_reader :iot_security_solution
#
# Creates initializes a new instance of the SecurityCenter class.
# @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
# @param base_url [String] the base URI of the service.
# @param options [Array] filters to be applied to the HTTP requests.
#
def initialize(credentials = nil, base_url = nil, options = nil)
super(credentials, options)
@base_url = base_url || 'https://management.azure.com'
fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
@credentials = credentials
@io_tsecurity_solutions_analytics = IoTSecuritySolutionsAnalytics.new(self)
@io_tsecurity_solutions_analytics_aggregated_alerts = IoTSecuritySolutionsAnalyticsAggregatedAlerts.new(self)
@io_tsecurity_solutions_analytics_aggregated_alert = IoTSecuritySolutionsAnalyticsAggregatedAlert.new(self)
@io_tsecurity_solutions_analytics_recommendation = IoTSecuritySolutionsAnalyticsRecommendation.new(self)
@io_tsecurity_solutions_analytics_recommendations = IoTSecuritySolutionsAnalyticsRecommendations.new(self)
@io_tsecurity_solutions = IoTSecuritySolutions.new(self)
@io_tsecurity_solutions_resource_group = IoTSecuritySolutionsResourceGroup.new(self)
@iot_security_solution = IotSecuritySolution.new(self)
@api_version = '2019-08-01'
@accept_language = 'en-US'
@long_running_operation_retry_timeout = 30
@generate_client_request_id = true
add_telemetry
end
#
# Makes a request and returns the body of the response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Hash{String=>String}] containing the body of the response.
# Example:
#
# request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
# path = "/path"
# options = {
# body: request_content,
# query_params: {'api-version' => '2016-02-01'}
# }
# result = @client.make_request(:put, path, options)
#
def make_request(method, path, options = {})
result = make_request_with_http_info(method, path, options)
result.body unless result.nil?
end
#
# Makes a request and returns the operation response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
#
def make_request_with_http_info(method, path, options = {})
result = make_request_async(method, path, options).value!
result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
result
end
#
# Makes a request asynchronously.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def make_request_async(method, path, options = {})
fail ArgumentError, 'method is nil' if method.nil?
fail ArgumentError, 'path is nil' if path.nil?
request_url = options[:base_url] || @base_url
if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
@request_headers['Content-Type'] = options[:headers]['Content-Type']
end
request_headers = @request_headers
request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
options.merge!({headers: request_headers.merge(options[:headers] || {})})
options.merge!({credentials: @credentials}) unless @credentials.nil?
super(request_url, method, path, options)
end
private
#
# Adds telemetry information.
#
def add_telemetry
sdk_information = 'azure_mgmt_security'
sdk_information = "#{sdk_information}/0.18.2"
add_user_agent_information(sdk_information)
end
end
end
| 42.646341 | 154 | 0.734487 |
91da08fd6663ce7740da01850964bf3875925f57 | 1,079 | json.total @total
json.rows @participants do |participant|
json.cache! participant, expires_in: 5.minutes do
json.id participant.id
json.first_middle truncated_formatter(participant.first_middle)
json.first_name truncated_formatter(participant.first_name)
json.middle_initial participant.middle_initial
json.last_name truncated_formatter(participant.last_name)
json.name truncated_formatter(participant.full_name)
json.mrn truncated_formatter(participant.mrn)
json.external_id truncated_formatter(participant.external_id)
json.notes notes_formatter(participant)
json.date_of_birth format_date(participant.date_of_birth)
json.gender participant.gender
json.ethnicity participant.ethnicity
json.race participant.race
json.address truncated_formatter(participant.address)
json.phone phoneNumberFormatter(participant)
json.edit registry_edit_formatter(participant)
json.associate associate_formatter(participant, @protocol)
json.recruitment_source truncated_formatter(participant.recruitment_source)
end
end | 46.913043 | 79 | 0.81835 |
e2f16f59351498080337fb2a5e873d1c0da3e33e | 3,287 | class Filebeat < Formula
desc "File harvester to ship log files to Elasticsearch or Logstash"
homepage "https://www.elastic.co/products/beats/filebeat"
url "https://github.com/elastic/beats.git",
tag: "v7.16.3",
revision: "d420ccdaf201e32a524632b5da729522e50257ae"
# Outside of the "x-pack" folder, source code in a given file is licensed
# under the Apache License Version 2.0
license "Apache-2.0"
head "https://github.com/elastic/beats.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "44740e94c639a000a7b0dfd8a0ff7cd3ac1aa6360223447e67dec7bbc99fba5a"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "a6d01054cb11dfebbc093e916c2fa9a4cb13419a5bec0fbefab2d62f608ff582"
sha256 cellar: :any_skip_relocation, monterey: "8c88ff8e175c674402f6c6ed5314d320800c46ab3fe609b0243caded3d41f6fd"
sha256 cellar: :any_skip_relocation, big_sur: "53313e34a2c27dad9667a2fe2b3a55138f46dfb473feeac4ee7314c54a4424a8"
sha256 cellar: :any_skip_relocation, catalina: "9d14e975d586d638adbe8b1277267cd69872de54faafe0e3d25c758f84add1bf"
sha256 cellar: :any_skip_relocation, x86_64_linux: "890d3e7ef61b74442560b84c77d7fc0d1dfc006779d5be2a0bc2c88916a44875"
end
depends_on "go" => :build
depends_on "mage" => :build
depends_on "[email protected]" => :build
uses_from_macos "rsync" => :build
def install
# remove non open source files
rm_rf "x-pack"
cd "filebeat" do
# don't build docs because it would fail creating the combined OSS/x-pack
# docs and we aren't installing them anyway
inreplace "magefile.go", "mg.SerialDeps(Fields, Dashboards, Config, includeList, fieldDocs,",
"mg.SerialDeps(Fields, Dashboards, Config, includeList,"
# prevent downloading binary wheels during python setup
system "make", "PIP_INSTALL_PARAMS=--no-binary :all", "python-env"
system "mage", "-v", "build"
system "mage", "-v", "update"
(etc/"filebeat").install Dir["filebeat.*", "fields.yml", "modules.d"]
(etc/"filebeat"/"module").install Dir["build/package/modules/*"]
(libexec/"bin").install "filebeat"
prefix.install "build/kibana"
end
(bin/"filebeat").write <<~EOS
#!/bin/sh
exec #{libexec}/bin/filebeat \
--path.config #{etc}/filebeat \
--path.data #{var}/lib/filebeat \
--path.home #{prefix} \
--path.logs #{var}/log/filebeat \
"$@"
EOS
end
service do
run opt_bin/"filebeat"
end
test do
log_file = testpath/"test.log"
touch log_file
(testpath/"filebeat.yml").write <<~EOS
filebeat:
inputs:
-
paths:
- #{log_file}
scan_frequency: 0.1s
output:
file:
path: #{testpath}
EOS
(testpath/"log").mkpath
(testpath/"data").mkpath
fork do
exec "#{bin}/filebeat", "-c", "#{testpath}/filebeat.yml",
"-path.config", "#{testpath}/filebeat",
"-path.home=#{testpath}",
"-path.logs", "#{testpath}/log",
"-path.data", testpath
end
sleep 1
log_file.append_lines "foo bar baz"
sleep 5
assert_predicate testpath/"filebeat", :exist?
end
end
| 33.886598 | 123 | 0.657134 |
1cd05a54aae018c200a279c49a9c2e9ec23d33e9 | 4,688 | #! /usr/bin/ruby
## -*- Mode: Ruby -*-
require "uconv" ;
require "rexml/document" ;
include REXML ;
$LOAD_PATH.push("~/lib/ruby") ;
require "sexp.rb" ;
#======================================================================
# Syntax
=begin
<head> body1 body2 </head>
<==>
(head body1 body2)
<head attr1="value1" attr2="value2"> body </head>
<==>
((head (attr1 "value1") (attr2 "value2")) body)
<!-- comment -->
<==>
(() "!-- comment -->")
{any text}
<==>
"{any text}"
=end
#======================================================================
# SexpXML module
module SexpXML
#--------------------------------------------------
def xml2sexp(node)
if(node.kind_of?(Element)) then
## pick-up head
tag = Uconv.u8toeuc(node.name) ;
## convert attributes
attrs = [] ;
node.attributes.each{|name,attr|
attrPair = [Uconv.u8toeuc(name),Uconv.u8toeuc(attr.value)] ;
attrs.push(Sexp::listByArray(attrPair)) ;
}
## convert head of node
if(attrs.length==0) then
head = tag ;
else
head = Sexp::cons(tag,Sexp::listByArray(attrs)) ;
end
## convert children
children = [] ;
node.each { |child|
children.push(xml2sexp(child)) ;
}
sexp = Sexp::cons(head,Sexp::listByArray(children)) ;
elsif(node.kind_of?(Comment)) then
sexp = Sexp::list(Sexp::NIL,
Uconv.u8toeuc(node.to_s.gsub("\n","\\n"))) ;
else
sexp = '"' + Uconv.u8toeuc(node.to_s).gsub("\n","\\n") + '"' ;
end
return sexp ;
end
#--------------------------------------------------
def sexp2xml(sexp)
if(sexp.kind_of?(Sexp) && sexp.cons?()) then
if(sexp.car().nil?()) then # comment
node = Comment.new(sexp.second().to_s.gsub("\\\\n","\n")) ;
else # normal node
if(sexp.car().cons?()) then # with attributes
head = sexp.caar();
node = Element.new(head.to_s) ;
attrs = sexp.cdar();
attrs.each() {|a|
key = a.first().to_s ;
value = a.second().to_s ;
node.add_attribute(key,value) ;
attrs = attrs.cdr() ;
}
else # without attributes
head = sexp.car() ;
node = Element.new(head.to_s) ;
end
#children
children = sexp.cdr() ;
children.each(){|c|
child = sexp2xml(c) ;
node.add(child) ;
}
end
else # terminal node (text)
text = sexp.to_s ;
l = text.length() ;
node = Text.new(Uconv.euctou8(text[1,l-2].gsub("\\\\n","\n"))) ;
end
return node ;
end
end
#======================================================================
# Sample Data
$SexpXmlSampleXMLData = <<__END_OF_DATA__
<html>
<head>
<title> This is a pen. </title>
<DefNode tag="foo" bar="baz">
<a x="y" z="&_bar;">
bar
<b _restargs_="*"/>
<InsertBody/>
</a>
</DefNode>
<DefSubst mainColor="black" subColor="white"/>
</head>
<body bgcolor="&_mainColor;" text="&_subColor;" link="red" vlink="blue">
<Include file="bsub.html"/>
aaa
<table></table>
<foo>kkk</foo>
<table>
<tr>
<td>
a
</td>
</tr>
<tr> <td>
b
<table>
<tr><td>
c
</td></tr>
</table>
</td> </tr>
</table>
bbb
<foo bar="barabara" who="you" sports="soccer"> </foo>
<foo> </foo>
<!-- --------------------------------------------------
-- test embodiex insert body?
-->
<DefNode tag="foo">
<f>
<InsertBody/>
</f>
</DefNode>
<DefNode tag="bar">
<b>
<InsertBody/>
<foo>
<InsertBody/>
</foo>
</b>
</DefNode>
<bar>
This is a test.
</bar>
<!-- --------------------------------------------------
-- test xpath
-->
<DefNode tag="baz">
<InsertBody xpath="bbb"/>
<InsertBody xpath="aaa"/>
<InsertBody xpath="ccc" xpathOpType="first"/>
</DefNode>
<baz>
<aaa> this is first aaa </aaa>
<bbb> this is first bbb </bbb>
<ccc> this is first ccc </ccc>
<aaa> this is second aaa </aaa>
<bbb> this is second bbb </bbb>
<ccc> this is second ccc </ccc>
<aaa> this is third aaa </aaa>
<bbb> this is third bbb </bbb>
<ccc> this is third ccc </ccc>
</baz>
<!-- --------------------------------------------------
-- test if
-->
<If type="bool" x="yes">
<Then>
[test 1] It is True !!!
</Then>
<Else>
[test 1] It is not True !!!
</Else>
</If>
<If type="bool" x="no">
<Then>
[test 2] It is True !!!
</Then>
<Else>
[test 2] It is not True !!!
</Else>
</If>
</body>
</html>
__END_OF_DATA__
#======================================================================
# for test
include SexpXML ;
doc = Document.new($SexpXmlSampleXMLData) ;
sexp = xml2sexp(doc) ;
$stdout << sexp.to_s << "\n" ;
newdoc = sexp2xml(sexp) ;
$stdout << Uconv.u8toeuc(newdoc.to_s) << "\n" ;
| 18.241245 | 72 | 0.489334 |
1c7af3bfa6c0b4aa855f00c1d5370d1ad9bb3bf2 | 1,241 | Pod::Spec.new do |s|
s.name = 'ZLPhotoBrowser'
s.version = '4.1.2'
s.summary = 'A lightweight and pure Swift implemented library for select photos from album'
s.description = <<-DESC
ZLPhotoBrowser 是一款纯swift实现的框架
* 支持图片、视频、GIF、LivePhoto选择
* 支持图片、视频编辑
* 支持自定义相机拍照及录像
更多自定义功能请查看 ZLPhotoConfiguration 定义
DESC
s.homepage = 'https://github.com/longitachi/ZLPhotoBrowser'
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = {'longitachi' => '[email protected]'}
s.source = {:git => 'https://github.com/longitachi/ZLPhotoBrowser.git', :tag => s.version}
s.ios.deployment_target = '10.0'
s.swift_versions = ['5.0', '5.1', '5.2']
s.requires_arc = true
s.frameworks = 'UIKit','Photos','PhotosUI','AVFoundation','CoreMotion'
s.resources = 'Sources/*.{png,bundle}'
s.subspec "Core" do |sp|
sp.source_files = ["Sources/**/*.swift", "Sources/ZLPhotoBrowser.h"]
end
end
| 36.5 | 107 | 0.495568 |
1da3bff4429a4cfc41160b1b8039f845a68f332e | 6,647 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/service_directory/version"
require "googleauth"
gem "google-cloud-core"
require "google/cloud" unless defined? Google::Cloud.new
require "google/cloud/config"
# Set the default configuration
Google::Cloud.configure.add_config! :service_directory do |config|
config.add_field! :credentials, nil, match: [String, Hash, Google::Auth::Credentials]
config.add_field! :lib_name, nil, match: String
config.add_field! :lib_version, nil, match: String
config.add_field! :interceptors, nil, match: Array
config.add_field! :timeout, nil, match: Numeric
config.add_field! :metadata, nil, match: Hash
config.add_field! :retry_policy, nil, match: [Hash, Proc]
end
module Google
module Cloud
module ServiceDirectory
##
# Create a new client object for LookupService.
#
# By default, this returns an instance of
# [Google::Cloud::ServiceDirectory::V1beta1::LookupService::Client](https://googleapis.dev/ruby/google-cloud-service_directory-v1beta1/latest/Google/Cloud/ServiceDirectory/V1beta1/LookupService/Client.html)
# for version V1beta1 of the API.
# However, you can specify specify a different API version by passing it in the
# `version` parameter. If the LookupService service is
# supported by that API version, and the corresponding gem is available, the
# appropriate versioned client will be returned.
#
# ## About LookupService
#
# Service Directory API for looking up service data at runtime.
#
# @param version [String, Symbol] The API version to connect to. Optional.
# Defaults to `:v1beta1`.
# @return [LookupService::Client] A client object for the specified version.
#
def self.lookup_service version: :v1beta1, &block
require "google/cloud/service_directory/#{version.to_s.downcase}"
package_name = Google::Cloud::ServiceDirectory
.constants
.select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") }
.first
package_module = Google::Cloud::ServiceDirectory.const_get package_name
package_module.const_get(:LookupService).const_get(:Client).new(&block)
end
##
# Create a new client object for RegistrationService.
#
# By default, this returns an instance of
# [Google::Cloud::ServiceDirectory::V1beta1::RegistrationService::Client](https://googleapis.dev/ruby/google-cloud-service_directory-v1beta1/latest/Google/Cloud/ServiceDirectory/V1beta1/RegistrationService/Client.html)
# for version V1beta1 of the API.
# However, you can specify specify a different API version by passing it in the
# `version` parameter. If the RegistrationService service is
# supported by that API version, and the corresponding gem is available, the
# appropriate versioned client will be returned.
#
# ## About RegistrationService
#
# Service Directory API for registering services. It defines the following
# resource model:
#
# - The API has a collection of
# Namespace
# resources, named `projects/*/locations/*/namespaces/*`.
#
# - Each Namespace has a collection of
# Service resources, named
# `projects/*/locations/*/namespaces/*/services/*`.
#
# - Each Service has a collection of
# Endpoint
# resources, named
# `projects/*/locations/*/namespaces/*/services/*/endpoints/*`.
#
# @param version [String, Symbol] The API version to connect to. Optional.
# Defaults to `:v1beta1`.
# @return [RegistrationService::Client] A client object for the specified version.
#
def self.registration_service version: :v1beta1, &block
require "google/cloud/service_directory/#{version.to_s.downcase}"
package_name = Google::Cloud::ServiceDirectory
.constants
.select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") }
.first
package_module = Google::Cloud::ServiceDirectory.const_get package_name
package_module.const_get(:RegistrationService).const_get(:Client).new(&block)
end
##
# Configure the google-cloud-service_directory library.
#
# The following configuration parameters are supported:
#
# * `credentials` (*type:* `String, Hash, Google::Auth::Credentials`) -
# The path to the keyfile as a String, the contents of the keyfile as a
# Hash, or a Google::Auth::Credentials object.
# * `lib_name` (*type:* `String`) -
# The library name as recorded in instrumentation and logging.
# * `lib_version` (*type:* `String`) -
# The library version as recorded in instrumentation and logging.
# * `interceptors` (*type:* `Array<GRPC::ClientInterceptor>`) -
# An array of interceptors that are run before calls are executed.
# * `timeout` (*type:* `Integer`) -
# Default timeout in milliseconds.
# * `metadata` (*type:* `Hash{Symbol=>String}`) -
# Additional gRPC headers to be sent with the call.
# * `retry_policy` (*type:* `Hash`) -
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) -
# The error codes that should trigger a retry.
#
# @return [Google::Cloud::Config] The default configuration used by this library
#
def self.configure
yield Google::Cloud.configure.service_directory if block_given?
Google::Cloud.configure.service_directory
end
end
end
end
| 44.610738 | 224 | 0.665413 |
e8b4e920bae48f9dd15a7228dd22542d44268d34 | 1,399 | require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module BeardWorld
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 38.861111 | 99 | 0.751966 |
3800a54de668f157899c1b83e0889f2269453398 | 278 | # frozen_string_literal: true
module Stall
module KuroneKoyamato
module Utils
protected
def price_with_currency(price)
[
price.format(symbol: '', separator: '.', delimiter: ''),
currency
].join
end
end
end
end
| 16.352941 | 66 | 0.582734 |
bfd0ff035bd833819ff63e3f59718af452410663 | 279 | #!/usr/bin/env ruby
# vim: set sw=2 sts=2 et tw=80 :
Puppet::Parser::Functions.newfunction(:mco_array_to_string, :type => :rvalue) do |args|
unless args[0].is_a? Array
fail ArgumentError, "Expected an array, but got a #{args[0].class}"
end
args[0].collect(&:to_s)
end
| 27.9 | 87 | 0.681004 |
e8204c40032e6a09c1706b25ea60cac152b94b0b | 143 | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def hello
render html: "hello, world!"
end
end | 23.833333 | 53 | 0.79021 |
6a1af05474802d1eed52c6d5b4e3abf11e3afd49 | 240 | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
end
| 34.285714 | 56 | 0.795833 |
389e6b3769e034fd8d95b11620a5f7f234d159c2 | 20,307 | require 'test/unit'
require 'stat'
require 'socket'
# Fixme: needs platform-specific stuff dealt with
class TestFile < Test::Unit::TestCase
#
# Setup some files in a test directory.
#
def setupTestDir
@start = Dir.getwd
teardownTestDir
begin
Dir.mkdir("_test")
rescue
$stderr.puts "Cannot run a file or directory test: " +
"will destroy existing directory _test"
exit(99)
end
File.open(File.join("_test", "_file1"), "w", 0644) {}
File.open(File.join("_test", "_file2"), "w", 0644) {}
@files = %w(. .. _file1 _file2)
end
def deldir(name)
File.chmod(0755, name)
Dir.foreach(name) do |f|
next if f == '.' || f == '..'
f = File.join(name, f)
if File.lstat(f).directory?
deldir(f)
else
File.chmod(0644, f) rescue true
File.delete(f)
end
end
Dir.rmdir(name)
end
def teardownTestDir
Dir.chdir(@start)
deldir("_test") if (File.exists?("_test"))
end
def setup
setupTestDir
@file = File.join("_test", "_touched")
touch("-a -t 122512341999 #@file")
@aTime = Time.local(1999, 12, 25, 12, 34, 00)
touch("-m -t 010112341997 #@file")
@mTime = Time.local(1997, 1, 1, 12, 34, 00)
end
def teardown
File.delete @file if File.exist?(@file)
teardownTestDir
end
Windows.dont do # FAT file systems only store mtime
def test_s_atime
assert_equal(@aTime, File.atime(@file))
end
end
def test_s_basename
assert_equal("_touched", File.basename(@file))
assert_equal("tmp", File.basename(File.join("/tmp")))
assert_equal("b", File.basename(File.join(*%w( g f d s a b))))
assert_equal("tmp", File.basename("/tmp", ".*"))
assert_equal("tmp", File.basename("/tmp", ".c"))
assert_equal("tmp", File.basename("/tmp.c", ".c"))
assert_equal("tmp", File.basename("/tmp.c", ".*"))
assert_equal("tmp.o", File.basename("/tmp.o", ".c"))
Version.greater_or_equal("1.8.0") do
assert_equal("tmp", File.basename(File.join("/tmp/")))
assert_equal("/", File.basename("/"))
assert_equal("/", File.basename("//"))
assert_equal("base", File.basename("dir///base", ".*"))
assert_equal("base", File.basename("dir///base", ".c"))
assert_equal("base", File.basename("dir///base.c", ".c"))
assert_equal("base", File.basename("dir///base.c", ".*"))
assert_equal("base.o", File.basename("dir///base.o", ".c"))
assert_equal("base", File.basename("dir///base///"))
assert_equal("base", File.basename("dir//base/", ".*"))
assert_equal("base", File.basename("dir//base/", ".c"))
assert_equal("base", File.basename("dir//base.c/", ".c"))
assert_equal("base", File.basename("dir//base.c/", ".*"))
assert_equal("base.o", File.basename("dir//base.o/", ".c"))
end
Version.less_than("1.8.0") do
assert_equal("", File.basename(File.join("/tmp/")))
assert_equal("", File.basename("/"))
end
Version.greater_or_equal("1.7.2") do
unless File::ALT_SEPARATOR.nil?
assert_equal("base", File.basename("dir" + File::ALT_SEPARATOR + "base"))
end
end
end
def test_s_chmod
assert_raise(Errno::ENOENT) { File.chmod(0, "_gumby") }
assert_equal(0, File.chmod(0))
Dir.chdir("_test")
begin
assert_equal(1, File.chmod(0, "_file1"))
assert_equal(2, File.chmod(0, "_file1", "_file2"))
assert_equal(_stat_map(0), File.stat("_file1").mode & 0777)
assert_equal(1, File.chmod(0400, "_file1"))
assert_equal(_stat_map(0400), File.stat("_file1").mode & 0777)
assert_equal(1, File.chmod(0644, "_file1"))
assert_equal(_stat_map(0644), File.stat("_file1").mode & 0777)
ensure
Dir.chdir("..")
end
end
def test_s_chown
super_user
end
def test_s_ctime
sys("touch #@file")
ctime = RubiconStat::ctime(@file)
@cTime = Time.at(ctime)
assert_equal(@cTime, File.ctime(@file))
end
def test_s_delete
Dir.chdir("_test")
assert_equal(0, File.delete)
assert_raise(Errno::ENOENT) { File.delete("gumby") }
assert_equal(2, File.delete("_file1", "_file2"))
end
def test_s_dirname
assert_equal("/", File.dirname(File.join("/tmp")))
assert_equal("g/f/d/s/a", File.dirname(File.join(*%w( g f d s a b))))
assert_equal("/", File.dirname("/"))
Version.greater_or_equal("1.8.0") do
assert_equal("/", File.dirname(File.join("/tmp/")))
end
Version.less_than("1.8.0") do
assert_equal("/tmp", File.dirname(File.join("/tmp/")))
end
Version.greater_or_equal("1.7.2") do
unless File::ALT_SEPARATOR.nil?
assert_equal("dir", File.dirname("dir" + File::ALT_SEPARATOR + "base"))
end
end
end
def test_s_expand_path
if $os == MsWin32
base = `cd`.chomp.tr '\\', '/'
tmpdir = "c:/tmp"
rootdir = "c:/"
else
base = `pwd`.chomp
tmpdir = "/tmp"
rootdir = "/"
end
assert_equal(base, File.expand_path(''))
assert_equal(File.join(base, 'a'), File.expand_path('a'))
assert_equal(File.join(base, 'a'), File.expand_path('a', nil)) # V0.1.1
# Because of Ruby-Talk:18512
assert_equal(File.join(base, 'a.'), File.expand_path('a.'))
assert_equal(File.join(base, '.a'), File.expand_path('.a'))
assert_equal(File.join(base, 'a..'), File.expand_path('a..'))
assert_equal(File.join(base, '..a'), File.expand_path('..a'))
assert_equal(File.join(base, 'a../b'), File.expand_path('a../b'))
b1 = File.join(base.split(File::SEPARATOR)[0..-2])
assert_equal(b1, File.expand_path('..'))
assert_equal("#{tmpdir}", File.expand_path("", "#{tmpdir}"))
assert_equal("#{tmpdir}/a", File.expand_path("a", "#{tmpdir}"))
assert_equal("#{tmpdir}/a", File.expand_path("../a", "#{tmpdir}/xxx"))
assert_equal("#{rootdir}", File.expand_path(".", "#{rootdir}"))
home = ENV['HOME']
if (home)
assert_equal(home, File.expand_path('~'))
assert_equal(home, File.expand_path('~', '/tmp/gumby/ddd'))
assert_equal(File.join(home, 'a'),
File.expand_path('~/a', '/tmp/gumby/ddd'))
else
skipping("$HOME not set")
end
begin
File.open("/etc/passwd") do |pw|
users = pw.readlines
line = ''
line = users.pop while users.nitems > 0 and (line.length == 0 || /^\+:/ =~ line)
if line.length > 0
line = line.split(':')
name, home = line[0], line[-2]
assert_equal(home, File.expand_path("~#{name}"))
assert_equal(home, File.expand_path("~#{name}", "/tmp/gumby"))
assert_equal(File.join(home, 'a'),
File.expand_path("~#{name}/a", "/tmp/gumby"))
end
end
rescue Errno::ENOENT
skipping("~user")
end
end
def test_extname
assert_equal(".c", File.extname("alpha.c"))
assert_equal("", File.extname("beta"))
assert_equal("", File.extname(".gamma"))
assert_equal(".", File.extname("delta."))
assert_equal(".c", File.extname("some/dir/alpha.c"))
assert_equal("", File.extname("some/dir/beta"))
assert_equal("", File.extname("some/dir/.gamma"))
assert_equal(".", File.extname("some/dir/delta."))
assert_equal(".e", File.extname("a.b.c.d.e"))
end
def generic_test_s_fnmatch(method)
assert_equal(true, File.send(method, 'cat', 'cat'))
assert_equal(false, File.send(method, 'cat', 'category'))
assert_equal(false, File.send(method, 'c{at,ub}s', 'cats'))
assert_equal(false, File.send(method, 'c{at,ub}s', 'cubs'))
assert_equal(false, File.send(method, 'c{at,ub}s', 'cat'))
assert_equal(true, File.send(method, 'c?t', 'cat'))
assert_equal(false, File.send(method, 'c\?t', 'cat'))
assert_equal(false, File.send(method, 'c??t', 'cat'))
assert_equal(true, File.send(method, 'c*', 'cats'))
assert_equal(true, File.send(method, '*s', 'cats'))
assert_equal(false, File.send(method, '*x*', 'cats'))
assert_equal(false, File.send(method, 'c/**/x', 'c/a/b/c/t'))
assert_equal(true, File.send(method, 'c/**/t', 'c/a/b/c/t'))
assert_equal(true, File.send(method, 'c/*/t', 'c/a/b/c/t'))
assert_equal(false, File.send(method, 'c/*/t', 'c/a/b/c/t',
File::FNM_PATHNAME))
assert_equal(true, File.send(method, 'c*t', 'cat'))
assert_equal(true, File.send(method, 'c\at', 'cat'))
assert_equal(false, File.send(method, 'c\at', 'cat', File::FNM_NOESCAPE))
assert_equal(true, File.send(method, 'a?b', 'a/b'))
assert_equal(false, File.send(method, 'a?b', 'a/b', File::FNM_PATHNAME))
assert_equal(false, File.send(method, '*', '.profile'))
assert_equal(true, File.send(method, '*', '.profile', File::FNM_DOTMATCH))
assert_equal(true, File.send(method, '*', 'dave/.profile'))
assert_equal(true, File.send(method, '*', 'dave/.profile',
File::FNM_DOTMATCH))
assert_equal(false, File.send(method, '*', 'dave/.profile',
File::FNM_PATHNAME))
assert_equal(false, File.send(method, '*/*', 'dave/.profile',
File::FNM_PATHNAME))
strict = File::FNM_PATHNAME | File::FNM_DOTMATCH
assert_equal(true, File.send(method, '*/*', 'dave/.profile', strict))
assert_equal(false, File.send(method, 'cat', 'CAt'))
assert_equal(true, File.send(method, 'cat', 'CAt', File::FNM_CASEFOLD))
assert_equal(true, File.send(method, 'c[au]t', 'cat'))
assert_equal(true, File.send(method, 'c[au]t', 'cut'))
assert_equal(false, File.send(method, 'c[au]t', 'cot'))
assert_equal(false, File.send(method, 'c[^au]t', 'cat'))
assert_equal(false, File.send(method, 'c[^au]t', 'cut'))
assert_equal(true, File.send(method, 'c[^au]t', 'cot'))
for ch in "a".."z"
inside = ch >= "h" && ch <= "p" || ch == "x"
str = "c#{ch}t"
comment = "matching #{str.inspect}"
assert_equal(inside, File.send(method, 'c[h-px]t', str), comment)
assert_equal(!inside, File.send(method, 'c[^h-px]t', str), comment)
end
end
def test_s_fnmatch
generic_test_s_fnmatch(:fnmatch)
end
def test_s_fnmatch?
generic_test_s_fnmatch(:fnmatch?)
end
def test_s_ftype
Dir.chdir("_test")
sock = nil
MsWin32.dont do
sock = UNIXServer.open("_sock")
File.symlink("_file1", "_file3") # may fail
end
begin
tests = {
"../_test" => "directory",
"_file1" => "file",
}
Windows.dont do
begin
tests[File.expand_path(File.readlink("/dev/tty"), "/dev")] =
"characterSpecial"
rescue Errno::EINVAL
tests["/dev/tty"] = "characterSpecial"
end
end
MsWin32.dont do
tests["_file3"] = "link"
tests["_sock"] = "socket"
end
Linux.only do
tests["/dev/"+`readlink /dev/fd0 || echo fd0`.chomp] = "blockSpecial"
system("mkfifo _fifo") # may fail
tests["_fifo"] = "fifo"
end
tests.each { |file, type|
if File.exists?(file)
assert_equal(type, File.ftype(file), file.dup)
else
skipping("#{type} not supported")
end
}
ensure
sock.close if sock
end
end
def test_s_join
[
%w( a b c d ),
%w( a ),
%w( ),
%w( a b .. c )
].each do |a|
assert_equal(a.join(File::SEPARATOR), File.join(*a))
end
end
def test_s_link
Dir.chdir("_test")
begin
assert_equal(0, File.link("_file1", "_file3"))
assert(File.exists?("_file3"))
Windows.dont do
assert_equal(2, File.stat("_file1").nlink)
assert_equal(2, File.stat("_file3").nlink)
assert(File.stat("_file1").ino == File.stat("_file3").ino)
end
ensure
Dir.chdir("..")
end
end
MsWin32.dont do
def test_s_lstat
Dir.chdir("_test")
File.symlink("_file1", "_file3") # may fail
assert_equal(0, File.stat("_file3").size)
assert(0 < File.lstat("_file3").size)
assert_equal(0, File.stat("_file1").size)
assert_equal(0, File.lstat("_file1").size)
end
end
def test_s_mtime
assert_equal(@mTime, File.mtime(@file))
end
# REFACTOR: this test is duplicated in TestFile
def test_s_open
file1 = "_test/_file1"
assert_raise(Errno::ENOENT) { File.open("_gumby") }
# test block/non block forms
f = File.open(file1)
begin
assert_equal(File, f.class)
ensure
f.close
end
assert_nil(File.open(file1) { |f| assert_equal(File, f.class)})
# test modes
modes = [
%w( r w r+ w+ a a+ ),
[ File::RDONLY,
File::WRONLY | File::CREAT,
File::RDWR,
File::RDWR + File::TRUNC + File::CREAT,
File::WRONLY + File::APPEND + File::CREAT,
File::RDWR + File::APPEND + File::CREAT
]]
for modeset in modes
sys("rm -f #{file1}")
sys("touch #{file1}")
mode = modeset.shift # "r"
# file: empty
File.open(file1, mode) { |f|
assert_nil(f.gets)
assert_raise(IOError) { f.puts "wombat" }
}
mode = modeset.shift # "w"
# file: empty
File.open(file1, mode) { |f|
assert_nil(f.puts("wombat"))
assert_raise(IOError) { f.gets }
}
mode = modeset.shift # "r+"
# file: wombat
File.open(file1, mode) { |f|
assert_equal("wombat\n", f.gets)
assert_nil(f.puts("koala"))
f.rewind
assert_equal("wombat\n", f.gets)
assert_equal("koala\n", f.gets)
}
mode = modeset.shift # "w+"
# file: wombat/koala
File.open(file1, mode) { |f|
assert_nil(f.gets)
assert_nil(f.puts("koala"))
f.rewind
assert_equal("koala\n", f.gets)
}
mode = modeset.shift # "a"
# file: koala
File.open(file1, mode) { |f|
assert_nil(f.puts("wombat"))
assert_raise(IOError) { f.gets }
}
mode = modeset.shift # "a+"
# file: koala/wombat
File.open(file1, mode) { |f|
assert_nil(f.puts("wallaby"))
f.rewind
assert_equal("koala\n", f.gets)
assert_equal("wombat\n", f.gets)
assert_equal("wallaby\n", f.gets)
}
end
# Now try creating files
filen = "_test/_filen"
File.open(filen, "w") {}
begin
assert(File.exists?(filen))
ensure
File.delete(filen)
end
File.open(filen, File::CREAT, 0444) {}
begin
assert(File.exists?(filen))
Cygwin.known_problem do
assert_equal(0444 & ~File.umask, File.stat(filen).mode & 0777)
end
ensure
WindowsNative.or_variant do
# to be able to delete the file on Windows
File.chmod(0666, filen)
end
File.delete(filen)
end
end
def test_s_readlink
MsWin32.dont do
Dir.chdir("_test")
File.symlink("_file1", "_file3") # may fail
assert_equal("_file1", File.readlink("_file3"))
assert_raise(Errno::EINVAL) { File.readlink("_file1") }
end
end
def test_s_rename
Dir.chdir("_test")
assert_raise(Errno::ENOENT) { File.rename("gumby", "pokey") }
assert_equal(0, File.rename("_file1", "_renamed"))
assert(!File.exists?("_file1"))
assert(File.exists?("_renamed"))
end
def test_s_size
file = "_test/_file1"
assert_raise(Errno::ENOENT) { File.size("gumby") }
assert_equal(0, File.size(file))
File.open(file, "w") { |f| f.puts "123456789" }
if $os == MsWin32
assert_equal(11, File.size(file))
else
assert_equal(10, File.size(file))
end
end
def test_s_split
%w{ "/", "/tmp", "/tmp/a", "/tmp/a/b", "/tmp/a/b/", "/tmp//a",
"/tmp//"
}.each { |file|
assert_equal( [ File.dirname(file), File.basename(file) ],
File.split(file), file )
}
end
# Stat is pretty much tested elsewhere, so we're minimal here
def test_s_stat
assert_instance_of(File::Stat, File.stat("."))
end
def test_s_symlink
MsWin32.dont do
Dir.chdir("_test")
File.symlink("_file1", "_file3") # may fail
assert(File.symlink?("_file3"))
assert(!File.symlink?("_file1"))
end
end
def test_s_truncate
file = "_test/_file1"
File.open(file, "w") { |f| f.puts "123456789" }
if $os <= MsWin32
assert_equal(11, File.size(file))
else
assert_equal(10, File.size(file))
end
File.truncate(file, 5)
assert_equal(5, File.size(file))
File.open(file, "r") { |f|
assert_equal("12345", f.read(99))
assert(f.eof?)
}
end
MsWin32.dont do
def myUmask
Integer(`sh -c umask`.chomp)
end
def test_s_umask
orig = myUmask
assert_equal(myUmask, File.umask)
assert_equal(myUmask, File.umask(0404))
assert_equal(0404, File.umask(orig))
end
end
def test_s_unlink
Dir.chdir("_test")
assert_equal(0, File.unlink)
assert_raise(Errno::ENOENT) { File.unlink("gumby") }
assert_equal(2, File.unlink("_file1", "_file2"))
end
def test_s_utime
Dir.chdir("_test")
begin
[
[ Time.at(18000), Time.at(53423) ],
[ Time.at(Time.now.to_i), Time.at(54321) ],
[ Time.at(121314), Time.now.to_i ] # observe the last instance is an integer!
].each { |aTime, mTime|
File.utime(aTime, mTime, "_file1", "_file2")
for file in [ "_file1", "_file2" ]
assert_equal(aTime.to_i, File.stat(file).atime.to_i)
assert_equal(mTime.to_i, File.stat(file).mtime.to_i)
end
}
ensure
Dir.chdir("..")
end
end
# Instance methods
Windows.dont do # FAT filesystems don't store this properly
def test_atime
File.open(@file) { |f| assert_equal(@aTime, f.atime) }
end
end
def test_chmod
Dir.chdir("_test")
File.open("_file1") { |f|
assert_equal(0, f.chmod(0))
assert_equal(_fstat_map(0), f.stat.mode & 0777)
assert_equal(0, f.chmod(0400))
assert_equal(_fstat_map(0400), f.stat.mode & 0777)
assert_equal(0, f.chmod(0644))
assert_equal(_fstat_map(0644), f.stat.mode & 0777)
}
end
def test_chown
super_user
end
def test_ctime
sys("touch #@file")
ctime = RubiconStat::ctime(@file)
@cTime = Time.at(ctime)
File.open(@file) { |f| assert_equal(@cTime, f.ctime) }
end
def test_flock
MsWin32.dont do
Dir.chdir("_test")
# parent forks, then waits for a SIGUSR1 from child. Child locks file
# and signals parent, then sleeps
# When parent gets signal, confirms file si locked, kills child,
# and confirms its unlocked
pid = fork
if pid
File.open("_file1", "w") { |f|
trap("USR1") {
assert_equal(false, f.flock(File::LOCK_EX | File::LOCK_NB))
Process.kill "KILL", pid
Process.waitpid(pid, 0)
assert_equal(0, f.flock(File::LOCK_EX | File::LOCK_NB))
return
}
sleep 10
fail("Never got signalled")
}
else
File.open("_file1", "w") { |f|
assert_equal(0, f.flock(File::LOCK_EX))
sleep 1
Process.kill "USR1", Process.ppid
sleep 10
fail "Parent never killed us"
}
end
end
end
def test_lstat
MsWin32.dont do
Dir.chdir("_test")
begin
File.symlink("_file1", "_file3") # may fail
f1 = File.open("_file1")
begin
f3 = File.open("_file3")
assert_equal(0, f3.stat.size)
assert(0 < f3.lstat.size)
assert_equal(0, f1.stat.size)
assert_equal(0, f1.lstat.size)
f3.close
ensure
f1.close
end
ensure
Dir.chdir("..")
end
end
end
def test_mtime
File.open(@file) { |f| assert_equal(@mTime, f.mtime) }
end
def test_path
File.open(@file) { |f| assert_equal(@file, f.path) }
end
def test_truncate
file = "_test/_file1"
File.open(file, "w") { |f|
f.syswrite "123456789"
f.truncate(5)
}
assert_equal(5, File.size(file))
File.open(file, "r") { |f|
assert_equal("12345", f.read(99))
assert(f.eof?)
}
end
end | 27.591033 | 87 | 0.57916 |
01a49568c2d41e4f8118de4e2f741ed60a0ed63f | 79 | require 'test_helper'
class BulkMessagesHelperTest < ActionView::TestCase
end
| 15.8 | 51 | 0.835443 |
26fdcab94ce0ff5b0cfb0f59b2b3cef8e29df100 | 1,670 | # frozen_string_literal: true
require 'soda/client'
module Sf311CaseService
extend self
SODA_CREDENTIALS = {
domain: 'data.sfgov.org',
app_token: 'QPCu2zzyc3jV5UkGfpOrGnXi7'
}
CASE_DATASET_ID = 'ktji-gk7t'
# https://dev.socrata.com/docs/datatypes/floating_timestamp.html
SODA_FLOATING_TIMESTAMP_FORMAT ='%Y-%m-%dT%T'
def get_blocked_bike_lane_case_data(options = {})
get_cases(
Sf311Case::SERVICE_SUBTYPES[:blocked_bike_lane],
options
)
end
def create_case(case_attributes)
if Rails.env.production?
# TODO: Ensure this call behaves as expected
client.post(CASE_DATASET_ID, [case_attributes])
else
Rails.logger.info("#{self.name}##{__method__} called successfully, actual case creation disabled in this environment (#{Rails.env})")
end
end
private
def client
@client ||= SODA::Client.new(SODA_CREDENTIALS)
end
def get_cases(subtype, from_datetime: nil, to_datetime: nil, offset: 0, limit: 10, format: :json)
request_params = {
service_subtype: subtype,
'$offset': offset,
'$limit': limit
}
query_conditions = []
if from_datetime
from_ts = from_datetime.strftime(SODA_FLOATING_TIMESTAMP_FORMAT)
query_conditions << "requested_datetime >= '#{from_ts}'"
end
if to_datetime
to_ts = to_datetime.strftime(SODA_FLOATING_TIMESTAMP_FORMAT)
query_conditions << "requested_datetime <= '#{to_ts}'"
end
request_params['$where'] = query_conditions.join(' and ') if query_conditions
client.get(
"https://data.sfgov.org/resource/#{CASE_DATASET_ID}.#{format}",
request_params
)
end
end
| 24.558824 | 139 | 0.690419 |
e9adf306188f146eeb682693b87fba793fd49dcb | 2,586 | require 'rails_helper'
RSpec.describe Spree::Promotion::Rules::FirstOrder, type: :model do
let(:rule) { Spree::Promotion::Rules::FirstOrder.new }
let(:order) { mock_model(Spree::Order, user: nil, email: nil) }
let(:user) { mock_model(Spree::LegacyUser) }
context "without a user or email" do
it { expect(rule).not_to be_eligible(order) }
it "sets an error message" do
rule.eligible?(order)
expect(rule.eligibility_errors.full_messages.first).
to eq "You need to login or provide your email before applying this coupon code."
end
end
context "first order" do
context "for a signed user" do
context "with no completed orders" do
before(:each) do
allow(user).to receive_message_chain(:orders, complete: [])
end
specify do
allow(order).to receive_messages(user: user)
expect(rule).to be_eligible(order)
end
it "should be eligible when user passed in payload data" do
expect(rule).to be_eligible(order, user: user)
end
end
context "with completed orders" do
before(:each) do
allow(order).to receive_messages(user: user)
end
it "should be eligible when checked against first completed order" do
allow(user).to receive_message_chain(:orders, complete: [order])
expect(rule).to be_eligible(order)
end
context "with another order" do
before { allow(user).to receive_message_chain(:orders, complete: [mock_model(Spree::Order)]) }
it { expect(rule).not_to be_eligible(order) }
it "sets an error message" do
rule.eligible?(order)
expect(rule.eligibility_errors.full_messages.first).
to eq "This coupon code can only be applied to your first order."
end
end
end
end
context "for a guest user" do
let(:email) { '[email protected]' }
before { allow(order).to receive_messages email: '[email protected]' }
context "with no other orders" do
it { expect(rule).to be_eligible(order) }
end
context "with another order" do
before { allow(rule).to receive_messages(orders_by_email: [mock_model(Spree::Order)]) }
it { expect(rule).not_to be_eligible(order) }
it "sets an error message" do
rule.eligible?(order)
expect(rule.eligibility_errors.full_messages.first).
to eq "This coupon code can only be applied to your first order."
end
end
end
end
end
| 34.026316 | 104 | 0.634957 |
3996b7a7b943c6ece61661124491aff1c4f209de | 431 | module Kedi
class EventLoop
def initialize
# 线程安全队列
@recv_chan = Queue.new
@alive? = false
end
def acquire()
@recv_chan << {
}
end
def schedule(message)
end
def run
@alive? = true
loop do
break unless @alive?
message = @recv_chan.deq
schedule(message)
end
end
def stop
@alive? = false
end
end
end | 13.060606 | 32 | 0.508121 |
261791cecceac2a91c8f2bd3b8a3639a2efcd224 | 760 | require 'metrics_adapter/version'
require 'active_support/all'
module MetricsAdapter
mattr_accessor :adapter
mattr_accessor :logger
mattr_accessor :adapter_options
self.adapter_options = {}
mattr_accessor :extra_attributes
self.extra_attributes = {}
mattr_accessor :trackers
self.trackers = []
mattr_accessor :thresholds
self.thresholds = {}
mattr_accessor :conditionals
self.conditionals = {}
module Adapters
autoload :Mixpanel, 'metrics_adapter/adapters/mixpanel'
autoload :Keen, 'metrics_adapter/adapters/keen'
end
module Trackers
autoload :Base, 'metrics_adapter/trackers/base'
autoload :SlowRequest, 'metrics_adapter/trackers/slow_request'
end
def self.configure(&block)
yield self
end
end
| 20.540541 | 66 | 0.756579 |
fff9950dd985cbbbc426c4fdb9214e8148fa4eba | 3,755 | # frozen_string_literal: true
describe Facter::Resolvers::SshResolver do
describe '#folders' do
let(:ecdsa_content) { load_fixture('ecdsa').read.strip! }
let(:rsa_content) { load_fixture('rsa').read.strip! }
let(:ed25519_content) { load_fixture('ed25519').read.strip! }
let(:ecdsa_fingerprint) do
Facter::FingerPrint.new('SSHFP 3 1 fd92cf867fac0042d491eb1067e4f3cabf54039a',
'SSHFP 3 2 a51271a67987d7bbd685fa6d7cdd2823a30373ab01420b094480523fabff2a05')
end
let(:rsa_fingerprint) do
Facter::FingerPrint.new('SSHFP 1 1 90134f93fec6ab5e22bdd88fc4d7cd6e9dca4a07',
'SSHFP 1 2 efaa26ff8169f5ffc372ebcad17aef886f4ccaa727169acdd0379b51c6c77e99')
end
let(:ed25519_fingerprint) do
Facter::FingerPrint.new('SSHFP 4 1 f5780634d4e34c6ef2411ac439b517bfdce43cf1',
'SSHFP 4 2 c1257b3865df22f3349f9ebe19961c8a8edf5fbbe883113e728671b42d2c9723')
end
let(:ecdsa_result) do
Facter::Ssh.new(ecdsa_fingerprint, 'ecdsa-sha2-nistp256', ecdsa_content, 'ecdsa')
end
let(:rsa_result) do
Facter::Ssh.new(rsa_fingerprint, 'ssh-rsa', rsa_content, 'rsa')
end
let(:ed25519_result) do
Facter::Ssh.new(ed25519_fingerprint, 'ssh-ed22519', ed25519_content, 'ed25519')
end
let(:paths) { %w[/etc/ssh /usr/local/etc/ssh /etc /usr/local/etc /etc/opt/ssh] }
let(:file_names) { %w[ssh_host_rsa_key.pub ssh_host_ecdsa_key.pub ssh_host_ed25519_key.pub] }
before do
paths.each { |path| allow(File).to receive(:directory?).with(path).and_return(false) unless path == '/etc' }
allow(File).to receive(:directory?).with('/etc').and_return(true)
allow(Facter::Util::FileHelper).to receive(:safe_read)
.with('/etc/ssh_host_ecdsa_key.pub', nil).and_return(ecdsa_content)
allow(Facter::Util::FileHelper).to receive(:safe_read)
.with('/etc/ssh_host_dsa_key.pub', nil).and_return(nil)
allow(Facter::Util::FileHelper).to receive(:safe_read)
.with('/etc/ssh_host_rsa_key.pub', nil).and_return(rsa_content)
allow(Facter::Util::FileHelper).to receive(:safe_read)
.with('/etc/ssh_host_ed25519_key.pub', nil).and_return(ed25519_content)
allow(Resolvers::Utils::SshHelper).to receive(:create_ssh)
.with('ssh-rsa', load_fixture('rsa_key').read.strip!)
.and_return(rsa_result)
allow(Resolvers::Utils::SshHelper).to receive(:create_ssh)
.with('ecdsa-sha2-nistp256', load_fixture('ecdsa_key').read.strip!)
.and_return(ecdsa_result)
allow(Resolvers::Utils::SshHelper).to receive(:create_ssh)
.with('ssh-ed25519', load_fixture('ed25519_key').read.strip!)
.and_return(ed25519_result)
end
after do
Facter::Resolvers::SshResolver.invalidate_cache
end
context 'when ssh_host_dsa_key.pub file is not readable' do
it 'returns resolved ssh' do
expect(Facter::Resolvers::SshResolver.resolve(:ssh)).to eq([rsa_result, ecdsa_result, ed25519_result])
end
end
context 'when ssh_host_ecdsa_key.pub file is also not readable' do
before do
allow(Facter::Util::FileHelper).to receive(:safe_read)
.with('/etc/ssh_host_ecdsa_key.pub', nil).and_return(nil)
end
it 'returns resolved ssh' do
expect(Facter::Resolvers::SshResolver.resolve(:ssh)).to eq([rsa_result, ed25519_result])
end
end
context 'when ssh fails to be retrieved' do
before do
paths.each { |path| allow(File).to receive(:directory?).with(path).and_return(false) }
end
it 'returns empty array' do
expect(Facter::Resolvers::SshResolver.resolve(:ssh)).to eq([])
end
end
end
end
| 39.946809 | 114 | 0.681225 |
21a13f3d1392ad8d98d8d0a9c48753b6bea115f9 | 2,281 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{amazon_associate}
s.version = "0.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Dan Pickett"]
s.date = %q{2009-08-01}
s.description = %q{interfaces with Amazon Associate's API using Hpricot}
s.email = %q{[email protected]}
s.extra_rdoc_files = [
"README.rdoc"
]
s.files = [
".autotest",
".gitignore",
".project",
"CHANGELOG",
"MIT-LICENSE",
"README.rdoc",
"Rakefile",
"VERSION.yml",
"amazon_associate.gemspec",
"lib/amazon_associate.rb",
"lib/amazon_associate/cache_factory.rb",
"lib/amazon_associate/caching_strategy.rb",
"lib/amazon_associate/caching_strategy/base.rb",
"lib/amazon_associate/caching_strategy/filesystem.rb",
"lib/amazon_associate/configuration_error.rb",
"lib/amazon_associate/element.rb",
"lib/amazon_associate/request.rb",
"lib/amazon_associate/request_error.rb",
"lib/amazon_associate/response.rb",
"test/amazon_associate/browse_node_lookup_test.rb",
"test/amazon_associate/cache_test.rb",
"test/amazon_associate/caching_strategy/filesystem_test.rb",
"test/amazon_associate/cart_test.rb",
"test/amazon_associate/request_test.rb",
"test/test_helper.rb",
"test/utilities/filesystem_test_helper.rb"
]
s.homepage = %q{http://github.com/dpickett/amazon_associate}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.5}
s.summary = %q{Amazon Associates API Interface using Hpricot}
s.test_files = [
"test/amazon_associate/browse_node_lookup_test.rb",
"test/amazon_associate/cache_test.rb",
"test/amazon_associate/caching_strategy/filesystem_test.rb",
"test/amazon_associate/cart_test.rb",
"test/amazon_associate/request_test.rb",
"test/test_helper.rb",
"test/utilities/filesystem_test_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
| 33.544118 | 105 | 0.700132 |
7999404e2d659745bf8b98f7b4df3fe9b2db15c5 | 2,977 | #
# Be sure to run `pod lib lint TKMAccountModule.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'TKMAccountModule'
s.version = '0.1.8'
s.summary = 'TKM 账号组件'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'TKM 账号组件'
s.homepage = 'https://github.com/TokiModularization/TKMAccountModule'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'tokihunter' => '[email protected]' }
s.source = { :git => 'https://github.com/TokiModularization/TKMAccountModule.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
#Framework模式
s.subspec 'FrameworkMode' do |fm|
fm.vendored_frameworks = 'TKMAccountModule/TKMAccountModuleSDK/*.framework'
# fm.resource = 'TKMAccountModule/TKMAccountModuleSDK/*.bundle'
end
#源码模式
s.subspec 'SourceMode' do |sm|
sm.source_files = [
'TKMAccountModule/Classes/**/*',
'TKMAccountModule/Interface/**/*.m'
]
sm.public_header_files = [
'TKMAccountModule/Classes/**/*.h'
]
# sm.resource_bundles = {
# 'TKMAccountModule' => ['TKMAccountModule/Assets/**/*.png']
# }
end
#对外接口
s.subspec 'Interface' do |interface|
interface.source_files = [
'TKMAccountModule/Interface/**/*.h',
]
interface.public_header_files = [
'TKMAccountModule/Interface/**/*.h'
]
end
#核心代码
s.subspec 'Core' do |core|
# FX=all pod install; 所有库都使用framework模式安装
isAllFX = ENV['FX'] == "all" || ENV['TKMAccountModule_FX'] == "all";
# FX=dependency pod install; 依赖库使用framework模式安装
isDependencyFX = ENV['FX'] == "dependency" || ENV['TKMAccountModule_FX'] == "dependency";
isDependency = !!__FILE__[".cocoapods/repos"];
if isAllFX || (isDependency && isDependencyFX)
core.dependency 'TKMAccountModule/FrameworkMode'
else
core.dependency 'TKMAccountModule/SourceMode'
core.dependency 'TKMAccountModule/Interface'
end
# core.public_header_files = 'Pod/Classes/**/*.h'
# core.frameworks = 'UIKit', 'MapKit'
core.dependency 'Masonry'
core.dependency 'TKModule'
core.dependency 'TKMResourceManager'
core.dependency 'TKMInfoManager'
core.pod_target_xcconfig = { 'OTHER_LDFLAGS' => '-ObjC' }
end
s.default_subspec = 'Core'
end
| 34.616279 | 119 | 0.659725 |
01094b55d8ef6ecb955ec0e238daba5bdf98ddb0 | 733 | module FHIR
# fhir/measure_report_type.rb
class MeasureReportType < PrimitiveCode
include Mongoid::Document
def as_json(*args)
result = super
result.delete('id')
unless self.fhirId.nil?
result['id'] = self.fhirId
result.delete('fhirId')
end
result
end
def self.transform_json(json_hash, extension_hash, target = MeasureReportType.new)
result = target
unless extension_hash.nil?
result['fhirId'] = extension_hash['id'] unless extension_hash['id'].nil?
result['extension'] = extension_hash['extension'].map { |ext| Extension.transform_json(ext) }
end
result['value'] = json_hash
result
end
end
end
| 26.178571 | 101 | 0.633015 |
210d7ba79683e1faa7420645d03a492fd3184146 | 597 | require 'spec_helper_acceptance'
describe 'splunk class' do
context 'default parameters' do
# Using puppet_apply as a helper
it 'works idempotently with no errors' do
pp = <<-EOS
class { '::splunk': }
EOS
# Run it twice and test for idempotency
apply_manifest(pp, catch_failures: true)
apply_manifest(pp, catch_changes: true)
end
describe package('splunk') do
it { is_expected.to be_installed }
end
describe service('splunk') do
it { is_expected.to be_enabled }
it { is_expected.to be_running }
end
end
end
| 22.961538 | 46 | 0.653266 |
ac6155ed4c145cdbc8d170c49cadc15abc175803 | 1,167 | # frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mlb_gameday/version'
Gem::Specification.new do |spec|
spec.name = 'mlb_gameday'
spec.version = MLBGameday::VERSION
spec.authors = ['Steven Hoffman']
spec.email = ['[email protected]']
spec.description = 'Access data about games and players from the ' \
'official MLB Gameday API'
spec.summary = 'Fetches gameday data from the MLB Gameday API'
spec.homepage = 'http://github.com/fustrate/mlb_gameday'
spec.license = 'MIT'
spec.files = `git ls-files`.split($RS)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = %w[lib]
spec.add_development_dependency 'bundler', '~> 1.9'
spec.add_development_dependency 'minitest', '~> 5.5'
spec.add_development_dependency 'rake', '~> 10.4'
spec.add_dependency 'chronic', '~> 0.10'
spec.add_dependency 'httparty', '~> 0.13'
spec.add_dependency 'nokogiri', '~> 1.6'
end
| 37.645161 | 74 | 0.653813 |
ffb6b127abc55827f11b54c4c57e433ffe1f924d | 1,165 | # frozen_string_literal: true
module Mutations
module IncidentManagement
module OncallSchedule
class Create < OncallScheduleBase
include FindsProject
graphql_name 'OncallScheduleCreate'
argument :project_path, GraphQL::ID_TYPE,
required: true,
description: 'The project to create the on-call schedule in.'
argument :name, GraphQL::STRING_TYPE,
required: true,
description: 'The name of the on-call schedule.'
argument :description, GraphQL::STRING_TYPE,
required: false,
description: 'The description of the on-call schedule.'
argument :timezone, GraphQL::STRING_TYPE,
required: true,
description: 'The timezone of the on-call schedule.'
def resolve(args)
project = authorized_find!(args[:project_path])
response ::IncidentManagement::OncallSchedules::CreateService.new(
project,
current_user,
args.slice(:name, :description, :timezone)
).execute
end
end
end
end
end
| 29.125 | 78 | 0.600858 |
e22e50221004042ba7d300f25cdb14e3051c9da5 | 19,479 | # Copyright (c) 2016, 2022, 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 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# A summary of a job execution on a Managed Database.
class DatabaseManagement::Models::JobExecutionSummary
DATABASE_TYPE_ENUM = [
DATABASE_TYPE_EXTERNAL_SIDB = 'EXTERNAL_SIDB'.freeze,
DATABASE_TYPE_EXTERNAL_RAC = 'EXTERNAL_RAC'.freeze,
DATABASE_TYPE_CLOUD_SIDB = 'CLOUD_SIDB'.freeze,
DATABASE_TYPE_CLOUD_RAC = 'CLOUD_RAC'.freeze,
DATABASE_TYPE_SHARED = 'SHARED'.freeze,
DATABASE_TYPE_DEDICATED = 'DEDICATED'.freeze,
DATABASE_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
DATABASE_SUB_TYPE_ENUM = [
DATABASE_SUB_TYPE_CDB = 'CDB'.freeze,
DATABASE_SUB_TYPE_PDB = 'PDB'.freeze,
DATABASE_SUB_TYPE_NON_CDB = 'NON_CDB'.freeze,
DATABASE_SUB_TYPE_ACD = 'ACD'.freeze,
DATABASE_SUB_TYPE_ADB = 'ADB'.freeze,
DATABASE_SUB_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
DEPLOYMENT_TYPE_ENUM = [
DEPLOYMENT_TYPE_ONPREMISE = 'ONPREMISE'.freeze,
DEPLOYMENT_TYPE_BM = 'BM'.freeze,
DEPLOYMENT_TYPE_VM = 'VM'.freeze,
DEPLOYMENT_TYPE_EXADATA = 'EXADATA'.freeze,
DEPLOYMENT_TYPE_EXADATA_CC = 'EXADATA_CC'.freeze,
DEPLOYMENT_TYPE_AUTONOMOUS = 'AUTONOMOUS'.freeze,
DEPLOYMENT_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
WORKLOAD_TYPE_ENUM = [
WORKLOAD_TYPE_OLTP = 'OLTP'.freeze,
WORKLOAD_TYPE_DW = 'DW'.freeze,
WORKLOAD_TYPE_AJD = 'AJD'.freeze,
WORKLOAD_TYPE_APEX = 'APEX'.freeze,
WORKLOAD_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# **[Required]** The identifier of the job execution.
# @return [String]
attr_accessor :id
# **[Required]** The name of the job execution.
# @return [String]
attr_accessor :name
# **[Required]** The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment in which the parent job resides.
# @return [String]
attr_accessor :compartment_id
# The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database Group where the parent job has to be executed.
# @return [String]
attr_accessor :managed_database_group_id
# **[Required]** The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of Managed Database associated with the job execution.
# @return [String]
attr_accessor :managed_database_id
# **[Required]** The name of the Managed Database associated with the job execution.
# @return [String]
attr_accessor :managed_database_name
# The type of Oracle Database installation.
# @return [String]
attr_reader :database_type
# The subtype of the Oracle Database. Indicates whether the database is a Container Database, Pluggable Database, or a Non-container Database.
# @return [String]
attr_reader :database_sub_type
# A list of the supported infrastructure that can be used to deploy the database.
# @return [String]
attr_reader :deployment_type
# Indicates whether the Oracle Database is part of a cluster.
# @return [BOOLEAN]
attr_accessor :is_cluster
# The workload type of the Autonomous Database.
# @return [String]
attr_reader :workload_type
# **[Required]** The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the parent job.
# @return [String]
attr_accessor :job_id
# **[Required]** The name of the parent job.
# @return [String]
attr_accessor :job_name
# **[Required]** The status of the job execution.
# @return [String]
attr_accessor :status
# **[Required]** The date and time when the job execution was created.
# @return [DateTime]
attr_accessor :time_created
# The date and time when the job execution was completed.
# @return [DateTime]
attr_accessor :time_completed
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'id': :'id',
'name': :'name',
'compartment_id': :'compartmentId',
'managed_database_group_id': :'managedDatabaseGroupId',
'managed_database_id': :'managedDatabaseId',
'managed_database_name': :'managedDatabaseName',
'database_type': :'databaseType',
'database_sub_type': :'databaseSubType',
'deployment_type': :'deploymentType',
'is_cluster': :'isCluster',
'workload_type': :'workloadType',
'job_id': :'jobId',
'job_name': :'jobName',
'status': :'status',
'time_created': :'timeCreated',
'time_completed': :'timeCompleted'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'id': :'String',
'name': :'String',
'compartment_id': :'String',
'managed_database_group_id': :'String',
'managed_database_id': :'String',
'managed_database_name': :'String',
'database_type': :'String',
'database_sub_type': :'String',
'deployment_type': :'String',
'is_cluster': :'BOOLEAN',
'workload_type': :'String',
'job_id': :'String',
'job_name': :'String',
'status': :'String',
'time_created': :'DateTime',
'time_completed': :'DateTime'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :id The value to assign to the {#id} property
# @option attributes [String] :name The value to assign to the {#name} property
# @option attributes [String] :compartment_id The value to assign to the {#compartment_id} property
# @option attributes [String] :managed_database_group_id The value to assign to the {#managed_database_group_id} property
# @option attributes [String] :managed_database_id The value to assign to the {#managed_database_id} property
# @option attributes [String] :managed_database_name The value to assign to the {#managed_database_name} property
# @option attributes [String] :database_type The value to assign to the {#database_type} property
# @option attributes [String] :database_sub_type The value to assign to the {#database_sub_type} property
# @option attributes [String] :deployment_type The value to assign to the {#deployment_type} property
# @option attributes [BOOLEAN] :is_cluster The value to assign to the {#is_cluster} property
# @option attributes [String] :workload_type The value to assign to the {#workload_type} property
# @option attributes [String] :job_id The value to assign to the {#job_id} property
# @option attributes [String] :job_name The value to assign to the {#job_name} property
# @option attributes [String] :status The value to assign to the {#status} property
# @option attributes [DateTime] :time_created The value to assign to the {#time_created} property
# @option attributes [DateTime] :time_completed The value to assign to the {#time_completed} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.id = attributes[:'id'] if attributes[:'id']
self.name = attributes[:'name'] if attributes[:'name']
self.compartment_id = attributes[:'compartmentId'] if attributes[:'compartmentId']
raise 'You cannot provide both :compartmentId and :compartment_id' if attributes.key?(:'compartmentId') && attributes.key?(:'compartment_id')
self.compartment_id = attributes[:'compartment_id'] if attributes[:'compartment_id']
self.managed_database_group_id = attributes[:'managedDatabaseGroupId'] if attributes[:'managedDatabaseGroupId']
raise 'You cannot provide both :managedDatabaseGroupId and :managed_database_group_id' if attributes.key?(:'managedDatabaseGroupId') && attributes.key?(:'managed_database_group_id')
self.managed_database_group_id = attributes[:'managed_database_group_id'] if attributes[:'managed_database_group_id']
self.managed_database_id = attributes[:'managedDatabaseId'] if attributes[:'managedDatabaseId']
raise 'You cannot provide both :managedDatabaseId and :managed_database_id' if attributes.key?(:'managedDatabaseId') && attributes.key?(:'managed_database_id')
self.managed_database_id = attributes[:'managed_database_id'] if attributes[:'managed_database_id']
self.managed_database_name = attributes[:'managedDatabaseName'] if attributes[:'managedDatabaseName']
raise 'You cannot provide both :managedDatabaseName and :managed_database_name' if attributes.key?(:'managedDatabaseName') && attributes.key?(:'managed_database_name')
self.managed_database_name = attributes[:'managed_database_name'] if attributes[:'managed_database_name']
self.database_type = attributes[:'databaseType'] if attributes[:'databaseType']
raise 'You cannot provide both :databaseType and :database_type' if attributes.key?(:'databaseType') && attributes.key?(:'database_type')
self.database_type = attributes[:'database_type'] if attributes[:'database_type']
self.database_sub_type = attributes[:'databaseSubType'] if attributes[:'databaseSubType']
raise 'You cannot provide both :databaseSubType and :database_sub_type' if attributes.key?(:'databaseSubType') && attributes.key?(:'database_sub_type')
self.database_sub_type = attributes[:'database_sub_type'] if attributes[:'database_sub_type']
self.deployment_type = attributes[:'deploymentType'] if attributes[:'deploymentType']
raise 'You cannot provide both :deploymentType and :deployment_type' if attributes.key?(:'deploymentType') && attributes.key?(:'deployment_type')
self.deployment_type = attributes[:'deployment_type'] if attributes[:'deployment_type']
self.is_cluster = attributes[:'isCluster'] unless attributes[:'isCluster'].nil?
raise 'You cannot provide both :isCluster and :is_cluster' if attributes.key?(:'isCluster') && attributes.key?(:'is_cluster')
self.is_cluster = attributes[:'is_cluster'] unless attributes[:'is_cluster'].nil?
self.workload_type = attributes[:'workloadType'] if attributes[:'workloadType']
raise 'You cannot provide both :workloadType and :workload_type' if attributes.key?(:'workloadType') && attributes.key?(:'workload_type')
self.workload_type = attributes[:'workload_type'] if attributes[:'workload_type']
self.job_id = attributes[:'jobId'] if attributes[:'jobId']
raise 'You cannot provide both :jobId and :job_id' if attributes.key?(:'jobId') && attributes.key?(:'job_id')
self.job_id = attributes[:'job_id'] if attributes[:'job_id']
self.job_name = attributes[:'jobName'] if attributes[:'jobName']
raise 'You cannot provide both :jobName and :job_name' if attributes.key?(:'jobName') && attributes.key?(:'job_name')
self.job_name = attributes[:'job_name'] if attributes[:'job_name']
self.status = attributes[:'status'] if attributes[:'status']
self.time_created = attributes[:'timeCreated'] if attributes[:'timeCreated']
raise 'You cannot provide both :timeCreated and :time_created' if attributes.key?(:'timeCreated') && attributes.key?(:'time_created')
self.time_created = attributes[:'time_created'] if attributes[:'time_created']
self.time_completed = attributes[:'timeCompleted'] if attributes[:'timeCompleted']
raise 'You cannot provide both :timeCompleted and :time_completed' if attributes.key?(:'timeCompleted') && attributes.key?(:'time_completed')
self.time_completed = attributes[:'time_completed'] if attributes[:'time_completed']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] database_type Object to be assigned
def database_type=(database_type)
# rubocop:disable Style/ConditionalAssignment
if database_type && !DATABASE_TYPE_ENUM.include?(database_type)
OCI.logger.debug("Unknown value for 'database_type' [" + database_type + "]. Mapping to 'DATABASE_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@database_type = DATABASE_TYPE_UNKNOWN_ENUM_VALUE
else
@database_type = database_type
end
# rubocop:enable Style/ConditionalAssignment
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] database_sub_type Object to be assigned
def database_sub_type=(database_sub_type)
# rubocop:disable Style/ConditionalAssignment
if database_sub_type && !DATABASE_SUB_TYPE_ENUM.include?(database_sub_type)
OCI.logger.debug("Unknown value for 'database_sub_type' [" + database_sub_type + "]. Mapping to 'DATABASE_SUB_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@database_sub_type = DATABASE_SUB_TYPE_UNKNOWN_ENUM_VALUE
else
@database_sub_type = database_sub_type
end
# rubocop:enable Style/ConditionalAssignment
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] deployment_type Object to be assigned
def deployment_type=(deployment_type)
# rubocop:disable Style/ConditionalAssignment
if deployment_type && !DEPLOYMENT_TYPE_ENUM.include?(deployment_type)
OCI.logger.debug("Unknown value for 'deployment_type' [" + deployment_type + "]. Mapping to 'DEPLOYMENT_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@deployment_type = DEPLOYMENT_TYPE_UNKNOWN_ENUM_VALUE
else
@deployment_type = deployment_type
end
# rubocop:enable Style/ConditionalAssignment
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] workload_type Object to be assigned
def workload_type=(workload_type)
# rubocop:disable Style/ConditionalAssignment
if workload_type && !WORKLOAD_TYPE_ENUM.include?(workload_type)
OCI.logger.debug("Unknown value for 'workload_type' [" + workload_type + "]. Mapping to 'WORKLOAD_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@workload_type = WORKLOAD_TYPE_UNKNOWN_ENUM_VALUE
else
@workload_type = workload_type
end
# rubocop:enable Style/ConditionalAssignment
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
id == other.id &&
name == other.name &&
compartment_id == other.compartment_id &&
managed_database_group_id == other.managed_database_group_id &&
managed_database_id == other.managed_database_id &&
managed_database_name == other.managed_database_name &&
database_type == other.database_type &&
database_sub_type == other.database_sub_type &&
deployment_type == other.deployment_type &&
is_cluster == other.is_cluster &&
workload_type == other.workload_type &&
job_id == other.job_id &&
job_name == other.job_name &&
status == other.status &&
time_created == other.time_created &&
time_completed == other.time_completed
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, name, compartment_id, managed_database_group_id, managed_database_id, managed_database_name, database_type, database_sub_type, deployment_type, is_cluster, workload_type, job_id, job_name, status, time_created, time_completed].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 43.970655 | 245 | 0.701525 |
260a291b29ffcf0e486a097ebfc5328a74ed04fd | 946 | module Scanny
module Checks
# Checks for use of the "before_filter" method with certain filters.
class BeforeFiltersCheck < Check
FILTERS = [:login_required, :admin_required]
# before_filter :login_required
def pattern
<<-EOT
SendWithArguments<
receiver = Self,
name = :before_filter,
arguments = ActualArguments<
array = [
any*,
SymbolLiteral<value = #{FILTERS.map(&:inspect).join(' | ')}>,
any*
]
>
>
EOT
end
def check(node)
filter_node = node.arguments.array.find do |argument|
argument.is_a?(Rubinius::AST::SymbolLiteral) &&
FILTERS.include?(argument.value)
end
issue :info,
"The \"before_filter\" method with :#{filter_node.value} filter is used."
end
end
end
end
| 26.277778 | 83 | 0.531712 |
39b0601f652cb260c66a3e8fb20e7ef275739988 | 2,862 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::BatchAI::Mgmt::V2018_03_01
module Models
#
# Values returned by the List operation.
#
class RemoteLoginInformationListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<RemoteLoginInformation>] The collection of returned
# remote login details.
attr_accessor :value
# @return [String] The continuation token.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<RemoteLoginInformation>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [RemoteLoginInformationListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for RemoteLoginInformationListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RemoteLoginInformationListResult',
type: {
name: 'Composite',
class_name: 'RemoteLoginInformationListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'RemoteLoginInformationElementType',
type: {
name: 'Composite',
class_name: 'RemoteLoginInformation'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.62 | 80 | 0.539832 |
4ab6faa3a538c80678d09c7ee6d5f7812a875b17 | 509 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe HacktoberfestProjectFetcherError do
it 'exposes an errors array and the query that led to the errors' do
errors = [1, 2, 3]
query = 'To be or not to be?'
message = 'That is the question'
error = HacktoberfestProjectFetcherError.new(
message,
errors: errors,
query: query
)
expect(error.errors).to eq errors
expect(error.query).to eq query
expect(error.message).to eq message
end
end
| 23.136364 | 70 | 0.689587 |
f8f9874aeaab45551b979653c8e638092f48b697 | 138 | class RemoveDraftsWithMissingProvider < ActiveRecord::Migration[4.2]
def change
Draft.where(provider_id: nil).destroy_all
end
end
| 23 | 68 | 0.789855 |
019cfb43b0899b0f747de732df8ace286b04f697 | 11,139 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CustomerInsights::Mgmt::V2017_01_01
module Models
#
# The Role Assignment resource format.
#
class RoleAssignmentResourceFormat < ProxyResource
include MsRestAzure
# @return [String] The hub name.
attr_accessor :tenant_id
# @return [String] The name of the metadata object.
attr_accessor :assignment_name
# @return [Hash{String => String}] Localized display names for the
# metadata.
attr_accessor :display_name
# @return [Hash{String => String}] Localized description for the
# metadata.
attr_accessor :description
# @return [ProvisioningStates] Provisioning state. Possible values
# include: 'Provisioning', 'Succeeded', 'Expiring', 'Deleting',
# 'HumanIntervention', 'Failed'
attr_accessor :provisioning_state
# @return [RoleTypes] Type of roles. Possible values include: 'Admin',
# 'Reader', 'ManageAdmin', 'ManageReader', 'DataAdmin', 'DataReader'
attr_accessor :role
# @return [Array<AssignmentPrincipal>] The principals being assigned to.
attr_accessor :principals
# @return [ResourceSetDescription] Profiles set for the assignment.
attr_accessor :profiles
# @return [ResourceSetDescription] Interactions set for the assignment.
attr_accessor :interactions
# @return [ResourceSetDescription] Links set for the assignment.
attr_accessor :links
# @return [ResourceSetDescription] Kpis set for the assignment.
attr_accessor :kpis
# @return [ResourceSetDescription] Sas Policies set for the assignment.
attr_accessor :sas_policies
# @return [ResourceSetDescription] Connectors set for the assignment.
attr_accessor :connectors
# @return [ResourceSetDescription] Views set for the assignment.
attr_accessor :views
# @return [ResourceSetDescription] The Role assignments set for the
# relationship links.
attr_accessor :relationship_links
# @return [ResourceSetDescription] The Role assignments set for the
# relationships.
attr_accessor :relationships
# @return [ResourceSetDescription] Widget types set for the assignment.
attr_accessor :widget_types
# @return [ResourceSetDescription] The Role assignments set for the
# assignment.
attr_accessor :role_assignments
# @return [ResourceSetDescription] Widget types set for the assignment.
attr_accessor :conflation_policies
# @return [ResourceSetDescription] The Role assignments set for the
# assignment.
attr_accessor :segments
#
# Mapper for RoleAssignmentResourceFormat class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RoleAssignmentResourceFormat',
type: {
name: 'Composite',
class_name: 'RoleAssignmentResourceFormat',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
tenant_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.tenantId',
type: {
name: 'String'
}
},
assignment_name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.assignmentName',
type: {
name: 'String'
}
},
display_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.displayName',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'properties.description',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
role: {
client_side_validation: true,
required: true,
serialized_name: 'properties.role',
type: {
name: 'Enum',
module: 'RoleTypes'
}
},
principals: {
client_side_validation: true,
required: true,
serialized_name: 'properties.principals',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'AssignmentPrincipalElementType',
type: {
name: 'Composite',
class_name: 'AssignmentPrincipal'
}
}
}
},
profiles: {
client_side_validation: true,
required: false,
serialized_name: 'properties.profiles',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
interactions: {
client_side_validation: true,
required: false,
serialized_name: 'properties.interactions',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
links: {
client_side_validation: true,
required: false,
serialized_name: 'properties.links',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
kpis: {
client_side_validation: true,
required: false,
serialized_name: 'properties.kpis',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
sas_policies: {
client_side_validation: true,
required: false,
serialized_name: 'properties.sasPolicies',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
connectors: {
client_side_validation: true,
required: false,
serialized_name: 'properties.connectors',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
views: {
client_side_validation: true,
required: false,
serialized_name: 'properties.views',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
relationship_links: {
client_side_validation: true,
required: false,
serialized_name: 'properties.relationshipLinks',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
relationships: {
client_side_validation: true,
required: false,
serialized_name: 'properties.relationships',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
widget_types: {
client_side_validation: true,
required: false,
serialized_name: 'properties.widgetTypes',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
role_assignments: {
client_side_validation: true,
required: false,
serialized_name: 'properties.roleAssignments',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
conflation_policies: {
client_side_validation: true,
required: false,
serialized_name: 'properties.conflationPolicies',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
},
segments: {
client_side_validation: true,
required: false,
serialized_name: 'properties.segments',
type: {
name: 'Composite',
class_name: 'ResourceSetDescription'
}
}
}
}
}
end
end
end
end
| 33.350299 | 78 | 0.479486 |
1c959770dc461fcca13d86008329332640f653fe | 1,980 | require 'spec_helper'
describe ExternalDiffUploader do
let(:diff) { create(:merge_request).merge_request_diff }
let(:path) { Gitlab.config.external_diffs.storage_path }
subject(:uploader) { described_class.new(diff, :external_diff) }
it_behaves_like "builds correct paths",
store_dir: %r[merge_request_diffs/mr-\d+],
cache_dir: %r[/external-diffs/tmp/cache],
work_dir: %r[/external-diffs/tmp/work]
context "object store is REMOTE" do
before do
stub_external_diffs_object_storage
end
include_context 'with storage', described_class::Store::REMOTE
it_behaves_like "builds correct paths",
store_dir: %r[merge_request_diffs/mr-\d+]
end
describe 'migration to object storage' do
context 'with object storage disabled' do
it "is skipped" do
expect(ObjectStorage::BackgroundMoveWorker).not_to receive(:perform_async)
diff
end
end
context 'with object storage enabled' do
before do
stub_external_diffs_setting(enabled: true)
stub_external_diffs_object_storage(background_upload: true)
end
it 'is scheduled to run after creation' do
expect(ObjectStorage::BackgroundMoveWorker).to receive(:perform_async).with(described_class.name, 'MergeRequestDiff', :external_diff, kind_of(Numeric))
diff
end
end
end
describe 'remote file' do
context 'with object storage enabled' do
before do
stub_external_diffs_setting(enabled: true)
stub_external_diffs_object_storage
diff.update!(external_diff_store: described_class::Store::REMOTE)
end
it 'can store file remotely' do
allow(ObjectStorage::BackgroundMoveWorker).to receive(:perform_async)
diff
expect(diff.external_diff_store).to eq(described_class::Store::REMOTE)
expect(diff.external_diff.path).not_to be_blank
end
end
end
end
| 29.117647 | 159 | 0.687879 |
edbcd5cae1002165cde42dc839db9542a22b1ec6 | 1,476 | # -*- encoding: utf-8 -*-
# stub: jekyll-titles-from-headings 0.4.0 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-titles-from-headings".freeze
s.version = "0.4.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Ben Balter".freeze]
s.date = "2017-08-11"
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/benbalter/jekyll-titles-from-headings".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.7.6".freeze
s.summary = "A Jekyll plugin to pull the page title from the first Markdown heading when none is specified.".freeze
s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<jekyll>.freeze, ["~> 3.3"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.43"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"])
else
s.add_dependency(%q<jekyll>.freeze, ["~> 3.3"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.43"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.5"])
end
else
s.add_dependency(%q<jekyll>.freeze, ["~> 3.3"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.43"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.5"])
end
end
| 38.842105 | 117 | 0.661924 |
79bd5b8530a16041b9931c9740d83244872b660b | 177 | def solution(s)
stack = []
s.each_char do |char|
if char == "("
stack << char
elsif stack.pop != "("
return 0
end
end
stack.empty? ? 1 : 0
end
| 12.642857 | 26 | 0.502825 |
ac751dc7bd6faee14fdc6dd91ebf289f56375061 | 374 | # Matcher that verifies that a process succeeds.
RSpec::Matchers.define :succeed do
match do |thing|
thing.exit_code.should == 0
end
failure_message_for_should do |actual|
"expected process to succeed. exit code: #{actual.exit_code}"
end
failure_message_for_should_not do |actual|
"expected process to fail. exit code: #{actual.exit_code}"
end
end
| 24.933333 | 65 | 0.735294 |
6a4ae5aafe1b93e1cd3723695d7b67c02c575565 | 3,198 | require_relative 'test_helper'
BYTEFIELD_CODE = <<-eos
;; This the source for the sample diagram illustrated in the project Read Me.
;; Some nice default background colors, used to distinguish header sections.
(defattrs :bg-green {:fill "#a0ffa0"})
(defattrs :bg-yellow {:fill "#ffffa0"})
(defattrs :bg-pink {:fill "#ffb0a0"})
(defattrs :bg-cyan {:fill "#a0fafa"})
(defattrs :bg-purple {:fill "#e4b5f7"})
(defn draw-group-label-header
"Creates a small borderless box used to draw the textual label headers
used below the byte labels for remotedb message diagrams.
Arguments are the number of colums to span and the text of the
label."
[span label]
(draw-box (text label [:math {:font-size 12}]) {:span span
:borders \#{}
:height 14}))
(defn draw-remotedb-header
"Generates the byte and field labels and standard header fields of a
request or response message for the remotedb database server with
the specified kind and args values."
[kind args]
(draw-column-headers)
(draw-group-label-header 5 "start")
(draw-group-label-header 5 "TxID")
(draw-group-label-header 3 "type")
(draw-group-label-header 2 "args")
(draw-group-label-header 1 "tags")
(next-row 18)
(draw-box 0x11 :bg-green)
(draw-box 0x872349ae [{:span 4} :bg-green])
(draw-box 0x11 :bg-yellow)
(draw-box (text "TxID" :math) [{:span 4} :bg-yellow])
(draw-box 0x10 :bg-pink)
(draw-box (hex-text kind 4 :bold) [{:span 2} :bg-pink])
(draw-box 0x0f :bg-cyan)
(draw-box (hex-text args 2 :bold) :bg-cyan)
(draw-box 0x14 :bg-purple)
(draw-box (text "0000000c" :hex [[:plain {:font-weight "light" :font-size 16}] " (12)"])
[{:span 4} :bg-purple])
(draw-box (hex-text 6 2 :bold) [:box-first :bg-purple])
(doseq [val [6 6 3 6 6 6 6 3]]
(draw-box (hex-text val 2 :bold) [:box-related :bg-purple]))
(doseq [val [0 0]]
(draw-box val [:box-related :bg-purple]))
(draw-box 0 [:box-last :bg-purple]))
;; Figure 48: Cue point response message.
(draw-remotedb-header 0x4702 9)
(draw-box 0x11)
(draw-box 0x2104 {:span 4})
(draw-box 0x11)
(draw-box 0 {:span 4})
(draw-box 0x11)
(draw-box (text "length" [:math] [:sub 1]) {:span 4})
(draw-box 0x14)
(draw-box (text "length" [:math] [:sub 1]) {:span 4})
(draw-gap "Cue and loop point bytes")
(draw-box nil :box-below)
(draw-box 0x11)
(draw-box 0x36 {:span 4})
(draw-box 0x11)
(draw-box (text "num" [:math] [:sub "hot"]) {:span 4})
(draw-box 0x11)
(draw-box (text "num" [:math] [:sub "cue"]) {:span 4})
(draw-box 0x11)
(draw-box (text "length" [:math] [:sub 2]) {:span 4})
(draw-box 0x14)
(draw-box (text "length" [:math] [:sub 2]) {:span 4})
(draw-gap "Unknown bytes" {:min-label-columns 6})
(draw-bottom)
eos
describe Asciidoctor::Diagram::BytefieldInlineMacroProcessor do
include_examples "inline_macro", :bytefield, BYTEFIELD_CODE, [:svg]
end
describe Asciidoctor::Diagram::BytefieldBlockMacroProcessor do
include_examples "block_macro", :bytefield, BYTEFIELD_CODE, [:svg]
end
describe Asciidoctor::Diagram::BytefieldBlockProcessor do
include_examples "block", :bytefield, BYTEFIELD_CODE, [:svg]
end
| 32.969072 | 90 | 0.65541 |
f71857af327a5034f6042238b2f694b9bcfbf8bc | 2,038 | module Rapidfire
class AttemptBuilder < Rapidfire::BaseService
attr_accessor :user, :survey, :questions, :answers, :params, :attempt_id
def initialize(params = {})
super(params)
build_attempt(params[:attempt_id])
end
def to_model
@attempt
end
def save!(options = {})
params.each do |question_id, answer_attributes|
if answer = @attempt.answers.find { |a| a.question_id.to_s == question_id.to_s }
text = answer_attributes[:answer_text]
# in case of checkboxes, values are submitted as an array of
# strings. we will store answers as one big string separated
# by delimiter.
text = text.values if text.is_a?(Hash)
answer.answer_text =
if text.is_a?(Array)
strip_checkbox_answers(text).join(Rapidfire.answers_delimiter)
elsif text.is_a?(ActionController::Parameters)
text.values.join(Rapidfire.answers_delimiter)
else
text
end
end
end
@attempt.save!(options)
end
def save(options = {})
save!(options)
rescue ActiveRecord::ActiveRecordError => e
# repopulate answers here in case of failure as they are not getting updated
@answers = @survey.questions.collect do |question|
@attempt.answers.find { |a| a.question_id == question.id }
end
false
end
private
def build_attempt(attempt_id)
if attempt_id.present?
@attempt = Attempt.find(attempt_id)
self.answers = @attempt.answers
self.user = @attempt.user
self.survey = @attempt.survey
self.questions = @survey.questions
else
@attempt = Attempt.new(user: user, survey: survey)
@answers = @survey.questions.collect do |question|
@attempt.answers.build(question_id: question.id)
end
end
end
def strip_checkbox_answers(answers)
answers.reject(&:blank?).reject { |t| t == "0" }
end
end
end
| 29.970588 | 88 | 0.618744 |
4a9e14e41b8d6d054b2be186939291b093ba2bc1 | 56 | FactoryGirl.define do
factory :meal do
end
end
| 9.333333 | 21 | 0.678571 |
4a63a148566c66724c50ce72fd3b09932ae71495 | 1,399 | #
# Cookbook Name:: sys
# Recipe:: time
#
# Copyright 2013, Victor Penso
#
# 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.
#
unless node['sys']['nis']['servers'].empty?
node.default['ohai']['disabled_plugins'] = [ :Passwd ]
package 'nis'
if node['sys']['nis']['domain'].empty?
node.default['sys']['nis']['domain'] = node['domain']
else
# we don't use a template here because this file must only contain
# the NIS domain on a single line - and no comments
file '/etc/defaultdomain' do
content node.default['sys']['nis']['domain'] << "\n"
end
end
template '/etc/yp.conf' do
source 'etc_yp.conf.erb'
variables(
:domain => node['sys']['nis']['domain'].chomp,
:servers => node['sys']['nis']['servers']
)
notifies :restart, 'service[nis]'
end
service 'nis' do
action [ :enable, :start ]
supports :restart => true
end
end
| 27.431373 | 74 | 0.664046 |
113e1c45620716da4c9f350cfeb6ecaf732e6e0f | 112 | # frozen_string_literal: true
require_relative '../span'
module Polites
class Span::Delete < Span
end
end
| 12.444444 | 29 | 0.741071 |
183eb29c0d8e6ea0afbfe8eca97efc67a9cbc939 | 5,887 | describe 'Ridgepole::Client#diff -> migrate' do
context 'when change column (add comment)' do
let(:actual_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false
t.integer "club_id", null: false
t.string "string", null: false
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false
end
ERB
end
let(:expected_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false, comment: "any comment"
t.integer "club_id", null: false, comment: "any comment2"
t.string "string", null: false, comment: "any comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "any comment4"
end
ERB
end
before { subject.diff(actual_dsl).migrate }
subject { client }
it {
delta = subject.diff(expected_dsl)
expect(delta.differ?).to be_truthy
expect(subject.dump).to match_ruby actual_dsl
delta.migrate
expect(subject.dump).to match_ruby expected_dsl
}
end
context 'when change column (delete comment)' do
let(:actual_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false, comment: "any comment"
t.integer "club_id", null: false, comment: "any comment2"
t.string "string", null: false, comment: "any comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "any comment4"
end
ERB
end
let(:expected_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false
t.integer "club_id", null: false
t.string "string", null: false
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false
end
ERB
end
before { subject.diff(actual_dsl).migrate }
subject { client }
it {
delta = subject.diff(expected_dsl)
expect(delta.differ?).to be_truthy
expect(subject.dump).to match_ruby actual_dsl
delta.migrate
expect(subject.dump).to match_ruby expected_dsl
}
end
context 'when change column (change comment)' do
let(:actual_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false, comment: "any comment"
t.integer "club_id", null: false, comment: "any comment2"
t.string "string", null: false, comment: "any comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "any comment4"
end
ERB
end
let(:expected_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false, comment: "other comment"
t.integer "club_id", null: false, comment: "other comment2"
t.string "string", null: false, comment: "other comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "other comment4"
end
ERB
end
before { subject.diff(actual_dsl).migrate }
subject { client }
it {
delta = subject.diff(expected_dsl)
expect(delta.differ?).to be_truthy
expect(subject.dump).to match_ruby actual_dsl
delta.migrate
expect(subject.dump).to match_ruby expected_dsl
}
end
context 'when change column (no change comment)' do
let(:actual_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade do |t|
t.integer "emp_no", null: false, comment: "any comment"
t.integer "club_id", null: false, comment: "any comment2"
t.string "string", null: false, comment: "any comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "any comment4"
end
ERB
end
before { subject.diff(actual_dsl).migrate }
subject { client }
it {
delta = subject.diff(actual_dsl)
expect(delta.differ?).to be_falsey
expect(subject.dump).to match_ruby actual_dsl
delta.migrate
expect(subject.dump).to match_ruby actual_dsl
}
end
context 'when create table (with comment)' do
let(:expected_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade, comment: "table comment" do |t|
t.integer "emp_no", null: false, comment: "other comment"
t.integer "club_id", null: false, comment: "other comment2"
t.string "string", null: false, comment: "other comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "other comment4"
end
ERB
end
subject { client }
it {
delta = subject.diff(expected_dsl)
expect(delta.differ?).to be_truthy
expect(subject.dump.strip).to be_empty
delta.migrate
expect(subject.dump).to match_ruby expected_dsl
}
end
context 'when drop table (with comment)' do
let(:actual_dsl) do
erbh(<<-ERB)
create_table "employee_clubs", force: :cascade, comment: "table comment" do |t|
t.integer "emp_no", null: false, comment: "other comment"
t.integer "club_id", null: false, comment: "other comment2"
t.string "string", null: false, comment: "other comment3"
t.text "text", <%= i cond(5.0, limit: 65535) %>, null: false, comment: "other comment4"
end
ERB
end
before { subject.diff(actual_dsl).migrate }
subject { client }
it {
delta = subject.diff('')
expect(delta.differ?).to be_truthy
expect(subject.dump).to match_ruby actual_dsl
delta.migrate
expect(subject.dump).to be_empty
}
end
end
| 33.073034 | 100 | 0.600985 |
abc38c09d511e5445c1bf5c6a3b85a2c996715c6 | 4,687 | # This file is part of Metasm, the Ruby assembly manipulation suite
# Copyright (C) 2007 Yoann GUILLOT
#
# Licence is LGPL, see LICENCE in the top-level directory
require 'metasm/exe_format/main'
require 'metasm/encode'
require 'metasm/decode'
module Metasm
class MZ < ExeFormat
MAGIC = 'MZ' # 0x4d5a
class Header < SerialStruct
mem :magic, 2, MAGIC
words :cblp, :cp, :crlc, :cparhdr, :minalloc, :maxalloc, :ss, :sp, :csum, :ip, :cs, :lfarlc, :ovno
mem :unk, 4
def encode(mz, relocs)
h = EncodedData.new
set_default_values mz, h, relocs
h << super(mz)
end
def set_default_values(mz, h=nil, relocs=nil)
return if not h
@cblp ||= Expression[[mz.label_at(mz.body, mz.body.virtsize), :-, mz.label_at(h, 0)], :%, 512] # number of bytes used in last page
@cp ||= Expression[[mz.label_at(mz.body, mz.body.virtsize), :-, mz.label_at(h, 0)], :/, 512] # number of pages used
@crlc ||= relocs.virtsize/4
@cparhdr ||= Expression[[mz.label_at(relocs, 0), :-, mz.label_at(h, 0)], :/, 16] # header size in paragraphs (16o)
@minalloc ||= ((mz.body.virtsize - mz.body.rawsize) + 15) / 16
@maxalloc ||= @minalloc
@sp ||= 0 # ss:sp points at 1st byte of body => works if body does not reach end of segment (or maybe the overflow make the stack go to header space)
@lfarlc ||= Expression[mz.label_at(relocs, 0), :-, mz.label_at(h, 0)]
super(mz)
end
def decode(mz)
super(mz)
raise InvalidExeFormat, "Invalid MZ signature #{h.magic.inspect}" if @magic != MAGIC
end
end
class Relocation < SerialStruct
words :offset, :segment
end
# encodes a word in 16 bits
def encode_word(val) Expression[val].encode(:u16, @endianness) end
# decodes a 16bits word from self.encoded
def decode_word(edata = @encoded) edata.decode_imm(:u16, @endianness) end
attr_accessor :endianness, :header, :source
# the EncodedData representing the content of the file
attr_accessor :body
# an array of Relocations - quite obscure
attr_accessor :relocs
def initialize(cpu=nil)
@endianness = cpu ? cpu.endianness : :little
@relocs = []
@header = Header.new
@body = EncodedData.new
@source = []
super(cpu)
end
# assembles the source in the body, clears the source
def assemble
@body << assemble_sequence(@source, @cpu)
@body.fixup @body.binding
# XXX should create @relocs here
@source.clear
end
# sets up @cursource
def parse_init
@cursource = @source
super()
end
# encodes the header and the relocation table, return them in an array, with the body.
def pre_encode
relocs = @relocs.inject(EncodedData.new) { |edata, r| edata << r.encode(self) }
header = @header.encode self, relocs
[header, relocs, @body]
end
# defines the exe-specific parser instructions:
# .entrypoint [<label>]: defines the program entrypoint to label (or create a new label at this location)
def parse_parser_instruction(instr)
case instr.raw.downcase
when '.entrypoint'
# ".entrypoint <somelabel/expression>" or ".entrypoint" (here)
@lexer.skip_space
if tok = @lexer.nexttok and tok.type == :string
raise instr, 'syntax error' if not entrypoint = Expression.parse(@lexer)
else
entrypoint = new_label('entrypoint')
@cursource << Label.new(entrypoint, instr.backtrace.dup)
end
@header.ip = Expression[entrypoint, :-, label_at(@body, 0, 'body')]
@lexer.skip_space
raise instr, 'eol expected' if t = @lexer.nexttok and t.type != :eol
end
end
# concats the header, relocation table and body
def encode
pre_encode.inject(@encoded) { |edata, pe| edata << pe }
@encoded.fixup @encoded.binding
encode_fix_checksum
end
# sets the file checksum (untested)
def encode_fix_checksum
@encoded.ptr = 0
decode_header
mzlen = @header.cp * 512 + @header.cblp
@encoded.ptr = 0
csum = [email protected]
(mzlen/2).times { csum += decode_word }
csum &= 0xffff
@header.csum = csum
hdr = @header.encode(self, nil)
@encoded[0, hdr.length] = hdr
end
# decodes the MZ header from the current offset in self.encoded
def decode_header
@header.decode self
end
# decodes the relocation table
def decode_relocs
@relocs.clear
@encoded.ptr = @header.lfarlc
@header.crlc.times { @relocs << Relocation.decode(self) }
end
# decodes the main part of the program
# mostly defines the 'start' export, to point to the MZ entrypoint
def decode_body
@body = @encoded[@header.cparhdr*[email protected]*[email protected]]
@body.virtsize += @header.minalloc * 16
@body.add_export 'start', @header.cs * 16 + @header.ip
end
def decode
decode_header
decode_relocs
decode_body
end
def each_section
yield @body, 0
end
end
end
| 28.579268 | 159 | 0.688073 |
4afbba579bdb16a8d5a2454ecc1f036e39b2efb9 | 1,240 | # frozen_string_literal: true
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "cookbook_release/version"
Gem::Specification.new do |spec|
spec.name = "cookbook_release"
spec.version = CookbookRelease::VERSION
spec.authors = ["Table XI"]
spec.email = ["[email protected]"]
spec.summary = "Rake tasks to assist with releasing your Chef cookbook."
spec.description = "Rake tasks to assist with releasing your Chef cookbook."
spec.homepage = "https://github.com/tablexi/cookbook_release"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rubocop"
spec.add_dependency "berkshelf"
# 1.15 requires github user and project set on every request
spec.add_dependency "github_changelog_generator", "~> 1.14.0"
spec.add_dependency "rake"
spec.add_dependency "stove"
end
| 35.428571 | 80 | 0.691129 |
6a5f8bc2a59e5dc0e877a7ebeae66d632a4359bb | 352 | # frozen_string_literal: true
module Types
module Ci
class TestCaseStatusEnum < BaseEnum
graphql_name 'TestCaseStatus'
::Gitlab::Ci::Reports::TestCase::STATUS_TYPES.each do |status|
value status,
description: "Test case that has a status of #{status}.",
value: status
end
end
end
end
| 22 | 71 | 0.633523 |
0848f5b6c6a549079cfe06479747dcb843899a7e | 858 | module Crawler
module Extractor
##
# Call all methods,starting with extract_, on 'data_block'
# collect all results and send them to #data_extracted
##
def extract_data(data_block)
result = {}
extractable = self.methods.select { |m| m != :extract_data && m.to_s[/extract_/] }
extractable.each do |extract_method|
begin
method_key = extract_method.to_s.match(/extract_(.+)$/)[1]
result[method_key.to_sym] = public_send(extract_method, data_block)
rescue => e
@logger.error "EXTRACT_ERROR: #{extract_method}: #{e}"
end
end
data_extracted(result)
end
##
# Do something with the extracted data...
##
def data_extracted(data)
p data
# insert data into store
# ...
# ....
# ..
data
end
end
end | 24.514286 | 88 | 0.586247 |
339695f6f468e6aa536e67ea27d6c5ac1599b77a | 346 | class AddAdditionalFieldsToVendors < ActiveRecord::Migration[5.2]
def change
add_column :spree_vendors, :t_distance, :string
add_column :spree_vendors, :address, :string
add_column :spree_vendors, :lat, :float
add_column :spree_vendors, :lng, :float
add_column :spree_vendors, :is_appointable, :boolean, default: true
end
end
| 31.454545 | 70 | 0.760116 |
382e190499837f621c210d4f642427b6503db6b3 | 1,049 | Pod::Spec.new do |s|
s.name = "NLEPlatform"
s.version = "0.0.16-d"
s.summary = "NLEPlatform"
s.license = {
:type => 'Copyright',
:text => <<-LICENSE
Bytedance copyright
LICENSE
}
s.authors = {"zhangyuanming"=>"[email protected]"}
s.homepage = "https://github.com/volcengine/volcengine-specs"
s.description = "make better video editing and development experience"
s.frameworks = ["AVFoundation", "Foundation", "UIKit", "CoreTelephony", "CoreMotion", "MediaToolbox", "GLKit", "OpenGLES", "VideoToolbox", "CoreMedia", "MetalPerformanceShaders", "MobileCoreServices", "CoreML", "Accelerate"]
s.requires_arc = true
s.libraries = ["xml2", "z", "c++"]
s.source = { :http => "https://sf3-ttcdn-tos.pstatp.com/obj/volcengine/#{s.name}/#{s.version}/#{s.name}.zip" }
s.ios.deployment_target = '9.0'
s.ios.vendored_framework = 'NLEPlatform.framework'
s.dependency 'TTVideoEditor', '>=9.x'
s.pod_target_xcconfig = { "VALID_ARCHS" => "armv7 arm64", 'ENABLE_BITCODE' => 'NO' }
end
| 43.708333 | 226 | 0.655863 |
e9acc5d413a03e6f8b6fd95f334debeff5b3c376 | 627 | class Digdag < Formula
desc "Workload Automation System"
homepage "https://www.digdag.io/"
url "https://dl.digdag.io/digdag-0.9.1.jar"
sha256 "424c04a73abce89851d3f59e9089007a1e47d353a5dd7d2688b6bde992e37cc6"
bottle :unneeded
depends_on :java => "1.8+"
def install
libexec.install "digdag-#{version}.jar" => "digdag.jar"
# Create a wrapper script to support OS X 10.9.
(bin/"digdag").write <<-EOS.undent
#!/bin/bash
exec /bin/bash "#{libexec}/digdag.jar" "$@"
EOS
end
test do
ENV.java_cache
assert_match version.to_s, shell_output("#{bin}/digdag --version")
end
end
| 24.115385 | 75 | 0.674641 |
26c8ac8b6ffde9a129599b01d89849f08d0efff7 | 5,009 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "Cookbook_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.327434 | 114 | 0.762228 |
abb16706209f01b98314b7598d392131ae025fdc | 528 | require "active_support"
require "active_support/core_ext"
require "cc/analyzer"
require "cc/yaml"
module CC
module CLI
autoload :Analyze, "cc/cli/analyze"
autoload :Command, "cc/cli/command"
autoload :Console, "cc/cli/console"
autoload :Engines, "cc/cli/engines"
autoload :Help, "cc/cli/help"
autoload :Init, "cc/cli/init"
autoload :Runner, "cc/cli/runner"
autoload :Test, "cc/cli/test"
autoload :ValidateConfig, "cc/cli/validate_config"
autoload :Version, "cc/cli/version"
end
end
| 26.4 | 54 | 0.69697 |
62895eabf9d7f3b15f49983c83ecf196d59b9cab | 821 | module Board::Model::AnpiPost
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include SS::Reference::Site
included do
store_in collection: "board_anpi_posts"
seqid :id
# 氏名
field :name, type: String
# 氏名(かな)
field :kana, type: String
# 電話番号
field :tel, type: String
# 住所
field :addr, type: String
# 性別
field :sex, type: String
# 年齢
field :age, type: String
# メールアドレス
field :email, type: String
# メッセージ
field :text, type: String
permit_params :name, :kana, :tel, :addr, :sex, :age, :email, :text
validates :name, presence: true, length: { maximum: 80 }
validates :text, presence: true
end
def sex_options
%w(male female).map { |m| [ I18n.t("member.options.sex.#{m}"), m ] }.to_a
end
end
| 21.605263 | 77 | 0.621194 |
627d355cbc56f4b56313feb41b1b76b748596d59 | 900 | $stdout.sync = true unless ENV["JETS_STDOUT_SYNC"] == "0"
$:.unshift(File.expand_path("../", __FILE__))
require "active_support"
require "active_support/concern"
require "active_support/core_ext"
require "active_support/dependencies"
require "active_support/ordered_hash"
require "active_support/ordered_options"
require "cfn_camelizer"
require "fileutils"
require "jets/gems"
require "memoist"
require "rainbow/ext/string"
gem_root = File.dirname(__dir__)
$:.unshift("#{gem_root}/lib")
$:.unshift("#{gem_root}/vendor/cfn-status/lib")
require "cfn_status"
require "jets/autoloaders"
Jets::Autoloaders.log! if ENV["JETS_AUTOLOAD_LOG"]
Jets::Autoloaders.once.setup
module Jets
RUBY_VERSION = "2.5.3"
MAX_FUNCTION_NAME_SIZE = 64
class Error < StandardError; end
extend Core # root, logger, etc
end
Jets::Autoloaders.once.preload("#{__dir__}/jets/db.rb") # required for booter.rb: setup_db
| 26.470588 | 90 | 0.763333 |
ab80425821ab1740f47f6f0ffd871b331c083b30 | 155 | name "php"
maintainer "Dwight Watson"
maintainer_email "[email protected]"
license "MIT"
description "Configure a Laravel application"
version "1.0.0" | 25.833333 | 45 | 0.8 |
bfd9b4ab34509391dc4b557792a991e65ac4a4c2 | 10,808 | # 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
module Aws::IAM
class InstanceProfile
extend Aws::Deprecations
# @overload def initialize(name, options = {})
# @param [String] name
# @option options [Client] :client
# @overload def initialize(options = {})
# @option options [required, String] :name
# @option options [Client] :client
def initialize(*args)
options = Hash === args.last ? args.pop.dup : {}
@name = extract_name(args, options)
@data = options.delete(:data)
@client = options.delete(:client) || Client.new(options)
end
# @!group Read-Only Attributes
# @return [String]
def name
@name
end
alias :instance_profile_name :name
# The path to the instance profile. For more information about paths,
# see [IAM Identifiers][1] in the *Using IAM* guide.
#
#
#
# [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
# @return [String]
def path
data[:path]
end
# The stable and unique string identifying the instance profile. For
# more information about IDs, see [IAM Identifiers][1] in the *Using
# IAM* guide.
#
#
#
# [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
# @return [String]
def instance_profile_id
data[:instance_profile_id]
end
# The Amazon Resource Name (ARN) specifying the instance profile. For
# more information about ARNs and how to use them in policies, see [IAM
# Identifiers][1] in the *Using IAM* guide.
#
#
#
# [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html
# @return [String]
def arn
data[:arn]
end
# The date when the instance profile was created.
# @return [Time]
def create_date
data[:create_date]
end
# @!endgroup
# @return [Client]
def client
@client
end
# Loads, or reloads {#data} for the current {InstanceProfile}.
# Returns `self` making it possible to chain methods.
#
# instance_profile.reload.data
#
# @return [self]
def load
resp = @client.get_instance_profile(instance_profile_name: @name)
@data = resp.instance_profile
self
end
alias :reload :load
# @return [Types::InstanceProfile]
# Returns the data for this {InstanceProfile}. Calls
# {Client#get_instance_profile} if {#data_loaded?} is `false`.
def data
load unless @data
@data
end
# @return [Boolean]
# Returns `true` if this resource is loaded. Accessing attributes or
# {#data} on an unloaded resource will trigger a call to {#load}.
def data_loaded?
!!@data
end
# @param [Hash] options ({})
# @return [Boolean]
# Returns `true` if the InstanceProfile exists.
def exists?(options = {})
begin
wait_until_exists(options.merge(max_attempts: 1))
true
rescue Aws::Waiters::Errors::UnexpectedError => e
raise e.error
rescue Aws::Waiters::Errors::WaiterFailed
false
end
end
# @param [Hash] options ({})
# @option options [Integer] :max_attempts (40)
# @option options [Float] :delay (1)
# @option options [Proc] :before_attempt
# @option options [Proc] :before_wait
# @return [InstanceProfile]
def wait_until_exists(options = {}, &block)
options, params = separate_params_and_options(options)
waiter = Waiters::InstanceProfileExists.new(options)
yield_waiter_and_warn(waiter, &block) if block_given?
waiter.wait(params.merge(instance_profile_name: @name))
InstanceProfile.new({
name: @name,
client: @client
})
end
# @deprecated Use [Aws::IAM::Client] #wait_until instead
#
# Waiter polls an API operation until a resource enters a desired
# state.
#
# @note The waiting operation is performed on a copy. The original resource remains unchanged
#
# ## Basic Usage
#
# Waiter will polls until it is successful, it fails by
# entering a terminal state, or until a maximum number of attempts
# are made.
#
# # polls in a loop until condition is true
# resource.wait_until(options) {|resource| condition}
#
# ## Example
#
# instance.wait_until(max_attempts:10, delay:5) {|instance| instance.state.name == 'running' }
#
# ## Configuration
#
# You can configure the maximum number of polling attempts, and the
# delay (in seconds) between each polling attempt. The waiting condition is set
# by passing a block to {#wait_until}:
#
# # poll for ~25 seconds
# resource.wait_until(max_attempts:5,delay:5) {|resource|...}
#
# ## Callbacks
#
# You can be notified before each polling attempt and before each
# delay. If you throw `:success` or `:failure` from these callbacks,
# it will terminate the waiter.
#
# started_at = Time.now
# # poll for 1 hour, instead of a number of attempts
# proc = Proc.new do |attempts, response|
# throw :failure if Time.now - started_at > 3600
# end
#
# # disable max attempts
# instance.wait_until(before_wait:proc, max_attempts:nil) {...}
#
# ## Handling Errors
#
# When a waiter is successful, it returns the Resource. When a waiter
# fails, it raises an error.
#
# begin
# resource.wait_until(...)
# rescue Aws::Waiters::Errors::WaiterFailed
# # resource did not enter the desired state in time
# end
#
#
# @yield param [Resource] resource to be used in the waiting condition
#
# @raise [Aws::Waiters::Errors::FailureStateError] Raised when the waiter terminates
# because the waiter has entered a state that it will not transition
# out of, preventing success.
#
# yet successful.
#
# @raise [Aws::Waiters::Errors::UnexpectedError] Raised when an error is encountered
# while polling for a resource that is not expected.
#
# @raise [NotImplementedError] Raised when the resource does not
#
# @option options [Integer] :max_attempts (10) Maximum number of
# attempts
# @option options [Integer] :delay (10) Delay between each
# attempt in seconds
# @option options [Proc] :before_attempt (nil) Callback
# invoked before each attempt
# @option options [Proc] :before_wait (nil) Callback
# invoked before each wait
# @return [Resource] if the waiter was successful
def wait_until(options = {}, &block)
self_copy = self.dup
attempts = 0
options[:max_attempts] = 10 unless options.key?(:max_attempts)
options[:delay] ||= 10
options[:poller] = Proc.new do
attempts += 1
if block.call(self_copy)
[:success, self_copy]
else
self_copy.reload unless attempts == options[:max_attempts]
:retry
end
end
Aws::Waiters::Waiter.new(options).wait({})
end
# @!group Actions
# @example Request syntax with placeholder values
#
# instance_profile.add_role({
# role_name: "roleNameType", # required
# })
# @param [Hash] options ({})
# @option options [required, String] :role_name
# The name of the role to add.
#
# This parameter allows (through its [regex pattern][1]) a string of
# characters consisting of upper and lowercase alphanumeric characters
# with no spaces. You can also include any of the following characters:
# \_+=,.@-
#
#
#
# [1]: http://wikipedia.org/wiki/regex
# @return [EmptyStructure]
def add_role(options = {})
options = options.merge(instance_profile_name: @name)
resp = @client.add_role_to_instance_profile(options)
resp.data
end
# @example Request syntax with placeholder values
#
# instance_profile.delete()
# @param [Hash] options ({})
# @return [EmptyStructure]
def delete(options = {})
options = options.merge(instance_profile_name: @name)
resp = @client.delete_instance_profile(options)
resp.data
end
# @example Request syntax with placeholder values
#
# instance_profile.remove_role({
# role_name: "roleNameType", # required
# })
# @param [Hash] options ({})
# @option options [required, String] :role_name
# The name of the role to remove.
#
# This parameter allows (through its [regex pattern][1]) a string of
# characters consisting of upper and lowercase alphanumeric characters
# with no spaces. You can also include any of the following characters:
# \_+=,.@-
#
#
#
# [1]: http://wikipedia.org/wiki/regex
# @return [EmptyStructure]
def remove_role(options = {})
options = options.merge(instance_profile_name: @name)
resp = @client.remove_role_from_instance_profile(options)
resp.data
end
# @!group Associations
# @return [Role::Collection]
def roles
batch = []
data[:roles].each do |d|
batch << Role.new(
name: d[:role_name],
data: d,
client: @client
)
end
Role::Collection.new([batch], size: batch.size)
end
# @deprecated
# @api private
def identifiers
{ name: @name }
end
deprecated(:identifiers)
private
def extract_name(args, options)
value = args[0] || options.delete(:name)
case value
when String then value
when nil then raise ArgumentError, "missing required option :name"
else
msg = "expected :name to be a String, got #{value.class}"
raise ArgumentError, msg
end
end
def yield_waiter_and_warn(waiter, &block)
if !@waiter_block_warned
msg = "pass options to configure the waiter; "
msg << "yielding the waiter is deprecated"
warn(msg)
@waiter_block_warned = true
end
yield(waiter.waiter)
end
def separate_params_and_options(options)
opts = Set.new([:client, :max_attempts, :delay, :before_attempt, :before_wait])
waiter_opts = {}
waiter_params = {}
options.each_pair do |key, value|
if opts.include?(key)
waiter_opts[key] = value
else
waiter_params[key] = value
end
end
waiter_opts[:client] ||= @client
[waiter_opts, waiter_params]
end
class Collection < Aws::Resources::Collection; end
end
end
| 30.022222 | 102 | 0.623335 |
3950c72e335fbe6797b379f56cb107a4482b49f2 | 1,491 | require 'test_helper'
module Haml
class InterpolationHelperTest < MiniTest::Unit::TestCase
def test_it_takes_text_and_returns_interpolations
replace = "this may \#{be} the \#{dup}"
t_name = "this_may_be_the_dup"
helper = Haml::I18n::Extractor::InterpolationHelper.new(replace, t_name)
assert helper.interpolations == ["be", "dup"], "can catch the interpolations"
end
def test_it_takes_text_and_custom_keynames
replace = "this may \#{be} the \#{dup}"
t_name = "this_may_be_the_dup"
helper = Haml::I18n::Extractor::InterpolationHelper.new(replace, t_name)
assert helper.keyname_with_vars == "t('.this_may_be_the_dup', :be => (be), :dup => (dup))",
"returns custom t() with vars"
end
def test_it_takes_text_and_returns_for_str_with_no_quotes
replace = "\\\#{is_this_hard?} what"
t_name = "is_this_hard_what"
helper = Haml::I18n::Extractor::InterpolationHelper.new(replace, t_name)
assert helper.interpolations == ["is_this_hard?"], "can catch the interpolations"
x = helper.keyname_with_vars
#puts x.inspect
assert x == "t('.is_this_hard_what', :is_this_hard => (is_this_hard?))",
"returns custom t() with vars"
end
# FIXME these don't work?
#%p \#{is_this_hard?} what
#%span I don't know if this \#{is_also} what
#%p= t('.what', :is_this_hard => is_this_hard?)
#%span= t('.i_dont_know_if_this_what', :is_also => is_also)
end
end
| 33.886364 | 97 | 0.667337 |
39b5c6e8af67e43190a6797f7b5a286b9b2eca44 | 1,136 | # frozen_string_literal: true
module DM
module Report
module PreparedReport
class New
def self.call(id, json_var, user, form_values: nil, form_errors: nil, remote: true) # rubocop:disable Metrics/ParameterLists
ui_rule = UiRules::Compiler.new(:prepared_report, :new, id: id, user: user, form_values: form_values, json_var: json_var)
rules = ui_rule.compile
layout = Crossbeams::Layout::Page.build(rules) do |page|
page.form_object ui_rule.form_object
page.form_values form_values
page.form_errors form_errors
page.form do |form|
form.action '/dataminer/prepared_reports/'
form.remote! if remote
form.add_field :id
form.add_field :json_var
form.add_field :database
form.add_field :report_template
form.add_field :report_description
# form.add_field :linked_users -- Only show when editing
form.add_field :existing_report
end
end
layout
end
end
end
end
end
| 33.411765 | 132 | 0.609155 |
794c62d43ea7ca0e0343aba76c8f0cf216f119b6 | 570 | require 'ffi'
module Multibit
extend FFI::Library
ffi_lib 'libmultibit_trie'
attach_function :make_fixedstridemultibit, [:uint], :pointer
attach_function :insert, [:pointer, :string], :void
attach_function :search, [:pointer, :string], :bool
class MultiBitTrie
def initialize(size)
@trie = Multibit.make_fixedstridemultibit(size)
end
def insert(binary)
Multibit.insert(@trie, binary)
end
def search(binary)
return Multibit.search(@trie, binary)
end
end
end
| 27.142857 | 64 | 0.635088 |
3963924a0668bf5d98d77b069b4ea725e8529eda | 7,482 | require 'rails_helper'
describe API::ProjectSnippets do
let(:project) { create(:project, :public) }
let(:user) { create(:user) }
let(:admin) { create(:admin) }
describe 'GET /projects/:project_id/snippets/:id' do
# TODO (rspeicher): Deprecated; remove in 9.0
it 'always exposes expires_at as nil' do
snippet = create(:project_snippet, author: admin)
get v3_api("/projects/#{snippet.project.id}/snippets/#{snippet.id}", admin)
expect(json_response).to have_key('expires_at')
expect(json_response['expires_at']).to be_nil
end
end
describe 'GET /projects/:project_id/snippets/' do
let(:user) { create(:user) }
it 'returns all snippets available to team member' do
project.add_developer(user)
public_snippet = create(:project_snippet, :public, project: project)
internal_snippet = create(:project_snippet, :internal, project: project)
private_snippet = create(:project_snippet, :private, project: project)
get v3_api("/projects/#{project.id}/snippets/", user)
expect(response).to have_http_status(200)
expect(json_response.size).to eq(3)
expect(json_response.map { |snippet| snippet['id']} ).to include(public_snippet.id, internal_snippet.id, private_snippet.id)
expect(json_response.last).to have_key('web_url')
end
it 'hides private snippets from regular user' do
create(:project_snippet, :private, project: project)
get v3_api("/projects/#{project.id}/snippets/", user)
expect(response).to have_http_status(200)
expect(json_response.size).to eq(0)
end
end
describe 'POST /projects/:project_id/snippets/' do
let(:params) do
{
title: 'Test Title',
file_name: 'test.rb',
code: 'puts "hello world"',
visibility_level: Snippet::PUBLIC
}
end
it 'creates a new snippet' do
post v3_api("/projects/#{project.id}/snippets/", admin), params
expect(response).to have_http_status(201)
snippet = ProjectSnippet.find(json_response['id'])
expect(snippet.content).to eq(params[:code])
expect(snippet.title).to eq(params[:title])
expect(snippet.file_name).to eq(params[:file_name])
expect(snippet.visibility_level).to eq(params[:visibility_level])
end
it 'returns 400 for missing parameters' do
params.delete(:title)
post v3_api("/projects/#{project.id}/snippets/", admin), params
expect(response).to have_http_status(400)
end
context 'when the snippet is spam' do
def create_snippet(project, snippet_params = {})
project.add_developer(user)
post v3_api("/projects/#{project.id}/snippets", user), params.merge(snippet_params)
end
before do
allow_any_instance_of(AkismetService).to receive(:is_spam?).and_return(true)
end
context 'when the snippet is private' do
it 'creates the snippet' do
expect { create_snippet(project, visibility_level: Snippet::PRIVATE) }
.to change { Snippet.count }.by(1)
end
end
context 'when the snippet is public' do
it 'rejects the shippet' do
expect { create_snippet(project, visibility_level: Snippet::PUBLIC) }
.not_to change { Snippet.count }
expect(response).to have_http_status(400)
expect(json_response['message']).to eq({ "error" => "Spam detected" })
end
it 'creates a spam log' do
expect { create_snippet(project, visibility_level: Snippet::PUBLIC) }
.to change { SpamLog.count }.by(1)
end
end
end
end
describe 'PUT /projects/:project_id/snippets/:id/' do
let(:visibility_level) { Snippet::PUBLIC }
let(:snippet) { create(:project_snippet, author: admin, visibility_level: visibility_level) }
it 'updates snippet' do
new_content = 'New content'
put v3_api("/projects/#{snippet.project.id}/snippets/#{snippet.id}/", admin), code: new_content
expect(response).to have_http_status(200)
snippet.reload
expect(snippet.content).to eq(new_content)
end
it 'returns 404 for invalid snippet id' do
put v3_api("/projects/#{snippet.project.id}/snippets/1234", admin), title: 'foo'
expect(response).to have_http_status(404)
expect(json_response['message']).to eq('404 Snippet Not Found')
end
it 'returns 400 for missing parameters' do
put v3_api("/projects/#{project.id}/snippets/1234", admin)
expect(response).to have_http_status(400)
end
context 'when the snippet is spam' do
def update_snippet(snippet_params = {})
put v3_api("/projects/#{snippet.project.id}/snippets/#{snippet.id}", admin), snippet_params
end
before do
allow_any_instance_of(AkismetService).to receive(:is_spam?).and_return(true)
end
context 'when the snippet is private' do
let(:visibility_level) { Snippet::PRIVATE }
it 'creates the snippet' do
expect { update_snippet(title: 'Foo') }
.to change { snippet.reload.title }.to('Foo')
end
end
context 'when the snippet is public' do
let(:visibility_level) { Snippet::PUBLIC }
it 'rejects the snippet' do
expect { update_snippet(title: 'Foo') }
.not_to change { snippet.reload.title }
end
it 'creates a spam log' do
expect { update_snippet(title: 'Foo') }
.to change { SpamLog.count }.by(1)
end
end
context 'when the private snippet is made public' do
let(:visibility_level) { Snippet::PRIVATE }
it 'rejects the snippet' do
expect { update_snippet(title: 'Foo', visibility_level: Snippet::PUBLIC) }
.not_to change { snippet.reload.title }
expect(response).to have_http_status(400)
expect(json_response['message']).to eq({ "error" => "Spam detected" })
end
it 'creates a spam log' do
expect { update_snippet(title: 'Foo', visibility_level: Snippet::PUBLIC) }
.to change { SpamLog.count }.by(1)
end
end
end
end
describe 'DELETE /projects/:project_id/snippets/:id/' do
let(:snippet) { create(:project_snippet, author: admin) }
it 'deletes snippet' do
admin = create(:admin)
snippet = create(:project_snippet, author: admin)
delete v3_api("/projects/#{snippet.project.id}/snippets/#{snippet.id}/", admin)
expect(response).to have_http_status(200)
end
it 'returns 404 for invalid snippet id' do
delete v3_api("/projects/#{snippet.project.id}/snippets/1234", admin)
expect(response).to have_http_status(404)
expect(json_response['message']).to eq('404 Snippet Not Found')
end
end
describe 'GET /projects/:project_id/snippets/:id/raw' do
let(:snippet) { create(:project_snippet, author: admin) }
it 'returns raw text' do
get v3_api("/projects/#{snippet.project.id}/snippets/#{snippet.id}/raw", admin)
expect(response).to have_http_status(200)
expect(response.content_type).to eq 'text/plain'
expect(response.body).to eq(snippet.content)
end
it 'returns 404 for invalid snippet id' do
delete v3_api("/projects/#{snippet.project.id}/snippets/1234", admin)
expect(response).to have_http_status(404)
expect(json_response['message']).to eq('404 Snippet Not Found')
end
end
end
| 32.960352 | 130 | 0.650628 |
1ada2b49dad12043cd440225964951d552b4efaf | 12,030 | # encoding: utf-8
require "moped/read_preference"
require "moped/readable"
require "moped/write_concern"
require "moped/collection"
require "moped/cluster"
require "moped/database"
module Moped
# A session in moped is root for all interactions with a MongoDB server or
# replica set.
#
# It can talk to a single default database, or dynamically speak to multiple
# databases.
#
# @example Single database (console-style)
# session = Moped::Session.new(["127.0.0.1:27017"])
# session.use(:moped)
# session[:users].find.one
#
# @example Multiple databases
# session = Moped::Session.new(["127.0.0.1:27017"])
# session.with(database: :admin) do |admin|
# admin.command(ismaster: 1)
# end
#
# @example Authentication
# session = Moped::Session.new %w[127.0.0.1:27017],
# session.with(database: "admin").login("admin", "s3cr3t")
#
# @since 1.0.0
class Session
include Optionable
# @!attribute cluster
# @return [ Cluster ] The cluster of nodes.
# @!attribute options
# @return [ Hash ] The configuration options.
attr_reader :cluster, :options
# Return +collection+ from the current database.
#
# @param (see Moped::Database#[])
#
# @return (see Moped::Database#[])
#
# @since 1.0.0
def [](name)
current_database[name]
end
# Return non system collection name from the current database.
#
# @param (see Moped::Database#collection_names)
#
# @return (see Moped::Database#collection_names)
#
# @since 1.0.0
def collection_names
current_database.collection_names
end
# Return non system collection name from the current database.
#
# @param (see Moped::Database#collections)
#
# @return (see Moped::Database#collections)
#
# @since 1.0.0
def collections
current_database.collections
end
# Run +command+ on the current database.
#
# @param (see Moped::Database#command)
#
# @return (see Moped::Database#command)
#
# @since 1.0.0
def command(op)
current_database.command(op)
end
# Get a list of all the database names for the session.
#
# @example Get all the database names.
# session.database_names
#
# @note This requires admin access on your server.
#
# @return [ Array<String>] All the database names.
#
# @since 1.2.0
def database_names
databases["databases"].map { |database| database["name"] }
end
# Get information on all databases for the session. This includes the name,
# size on disk, and if it is empty or not.
#
# @example Get all the database information.
# session.databases
#
# @note This requires admin access on your server.
#
# @return [ Hash ] The hash of database information, under the "databases"
# key.
#
# @since 1.2.0
def databases
with(database: :admin).command(listDatabases: 1)
end
# Disconnects all nodes in the session's cluster. This should only be used
# in cases # where you know you're not going to use the cluster on the
# thread anymore and need to force the connections to close.
#
# @return [ true ] True if the disconnect succeeded.
#
# @since 1.2.0
def disconnect
cluster.disconnect
end
# Drop the current database.
#
# @param (see Moped::Database#drop)
#
# @return (see Moped::Database#drop)
#
# @since 1.0.0
def drop
current_database.drop
end
# Provide a string inspection for the session.
#
# @example Inspect the session.
# session.inspect
#
# @return [ String ] The string inspection.
#
# @since 1.4.0
def inspect
"<#{self.class.name} seeds=#{cluster.seeds} database=#{current_database_name}>"
end
# Log in with +username+ and +password+ on the current database.
#
# @param (see Moped::Database#login)
#
# @raise (see Moped::Database#login)
#
# @since 1.0.0
def login(username, password)
current_database.login(username, password)
end
# Log out from the current database.
#
# @param (see Moped::Database#logout)
#
# @raise (see Moped::Database#login)
#
# @since 1.0.0
def logout
current_database.logout
end
# Setup validation of allowed write concern options.
#
# @since 2.0.0
option(:write).allow({ w: Optionable.any(Integer) }, { "w" => Optionable.any(Integer) })
option(:write).allow({ w: Optionable.any(String) }, { "w" => Optionable.any(String) })
option(:write).allow({ j: true }, { "j" => true })
option(:write).allow({ j: false }, { "j" => false })
option(:write).allow({ fsync: true }, { "fsync" => true })
option(:write).allow({ fsync: false }, { "fsync" => false })
# Setup validation of allowed read preference options.
#
# @since 2.0.0
option(:read).allow(
:nearest,
:primary,
:primary_preferred,
:secondary,
:secondary_preferred,
"nearest",
"primary",
"primary_preferred",
"secondary",
"secondary_preferred"
)
# Setup validation of allowed database options. (Any string or symbol)
#
# @since 2.0.0
option(:database).allow(Optionable.any(String), Optionable.any(Symbol))
# Setup validation of allowed max retry options. (Any integer)
#
# @since 2.0.0
option(:max_retries).allow(Optionable.any(Integer))
# Setup validation of allowed pool size options. (Any integer)
#
# @since 2.0.0
option(:pool_size).allow(Optionable.any(Integer))
# Setup validation of allowed retry interval options. (Any numeric)
#
# @since 2.0.0
option(:retry_interval).allow(Optionable.any(Numeric))
# Setup validation of allowed refresh interval options. (Any numeric)
#
# @since 2.0.0
option(:refresh_interval).allow(Optionable.any(Numeric))
# Setup validation of allowed down interval options. (Any numeric)
#
# @since 2.0.0
option(:down_interval).allow(Optionable.any(Numeric))
# Setup validation of allowed ssl options. (Any boolean)
#
# @since 2.0.0
option(:ssl).allow(true, false)
# Setup validation of allowed timeout options. (Any numeric)
#
# @since 2.0.0
option(:timeout).allow(Optionable.any(Numeric))
# Pass an object that responds to instrument as an instrumenter.
#
# @since 2.0.0
option(:instrumenter).allow(Optionable.any(Object))
# Setup validation of allowed auto_discover preference options.
#
# @since 1.5.0
option(:auto_discover).allow(true, false)
# Initialize a new database session.
#
# @example Initialize a new session.
# Session.new([ "localhost:27017" ])
#
# @param [ Array ] seeds An array of host:port pairs.
# @param [ Hash ] options The options for the session.
#
# @see Above options validations for allowed values in the options hash.
#
# @since 1.0.0
def initialize(seeds, options = {})
validate_strict(options)
@options = options
@cluster = Cluster.new(seeds, options)
end
# Create a new session with +options+ and use new socket connections.
#
# @example Change safe mode
# session.with(write: { w: 2 })[:people].insert(name: "Joe")
#
# @example Change safe mode with block
# session.with(write: { w: 2 }) do |session|
# session[:people].insert(name: "Joe")
# end
#
# @example Temporarily change database
# session.with(database: "admin") do |admin|
# admin.command ismaster: 1
# end
#
# @example Copy between databases
# session.use "moped"
# session.with(database: "backup") do |backup|
# session[:people].each do |person|
# backup[:people].insert person
# end
# end
#
# @param [ Hash ] options The options.
#
# @return [ Session ] The new session.
#
# @see #with
#
# @since 1.0.0
#
# @yieldparam [ Session ] session The new session.
def new(options = {})
session = with(options)
session.instance_variable_set(:@cluster, cluster.dup)
if block_given?
yield(session)
else
session
end
end
# Get the read preference for the session. Will default to primary if none
# was provided.
#
# @example Get the session's read preference.
# session.read_preference
#
# @return [ Object ] The read preference.
#
# @since 2.0.0
def read_preference
@read_preference ||= ReadPreference.get(options[:read] || :primary)
end
# Switch the session's current database.
#
# @example Switch the current database.
# session.use :moped
# session[:people].find.one # => { :name => "John" }
#
# @param [ String, Symbol ] database The database to use.
#
# @since 1.0.0
def use(database)
options[:database] = database
set_current_database(database)
end
# Create a new session with +options+ reusing existing connections.
#
# @example Change safe mode
# session.with(write: { w: 2 })[:people].insert(name: "Joe")
#
# @example Change safe mode with block
# session.with(write: { w: 2 }) do |session|
# session[:people].insert(name: "Joe")
# end
#
# @example Temporarily change database
# session.with(database: "admin") do |admin|
# admin.command ismaster: 1
# end
#
# @example Copy between databases
# session.use "moped"
# session.with(database: "backup") do |backup|
# session[:people].each do |person|
# backup[:people].insert person
# end
# end
#
# @param [ Hash ] options The session options.
#
# @return [ Session, Object ] The new session, or the value returned
# by the block if provided.
#
# @since 1.0.0
#
# @yieldparam [ Session ] session The new session.
def with(options = {})
session = dup
session.options.update(options)
if block_given?
yield(session)
else
session
end
end
# Get the write concern for the session. Will default to propagate if none
# was provided.
#
# @example Get the session's write concern.
# session.write_concern
#
# @return [ Object ] The write concern.
#
# @since 2.0.0
def write_concern
@write_concern ||= WriteConcern.get(options[:write] || { w: 1 })
end
class << self
# Create a new session from a URI.
#
# @example Initialize a new session.
# Session.connect("mongodb://localhost:27017/my_db")
#
# @param [ String ] MongoDB URI formatted string.
#
# @return [ Session ] The new session.
#
# @since 3.0.0
def connect(uri)
uri = Uri.new(uri)
session = new(*uri.moped_arguments)
session.login(uri.username, uri.password) if uri.auth_provided?
session
end
end
private
# Get the database that the session is currently using.
#
# @api private
#
# @example Get the current database.
# session.current_database
#
# @return [ Database ] The current database or nil.
#
# @since 2.0.0
def current_database
return @current_database if @current_database
if database = options[:database]
set_current_database(database)
else
raise "No database set for session. Call #use or #with before accessing the database"
end
end
def current_database_name
@current_database ? current_database.name : :none
end
def initialize_copy(_)
@options = @options.dup
@read_preference = nil
@write_concern = nil
@current_database = nil
end
def set_current_database(database)
@current_database = Database.new(self, database)
end
end
end
| 27.033708 | 93 | 0.612968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.